【问题标题】:TensorFlow 'Variable' has no trainable parametersTensorFlow“变量”没有可训练的参数
【发布时间】:2022-01-25 08:58:52
【问题描述】:

我正在使用 Keras Lambda 层进行一些具有可训练权重张量的操作(或者至少应该如此);为此,我选择了一个 tf.Variable 作为参数,但尽管 trainable=True,但摘要显示 0 个可训练参数。

weights = tf.Variable(initial_value=tf.random.normal((300,)), trainable=True)
custom_layer = keras.layers.Lambda(custom_func)((input_layer, weights))

独立于 trainable=True,权重仍然不可训练。 另一种选择是使用如下层:

weights = Dense(300, activation='linear', use_bias=False)

在这种情况下,由于 tf.math.multiply 不接受(至少根据我的实验)以任何方式(我尝试了 .get_weights() 和 .variables)的密集层参数,我在 custom_func 中遇到了麻烦。

非常欢迎所有获得可训练权重张量的解决方案,提前感谢您。

【问题讨论】:

  • 你能分享custom_func代码吗?
  • 这可能很容易通过制作适当的自定义层来解决。
  • @newt custom_func 代码只是一个 tf.math.multiply(tensor_A, weights) 其中 tensor_A 源自对 input_layer 的一些格式良好的操作
  • @Dr.Snoopy 我找不到更好的方法来计算自定义层,其输出张量是可训练权重向量的元素乘积和模型另一层的结果.

标签: python tensorflow keras tf.keras keras-layer


【解决方案1】:

将变量与 lambda 函数一起使用可能会导致错误,因为 custom_layer 不会直接跟踪 weights,因此张量不会出现在可训练的权重中。

这可以通过继承Layer类来解决,如下所示:

class custom_layer(tf.keras.layers.Layer):
  def __init__(self):
      super(custom_layer, self).__init__()
      self.weights = tf.Variable(...)        #define weights here

    def call(self, inputs):
      return custom_func(..)

【讨论】:

    猜你喜欢
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 2020-07-16
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多