如何在Keras输出每级精度?

spi*_*der 17 python machine-learning neural-network conv-neural-network keras

Caffe不仅可以打印整体精度,还可以打印每级精度.

在Keras日志中,只有整体准确性.我很难计算出单独的类精度.

Epoch 168/200

0s - 损失:0.0495 - acc:0.9818 - val_loss:0.0519 - val_acc:0.9796

Epoch 169/200

0s - 损失:0.0519 - acc:0.9796 - val_loss:0.0496 - val_acc:0.9815

大纪元170/200

0s - 损失:0.0496 - acc:0.9815 - val_loss:0.0514 - val_acc:0.9801

谁知道如何在keras中输出每级精度?

des*_*aut 18

精确度和召回率是多类别分类的更有用的度量(见定义).继Keras MNIST CNN例子(10级分类),你可以使用每类措施,classification_reportsklearn.metrics:

from sklearn.metrics import classification_report
import numpy as np

Y_test = np.argmax(y_test, axis=1) # Convert one-hot to index
y_pred = model.predict_classes(x_test)
print(classification_report(Y_test, y_pred))
Run Code Online (Sandbox Code Playgroud)

结果如下:

         precision    recall  f1-score   support

      0       0.99      1.00      1.00       980
      1       0.99      0.99      0.99      1135
      2       1.00      0.99      0.99      1032
      3       0.99      0.99      0.99      1010
      4       0.98      1.00      0.99       982
      5       0.99      0.99      0.99       892
      6       1.00      0.99      0.99       958
      7       0.97      1.00      0.99      1028
      8       0.99      0.99      0.99       974
      9       0.99      0.98      0.99      1009

avg / total   0.99      0.99      0.99     10000
Run Code Online (Sandbox Code Playgroud)

  • @desertnaut。非常感谢,这对我非常有用。该代码可以在测试时间内输出每个班级的准确性,但是如何在Keras的培训过程中打印每个班级的准确性呢? (3认同)

小智 6

您可能希望使用回调,您可以轻松地将其添加到model.fit()呼叫中。

例如,您可以使用keras.callbacks.Callback接口定义自己的类。我建议使用该on_epoch_end()函数,因为如果您决定使用该详细设置打印,它将在您的训练摘要中很好地格式化。请注意,此特定代码块设置为使用 3 个类,但您当然可以将其更改为您想要的数量。

# your class labels
classes = ["class_1","class_2", "class_3"]

class AccuracyCallback(tf.keras.callbacks.Callback):

    def __init__(self, test_data):
        self.test_data = test_data

    def on_epoch_end(self, epoch, logs=None):
        x_data, y_data = self.test_data

        correct = 0
        incorrect = 0

        x_result = self.model.predict(x_data, verbose=0)

        x_numpy = []

        for i in classes:
            self.class_history.append([])

        class_correct = [0] * len(classes)
        class_incorrect = [0] * len(classes)

        for i in range(len(x_data)):
            x = x_data[i]
            y = y_data[i]

            res = x_result[i]

            actual_label = np.argmax(y)
            pred_label = np.argmax(res)

            if(pred_label == actual_label):
                x_numpy.append(["cor:", str(y), str(res), str(pred_label)])     
                class_correct[actual_label] += 1   
                correct += 1
            else:
                x_numpy.append(["inc:", str(y), str(res), str(pred_label)])
                class_incorrect[actual_label] += 1
                incorrect += 1

        print("\tCorrect: %d" %(correct))
        print("\tIncorrect: %d" %(incorrect))

        for i in range(len(classes)):
            tot = float(class_correct[i] + class_incorrect[i])
            class_acc = -1
            if (tot > 0):
                class_acc = float(class_correct[i]) / tot

            print("\t%s: %.3f" %(classes[i],class_acc)) 

        acc = float(correct) / float(correct + incorrect)  

        print("\tCurrent Network Accuracy: %.3f" %(acc))
Run Code Online (Sandbox Code Playgroud)

然后,您将需要将新回调配置为适合您的模型。假设您的验证数据 ( val_data) 是一些元组对,您可以使用以下内容:

accuracy_callback = AccuracyCallback(val_data)

# you can use the history if desired
history = model.fit( x=_, y=_, verbose=1, 
           epochs=_, shuffle=_, validation_data = val_data,
           callbacks=[accuracy_callback], batch_size=_
         )
Run Code Online (Sandbox Code Playgroud)

请注意,_ 表示可能会根据您的配置更改的值