Python 使用 scikit-learn 的 Imputer 模块预测缺失值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25017626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Predicting missing values with scikit-learn's Imputer module
提问by rayu
I am writing a very basic program to predict missing values in a dataset using scikit-learn's Imputerclass.
我正在编写一个非常基本的程序来使用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
采纳答案by jonrsharpe
Per the documentation, sklearn.preprocessing.Imputer.fit_transformreturns a new array, it doesn't alter the argument array. The minimal fix is therefore:
根据文档,sklearn.preprocessing.Imputer.fit_transform返回一个新数组,它不会改变参数数组。因此,最小的修复是:
X = imp.fit_transform(X)
回答by MD SAZID KHAN
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])
回答by msklc
After scikit-learn version 0.20impute module using changed. So now we use imputer like;
在scikit-learn 0.20 版后,impute 模块使用发生了变化。所以现在我们使用 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.nanis used
而不是“男”,np.nan使用
Don't need to use axisparameter
不需要使用axis参数
We can use impor imputerinstead of my imputevariable
我们可以使用imp或imputer代替我的impute变量

