python - scikit-learn 中预计算内核的网格搜索中的嵌套交叉验证

标签 python machine-learning scikit-learn

我有一个大小为 NxN 的预计算内核。我正在使用 GridSearchCV 调整带有 kernel='precomputed' 的 SVM 的 C 参数,如下所示:

C_range = 10. ** np.arange(-2, 9)
param_grid = dict(C=C_range)
grid = GridSearchCV(SVC(kernel='precomputed'), param_grid=param_grid, cv=StratifiedKFold(y=data_label, n_folds=10))
grid.fit(kernel, data_label)
print grid.best_score_

这工作得很好,但是因为我使用完整的数据进行预测(使用 grid.predict(kernel)),它会过拟合(大多数时候我得到 precision/recall = 1.0)。

所以我想首先通过交叉验证将我的数据分成 10 个 block (9 个用于训练,1 个用于测试),并且在每个折叠中,我想运行 GridSearch 来调整训练集上的 C 值,并且在测试集上测试。

为了做到这一点,我将内核矩阵分成 100x100 和 50x50 子矩阵,在其中一个子矩阵上运行 grid.fit(),在另一个子矩阵上运行 grid.predict()。

但是我得到以下错误:

ValueError: X.shape[1] = 50 should be equal to 100, the number of features at training time

我想训练内核应该与测试内核具有相同的维度,但我不明白为什么,因为我只是为 100x100 和 50x50 计算 np.dot(X, X.T),因此最终内核具有不同的维度..

最佳答案

scikit 学习 doc说:

Set kernel='precomputed' and pass the Gram matrix instead of X in the fit method. At the moment, the kernel values between all training vectors and the test vectors must be provided.

所以我猜不可能用预先计算的内核进行(简单的)交叉验证。

关于python - scikit-learn 中预计算内核的网格搜索中的嵌套交叉验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24595874/

相关文章:

machine-learning - 为什么PCA效果很好而保留的总方差很小?

python - 使用 TF-IDF 分数进行文本分类的 KNN

python - 科学数据包 : calculate precision and recall using cross_val_score function

python - 如何使用python从gmail下载附件?

r - 何时在 R 中的插入符包中使用 train() 的索引和种子参数

Python 从线程更新 Matplotlib

machine-learning - 如何为不同的客户预测不同的标签

python - 制作额外的树模型时出现 ValueError : Unknown label type: array([0. 11],...)

python - 在主窗口上使用 QProcessAnimation

python - 在类方法中定义一个函数是非 pythonic 的吗?