我想在学习模型时使用 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)
我想在学习模型的同时调整模型的超参数。什么是正确的管道?
最佳答案
如果您想进行超参数选择,请查看 RandomizedSearchCV
或 GridSearchCV
.如果您想在之后使用最好的模型,请使用 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/