python - How to get my custom kernel working? -


import numpy np import sklearn.svm svm 

here kernel function

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

and data

x1 = np.random.random((50,5)) x1 = x1/np.sum(x1) x1 = x1.t y1 = [0, 0, 1, 1, 1] 

then use sklearn svm

my_svm = svm.svc(kernel=my_kernel) my_svm.fit(x1,y1) 

it outputs

svc(c=1.0, cache_size=200, class_weight=none, coef0=0.0, degree=3, gamma=0.0,   kernel=<function my_kernel @ 0x109891e18>, max_iter=-1,   probability=false, random_state=none, shrinking=true, tol=0.001,   verbose=false) 

but when use predict()

y_pred = my_svm.predict(x1) 

it says

    --------------------------------------------------------------------------- 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 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 equal %d, "     305                                  "the number of samples @ 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 equal 5, number of samples @ training time 

the problem lies in kernel function dot product should

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

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -