简体   繁体   English

分类器如何预测一个类? (对于张量流/keras)

[英]How does classifier predict a class? (for tensorflow/keras)

I want to implement the model by myself and thus have to know how does it classify the data.我想自己实现模型,因此必须知道它如何对数据进行分类。 I build a model for 12-class classifier and it predicts fine.我为 12 类分类器构建了一个模型,它预测得很好。 But the last conv layer just outputs 12 floating point value and I don't know how it suddenly predicts the right class.但是最后一个 conv 层只输出 12 个浮点值,我不知道它是如何突然预测正确的类的。

Can someone explain for me?有人可以为我解释一下吗? Like is it depend on some threshold or it chooses the max value or something?就像它取决于某个阈值还是选择最大值或其他什么? Thanks!谢谢!

According to the documentation of SparseCategoricalAccuracy , it's equivalent to this computation:根据SparseCategoricalAccuracy的文档,它相当于这个计算:

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

This means that it calculates the frequency with which the maximum value per row of y_pred matches y_true .这意味着它计算y_pred每行的y_predy_true匹配的y_true For instance:例如:

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

Because [2] != [1] and [1] == [1] so 0.5 of the time, they are equal.因为[2] != [1][1] == [1]所以有 0.5 次,它们是相等的。

you need to add a flatten layer to your model followed by a dense layer.您需要在模型中添加一个扁平层,然后是一个密集层。 The dense layer should have 12 nodes and use the softmax activation as shown below' Your model will now output a list of 12 probability values for each image.密集层应该有 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)

documentation for model.evaluate and model.predict is here. model.evaluate 和 model.predict 的文档在这里。 Don't forget to recompile your model after you add the two layers.添加两个层后,不要忘记重新编译模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM