我试图建立一个嵌套循环,用来创建一个2-模糊零矩阵来解决LCS问题(动态规划)。后来,这被用于计算Rouge-L分数(输入是张量,而不是字符串),但是提高ValueError: The two structures don't have the same nested structure.总是出错的。
我检查了一些类似的问题,并修改了一些代码,但它仍然不能工作(我在这里提供的代码是最终代码):
# the origin code is below, in which sub and string are both string(type), len_sub and len_string are both int:
lengths = [[0 for i in range(0,len_sub+1)] for j in range(0,len_string+1)]
# but in the new code that I need, the sub and string are both tensor, so I code like this:
len_string = tf.shape(string)[0]
len_sub = tf.shape(sub)[0]
def _add_zeros(i,inner):
inner.append(0)
return i+1, inner
def _add_inners(j, lengths):
i=0
inner = []
_, inner = tf.while_loop(
cond=lambda i,*_: i<=len_sub,
body=_add_zeros,
loop_vars=[i,inner],
shape_invariants=[0,len(inner)])
lengths.append(inner)
return j+1, lengths
lengths = []
j = 0
_, lengths = tf.while_loop(
cond=lambda j,*_: j<=len_string,
body=_add_inners,
loop_vars=[j,lengths],
shape_invariants=[0,len(lengths)])ValueError: The two structures don't have the same nested structure.
First structure: type=list str=[0, []]
Second structure: type=list str=[0, 0]
More specifically: Substructure "type=list str=[]" is a sequence, while substructure "type=int str=0" is not
Entire first structure:
[., []]
Entire second structure:
[., .] 我不知道为什么会出错。如果你能帮忙我会很感激的。
发布于 2019-04-12 16:54:45
基本上,错误消息所指的是,您的返回值是一个列表,而它希望它是一个数字,这是有意义的,因为您已经将您的shape_invariants定义为[0, len(lengths)],这两种结构都是整数,因此第二个结构被定义为[.,.],但是第一个结构是一个数字,而一个列表[., []],它在传递长度时再次生成sens。
TLDR:要么将shape_invariants=[0,len(lengths)])改为shape_invariants=[0,lengths]),要么将loop_vars=[j,lengths]更改为loop_vars=[j,len(lengths)],
https://stackoverflow.com/questions/55484834
复制相似问题