我目前正在尝试使用线性回归实现交叉验证。线性回归可以正常工作,但是当我尝试进行交叉验证时,我得到了以下错误:
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
。
在 rmse_10cv = np.sqrt(xval_err/len(X_train))
中,X_train
是在循环内部定义的,所以它会取循环最后一次迭代的值。请注意输出中每次折叠的训练索引,以确保 X_train
的长度始终相同,否则你的 rmse_10cv
计算将无效。
我按照我描述的修复方法运行了你的代码,并在循环前添加了以下内容:
我没有遇到任何错误。