Scikit-learn:linear_model.SGDClassifier():ValueError:调用partial_fit()时ndarray不是C-contiguous

时间:2013-10-09 14:10:57

标签: python machine-learning scikit-learn

我正在尝试运行linear_model.SGDClassifier()并在它分类的每个示例之后更新它。 我的代码适用于一个小的功能文件(10个功能),但是当我给它一个更大的功能文件(大约80000个功能,但非常稀疏)时,它会一直给我错误,第一次调用partial_fit()。

这是我在伪代码中所做的:

X, y = load_svmlight_file(train_file)
classifier = linear_model.SGDClassifier()
classifier.fit(X, y)

for every test_line in test file:
  test_X, test_y = getFeatures(test_line)
  # This gives me a Python list for X
  # and an integer label for y

  print "prediction: %f" % = classifier.predict([test_X])

  classifier.partial_fit(csr_matrix([test_X]),
                         csr_matrix([Y_GroundTruth])
                         classes=np.unique(y) )

我为partial_fit()行留下的错误是:

  File "/bla/bla/epd/lib/python2.7/site-packages/sklearn/linear_model/stochastic_gradient.py", line 487, in partial_fit
    coef_init=None, intercept_init=None)
  File "/bla/bla/epd/lib/python2.7/site-packages/sklearn/linear_model/stochastic_gradient.py", line 371, in _partial_fit
    sample_weight=sample_weight, n_iter=n_iter)
  File "/bla/bla/epd/lib/python2.7/site-packages/sklearn/linear_model/stochastic_gradient.py", line 451, in _fit_multiclass
    for i in range(len(self.classes_)))
  File "/bla/bla/epd/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 517, in __call__
    self.dispatch(function, args, kwargs)
  File "/bla/bla/epd/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 312, in dispatch
    job = ImmediateApply(func, args, kwargs)
  File "/bla/bla/epd/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 136, in __init__
    self.results = func(*args, **kwargs)
  File "/bla/bla/epd/lib/python2.7/site-packages/sklearn/linear_model/stochastic_gradient.py", line 284, in fit_binary
    est.power_t, est.t_, intercept_decay)
  File "sgd_fast.pyx", line 327, in sklearn.linear_model.sgd_fast.plain_sgd (sklearn/linear_model/sgd_fast.c:7568)
ValueError: ndarray is not C-contiguous

我也试过提供partial.fit()Python数组,或者numpy数组(默认情况下是C-contiguous(sort = C),我想),但这给出了相同的结果。 classes属性不是我想的问题。如果我将其遗漏或者在硬编码中给出正确的类,则会出现相同的错误。

我注意到当我打印分类器的_coef数组的标志时,它说:

Flags of coef_ array:
  C_CONTIGUOUS : False
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False 

我确信我做错了什么,但实际上,我看不出是什么......

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:3)

对于记录(因此这个问题似乎没有答案),这个问题在scikit-learn邮件列表上是previously answered。这是scikit-learn 0.14 SGDClassifier中的一个错误。解决方法是将最初的fit替换为partial_fit

更新:几分钟前我fixed the bug