[英]Predicting missing values with scikit-learn's Imputer module
I am writing a very basic program to predict missing values in a dataset using scikit-learn's Imputer class.我正在编写一个非常基本的程序来使用scikit-learn 的 Imputer类预测数据集中的缺失值。
I have made a NumPy array, created an Imputer object with strategy='mean' and performed fit_transform() on the NumPy array.我制作了一个 NumPy 数组,创建了一个带有 strategy='mean' 的 Imputer 对象,并在 NumPy 数组上执行了 fit_transform()。
When I print the array after performing fit_transform(), the 'Nan's remain, and I dont get any prediction.当我在执行 fit_transform() 后打印数组时,'Nan's 仍然存在,我没有得到任何预测。
What am I doing wrong here?我在这里做错了什么? How do I go about predicting the missing values?
我如何去预测缺失值?
import numpy as np
from sklearn.preprocessing import Imputer
X = np.array([[23.56],[53.45],['NaN'],[44.44],[77.78],['NaN'],[234.44],[11.33],[79.87]])
print X
imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
imp.fit_transform(X)
print X
Per the documentation , sklearn.preprocessing.Imputer.fit_transform
returns a new array , it doesn't alter the argument array.根据文档,
sklearn.preprocessing.Imputer.fit_transform
返回一个新数组,它不会改变参数数组。 The minimal fix is therefore:因此,最小的修复是:
X = imp.fit_transform(X)
After scikit-learn version 0.20 the usage of impute module was changed.在scikit-learn 0.20 版之后,impute 模块的用法发生了变化。 Now, we can use imputer like;
现在,我们可以使用 imputer 之类的;
from sklearn.impute import SimpleImputer
impute = SimpleImputer(missing_values=np.nan, strategy='mean')
impute.fit(X)
X=impute.transform(X)
Pay attention:请注意:
Instead of 'NaN' , np.nan is used使用np.nan而不是'NaN'
Don't need to use axis parameter不需要使用axis参数
We can use imp or imputer instead of my impute
variable我们可以使用imp或imputer代替我的
impute
变量
Note: Due to the change in the sklearn library 'NaN' has to be replaced with np.nan as shown below.注意:由于 sklearn 库 'NaN' 的变化,必须用 np.nan 替换,如下所示。
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values= np.nan,strategy='mean',axis=0)
imputer = imputer.fit(X[:,1:3])
X[:,1:3]= imputer.transform(X[:,1:3])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.