如何将二进制权重值 (0,1) 或 (-1,1) 设置为 Keras 中的图层?
How can I set binary weights values (0,1) or (-1,1) to the layer in Keras?
我想问一下我是否可以将(任何)Keras 层中的权重初始值设定为二进制值 - 例如,简单 Dense 层的权重仅为 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])
我想问一下我是否可以将(任何)Keras 层中的权重初始值设定为二进制值 - 例如,简单 Dense 层的权重仅为 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])