【问题标题】:How does classifier predict a class? (for tensorflow/keras)分类器如何预测一个类别? (对于张量流/keras)
【发布时间】:2021-03-01 01:49:02
【问题描述】:

我想自己实现模型,因此必须知道它是如何对数据进行分类的。我为 12 类分类器建立了一个模型,它预测得很好。但是最后一个 conv 层只输出 12 个浮点值,我不知道它是如何突然预测正确的类的。

谁能帮我解释一下?就像它取决于某个阈值还是选择最大值或其他什么?谢谢!

【问题讨论】:

    标签: python tensorflow keras deep-learning classification


    【解决方案1】:

    根据SparseCategoricalAccuracy的文档,相当于这个计算:

    acc = np.dot(sample_weight, np.equal(y_true, np.argmax(y_pred, axis=1))
    

    这意味着它计算y_pred 的每行最大值与y_true 匹配的频率。例如:

    m = tf.keras.metrics.SparseCategoricalAccuracy()
    m.update_state([[2], [1]], [[0.1, 0.6, 0.3],  # max at 1 
                                [0.05, 0.95, 0]]) # max at 1 
    m.result().numpy()
    
    0.5
    

    因为[2] != [1][1] == [1] 在0.5 的时间里是相等的。

    【讨论】:

      【解决方案2】:

      您需要在模型中添加一个展平层,然后是一个密集层。密集层应该有 12 个节点并使用如下所示的 softmax 激活“您的模型现在将为每个图像输出一个包含 12 个概率值的列表。

      flatten=tf.keras.layers.Flatten()(last_conv_layer)
      output = Dense(12, activation='softmax')(flatten)
      #after you train you can evaluate your model on your test set using model.evaluate() 
      #to make Predictions use model.predict()
      predictions=model.predict(.....
      #you can get the index of the predicted class for the images you predict with
      for p in predictions:
          predicted_index=argmax(p)
          print (predicted_index)
      

      model.evaluate 和 model.predict 的文档是 here. 添加这两个层后不要忘记重新编译模型。

      【讨论】:

        猜你喜欢
        • 2017-06-22
        • 1970-01-01
        • 2020-08-12
        • 1970-01-01
        • 2015-08-11
        • 1970-01-01
        • 2018-04-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多