交叉验证和分数
Cross-validation and scores
我在调整模型的超参数时使用训练数据集(即 X_train、y_train)。我需要使用测试数据集(即 X_test、y_test)作为最终检查,以确保我的模型没有偏差。
我写了
folds = 4
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=(1/folds), random_state=38, stratify=y)
clf_logreg = Pipeline(steps=[('preprocessor', preprocessing),
('model', LogisticRegression(solver='lbfgs', max_iter=100))])
cv = KFold(n_splits=(folds - 1))
scores_logreg = cross_val_score(clf_logreg, X_train, y_train, cv = cv)
并且,为了获得 f1 分数,
cross_val_score(clf_logreg, X_train, y_train, scoring=make_scorer(f1_score, average='weighted'),
cv=cv)
这个returns
scores_logreg: [0.94422311, 0.99335548, 0.97209302]
对于 f1:[0.97201365, 0.9926906 , 0.98925453]
为了检查考试,这样写对吗
cross_val_score(clf_logreg, X_test, y_test, scoring=make_scorer(f1_score, average='weighted'), cv=cv) # not sure if it is ok to let cv
或者也许
predicted_logreg= clf_logreg.predict(X_test)
f1 = f1_score(y_test, predicted_logreg)
返回的值不同。
cross_val_score
用于通过交叉验证对模型进行评分,如果您这样做:
cross_val_score(clf_logreg, X_test, y_test,
scoring=make_scorer(f1_score, average='weighted'), cv=cv)
你正在对你的测试集进行重做交叉验证,这没有多大意义,除非你现在在比你的火车更小的数据集上训练你的模型。
我认为 scikit learn 上的 help page on cross validation 说明了这一点,您不需要在测试集上重新运行交叉验证:
你只需要做:
predicted_logreg= clf_logreg.predict(X_test)
f1 = f1_score(y_test, predicted_logreg)
我在调整模型的超参数时使用训练数据集(即 X_train、y_train)。我需要使用测试数据集(即 X_test、y_test)作为最终检查,以确保我的模型没有偏差。 我写了
folds = 4
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=(1/folds), random_state=38, stratify=y)
clf_logreg = Pipeline(steps=[('preprocessor', preprocessing),
('model', LogisticRegression(solver='lbfgs', max_iter=100))])
cv = KFold(n_splits=(folds - 1))
scores_logreg = cross_val_score(clf_logreg, X_train, y_train, cv = cv)
并且,为了获得 f1 分数,
cross_val_score(clf_logreg, X_train, y_train, scoring=make_scorer(f1_score, average='weighted'),
cv=cv)
这个returns
scores_logreg: [0.94422311, 0.99335548, 0.97209302]
对于 f1:[0.97201365, 0.9926906 , 0.98925453]
为了检查考试,这样写对吗
cross_val_score(clf_logreg, X_test, y_test, scoring=make_scorer(f1_score, average='weighted'), cv=cv) # not sure if it is ok to let cv
或者也许
predicted_logreg= clf_logreg.predict(X_test)
f1 = f1_score(y_test, predicted_logreg)
返回的值不同。
cross_val_score
用于通过交叉验证对模型进行评分,如果您这样做:
cross_val_score(clf_logreg, X_test, y_test,
scoring=make_scorer(f1_score, average='weighted'), cv=cv)
你正在对你的测试集进行重做交叉验证,这没有多大意义,除非你现在在比你的火车更小的数据集上训练你的模型。
我认为 scikit learn 上的 help page on cross validation 说明了这一点,您不需要在测试集上重新运行交叉验证:
你只需要做:
predicted_logreg= clf_logreg.predict(X_test)
f1 = f1_score(y_test, predicted_logreg)