用sklearn.preprocessing做数据预处理(五)——缺失数据

在scikit-learn的模型中都是假设输入的数据是数值型的,并且都是有意义的。但如果有缺失数据是通过NAN或者空值来表示的话,就无法识别与计算了。要弥补缺失值可以使用均值、中位数、众数等。Imputer这个类可以实现。

import numpy as np
from sklearn.preprocessing import Imputer
imp = Imputer(missing_values='NaN', strategy='mean', axis=0 )
imp.fit([[1,1],[np.nan,1],[7,7]])    #第一类平均值(1+7)/2=4,第二列平均值(1+1+7)/3=3

Imputer(axis=0, copy=True, missing_values='NaN', strategy='mean', verbose=0)

x = [[np.nan, 2], [6, np.nan], [7,6]]   #第一列np.nan用平均值4代替,第二列np.nan用平均值3来代替
imp.transform(x)

array([[4., 2.],
       [6., 3.],
       [7., 6.]])

Imputer类同样也可以支持稀疏矩阵,以下例子将0作为了缺失值,为其补上均值

import scipy.sparse as sp
#创建一个稀疏矩阵
x = sp.csc_matrix([[1,2],[0,3],[7,6]])
imp = Imputer(missing_values=0, strategy='mean', verbose=0 )
imp.fit(x)
x_test = sp.csc_matrix([[0,2], [6,0], [7,6]])
imp.transform(x_test)

array([[4.        , 2.        ],
       [6.        , 3.66666667],
       [7.        , 6.        ]])

猜你喜欢

转载自blog.csdn.net/weixin_44530236/article/details/88078270