26

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

RandomForestClassifier和对象上的分类很好GradientBoostingClassifier,但使用SVCfromsklearn.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 很好地处理丢失的数据?请记住,丢失的数据适用于随机森林和其他分类器。

4

3 回答 3

26

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

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

(从页面复制并修改)

>>> 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)
于 2012-07-12T15:34:29.820 回答
6

您可以删除具有缺失特征的样本,也可以将缺失特征替换为其按列的中位数或均值。

于 2012-07-12T08:17:36.863 回答
1

这里最受欢迎的答案已经过时了。“Imputer”现在是“SimpleImputer”。此处给出了当前解决此问题的方法。估算训练和测试数据对我的工作如下:

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)
于 2021-05-31T11:31:53.757 回答