如何在tensorflow中进行权重裁剪?

3

我在mnist数据集上用tensorflow编写了一个wgan,并且它表现良好,但我发现很难在tensorflow中剪裁判别器模型的权重[-0.01,0.01]。在keras中,我们可以使用权重剪裁来解决。

for l in self.discriminator.layers:
    weights = l.get_weights()
    weights = [np.clip(w, -self.clip_value, self.clip_value) for w in weights]
    l.set_weights(weights)

我发现了一份有关于裁剪鉴别器权重的TensorFlow文档。

tf.contrib.gan.features.clip_discriminator_weights(
    optimizer,
    model,
    weight_clip
)

除此之外,关于如何使用这个函数并没有太多的说明。

#my tf code
def generator(z):
    h=tf.nn.relu(layer_mlp(z,"g1",[10,128]))
    prob=tf.nn.sigmoid(layer_mlp(h,"g2",[128,784]))
    return prob


def discriminator(x):
    h=tf.nn.relu(layer_mlp(x,"d1",[784,128]))
    logit=layer_mlp(h,"d2",[128,1])
    prob=tf.nn.sigmoid(logit)
    return prob

G_sample=generator(z)
D_real= discriminator(x)
D_fake= discriminator(G_sample)


D_loss = tf.reduce_mean(D_real) - tf.reduce_mean(D_fake)
G_loss = -tf.reduce_mean(D_fake)

for epoch in epochs:
    #training the model
2个回答

4

补充Yaakov的回答,您可以使用tf.clip_by_value与可训练变量一起使用,如此库所示https://github.com/hcnoh/WGAN-tensorflow2

for w in model.discriminator.trainable_variables:
  w.assign(tf.clip_by_value(w, -clip_const, clip_const))

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接