谱归一化(Spectral Normalization)在以LSTM为判别器的GAN中的运用(tensorflow2)

本人自用,效果未知。目测有提升但并不大。

1.创建SpectralNorm.py

import tensorflow as tf


class SpectralNorm(tf.keras.constraints.Constraint):
    def __init__(self, n_iter=5):  # 超参数,据说5次就够了
        self.n_iter = n_iter

    def call(self, input_weights):
        w = tf.reshape(input_weights, (-1, input_weights.shape[-1]))
        u = tf.random.normal((w.shape[0], 1))
        for _ in range(self.n_iter):
            v = tf.matmul(w, u, transpose_a=True)
            v /= tf.norm(v)
            u = tf.matmul(w, v)
            u /= tf.norm(u)
        spec_norm = tf.matmul(u, tf.matmul(w, v), transpose_a=True)
        return input_weights / spec_norm

2.在主程序中

from SpectralNorm import SpectralNorm

在判别器搭建网络时

    def build_discriminator(self):
        # 定义判别器网络
        model = Sequential()
        model.add(LSTM(units=self.hidden_dim,
                       kernel_constraint=SpectralNorm(),
                       recurrent_constraint=SpectralNorm(),
                       return_sequences=True))

即参数设置中添加
kernel_constraint=SpectralNorm()                       
recurrent_constraint=SpectralNorm()
即可

原理上来说也可以再加一句bias_constraint=SpectralNorm(),但目测没有什么意义,懒得加了

此外注意谱归一化只能在判别器中使用,不能在生成器中使用,并且注意使用谱归一化后不能再使用BatchNormalization(批标准化)之类的网络层。

以上

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值