gpt4 book ai didi

python - 我应该如何修改 SVM 方法的测试数据才能使用 `precomputed` 核函数而不会出错?

转载 作者:太空宇宙 更新时间:2023-11-04 02:00:51 25 4
gpt4 key购买 nike

我正在使用 sklearn.svm.SVR 进行“回归任务”,我想使用我的“自定义内核方法”。这是数据集示例和代码:

 index   density     speed        label
0 14 58.844020 77.179139
1 29 67.624946 78.367394
2 44 77.679100 79.143744
3 59 79.361877 70.048869
4 74 72.529289 74.499239
.... and so on

from sklearn import svm
import pandas as pd
import numpy as np

density = np.random.randint(0,100, size=(3000, 1))
speed = np.random.randint(20,80, size=(3000, 1)) + np.random.random(size=(3000, 1))
label = np.random.randint(20,80, size=(3000, 1)) + np.random.random(size=(3000, 1))

d = np.hstack((a,b,c))
data = pd.DataFrame(d, columns=['density', 'speed', 'label'])
data.density = data.density.astype(dtype=np.int32)

def my_kernel(X,Y):
return np.dot(X,X.T)

svr = svm.SVR(kernel=my_kernel)
x = data[['density', 'speed']].iloc[:2000]
y = data['label'].iloc[:2000]
x_t = data[['density', 'speed']].iloc[2000:3000]
y_t = data['label'].iloc[2000:3000]

svr.fit(x,y)
y_preds = svr.predict(x_t)

问题发生在最后一行 svm.predict 里面说:

X.shape[1] = 1000 should be equal to 2000, the number of samples at training time

我在网上搜索以找到解决问题的方法,但许多类似的问题(例如 {1}、{ 2 }、{ 3 })都没有得到解答。

实际上,我之前曾将 SVM 方法与 rbfsigmoid 等一起使用,代码运行良好,但这是我第一次使用自定义内核和我怀疑一定是这个错误发生的原因。

因此,经过一些研究和阅读文档后,我发现当使用预计算 内核时,SVR.predict() 的矩阵形状必须像[n_samples_test, n_samples_train] 形状。

我想知道如何修改 x_test 以获得预测并且一切正常,没有问题,就像我们不使用自定义内核时一样?

如果可能,请描述“预计算内核中svm.predict函数的输入与其他内核不同的原因”。

我真的希望与这个问题相关的悬而未决的问题能够分别得到回答。

最佳答案

问题出在您的内核函数中,它无法完成工作。

作为文档 https://scikit-learn.org/stable/modules/svm.html#using-python-functions-as-kernels说,“你的内核必须将两个形状为 (n_samples_1, n_features) 的矩阵作为参数,(n_samples_2, n_features) 并返回一个形状为 (n_samples_1 , n_samples_2)。”同一页面上的示例内核满足此条件:

def my_kernel(X, Y):
return np.dot(X, Y.T)

在你的函数中,dot 的第二个参数是 X.T,因此输出的形状是 (n_samples_1, n_samples_1) 而不是那个预计。

关于python - 我应该如何修改 SVM 方法的测试数据才能使用 `precomputed` 核函数而不会出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55759533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com