tor*_*eff 12 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)
Run Code Online (Sandbox Code Playgroud)
在这一步,我不太确定是否应该使用 model.fit() ,因为在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)
Run Code Online (Sandbox Code Playgroud)
我想在学习模型的同时调整模型的超参数。什么是正确的管道?
Ber*_*man 11
如果要进行超参数选择,请查看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_
Run Code Online (Sandbox Code Playgroud)
http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html
您的第二个示例适合进行交叉验证。请参阅此处的示例:http : //scikit-learn.org/stable/modules/cross_validation.html#computing-cross-validated-metrics
拟合将在cross_val_score函数内部完成,您无需事先担心。
[已编辑] 如果除了交叉验证之外,您还想训练模型,可以model.fit()事后调用。
| 归档时间: |
|
| 查看次数: |
4441 次 |
| 最近记录: |