tf.print
几乎在所有情况下都有效。
下面提到的代码表明tf.print
内部按预期工作init
的方法Custom Layer
和里面一个Method
打电话自init
方法一Custom Layer
.
import tensorflow as tf
class MyLayer(tf.keras.layers.Layer):
def __init__(self, units, **kwargs):
self.units = units
tf.print('units', tf.convert_to_tensor(units)) # Inside init method
self.call(10) # Method called from init Method
super().__init__(**kwargs)
def call(self, inputs):
tf.print('inputs', tf.convert_to_tensor(inputs)) #Inside Method of Custom Layer
return inputs
def get_model():
inp = tf.keras.layers.Input(shape=(1,))
out = MyLayer(8)(inp)
model = tf.keras.Model(inputs=inp, outputs=out)
#model.summary()
return model
def train():
model = get_model()
model.compile(optimizer="adam", loss="mae")
x_train = [2, 3, 4, 1, 2, 6]
y_train = [1, 0, 1, 0, 1, 1]
model.fit(x_train, y_train)
if __name__ == '__main__':
train()
输出的tf.print
上面代码中使用的语句如下所示:
units 8
inputs 10
inputs [[2]
[6]
[3]
[2]
[1]
[4]]
如果你看到那个tf.print
在任何其他情况下都无法按预期工作,请分享可重现的代码,以便Tensorflow Community
可以看一下。