简体   繁体   中英

String Kernel SVM with Scikit-learn

I am new to scikit-learn and I saw a sample solution posted in one of other questions on string kernels in scikitearn on Stackoverflow. So i tried that out, but I am getting this error message:

>>> X = np.arange(len(data)).reshape(-1, 1)
>>> X
   array([[0],
   [1],
   [2]])

    def string_kernel(X, Y):
    ... R = np.zeros((len(x), len(y)))
    ... for x in X:
    ...     for y in Y:
    ...         i = int(x[0])
    ...         j = int(y[0])
    ...         R[i, j] = data[i][0] == data[j][0]
    ... return R

>>> clf = SVC(kernel=string_kernel)
>>> clf.fit(X, ['no', 'yes', 'yes'])

This is the Error message I get:

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/sklearn/svm/base.py", line 178, in   fit
  fit(X, y, sample_weight, solver_type, kernel, random_seed=seed)
  File "/Library/Python/2.7/site-packages/sklearn/svm/base.py", line 217, in    _dense_fit
   X = self._compute_kernel(X)
  File "/Library/Python/2.7/site-packages/sklearn/svm/base.py", line 345, in _compute_kernel
  kernel = self.kernel(X, self.__Xfit)
  File "<stdin>", line 2, in string_kernel
  UnboundLocalError: local variable 'x' referenced before assignment

The specific error you're seeing actually has nothing to do with SVM. On this line in your string_kernel function:

R = np.zeros((len(x), len(y)))

lowercase x (and y ) are currently undefined, hence the UnboundLocalError . You larsmans probably meant len(X) and len(Y) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM