我有一个经过训练的CRNN模型,它应该可以从图像中识别文本。它真的很有效,到目前为止还不错。
我的输出是一个CTC损失层,我使用tensorflow函数keras.backend.ctc_decode对其进行解码,正如文档所说(https://code.i-harness.com/en/docs/tensorflow~python/tf/keras/backend/ctc_decode),该函数返回一个具有解码结果的Tuple和一个具有预测对数概率的Tensor。
通过对模型进行一些测试,我得到了以下结果:
True value: test0, prediction: test0, log_p: 1.841524362564087
True value: test1, prediction: test1, log_p: 0.9661365151405334
True value: test2, prediction: test2, log_p: 1.0634151697158813
True value: test3, prediction: test3, log_p: 2.471940755844116
True value: test4, prediction: test4, log_p: 1.4866207838058472
True value: test5, prediction: test5, log_p: 0.7630811333656311
True value: test6, prediction: test6, log_p: 0.35642576217651367
True value: test7, prediction: test7, log_p: 1.5693446397781372
True value: test8, prediction: test8, log_p: 0.9700028896331787
True value: test9, prediction: test9, log_p: 1.4783780574798584预测总是正确的。然而,我认为它的概率似乎不是我所期望的。它们看起来完全是随机数,甚至比1或2还要大!我做错了什么??
发布于 2021-01-10 13:13:20
好吧,我猜你把Probability和Log Probability搞混了。虽然您的直觉是正确的,但概率值高于或低于0-1的任何值都会很奇怪。但是你的函数给你的不是对数概率,而是对数概率,它实际上是对数刻度的概率。所以你的模型一切都很好。
如果您想知道为什么我们使用对数概率而不是概率本身,那么它主要与缩放问题有关,但是,您可以阅读线程here
将日志概率转换为实际概率的示例:
import numpy as np
# some random log probabilities
log_probs = [-8.45855173, -7.45855173, -6.45855173, -5.45855173, -4.45855173, -3.45855173, -2.45855173, -1.45855173, -0.45855173]
# Let's turn these into actual probabilities (NOTE: If you have "negative" log probabilities, then simply negate the exponent, like np.exp(-x))
probabilities = np.exp(log_probs)
print(probabilities)
# Output:
[2.12078996e-04, 5.76490482e-04, 1.56706360e-03, 4.25972051e-03, 1.15791209e-02, 3.14753138e-02, 8.55587737e-02, 2.32572860e-01, 6.32198578e-01] # everything is between [0-1]发布于 2021-03-11 15:04:52
我的代码中的简短示例:
predictions, log_probabilities = keras.backend.ctc_decode(pred, input_length=input_len, greedy=False,top_paths=5)
The Log-probabilites are: tf.Tensor([-0.00242825 -6.6236324 -7.3623376 -9.540713 -9.54832 ], shape=(5,), dtype=float32)
probabilities = tf.exp(log_probabilities)
The probabilities are: tf.Tensor([0.9975747 0.0013286 0.00063471 0.00007187 0.00007132], shape=(5,), dtype=float32)我认为这里要概述的重要一点是,当使用参数greedy=True时,返回的log_probability是正的,因此需要对其求反。
本质上,beam_width为1的beam_search等同于贪婪搜索。然而,以下两种方法给出的结果是不同的:
predictions_beam, log_probabilities_beam = keras.backend.ctc_decode(pred, input_length=input_len, greedy=False,top_paths=1)vs
predictions_greedy, log_probabilities_greedy = keras.backend.ctc_decode(pred, input_length=input_len, greedy=True)从后者总是返回正对数的意义上说,因此,有必要在np.exp(log_probabilities)/tf.exp(log_probabilities)之前对其求反。
https://stackoverflow.com/questions/65647571
复制相似问题