【问题标题】:Why is call called twice during model.fit为什么在model.fit期间调用两次
【发布时间】:2021-07-02 06:57:01
【问题描述】:
import tensorflow as tf
import numpy as np
x=np.random.rand(20,10,64)
y=np.random.randint(10,size=(20,1))
class mymodel(tf.keras.Model):
  def __init__(self):
    super(mymodel,self).__init__()
    self.l1 = tf.keras.layers.LSTM(10,return_state=True)
    self.l2 = tf.keras.layers.Dense(10,activation=tf.keras.activations.softmax)
  def call(self,input):
    print('hi')
    x=self.l1(input)
    # tf.print(x[0],x[1],x[2])
    x=self.l2(x[0])
    return x
model =mymodel()
model.compile(loss = tf.keras.losses.SparseCategoricalCrossentropy())
model.fit(x,y)

当我运行上面的代码时,我得到了 2 hi 打印出来。在这个例子中,只有 1 个 epoch 并且在那个 epoch 1 批次(批次大小为 20)内,那么为什么调用方法被调用了两次。

【问题讨论】:

    标签: tensorflow


    【解决方案1】:

    相关:tf.print() vs Python print vs tensor.eval()

    在调用函数中插入的 Python print 只会在第一次执行时,在下面构建图形时。第二次调用由 TF 急切执行触发,同样只是第一次(如果您在 model.fit 之前运行 tf.compat.v1.disable_eager_execution(),您将只看到一个打印的 hi)。

    但是,如果您第二次运行model.fit(第三次,...),您会注意到没有打印任何内容。这是因为,一旦构建了图形,前向传递就不再执行 call 函数。如果要打印与前向传递的每次执行相关的内容,则应使用 tf.print("hi")。您会注意到,这样一来,model.fit 中的每个 eopch 都会发生一个且只有一个打印。

    【讨论】:

    • 因此,tf.print('hi') 继续在每个 model.fit 调用上打印 hi,因为 tf.print 成为图形本身的一部分。我的理解正确吗?
    • 没错! tf.print 成为图中的一个节点,在 TF2 中它每次都会运行
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 2021-11-25
    • 2012-12-12
    • 2015-12-24
    • 2012-12-10
    • 2014-01-11
    相关资源
    最近更新 更多