在 python 中尝试交叉验证时出错

Error when attempting cross validation in python

我目前正在尝试使用线性回归实现交叉验证。线性回归有效,但是当我尝试交叉验证时出现此错误:

TypeError: only integer scalar arrays can be converted to a scalar index

我在代码的第 5 行收到此错误。

这是我的代码:

for train_index, test_index in kf.split(X):
    print("TRAIN:", train_index, "TEST:", test_index)
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    linreg.fit(X_train, Y_train)
    # p = np.array([linreg.predict(xi) for xi in x[test]])
    p = linreg.predict(X_test)
    e = p-Y_test
    xval_err += np.dot(e,e)

rmse_10cv = np.sqrt(xval_err/len(X_train))

有人可以帮我解决这个问题吗?

提前致谢!

您的代码存在一些问题。

第 5 行 Y_train 未定义。我想你想要小写 y_train.

同样,您希望第 8 行 e = p-y_test

In rmse_10cv = np.sqrt(xval_err/len(X_train)) X_train 是在你的循环中定义的,所以它将在你的循环的最后一次迭代中取值。观察你的输出,在哪里打印你的每一次折叠的训练指数,以确保 X_train 的长度始终相同,否则你的 rmse_10cv 的计算将无效。

我 运行 您的代码包含我描述的修复以及循环之前的以下内容:

import numpy as np
from sklearn.model_selection import KFold
from sklearn.linear_model import LinearRegression
X = X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
y = np.array([1, 2, 3, 4])
kf = KFold(n_splits=2)
linreg = LinearRegression()
xval_err = 0

而且我没有收到任何错误。