离群点检测python代码实现
时间: 2023-10-13 21:26:26 浏览: 83
离群点检测是一种用于识别数据集中异常值的技术,下面是一些常见的离群点检测算法的Python实现。
1. 基于统计学的离群点检测(Z-score)
```python
import numpy as np
from scipy.stats import zscore
def detect_outlier_zscore(data, threshold=3):
z_scores = zscore(data)
return np.where(np.abs(z_scores) > threshold)
```
2. 基于箱线图的离群点检测
```python
import numpy as np
def detect_outlier_boxplot(data):
q1, q3 = np.percentile(data, [25, 75])
iqr = q3 - q1
lower_bound = q1 - (1.5 * iqr)
upper_bound = q3 + (1.5 * iqr)
return np.where((data < lower_bound) | (data > upper_bound))
```
3. 基于密度的离群点检测(DBSCAN)
```python
from sklearn.cluster import DBSCAN
import numpy as np
def detect_outlier_dbscan(data, eps=0.5, min_samples=5):
dbscan = DBSCAN(eps=eps, min_samples=min_samples)
dbscan.fit(data.reshape(-1, 1))
return np.where(dbscan.labels_ == -1)
```
以上是一些常见的离群点检测算法的Python代码实现,当然也有其他算法可以用于离群点检测,比如LOF(Local Outlier Factor)等。需要根据实际情况选择合适的算法。