python-3.x - sklearn 中的交叉验证 : do I need to call fit() as well as cross_val_score()?

标签 python-3.x scikit-learn cross-validation

我想在学习模型时使用 k 折交叉验证。到目前为止,我这样做是这样的:

# splitting dataset into training and test sets
X_train, X_test, y_train, y_test = train_test_split(dataset_1, df1['label'], test_size=0.25, random_state=4222)

# learning a model
model = MultinomialNB()
model.fit(X_train, y_train)
scores = cross_val_score(model, X_train, y_train, cv=5)

在这一步我不太确定是否应该使用 model.fit(),因为在 official documentation of sklearn它们不适合,只是按如下方式调用 cross_val_score(它们甚至不将数据拆分为训练集和测试集):
from sklearn.model_selection import cross_val_score
clf = svm.SVC(kernel='linear', C=1)
scores = cross_val_score(clf, iris.data, iris.target, cv=5)

我想在学习模型的同时调整模型的超参数。什么是正确的管道?

最佳答案

如果您想进行超参数选择,请查看 RandomizedSearchCVGridSearchCV .如果您想在之后使用最好的模型,请使用 refit=True 调用其中任何一个。然后使用 best_estimator_ .

from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RandomizedSearchCV

log_params = {'penalty': ['l1', 'l2'], 'C': [1E-7, 1E-6, 1E-6, 1E-4, 1E-3]}
clf = LogisticRegression()
search = RandomizedSearchCV(clf, scoring='average_precision', cv=10,
                            n_iter=10, param_distributions=log_params,
                            refit=True, n_jobs=-1)
search.fit(X_train, y_train)
clf = search.best_estimator_

http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html

关于python-3.x - sklearn 中的交叉验证 : do I need to call fit() as well as cross_val_score()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50329349/

相关文章:

python - 让 IPython 使用 Python 3 而不是 Python 2 运行

python - 更改数据框日期列的日期格式

python - KNN 查询数据维度必须与训练数据维度匹配

machine-learning - 如果我们在管道中包含 Transformer,scikit-learn 的 `cross_val_score` 和 `GridsearchCV` 的 k 倍交叉验证分数是否有偏差?

python - Scikit learn 中的交叉验证与网格搜索

python - RepeatedKFold 到底是什么意思?

Python - HTTP 多部分/表单数据 POST 请求

python - 是否可以将以一种方式堆叠的 Python 数组 reshape 为另一种堆叠类型?

python - 如何在sklearn的拟合函数中选择要优化的指标?

python - Python 中的训练-测试分割似乎无法正常工作?