python sklearn f1_score

参考

https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html?highlight=f1_score(官方文档)

代码

from sklearn.metrics import f1_score
y_true = [0, 1, 2, 0, 1, 2]
y_pred = [0, 2, 1, 0, 0, 1]
f1_score(y_true, y_pred, average='macro')
f1_score(y_true, y_pred, average='micro')
f1_score(y_true, y_pred, average='weighted')
# 对多分类任务的不同任务手动赋权
score_list = f1_score(y_true1, y_pred1, average=None, labels=[0, 1, 2, 3])
score = (score_list[0] * weight0 + score_list[1] * weight1 + score_list[2] * weight2 + score_list[3] * weight3) / (weight0 + weight1 + weight2 + weight3)

参数

  • y_true
  • y_pred
  • labels:手动输入标签的顺序,在多分类情况下,单一类型的f1 score输出顺序就依赖此,需配合将average参数设置为None
  • pos_label:str or int, default=1
    The class to report if average=‘binary’ and the data is binary. If the data are multiclass or multilabel, this will be ignored; setting labels=[pos_label] and average != ‘binary’ will report scores for that label only.
  • average{‘micro’, ‘macro’, ‘samples’,’weighted’, ‘binary’} or None, default=’binary’
    If None, the scores for each class are returned.
  • sample_weightarray-like of shape (n_samples,), default=None
  • zero_division“warn”, 0 or 1, default=”warn”

自动k折并评分

# 自动5折并自动计算f1
from sklearn.model_selection import cross_val_score
# from sklearn.metrics import make_scorer
from sklearn.linear_model import LogisticRegression
LR = LogisticRegression()
# 直接得到得分 cv表示几折
score = cross_val_score(LR, X=X1, y=y1, verbose=0, cv=2
                        scoring='f1_macro')
print(score)
# 获取预测值
pre = cross_val_predict(LR, X=X1, y=y1)
print(pre)

你可能感兴趣的:(机器学习,数据预处理,传统机器学习,python,数据分析,机器学习)