如何在不使用scikit-learn的情况下为K折交叉验证创建训练集?

我有一个包含95行和9列的数据集,想进行5折交叉验证。在训练中,前8列(特征)用于预测第九列。我的测试集是正确的,但我的x训练集大小为(4,19,9),而它应该只有8列,我的y训练集大小为(4,9),而它应该有19行。我在索引子数组时是否犯了错误?

kdata = data[0:95,:] # 需要总行数能被5整除,所以忽略最后2行 np.random.shuffle(kdata) # 打乱所有行folds = np.array_split(kdata, k) # 每个折叠是19行 x 9列for i in range (k-1):    xtest = folds[i][:,0:7] # 将第i个折叠设为测试集    ytest = folds[i][:,8]    new_folds = np.delete(folds,i,0)    xtrain = new_folds[:][:][0:7] # 训练集是所有折叠的所有行 x 8列    ytrain = new_folds[:][:][8]   # 训练y是所有折叠的所有行 x 1列

回答:

欢迎来到Stack Overflow。

一旦你创建了一个新的折叠,你需要使用np.row_stack()按行堆叠它们。

另外,我认为你在切片数组时有误,在Python或Numpy中,切片行为是[包含:不包含],因此,当你指定切片为[0:7]时,你只取了7列,而不是你想要的8个特征列。

类似地,如果你在for循环中指定了5折,它应该是range(k),这会给你[0,1,2,3,4],而不是range(k-1),这只会给你[0,1,2,3]

修改后的代码如下:

folds = np.array_split(kdata, k) # 每个折叠是19行 x 9列np.random.shuffle(kdata) # 打乱所有行folds = np.array_split(kdata, k)for i in range (k):    xtest = folds[i][:,:8] # 将第i个折叠设为测试集    ytest = folds[i][:,8]    new_folds = np.row_stack(np.delete(folds,i,0))    xtrain = new_folds[:, :8]    ytrain = new_folds[:,8]    # 一些打印函数来帮助你调试    print(f'Fold {i}')    print(f'xtest shape  : {xtest.shape}')    print(f'ytest shape  : {ytest.shape}')    print(f'xtrain shape : {xtrain.shape}')    print(f'ytrain shape : {ytrain.shape}\n')

这将为你打印出折叠以及训练和测试集的所需形状:

Fold 0xtest shape  : (19, 8)ytest shape  : (19,)xtrain shape : (76, 8)ytrain shape : (76,)Fold 1xtest shape  : (19, 8)ytest shape  : (19,)xtrain shape : (76, 8)ytrain shape : (76,)Fold 2xtest shape  : (19, 8)ytest shape  : (19,)xtrain shape : (76, 8)ytrain shape : (76,)Fold 3xtest shape  : (19, 8)ytest shape  : (19,)xtrain shape : (76, 8)ytrain shape : (76,)Fold 4xtest shape  : (19, 8)ytest shape  : (19,)xtrain shape : (76, 8)ytrain shape : (76,)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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