我目前正在尝试使用线性回归实现交叉验证。线性回归有效,但是当我尝试交叉验证时,出现此错误:
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
。
同样,您想要e = p-y_test
第 8 行。
在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
我没有收到任何错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句