【问题标题】:Tensorflow 2.0: kernel_constraint not workingTensorflow 2.0:kernel_constraint 不起作用
【发布时间】:2019-12-26 03:03:39
【问题描述】:

我尝试对卷积层施加一些约束,但似乎不起作用。

import tensorflow as tf
import numpy as np
c2 = tf.keras.layers.Conv2D(filters=1, kernel_size=3, strides=(1, 1),
                            kernel_initializer=tf.keras.initializers.constant(-20.),
                            kernel_constraint=tf.keras.constraints.non_neg(), padding='valid')
x = np.reshape([1. for i in range(9)], (1, 3, 3, 1))
y = c2(x)
print(y)

我希望 0 作为答案,但它给了我

tf.Tensor([[[[-180.]]]], shape=(1, 1, 1, 1), dtype=float32)

忽略 kernel_constraint 函数。

我错过了什么还是一个错误?顺便说一句,我使用 Windows 作为平台

【问题讨论】:

    标签: constraints conv-neural-network tensorflow2.0


    【解决方案1】:

    它归结为在第一次构建 Layer 对象时是初始化程序还是约束优先。似乎在这种情况下,初始化程序优先。考虑到 Keras 约束文档中的内容,这是有道理的:

    “来自约束模块的函数允许设置约束(例如。 优化过程中网络参数的非负性)。”

    (参考:https://keras.io/constraints/)。

    关键字词组是“优化期间”。在您的代码示例中,不涉及优化(即没有训练或fit())调用。您的代码可以稍作修改以显示约束实际上是有效的:

    import tensorflow as tf
    import numpy as np
    
    c2 = tf.keras.layers.Conv2D(filters=1, kernel_size=3, strides=(1, 1),
                                kernel_initializer=tf.keras.initializers.constant(-20.),
                                kernel_constraint=tf.keras.constraints.non_neg(), padding='valid')
    
    x = tf.constant(np.reshape([1. for i in range(9)], (1, 3, 3, 1)))
    
    optimizer = tf.optimizers.SGD(0.01)
    with tf.GradientTape() as tape:
      y = c2(x)
      print(y)
      gradients = tape.gradient(y, c2.variables)
      optimizer.apply_gradients(zip(gradients, c2.variables))
    
    print(c2.get_weights())  # <-- See that the weights are all 0s now.
    

    【讨论】:

    • 我明白了。谢谢解释
    猜你喜欢
    • 2019-10-30
    • 2018-12-23
    • 1970-01-01
    • 2021-04-10
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    相关资源
    最近更新 更多