如何使用样本权重进行交叉验证?

How can I do cross validation with sample weights?

我正在尝试将文本数据分类为多个 类。我想执行交叉验证来比较几个具有样本权重的模型。

对于每个模型,我可以像这样放置一个参数。

all_together = y_train.to_numpy()
unique_classes = np.unique(all_together)
c_w = class_weight.compute_class_weight('balanced', unique_classes, all_together)
clf = MultinomialNB().fit(X_train_tfidf, y_train, sample_weight=[c_w[i] for i in all_together])

cross_val_score() 似乎不允许关于 sample_weight 的参数。 我如何通过交叉验证来做到这一点?

models = [
    RandomForestClassifier(n_estimators=200, max_depth=3, random_state=0),
   LinearSVC(),
    MultinomialNB(),
    LogisticRegression(random_state=0),
]

all_together = y_train.to_numpy()
unique_classes = np.unique(all_together)
c_w = class_weight.compute_class_weight('balanced', unique_classes, all_together)
    
CV = 5
cv_df = pd.DataFrame(index=range(CV * len(models)))
entries = []
for model in models:
    model_name = model.__class__.__name__
    f1_micros = cross_val_score(model,  X_tfidf, y_train, scoring='f1_micro', cv=CV)
    for fold_idx, f1_micro in enumerate(f1_micros):
        entries.append((model_name, fold_idx, f1_micro))
cv_df_women = pd.DataFrame(entries, columns=['model_name', 'fold_idx', 'f1_micro'])

cross_val_score 有一个名为 fit_params 的参数,它接受参数(键)和值的字典以传递给估计器的 fit() 方法。在你的情况下,你可以做

cross_val_score(model, X_tfidf, y_train, scoring='f1_micro', cv=CV, fit_params={'sample_weight': [c_w[i] for i in all_together]})