tensorflow tf.edit_distance
函数如何工作?
它如何比较存储在等效于 2d 或 3d 密集矩阵的两个不同稀疏矩阵中的字符串。
tensorflow 网页上给出的示例 https://www.tensorflow.org/api_docs/python/tf/edit_distance不是那么明显。请使用其他示例提供解释。
这个例子也不清楚。
#'hypothesis' is a tensor of shape [2, 1] with variable-length values:
#(0,0) = ["a"] and (1,0) = ["b"]
hypothesis = tf.SparseTensor([[0, 0, 0],[1, 0, 0]],["a", "b"],(2, 1, 1))
#'truth' is a tensor of shape `[2, 2]` with variable-length values:
#(0,0) = [], (0,1) = ["a"], (1,0) = ["b", "c"],(1,1) = ["a"]
truth = tf.SparseTensor([[0, 1, 0],[1, 0, 0],[1, 0, 1],[1, 1, 0]],["a", "b",
"c", "a"],(2, 2, 2))
normalize = True
#'output' is a tensor of shape [2, 2] with edit distances normalized by
#'truth' lengths.
output ==> [[inf, 1.0],[0.5, 1.0]],
(0,0): no truth, (0,1): no hypothesis, (1,0): addition, (1,1): no hypothesis
[2,2]维度的输出如何?
规范化在这里做什么?
最佳答案
密集形式的假设如下所示
[[['a']],
[['b']]] # (2, 1, 1)
事实就是这样
[[[],['a']],
[['b', 'c'], ['a']]] # (2, 2, 2)
我们正试图找到 Levenshtein distance假设与真值之间。 所以,这是正在发生的事情:
在 (0,0,0) - 假设中的 ['a'] 距离 [] 有多远 - 那个位置没有真相所以无法计算距离
at (0,0,1) - 因为在假设的那个位置没有任何东西,我们返回 1。与上面的情况不同,距离是 1 因为理论上可以通过插入一个字符使假设与真实相同(参见 Levenshtein 距离计算)
在 (1,0,0) - 炒作中的 ['b'] 与真实中的 ['b', 'c'] 有多远。这又是 1,因为我们可以插入一个字符使 hyp 与 truth 相同。但是,我们选择标准化输出距离。所以我们除以真值段的长度,即 2。所以你得到 0.5
在 (1,0,1) - hyp 中的 [] 距离 ['a'] 有多远,因为在 hyp 的那个位置没有任何东西,我们返回 1
输出为 (2,2) 因为 hyp 和 truth 的秩为 3。函数返回秩为 (rank-1) 的张量
想象一下我们在这里尝试做什么会有所帮助。您在假设中有 2 个序列,在真相中有 2 个序列。因此,您的输出分数将是您获得每个序列中每个位置的分数。
这是一个示例,我们尝试将 4 个假设与真值相匹配。我认为您必须为您在评论中描述的用例的每个真值序列执行此操作 - 如果您发现更有效的方法,请告诉我:-)
import tensorflow as tf
hypothesis = tf.SparseTensor(
[[0, 0, 0],
[1, 0, 0],
[2, 0, 0],
[3, 0, 0]],
["a", "b", "c", "d"],
(4, 1, 1))
truth = tf.SparseTensor([[0, 0, 0], [0, 0, 1], [0, 1, 0]], ["b", "c", "a"], (1,2,2))
num_hyp = 4
truth = tf.sparse_concat(0, [truth] * num_hyp)
d = tf.edit_distance(hypothesis, truth)
with tf.Session() as sess:
print(sess.run(d))
输出:
[[1. 1. ]
[0.5 1. ]
[0.5 1. ]
[1. 1. ]]
关于python - tensorflow tf.edit_distance 需要解释吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51612489/