svm CUSTOM KERNEL PYTHON ERROR

时间:2015-03-29 04:00:25

标签: python kernel svm

我正在尝试在python中创建一个自定义内核。这是我的代码:

from sklearn import datasets
from sklearn.svm import SVC
from sklearn import svm

from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt
import PIL
from PIL import Image
import pylab as pl 
import math

digits = datasets.load_digits()


X = digits.data[:-200]

Y = digits.target[:-200]



def kernal6(x,y):
    d=np.linalg.norm(x-y)
    Xn=np.linalg.norm(x)
    Yn=np.linalg.norm(y)
    return (Xn+Yn-d)/np.sqrt(Xn*Yn)    


clf5 = svm.SVC(kernel=kernal6)
clf5.fit(X,Y)

但我一直收到这个错误:

IndexError:元组索引超出范围

2 个答案:

答案 0 :(得分:1)

您返回错误的值。内核函数应该返回一个矩阵。查看this以查看适当内核函数的示例

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets

digits = datasets.load_digits()
X = digits.data[:-200, :2]  #You were doing this wrong too
Y = digits.target[:-200]

def my_kernel(x, y):
    M = np.array([[2, 0], [0, 1.0]])
    return np.dot(np.dot(x, M), y.T) #returns a matrix

def kernal6(x,y):
    d=np.linalg.norm(x-y)
    Xn=np.linalg.norm(x)
    Yn=np.linalg.norm(y)
    return (Xn+Yn-d)/np.sqrt(Xn*Yn) #returns a float    

print "Testing SVC with my_kernel"
clf = svm.SVC(kernel=my_kernel)
clf.fit(X, Y) #works fine
print "Success!"

print "Testing kernal6"
print "kernal6 direct call:",kernal6(X, X) #will return a result
clf = svm.SVC(kernel=kernal6)
try:
    clf.fit(X, Y)#fails
except:
    print "Failed to fit with kernal6"

答案 1 :(得分:0)

IndexError意味着您正在尝试访问未定义的索引的数组/元组值。您尝试访问元组(它表示元组索引超出范围)的唯一时间是您声明XY。因此,它必须是切片符号的问题。我认为原因是因为元组没有多于或等于200个元素(数组[: - 200]返回len(数组) - 200,它可能再次为负整数);但是,我无法运行你的代码,因为我的翻译会抛出错误,所以如果我错了,我很抱歉。