如何让我的自定义内核工作?

How to get my custom kernel working?

import numpy as np
import sklearn.svm as svm

这是我的核函数

def my_kernel(p1, p2):
    r = 1-np.dot(p1.T, p2)
    return np.exp(-r**2/4)

还有我的数据

X1 = np.random.random((50,5))
X1 = X1/np.sum(X1)
X1 = X1.T
Y1 = [0, 0, 1, 1, 1]

然后使用sklearn svm

my_svm = svm.SVC(kernel=my_kernel)
my_svm.fit(X1,Y1)

它输出

SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0,
  kernel=<function my_kernel at 0x109891e18>, max_iter=-1,
  probability=False, random_state=None, shrinking=True, tol=0.001,
  verbose=False)

但是当我使用 predict()

y_pred = my_svm.predict(X1)

它说

    ---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-151-48e55060e495> in <module>()
----> 1 y_pred = my_svm.predict(X1)

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/sklearn/svm/base.py in predict(self, X)
    498             Class labels for samples in X.
    499         """
--> 500         y = super(BaseSVC, self).predict(X)
    501         return self.classes_.take(np.asarray(y, dtype=np.intp))
    502 

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/sklearn/svm/base.py in predict(self, X)
    290         X = self._validate_for_predict(X)
    291         predict = self._sparse_predict if self._sparse else self._dense_predict
--> 292         return predict(X)
    293 
    294     def _dense_predict(self, X):

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/sklearn/svm/base.py in _dense_predict(self, X)
    304                 raise ValueError("X.shape[1] = %d should be equal to %d, "
    305                                  "the number of samples at training time" %
--> 306                                  (X.shape[1], self.shape_fit_[0]))
    307 
    308         svm_type = LIBSVM_IMPL.index(self._impl)

ValueError: X.shape[1] = 50 should be equal to 5, the number of samples at training time

问题出在核函数的点积应该是

def my_kernel(p1, p2):
    r = 1-np.dot(p1, p2.T)
    return np.exp(-r**2/4)