gpt4 book ai didi

python - tensorflow ,tf.while_loop : The two structures don't have the same nested structure

转载 作者:行者123 更新时间:2023-11-28 18:58:31 30 4
gpt4 key购买 nike

我尝试构建一个嵌套循环,用于创建 2 维零矩阵来解决 LCS 问题(动态规划)。这后来用于计算 Rouge-L 分数(输入是张量,而不是字符串),但它总是出错引发 ValueError: The two structures don't have the same nested structure.

我查了一些类似的问题,我修改了一些代码,还是不行(我放在这里的代码是最终代码):

  1. 我改变了 shape_invariants。我现在使用 len(inner) 来动态获取 inner 的形状。
  2. 仍然是 shape_invariants,我现在将 1 更改为 0(shape_invariants 中的第一个参数)。我以为标量的形状是 1,但我在 github 上查看了一些源代码,发现它都使用了 0。

# 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:
[., .]

我不知道为什么会出错。如果您能提供帮助,我将不胜感激。

最佳答案

您好基本上错误消息是说您的返回值是一个列表,而它期望它是一个数字,这是有道理的,因为您已将 shape_invariants 定义为 [0, len(lengths) ] 两者都是整数,因此第二个结构定义为 [.,.] 但是第一个结构是一个数字和一个列表 [., []]当您传递长度时,这再次有意义。

TLDR:将您的 shape_invariants=[0,len(lengths)]) 更改为 shape_invariants=[0,lengths]) 或更改您的 loop_vars= [j,lengths]loop_vars=[j,len(lengths)],

关于python - tensorflow ,tf.while_loop : The two structures don't have the same nested structure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55484834/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com