Scikit Learn 管道:调用 .fit() 和 .score() 与 cross_val_score()

Scikit Learn Pipeline: Calling .fit() and .score() vs cross_val_score()

假设我们有以下管道:

example_pipe = Pipeline(steps=[
    ('scaler', StandardScaler()),
    ('selector', SelectKBest(k=len(X.columns)-5)),
    ('classifier', KNeighborsClassifier())
])

现在我们想要获得管道的性能:

# 1)
cross_val_score(example_pipe, X, y, cv=5, scoring='accuracy').mean()

# 2)
example_pipe.fit(X_train, y_train)
example_pipe.score(X_test, y_test)

就我们得到的分数而言,第一个与第二个有何不同(当然除了它进行交叉验证)?在使用 cross_val_score().

之前我们是否必须调用 example_pipe.fit()

我在文档中找到了以下方法,但有点混乱,因为我认为调用 .fit() 已经意味着调用 .transform().

fit(X[, y]) --> Fit the model

fit_predict(X[, y]) --> Applies fit_predict of last step in pipeline after transforms.

fit_transform(X[, y]) --> Fit the model and transform with the final estimator

score(X[, y, sample_weight]) --> Apply transforms, and score with the final estimator

Do we have to call example_pipe.fit() before using cross_val_score()?

如果你去Scikit-Learn Documentation,你会找到答案:

cross_val_score先拟合你的example_pipe,然后得到交叉验证的分数