在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

rmse_10cv = np.sqrt(xval_err/len(X_train)) 中,X_train 是在循环内部定义的,所以它会取循环最后一次迭代的值。请注意输出中每次折叠的训练索引,以确保 X_train 的长度始终相同,否则你的 rmse_10cv 计算将无效。

我按照我描述的修复方法运行了你的代码,并在循环前添加了以下内容:

我没有遇到任何错误。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注