【问题标题】:How can I set binary weights values (0,1) or (-1,1) to the layer in Keras?如何在 Keras 中为图层设置二进制权重值 (0,1) 或 (-1,1)?
【发布时间】:2021-02-09 18:45:49
【问题描述】:

我想问一下我是否可以将(任何)Keras 层中的权重初始化器设置为二进制值 - 例如,简单 Dense 层的权重仅为 0 和 1?这将有助于例如在 Conv1D 层的情况下放宽计算时间。

谢谢你, J

【问题讨论】:

    标签: keras neural-network binary initialization


    【解决方案1】:

    是的,这可以通过创建自定义初始化程序来实现:

    def binary_weights(shape, dtype=tf.float32):
        """This function generates weights of random 0s and 1s based on the provided shape"""
        # build logits matrix:
        logits = tf.fill((shape[0], 2), 0.5)
        # uniformly pick the class.
        return tf.cast(tf.random.categorical(tf.math.log(logits), shape[1]), dtype=dtype)
    

    那么当你指定层时:

    model = tf.keras.models.Sequential([
        tf.keras.layers.Dense(units, kernel_initializer=binary_weights, input_shape=[num_features,]),
        ...
    ])
    

    检查生成的权重:

    print(model.layers[0].get_weights()[0])
    

    【讨论】:

    • 太棒了!谢谢!它是否明确设置范围 [0,1] 或 0 和 1?
    • 感谢您的反馈,对不起,我写错了,它会生成一个随机零和一的权重。
    • 我还添加了一行让你检查权重的样子,你必须提供变量unitsnum_features
    • 好的,但是方向很明确,只需要初始化权重就可以了!无论如何,谢谢!
    • @Yevhenii 我已经修复了 binary_weights 函数,它应该为您提供 0 到 1s 之间的正确二进制值
    猜你喜欢
    • 2017-03-22
    • 1970-01-01
    • 2021-06-01
    • 2019-01-19
    • 2017-09-28
    • 2021-05-07
    • 2018-03-17
    • 1970-01-01
    • 2020-10-31
    相关资源
    最近更新 更多