Sparse precomputed Gram matrices in sklearn svm?



我想将一个稀疏的预计算的 Gram 矩阵传递给 sklearn.svm.SVC.fit。下面是一些工作代码:

import numpy as np
from sklearn import svm
X = np.array([[0, 0], [1, 1]])
y = [0, 1]
clf = svm.SVC(kernel='precomputed')
gram = np.dot(X, X.T)
clf.fit(gram, y) 

但是如果我有:

from scipy.sparse import csr_matrix
sparse_gram = csr_matrix(gram)
clf.fit(sparse_gram, y)

我得到:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/sklearn/svm/base.py", line 191, in fit
    fit(X, y, sample_weight, solver_type, kernel)
  File "/usr/local/lib/python2.7/dist-packages/sklearn/svm/base.py", line 235, in _dense_fit
    max_iter=self.max_iter)
TypeError: Argument 'X' has incorrect type (expected numpy.ndarray, got csr_matrix)

事实上,我最终进入了_dense_fit函数(参见上面说的第 235 行)让我觉得我需要做一些特别的事情来告诉适合使用稀疏矩阵。但我不知道该怎么做。

更新:我刚刚检查了 fit 函数 (https://sourcegraph.com/github.com/scikit-learn/scikit-learn/symbols/python/sklearn/svm/base/BaseLibSVM/fit) 的代码,现在我更加困惑:

    self._sparse = sp.isspmatrix(X) and not self._pairwise
    if self._sparse and self._pairwise:
        raise ValueError("Sparse precomputed kernels are not supported. "
                         "Using sparse data and dense kernels is possible "
                         "by not using the ``sparse`` parameter")

所以我想正如它所说,"不支持稀疏预计算内核",这确实是我想做的,所以我可能不走运。(不过,我实际上没有看到该错误是一个错误吗?

所以我可能不走运。

是的。对此感到抱歉。

是我实际上没有看到该错误的错误吗?

是的:发布的代码集

self._sparse = sp.isspmatrix(X) and not self._pairwise

然后检查

self._sparse and self._pairwise

以引发异常。这个条件是不可能满足的。我刚刚推送了一个补丁来解决这个问题,感谢您的报告。

最新更新