gpt4 book ai didi

python - sklearn svm 中的稀疏预计算 Gram 矩阵?

转载 作者:太空宇宙 更新时间:2023-11-03 18:35:40 26 4
gpt4 key购买 nike

我想将稀疏的预计算 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 使用稀疏矩阵。但我不知道该怎么做。

更新:我刚刚检查了 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")

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

最佳答案

so I'm probably out of luck.

是的。对此感到抱歉。

Is it a bug that I didn't actually see that error though?

是的:已发布的代码集

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

然后检查

self._sparse and self._pairwise

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

关于python - sklearn svm 中的稀疏预计算 Gram 矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21639685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com