我有一个包含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,)