首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我如何修剪最高的重量在丹索尔流动层?tfmot.sparsity.keras.prune_low_magnitude

我如何修剪最高的重量在丹索尔流动层?tfmot.sparsity.keras.prune_low_magnitude
EN

Stack Overflow用户
提问于 2019-08-07 13:28:54
回答 1查看 506关注 0票数 2

我想修剪一个tf层的最高重量值。我正在考虑使用tf.nn.top_k,但我不太确定我将如何做到这一点。

文档:大小代码:

代码语言:javascript
复制
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)
])
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-07 13:47:08

假设w是您想要修剪的层的权重矩阵,而k是应该修剪的权重的百分比,那么这应该对您有好处:

代码语言:javascript
复制
# 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回购。请注意,在那个项目中,我正在修剪最小的k权重。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57395645

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档