我正在尝试实现一个自定义的rbf核函数。然而,我得到以下错误。我不知道为什么预期会有一定数量的数据点? 此代码行出错:
rbf_y = rbf_kernel.predict(X_test)
代码
def myKernel(x,y):
pairwise_dists = squareform(pdist(x, 'euclidean'))
K = scip.exp(-pairwise_dists ** 2 / .08 ** 2)
return K
rbf_kernel = svm.SVC(kernel=myKernel, C=1).fit(X_train, Y_train.ravel())
rbf_y = rbf_kernel.predict(X_test)
rbf_accuracy = accuracy_score(Y_test, rbf_y)
错误:
ValueError: X.shape[1] = 15510 should be equal to 31488, the number of samples at training time
数据形状
X_train shape: (31488, 128)
X_test shape: (15510, 128)
Y_train shape: (31488, 1)
Y_test shape: (15510, 1)
从内核返回形状
myKernel(X_train, X_train).shape = (31488, 31488)
自定义内核
kernel(X, Y)
应该计算矩阵X
和矩阵Y
之间的相似性度量,并且输出的形状应该是[X.shape[0], Y.shape[0]]
。内核函数忽略Y
,并返回一个[X.shape[0], X.shape[0]]
形状的矩阵,这将导致您看到的错误要解决此问题,请实现一个核函数来计算正确形状的核矩阵。sciketlearn的custom kernels documentation提供了一些简单的例子来说明这是如何工作的
对于您的特定内核,您可以尝试用
cdist(x, y)
代替squareform(pdist(x))
相关问题 更多 >
编程相关推荐