我在 Tensorflow 中有一个网络,我想定义一个函数,通过 tf.layers.dense
层(显然是同一层)传递它的输入。我看到了 reuse
参数,但为了正确使用它,我似乎需要保留一个全局变量来记住我的函数是否已被调用。有更清洁的方法吗?
最佳答案
我找到了 tf.layers.Dense比上面的答案更干净。您只需要一个预先定义的 Dense 对象。然后您可以重复使用它任意次。
import tensorflow as tf
# Define Dense object which is reusable
my_dense = tf.layers.Dense(3, name="optional_name")
# Define some inputs
x1 = tf.constant([[1,2,3], [4,5,6]], dtype=tf.float32)
x2 = tf.constant([[4,5,6], [7,8,9]], dtype=tf.float32)
# Use the Dense layer
y1 = my_dense(x1)
y2 = my_dense(x2)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
y1 = sess.run(y1)
y2 = sess.run(y2)
print(y1)
print(y2)
事实上 tf.layers.dense
函数在内部构造了一个 Dense 对象并将您的输入传递给该对象。有关详细信息,请查看 code .
关于python - 如何重用 Dense 层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43392838/