如何让SVM与scikit-learn中缺少的数据很好地配合?

时间:2012-07-11 21:26:25

标签: python machine-learning scikit-learn

我正在使用scikit-learn进行一些数据分析,而我的数据集有一些缺失值(由NA表示)。我使用genfromtxt将数据加载到dtype='f8',然后开始训练我的分类器。

RandomForestClassifierGradientBoostingClassifier个对象的分类正常,但使用SVC中的sklearn.svm会导致以下错误:

    probas = classifiers[i].fit(train[traincv], target[traincv]).predict_proba(train[testcv])
  File "C:\Python27\lib\site-packages\sklearn\svm\base.py", line 409, in predict_proba
    X = self._validate_for_predict(X)
  File "C:\Python27\lib\site-packages\sklearn\svm\base.py", line 534, in _validate_for_predict
    X = atleast2d_or_csr(X, dtype=np.float64, order="C")
  File "C:\Python27\lib\site-packages\sklearn\utils\validation.py", line 84, in atleast2d_or_csr
    assert_all_finite(X)
  File "C:\Python27\lib\site-packages\sklearn\utils\validation.py", line 20, in assert_all_finite
    raise ValueError("array contains NaN or infinity")
ValueError: array contains NaN or infinity

是什么给出的?如何使SVM与丢失的数据很好地配合?请记住,缺失的数据适用于随机森林和其他分类器。

3 个答案:

答案 0 :(得分:24)

在使用SVM之前,您可以进行数据插补以处理缺失值。

编辑:在scikit-learn中,有一种非常简单的方法可以做到这一点,如this page所示。

(从页面复制并修改)

>>> 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)

答案 1 :(得分:6)

您可以删除缺少要素的样本,也可以使用列中间或方法替换缺少的要素。

答案 2 :(得分:0)

这里最受欢迎的答案已经过时。 “Imputer”现在是“SimpleImputer”。目前解决这个问题的方法是here。输入训练和测试数据对我有用,如下所示:

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)