【问题标题】:Understanding `TypeError: An op outside of the function building code is being passed a "Graph" tensor.` error了解`TypeError:函数构建代码之外的操作正在传递“图形”张量。`错误
【发布时间】:2021-02-19 17:30:23
【问题描述】:

我在自定义实验框架中使用 TF2.4,并在第一次访问属性时使用mlworkflow.lazyproperty 装饰器来构造属性(如tf.keras.Model())。

对于我的大多数深度学习实验,这个框架运行良好,但在我的实验中尝试另一个头时,我遇到了 TypeError: An op outside of the function building code is being passed a "Graph" tensor. 错误。

我设法将问题减少到以下最小工作示例,其中,当使用我的自定义对象 Head_1() 时,会引发错误,但在使用 Head_2(tf.keras.layers.Layer) 时,它工作正常。

import numpy as np
from mlworkflow import lazyproperty

class Head_1():
    def __call__(self, inputs):
        return tf.ones((20,25))[tf.newaxis] + inputs[...,0]

class Head_2(tf.keras.layers.Layer):
    def call(self, inputs):
        return tf.ones((20,25))[tf.newaxis] + inputs[...,0]

class Experiment():
    @lazyproperty
    def model(self):
        inputs = tf.keras.Input(dtype=tf.float32, shape=(20, 25, 3))
        model = tf.keras.layers.Conv2D(5, 1)
        head = Head_1()
        logits = model(inputs)
        outputs = head(logits)
        return tf.keras.Model(inputs, outputs)

    @tf.function
    def run(self, data):
        return self.model(data, training=True)

exp = Experiment()
exp.run(np.ones((1, 20, 25, 3), dtype=np.float32))

谁能解释为什么Head_1 将«_"Graph" tensor_» 传递给«_op outside the function building code_» 而Head_2 没有?

我不能使用Head_2,因为我需要我的自定义对象来控制__call__ 方法中发生的事情。

【问题讨论】:

    标签: python tensorflow keras tensorflow2.0


    【解决方案1】:

    解决方案是在调用run 之前创建模型。具体

    exp = Experiment()
    _ = exp.model    # creates model before first call of the tf.function
    exp.run(np.ones((1, 20, 25, 3), dtype=np.float32))
    

    【讨论】:

      猜你喜欢
      • 2021-09-27
      • 2020-02-22
      • 2020-06-18
      • 2020-09-30
      • 2020-12-24
      • 1970-01-01
      • 2019-12-08
      • 2020-06-04
      • 1970-01-01
      相关资源
      最近更新 更多