我想要获得每个类(我有4个类)和每个交叉验证折叠的F1分数。clf是我训练的模型,X_test是测试集的特征,y_test是测试集的标签。因为我做的是5折交叉验证,所以我应该在第一折中为每个班级获得4分的F1分数,在第二折中获得4分。总共20个。我能用python简单地做到这一点吗?
下面这行代码将给出所有类的平均F1,每个折叠层只有5个值。我检查了cross_val_score (https://scikit-learn.org/stable/modules/model_evaluation.html)中变量scoring的选项,似乎无法获得每个文件夹中每个类的F1分数(或者我可能在某个地方迷路了)。
scores = cross_val_score(clf, X_test, y_test, cv=5, scoring='f1_macro')发布于 2020-05-07 17:28:09
好吧,我找到了一个解决方案。X是我的要素数据帧,y是标签。f1_score(y_test, y_pred, average=None)给出了每个类的F1分数,而不是聚合。因此,每个折叠,我们训练模型,并在测试集上进行尝试。
from sklearn.model_selection import KFold
cv = KFold(n_splits=5, shuffle=False)
for train_index, test_index in cv.split(X):
X_train, X_test = X.iloc[train_index], X.iloc[test_index]
y_train, y_test = y.iloc[train_index], y.iloc[test_index]
clf = clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print(f1_score(y_test, y_pred, average=None))然后,结果将是:
[0.99320793 0.79749478 0.34782609 0.44243792]
[0.99352309 0.82583622 0.34615385 0.48873874]
[0.99294785 0.78794403 0.28571429 0.42403628]
[0.99324611 0.79236813 0.31654676 0.43778802]
[0.99327615 0.79136691 0.32704403 0.42410197]其中,每一行都有每个文件夹的F1分数,每个值代表每个类的F1分数。
如果有更短更简单的解决方案,请随时张贴。
https://stackoverflow.com/questions/61640817
复制相似问题