簡體   English   中英

如何將二進制權重值 (0,1) 或 (-1,1) 設置到 Keras 中的層?

[英]How can I set binary weights values (0,1) or (-1,1) to the layer in Keras?

我想問我是否可以將(任何)Keras 層中的權重初始化程序設置為二進制值 - 例如,簡單密集層的權重僅為 0 和 1? 這將有助於例如在 Conv1D 層的情況下放寬計算時間。

謝謝你,J

是的,這可以通過創建自定義初始化程序來實現:

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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM