python - 在 self._compute_kernel(X) 中引发 ValueError ("X.shape[0] should be equal to X.shape[1]")

标签 python machine-learning scikit-learn svm

在我的代码中,X 和 y 是训练数据:

from sklearn.svm import SVC
clf = SVC(kernel=lambda x,y:gauss_kernel(x, y, 100) )
print(X.shape[0])
print(X.shape[1])
print(X.shape)

clf.fit(X, y)

我收到以下错误:

211
2
(211, 2)
/Users/mona/anaconda/lib/python3.6/site-packages/sklearn/utils/validation.py:547: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
  y = column_or_1d(y, warn=True)
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-23-1f163ab380a5> in <module>()
      8 print(X.shape)
      9 
---> 10 clf.fit(X, y)
     11 plot_data()
     12 plot_boundary(svm,-.5,.3,-.8,.6)

~/anaconda/lib/python3.6/site-packages/sklearn/svm/base.py in fit(self, X, y, sample_weight)
    185 
    186         seed = rnd.randint(np.iinfo('i').max)
--> 187         fit(X, y, sample_weight, solver_type, kernel, random_seed=seed)
    188         # see comment on the other call to np.iinfo in this file
    189 

~/anaconda/lib/python3.6/site-packages/sklearn/svm/base.py in _dense_fit(self, X, y, sample_weight, solver_type, kernel, random_seed)
    226             X = self._compute_kernel(X)
    227 
--> 228             if X.shape[0] != X.shape[1]:
    229                 raise ValueError("X.shape[0] should be equal to X.shape[1]")
    230 

IndexError:元组索引超出范围

这是我编写的定制高斯内核:

import math
def gauss_kernel(x1, x2, gamma):
    sigma = math.sqrt(gamma) 
    return np.exp(-np.sum((x1-x2)**2)/(2*sigma**2))

我应该如何解决这个问题?当我查看 sklearn 中的 SVM 示例时,它们基本上做同样的事情。我相信我忽略了一些小事情,但在与 sklearn 示例匹配时无法确定问题。

最佳答案

请确保您的自定义内核的输出是方阵。

目前,您的 gauss_kernel 实现将返回一个数字,而不是一个数组。因此调用 shape[0] 或 shape[1] 会抛出“元组索引超出范围错误”。

所以解决这个问题:

import math
def gauss_kernel(x1, x2):
    sigma = math.sqrt(100) 
    return np.array([np.exp(-np.sum((x1-x2)**2)/(2*sigma**2))])

然后使用您的代码。

注意:这只是将单个数字包装到数组的解决方法。您应该检查您的原始 gauss_kernel 有什么问题,它返回的是单个数字。

关于python - 在 self._compute_kernel(X) 中引发 ValueError ("X.shape[0] should be equal to X.shape[1]"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47564504/

相关文章:

python - networkx 最佳实践在遍历边缘时获取边缘属性值

python - 如何在 scikit-learn 中使用 SGDRegressor

python - 为什么 CPU 上的 RandomForestClassifier(使用 SKLearn)和 GPU 上的 RandomForestClassifier(使用 RAPID)会得到不同的分数,而且差别很大?

python - sklearn : Hyperparameter tuning by gradient descent?

algorithm - SVM 中的决策边界和权重向量

python - 在 scikit-learn 中使用预训练手套词嵌入

python - 根据索引和值填充 scipy/numpy 矩阵

python - 如何清除 Tkinter ListBox Python

python - 使用scrapy抓取动态内容

python - 使用 mlpack 时 Cython 模块中的 undefined symbol