5 scikit-learn multilabel-classification precision-recall keras
我正在使用 tf-keras 训练神经网络。它是一个多标签分类,其中每个样本属于多个类 [1,0,1,0..etc] .. 最终模型线(只是为了清楚起见)是:
model.add(tf.keras.layers.Dense(9, activation='sigmoid'))#final layer
model.compile(loss='binary_crossentropy', optimizer=optimizer,
metrics=[tf.keras.metrics.BinaryAccuracy(),
tfa.metrics.F1Score(num_classes=9, average='macro',threshold=0.5)])
Run Code Online (Sandbox Code Playgroud)
我需要生成这些的精确度、召回率和 F1 分数(我已经得到了训练期间报告的 F1 分数)。为此,我使用 sklearns 分类报告,但我需要确认我在多标签设置中正确使用它。
from sklearn.metrics import classification_report
pred = model.predict(x_test)
pred_one_hot = np.around(pred)#this generates a one hot representation of predictions
print(classification_report(one_hot_ground_truth, pred_one_hot))
Run Code Online (Sandbox Code Playgroud)
这工作正常,我得到了每个类的完整报告,包括与张量流插件(对于宏 F1)的 F1score 指标相匹配的 F1 分数。抱歉,这篇文章很冗长,但我不确定的是:
在多标签设置的情况下,预测需要进行 one-hot 编码是否正确?如果我传递正常的预测分数(S形概率),则会抛出错误......
谢谢。
classification_report用于二元分类、多类分类和多标签分类都是正确的。
在多类分类的情况下,标签不是一次性编码的。它们只需是indices或labels。
您可以看到下面的两个代码产生相同的输出:
带索引的示例
from sklearn.metrics import classification_report
import numpy as np
labels = np.array(['A', 'B', 'C'])
y_true = np.array([1, 2, 0, 1, 2, 0])
y_pred = np.array([1, 2, 1, 1, 1, 0])
print(classification_report(y_true, y_pred, target_names=labels))
Run Code Online (Sandbox Code Playgroud)
带标签的示例
from sklearn.metrics import classification_report
import numpy as np
labels = np.array(['A', 'B', 'C'])
y_true = labels[np.array([1, 2, 0, 1, 2, 0])]
y_pred = labels[np.array([1, 2, 1, 1, 1, 0])]
print(classification_report(y_true, y_pred))
Run Code Online (Sandbox Code Playgroud)
两者均返回
precision recall f1-score support
A 1.00 0.50 0.67 2
B 0.50 1.00 0.67 2
C 1.00 0.50 0.67 2
accuracy 0.67 6
macro avg 0.83 0.67 0.67 6
weighted avg 0.83 0.67 0.67 6
Run Code Online (Sandbox Code Playgroud)
在多标签分类的上下文中,classification_report可以像下面的示例一样使用:
from sklearn.metrics import classification_report
import numpy as np
labels =['A', 'B', 'C']
y_true = np.array([[1, 0, 1],
[0, 1, 0],
[1, 1, 1]])
y_pred = np.array([[1, 0, 0],
[0, 1, 1],
[1, 1, 1]])
print(classification_report(y_true, y_pred, target_names=labels))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7265 次 |
| 最近记录: |