我正在使用scikit learn进行一些数据分析,我的数据集有一些缺失的值(用NA
表示)。我用genfromtxt
和dtype='f8'
加载数据,然后开始训练我的分类器。
RandomForestClassifier
和GradientBoostingClassifier
对象的分类很好,但使用sklearn.svm
中的SVC
会导致以下错误:
probas = classifiers[i].fit(train[traincv], target[traincv]).predict_proba(train[testcv])
File "C:Python27libsite-packagessklearnsvmbase.py", line 409, in predict_proba
X = self._validate_for_predict(X)
File "C:Python27libsite-packagessklearnsvmbase.py", line 534, in _validate_for_predict
X = atleast2d_or_csr(X, dtype=np.float64, order="C")
File "C:Python27libsite-packagessklearnutilsvalidation.py", line 84, in atleast2d_or_csr
assert_all_finite(X)
File "C:Python27libsite-packagessklearnutilsvalidation.py", line 20, in assert_all_finite
raise ValueError("array contains NaN or infinity")
ValueError: array contains NaN or infinity
什么东西?如何使SVM能够很好地处理缺失的数据?请记住,丢失的数据适用于随机林和其他分类器。。
在使用SVM之前,可以进行数据插补以处理缺失值。
编辑:在scikit学习中,有一种非常简单的方法可以做到这一点,如本页所示。
(从页面复制并修改)
>>> import numpy as np
>>> from sklearn.preprocessing import Imputer
>>> # missing_values is the value of your placeholder, strategy is if you'd like mean, median or mode, and axis=0 means it calculates the imputation based on the other feature values for that sample
>>> imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
>>> imp.fit(train)
Imputer(axis=0, copy=True, missing_values='NaN', strategy='mean', verbose=0)
>>> train_imp = imp.transform(train)
您可以删除具有缺失特征的样本,也可以用它们的列中值或均值替换缺失的特征。
这里最流行的答案已经过时了"脉冲";现在是";SimpleImputter";。这里给出了目前解决这个问题的方法。输入训练和测试数据对我来说如下:
from sklearn import svm
import numpy as np
from sklearn.impute import SimpleImputer
imp = SimpleImputer(missing_values=np.nan, strategy='mean')
imp = imp.fit(x_train)
X_train_imp = imp.transform(x_train)
X_test_imp = imp.transform(x_test)
clf = svm.SVC()
clf = clf.fit(X_train_imp, y_train)
predictions = clf.predict(X_test_imp)