python - 如何重用 Dense 层?

标签 python tensorflow neural-network

我在 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/

相关文章:

python - ValueError : No gradients provided for any variable while doing regression for integer values,,其中包括使用 keras 的底片

python - 减少 CNN 模型中的验证损失

python - 如何绘制 tensorflow 神经网络对象

python - wx.NotificationMessage 属性错误: 'module' object has no attribute 'NotificationMessage'

python - Ctypes:OSError:异常:堆栈溢出

python - 类型错误 : 'int' object is not callable

python-3.x - 具有 tensorflow 问题的稳定基线

python - Keras 中损失函数的导数

python - 使用神经网络的骑士之旅

tensorflow - 图像分类迁移学习需要负例吗?