缺失值处理
方法一: 删除含有缺失值的行数据
方法二:填补,包含单特征填补和多特征填补。单特征填补比较简单,只需要考虑单列数据,一般是用其平均值,中位数,众数填补。1
2
3
4
5
6
7
8
9import numpy as np
from sklearn.impute import SimpleImputer
imp = SimpleImputer(missing_values=np.nan, strategy='mean')
data = [[1, 2, 3], [np.nan, 3, 5], [7, 6, 9]]
imp.fit(data)
imp.transform(data)
1., 2., 3.], array([[
[4., 3., 5.],
[7., 6., 9.]])
随机森林填补1
2
3
4
5
6
7
8
9
10
11
12import numpy as np
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
imp = IterativeImputer(max_iter=10, random_state=0)
data = [[1, 2, 3], [3, 6, 7], [4, 8, 12], [np.nan, 3, 1], [7, np.nan, 10]]
imp.fit(data)
imp.transform(data)
1. , 2. , 3. ], array([[
[ 3. , 6. , 7. ],
[ 4. , 8. , 12. ],
[ 1.50207882, 3. , 1. ],
[ 7. , 13.99140168, 10. ]])
R 包 mice 处理1
2
3
4
5
6
7
8library(mice)
md.pattern(airquality) #缺失值可视化
> Wind Temp Month Day Solar.R Ozone
111 1 1 1 1 1 1 0
35 1 1 1 1 1 0 1
5 1 1 1 1 0 1 1
2 1 1 1 1 0 0 2
0 0 0 0 7 37 44
左边第一列,为不同缺失情况下的样本数
右边第一列,为不同缺失情况下的缺失个数
最下面一行,每个列有多少个缺失值1
2
3
4
5imputed_Data <- mice(airquality, m=5, maxit = 50, method = 'pmm', seed = 1024)
stripplot(imputed_Data, col=c("grey",mdc(2)),pch=c(1,20)) #填充可视化
xyplot(imputed_Data , Ozone ~ Solar.R | .imp, pch=20,cex=1.2) #分面板观察填充
fit=with(imputed_Data,lm(Ozone ~ Wind + Solar.R + Temp))
completeData <- complete(imputed_Data,1) # 用第一种结果填充
异常值处理
方法一:单列异常值处理,使用箱线图观察1
2
3
4import matplotlib.pyplot as plt
import pandas ad pd
data.boxplot()
plt.show()
方法二:使用 PyOD 进行异常值检测(ML)1
2
3
4
5
6from pyod.models.iforest import IForest
import pandas ad pd
clf = IForest()
clf.fit(data)
clf.predict(data)
>>>array([1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) # 1不正常,0正常