因为我有一个小数据集,所以我LOOCV
在sklearn
.
当我运行分类器时,收到以下错误:
"Number of labels=41 does not match number of samples=42"
.
我使用以下代码生成了测试集和训练集:
otu_trans = test_train.transpose()
# transpose otu table
merged = pd.concat([otu_trans, metadata[status]], axis=1, join='inner')
# merge phenotype column from metadata file with transposed otu table
X = merged.drop([status],axis=1)
# drop status from X
y = merged[status]
encoder = LabelEncoder()
y = pd.Series(encoder.fit_transform(y),
index=y.index, name=y.name)
# convert T and TF lables to 0 and 1 respectively
loocv = LeaveOneOut()
loocv.get_n_splits(X)
for train_index, test_index in loocv.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]
print(X_train, X_test, y_train, y_test)
当我检查它的形状时X_train
,X_test
它42,41
不是41,257
我认为应该的样子,因此似乎数据沿错误的轴进行了分区。
谁能向我解释为什么会发生这种情况?
谢谢
首先,初始矩阵X
根本不会受到影响。它仅用于生成索引和拆分数据。
首字母的形状X
将始终相同。
现在,这是一个使用拆分的简单示例LOOCV
:
import numpy as np
from sklearn.model_selection import LeaveOneOut
# I produce fake data with same dimensions as yours.
#fake data
X = np.random.rand(41,257)
#fake labels
y = np.random.rand(41)
#Now check that the shapes are correct:
X.shape
y.shape
这会给你:
(41, 257)
(41,)
现在拆分:
loocv = LeaveOneOut()
loocv.get_n_splits(X)
for train_index, test_index in loocv.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]
#classifier.fit(X_train, y_train)
#classifier.predict(X_test)
X_train.shape
X_test.shape
这打印:
(40, 257)
(1, 257)
如您所见,X_train
包含40
样本和X_test
仅包含1
样本。这是正确的,因为我们使用LOOCV
拆分。
初始 X 矩阵共有 42 个样本,因此我们使用 41 个用于训练,1 个用于测试。
这个循环会产生很多X_train
和X_test
矩阵。具体来说,它会产生N
矩阵 where N
= number of samples
(在我们的例子中:)N = 41
。
N
等于loocv.get_n_splits(X)
。
希望这可以帮助
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句