我正在尝试拆分数据集以在 sklearn 中进行交叉验证和 GridSearch。 我想定义自己的拆分,但 GridSearch 只采用内置的交叉验证方法。
但是,我不能使用内置的交叉验证方法,因为我需要某些示例组位于同一折叠中。 所以,如果我有例子: [A1, A2, A3, A4, A5, B1, B2, B3, C1, C2, C3, C4, ...., Z1, Z2, Z3]
我想执行交叉验证,这样来自每个组 [A,B,C...] 的示例只存在一个折叠中。
即K1包含[D,E,G,J,K...],K2包含[A,C,L,M,...],K3包含[B,F,I,...]等等
最佳答案
这类事情通常可以用 sklearn.cross_validation.LeaveOneLabelOut
来完成。您只需要构建一个标签向量来对您的组进行编码。即,K1
中的所有样本将采用标签 1
,K2
中的所有样本将采用标签 2,依此类推。
这是一个带有假数据的完全可运行的示例。重要的几行是创建 cv
对象的那一行,以及对 cross_val_score
import numpy as np
n_features = 10
# Make some data
A = np.random.randn(3, n_features)
B = np.random.randn(5, n_features)
C = np.random.randn(4, n_features)
D = np.random.randn(7, n_features)
E = np.random.randn(9, n_features)
# Group it
K1 = np.concatenate([A, B])
K2 = np.concatenate([C, D])
K3 = E
data = np.concatenate([K1, K2, K3])
# Make some dummy prediction target
target = np.random.randn(len(data)) > 0
# Make the corresponding labels
labels = np.concatenate([[i] * len(K) for i, K in enumerate([K1, K2, K3])])
from sklearn.cross_validation import LeaveOneLabelOut, cross_val_score
cv = LeaveOneLabelOut(labels)
# Use some classifier in crossvalidation on data
from sklearn.linear_model import LogisticRegression
lr = LogisticRegression()
scores = cross_val_score(lr, data, target, cv=cv)
但是,您当然有可能遇到想要完全手动定义折叠的情况。在这种情况下,您需要创建一个 iterable
(例如 list
)对 (train, test)
指示通过索引获取哪些样本进入你的火车和测试集的每一折。让我们检查一下:
# create train and test folds from our labels:
cv_by_hand = [(np.where(labels != label)[0], np.where(labels == label)[0])
for label in np.unique(labels)]
# We check this against our existing cv by converting the latter to a list
cv_to_list = list(cv)
print cv_by_hand
print cv_to_list
# Check equality
for (train1, test1), (train2, test2) in zip(cv_by_hand, cv_to_list):
assert (train1 == train2).all() and (test1 == test2).all()
# Use the created cv_by_hand in cross validation
scores2 = cross_val_score(lr, data, target, cv=cv_by_hand)
# assert equality again
assert (scores == scores2).all()
关于python - 自定义交叉验证拆分 sklearn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24078301/