我想通过将我的自定义评分函数与预定义分割上的手动计算进行比较,来确保其行为符合预期,使用train_test_split
进行分割。
然而,我似乎无法将这个分割传递给cross_val_score
。默认情况下,它使用3折交叉验证,我无法模拟它使用的分割。我认为答案在于cv
参数,但我不知道如何以正确的形式传递一个可迭代对象。
回答:
如果你已经有了一个预定义的分割,你可以直接训练你的模型,并在测试数据的预测上应用自定义评分函数来匹配计算。你不需要使用cross_val_score
。
我相当确定有更简单更好的方法,但这是我想到的,因为cross_val_score
的文档不够清晰。
你是对的,这取决于你如何使用cv
参数,我使用了这种格式:一个产生训练、测试分割的可迭代对象
。
这个想法是创建一个能够产生训练、测试分割索引的对象,我参考了:http://fa.bianp.net/blog/2015/holdout-cross-validation-generator/。
假设你已经有了训练测试分割。我使用了sklearn
内置的分割并返回了索引:
from sklearn.model_selection import cross_val_scoreX_train, X_valid, y_train, y_valid, indices_train, indices_test = train_test_split(train_X, train_y, np.arange(X_train.shape[0]), test_size=0.2, random_state=42)
然后,我创建了一个类来使用train_test_split
的输出产生训练、测试分割索引:
class HoldOut: def __init__(self, indices_train, indices_test): self.ind_train = indices_train self.ind_test = indices_test def __iter__(self): yield self.ind_train, self.ind_test
然后你可以简单地将Holdout
对象传递给cv
参数:
cross_val_score(RandomForestClassifier(random_state=42, n_estimators=10), train_X, train_y, cv=HoldOut(indices_train, indices_test), verbose=1)