python - tensorflow :cannot be accessed here: it is defined in another function or code block

标签 python tensorflow tensorflow2.0

我正在实现简单的 RNN。在其中我想返回列表中每个时间步的输出,稍后我可以将其提供给优化器。我在没有 @tf.function 的情况下构建了工作 rnn .但是添加后@tf.function它给出了问题

def basic_rnn_cell(self,x,s):#Note :These function are defined in class
    s=self.U*x+self.W*s+self.b #U,W,b and all are tf.Variable
    y=self.V*s+self.c
    return y,s

@tf.function
def rnn(self,X):
    outputs=[]
    state=self.state
    for x in X:
        output,state=self.basic_rnn_cell(x,state)
        outputs.append(output)
    return outputs
这就是我的称呼:
x=np.array([0.01,0.02,0.03],dtype=np.float32)
o.rnn(x)
我得到的错误:
raise errors.InaccessibleTensorError(
tensorflow.python.framework.errors_impl.InaccessibleTensorError: The tensor 'Tensor("while/add_2:0", shape=(), dtype=float32)' cannot be accessed here: it is defined in another function or code block. 
Use return values, explicit Python locals or TensorFlow collections to access it. Defined in: FuncGraph(name=while_body_44, id=2538759416224); accessed from: FuncGraph(name=rnn, id=2538758824096). 

最佳答案

这是因为使用python列表临时保存张量对象。内存回收机制会删除您在跟踪该功能后保存的内容,因此无法实现。
如果你想保存那些临时张量,你必须使用 tf.TensorArray作为替代。可以引用这个:https://www.tensorflow.org/guide/function#loops

关于python - tensorflow :cannot be accessed here: it is defined in another function or code block,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64567161/

相关文章:

python - 在 tf 函数内迭代 tf.Tensor 以生成基于 NamedTuple 的数据集项列表

python - 处理多个 Python 版本和 PIP?

python - 具有部分洗牌功能的 Tensorflow 数据集

python - Tensorflow 保留所有文件。如何防止这种情况?

javascript - 将 TensorFlow JS model.predict 的值获取到变量中

python - (已解决)Tensorflow 联合 | tff.learning.from_keras_model() 带有 DenseFeature 层和多个输入的模型

python - 如何在 Tensorflow Object Detection API v2 中同时训练和评估

python - Pywinauto 无法找到/关闭弹出窗口

python - 错误: 'utf-8' codec can't decode byte 0xb0 in position 14: invalid start byte

python - 创建一个列出值的数据透视表