如果您有预定义的拆分,您只需训练您的模型并将自定义评分函数应用于测试数据的预测以匹配计算。你不需要使用cross_val_score。
我很确定有更好更简单的方法,但这是我想出的,因为 cross_val_score 文档不是很清楚。
你说得对,这与你如何使用cv 参数有关,而我使用了这种格式:An iterable yielding train, test splits。
这个想法是创建一个产生训练、测试拆分索引的对象,我提到了:http://fa.bianp.net/blog/2015/holdout-cross-validation-generator/。
假设您已经有一个火车测试拆分。我使用了sklearn 内置拆分并返回了索引:
from sklearn.model_selection import cross_val_score
X_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)