【问题标题】:How do I prune over the highest weights in tensorflow layer? tfmot.sparsity.keras.prune_low_magnitude如何修剪 tensorflow 层中的最高权重? tfmot.sparsity.keras.prune_low_magnitude
【发布时间】:2019-08-07 13:28:54
【问题描述】:

我想修剪 tf 层中的最高权重值。我正在考虑使用tf.nn.top_k,但我不确定我将如何去做。

文档:https://www.tensorflow.org/model_optimization/api_docs/python/tfmot/sparsity/keras/prune_low_magnitude 代码:

pruning_params = {
    'pruning_schedule': PolynomialDecay(initial_sparsity=0.2,
        final_sparsity=0.8, begin_step=1000, end_step=2000),
    'block_size': (2, 3),
    'block_pooling_type': 'MAX'
}

model = keras.Sequential([
    layers.Dense(10, activation='relu', input_shape=(100,)),
    prune_low_magnitude(layers.Dense(2, activation='tanh'), **pruning_params)
])

【问题讨论】:

  • 为什么要修剪最高的权重?
  • 我想实现一个 WTA 自动编码器,所以我计划以这种方式实现生命周期稀疏性和空间稀疏性。 @gorjan

标签: tensorflow keras tf.keras pruning


【解决方案1】:

假设 w 是您要修剪的层的权重矩阵,k 是应该修剪的权重百分比,这应该可以解决问题:

# Convert k from percentage to integer representing the number of weights
k = tf.cast(tf.round(tf.size(w, out_type=tf.float32) * tf.constant(k)), dtype=tf.int32)
# Reshape flatten the weight matrix
w_reshaped = tf.reshape(w, [-1])
# Select the indices of the largest k weights
_, indices = tf.nn.top_k(w_reshaped, k, sorted=True, name=None)
# Set the elements matching the indices to 0
mask = tf.scatter_nd_update(tf.Variable(tf.ones_like(w_reshaped, dtype=tf.float32), name="mask", trainable=False), tf.reshape(indices, [-1, 1]), tf.zeros([k], tf.float32))
# Update the weight matrix w
w.assign(tf.reshape(w_reshaped * mask, tf.shape(w)))

这是基于此Github repo。请注意,在那个项目中,我正在修剪最小的k 权重。

【讨论】:

  • 感谢您的帮助 - 非常感谢
  • 你如何建议我修改掩码,然后修剪最大的 k 权重。我一直在考虑使用 if not in indices 之类的东西,然后设置为 0。
  • 按照上面的sn-p代码使用即可。在示例中,我修改了 Github 存储库中的代码以适合您的目的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
  • 1970-01-01
相关资源
最近更新 更多