|
| 1 | +import os |
| 2 | +from os import path |
| 3 | +import numpy as np |
| 4 | +from tqdm import trange |
| 5 | + |
| 6 | +from ydata_synthetic.synthesizers.gan import BaseModel |
| 7 | +from ydata_synthetic.synthesizers.loss import Mode, gradient_penalty |
| 8 | +from ydata_synthetic.synthesizers import TrainParameters |
| 9 | + |
| 10 | +import tensorflow as tf |
| 11 | +from tensorflow.keras.layers import Input, Dense, Dropout |
| 12 | +from tensorflow.keras import Model |
| 13 | +from tensorflow.keras.optimizers import Adam |
| 14 | + |
| 15 | +class CRAMERGAN(BaseModel): |
| 16 | + |
| 17 | + __MODEL__='CRAMERGAN' |
| 18 | + |
| 19 | + def __init__(self, model_parameters, gradient_penalty_weight=10): |
| 20 | + """Create a base CramerGAN. |
| 21 | +
|
| 22 | + Based according to the WGAN paper - https://arxiv.org/pdf/1705.10743.pdf |
| 23 | + CramerGAN, a solution to biased Wassertein Gradients https://arxiv.org/abs/1705.10743""" |
| 24 | + self.gradient_penalty_weight = gradient_penalty_weight |
| 25 | + super().__init__(model_parameters) |
| 26 | + |
| 27 | + def define_gan(self): |
| 28 | + self.generator = Generator(self.batch_size). \ |
| 29 | + build_model(input_shape=(self.noise_dim,), dim=self.layers_dim, data_dim=self.data_dim) |
| 30 | + |
| 31 | + self.critic = Critic(self.batch_size). \ |
| 32 | + build_model(input_shape=(self.data_dim,), dim=self.layers_dim) |
| 33 | + |
| 34 | + self.g_optimizer = Adam(self.g_lr, beta_1=self.beta_1, beta_2=self.beta_2) |
| 35 | + self.c_optimizer = Adam(self.d_lr, beta_1=self.beta_1, beta_2=self.beta_2) |
| 36 | + |
| 37 | + # The generator takes noise as input and generates records |
| 38 | + z = Input(shape=(self.noise_dim,), batch_size=self.batch_size) |
| 39 | + fake = self.generator(z, training=True) |
| 40 | + logits = self.critic(fake, training=True) |
| 41 | + |
| 42 | + # Compile the critic |
| 43 | + self.critic.compile(loss=self.c_lossfn, |
| 44 | + optimizer=self.c_optimizer, |
| 45 | + metrics=['accuracy']) |
| 46 | + |
| 47 | + # Generator and critic model |
| 48 | + _model = Model(z, logits) |
| 49 | + _model.compile(loss=self.g_lossfn, optimizer=self.g_optimizer) |
| 50 | + |
| 51 | + def gradient_penalty(self, real, fake): |
| 52 | + gp = gradient_penalty(self.f_crit, real, fake, mode=Mode.CRAMER) |
| 53 | + return gp |
| 54 | + |
| 55 | + def update_gradients(self, x): |
| 56 | + """Compute and apply the gradients for both the Generator and the Critic. |
| 57 | +
|
| 58 | + :param x: real data event |
| 59 | + :return: generator gradients, critic gradients |
| 60 | + """ |
| 61 | + # Update the gradients of critic for n_critic times (Training the critic) |
| 62 | + |
| 63 | + ##New generator gradient_tape |
| 64 | + noise= tf.random.normal([x.shape[0], self.noise_dim], dtype=tf.dtypes.float32) |
| 65 | + noise2= tf.random.normal([x.shape[0], self.noise_dim], dtype=tf.dtypes.float32) |
| 66 | + |
| 67 | + with tf.GradientTape() as g_tape, tf.GradientTape() as d_tape: |
| 68 | + fake=self.generator(noise, training=True) |
| 69 | + fake2=self.generator(noise2, training=True) |
| 70 | + |
| 71 | + g_loss = self.g_lossfn(x, fake, fake2) |
| 72 | + |
| 73 | + c_loss = self.c_lossfn(x, fake, fake2) |
| 74 | + |
| 75 | + # Get the gradients of the generator |
| 76 | + g_gradients = g_tape.gradient(g_loss, self.generator.trainable_variables) |
| 77 | + |
| 78 | + # Update the weights of the generator |
| 79 | + self.g_optimizer.apply_gradients( |
| 80 | + zip(g_gradients, self.generator.trainable_variables) |
| 81 | + ) |
| 82 | + |
| 83 | + c_gradient = d_tape.gradient(c_loss, self.critic.trainable_variables) |
| 84 | + # Update the weights of the critic using the optimizer |
| 85 | + self.c_optimizer.apply_gradients( |
| 86 | + zip(c_gradient, self.critic.trainable_variables) |
| 87 | + ) |
| 88 | + |
| 89 | + return c_loss, g_loss |
| 90 | + |
| 91 | + def g_lossfn(self, real, fake, fake2): |
| 92 | + """Compute generator loss function according to the CramerGAN paper. |
| 93 | +
|
| 94 | + :param real: A real sample |
| 95 | + :param fake: A fake sample |
| 96 | + :param fak2: A second fake sample |
| 97 | + :return: Loss of the generator |
| 98 | + """ |
| 99 | + g_loss = tf.norm(self.critic(real, training=True) - self.critic(fake, training=True), axis=1) + \ |
| 100 | + tf.norm(self.critic(real, training=True) - self.critic(fake2, training=True), axis=1) - \ |
| 101 | + tf.norm(self.critic(fake, training=True) - self.critic(fake2, training=True), axis=1) |
| 102 | + return tf.reduce_mean(g_loss) |
| 103 | + |
| 104 | + def f_crit(self, real, fake): |
| 105 | + """ |
| 106 | + Computes the critic distance function f between two samples |
| 107 | + :param real: A real sample |
| 108 | + :param fake: A fake sample |
| 109 | + :return: Loss of the critic |
| 110 | + """ |
| 111 | + return tf.norm(self.critic(real, training=True) - self.critic(fake, training=True), axis=1) - tf.norm(self.critic(real, training=True), axis=1) |
| 112 | + |
| 113 | + def c_lossfn(self, real, fake, fake2): |
| 114 | + """ |
| 115 | + :param real: A real sample |
| 116 | + :param fake: A fake sample |
| 117 | + :param fak2: A second fake sample |
| 118 | + :return: Loss of the critic |
| 119 | + """ |
| 120 | + f_real = self.f_crit(real, fake2) |
| 121 | + f_fake = self.f_crit(fake, fake2) |
| 122 | + loss_surrogate = f_real - f_fake |
| 123 | + gp = self.gradient_penalty(real, [fake, fake2]) |
| 124 | + return tf.reduce_mean(- loss_surrogate + self.gradient_penalty_weight*gp) |
| 125 | + |
| 126 | + @staticmethod |
| 127 | + def get_data_batch(train, batch_size, seed=0): |
| 128 | + # np.random.seed(seed) |
| 129 | + # x = train.loc[ np.random.choice(train.index, batch_size) ].values |
| 130 | + # iterate through shuffled indices, so every sample gets covered evenly |
| 131 | + start_i = (batch_size * seed) % len(train) |
| 132 | + stop_i = start_i + batch_size |
| 133 | + shuffle_seed = (batch_size * seed) // len(train) |
| 134 | + np.random.seed(shuffle_seed) |
| 135 | + train_ix = np.random.choice(list(train.index), replace=False, size=len(train)) # wasteful to shuffle every time |
| 136 | + train_ix = list(train_ix) + list(train_ix) # duplicate to cover ranges past the end of the set |
| 137 | + x = train.loc[train_ix[start_i: stop_i]].values |
| 138 | + return np.reshape(x, (batch_size, -1)) |
| 139 | + |
| 140 | + def train_step(self, train_data): |
| 141 | + critic_loss, g_loss = self.update_gradients(train_data) |
| 142 | + return critic_loss, g_loss |
| 143 | + |
| 144 | + def train(self, data, train_arguments: TrainParameters): |
| 145 | + iterations = int(abs(data.shape[0] / self.batch_size) + 1) |
| 146 | + |
| 147 | + # Create a summary file |
| 148 | + train_summary_writer = tf.summary.create_file_writer(path.join('..\cramergan_test', 'summaries', 'train')) |
| 149 | + |
| 150 | + with train_summary_writer.as_default(): |
| 151 | + for epoch in trange(train_arguments.epochs): |
| 152 | + for iteration in range(iterations): |
| 153 | + batch_data = self.get_data_batch(data, self.batch_size) |
| 154 | + c_loss, g_loss = self.train_step(batch_data) |
| 155 | + |
| 156 | + if iteration % train_arguments.sample_interval == 0: |
| 157 | + # Test here data generation step |
| 158 | + # save model checkpoints |
| 159 | + if path.exists('./cache') is False: |
| 160 | + os.mkdir('./cache') |
| 161 | + model_checkpoint_base_name = './cache/' + train_arguments.cache_prefix + '_{}_model_weights_step_{}.h5' |
| 162 | + self.generator.save_weights(model_checkpoint_base_name.format('generator', iteration)) |
| 163 | + self.critic.save_weights(model_checkpoint_base_name.format('critic', iteration)) |
| 164 | + |
| 165 | + print( |
| 166 | + "Epoch: {} | critic_loss: {} | gen_loss: {}".format( |
| 167 | + epoch, c_loss, g_loss |
| 168 | + )) |
| 169 | + |
| 170 | + self.g_optimizer=self.g_optimizer.get_config() |
| 171 | + self.critic_optimizer=self.c_optimizer.get_config() |
| 172 | + |
| 173 | + def save(self, path): |
| 174 | + """Strip down the optimizers from the model then save.""" |
| 175 | + for attr in ['g_optimizer', 'c_optimizer']: |
| 176 | + try: |
| 177 | + delattr(self, attr) |
| 178 | + except AttributeError: |
| 179 | + continue |
| 180 | + super().save(path) |
| 181 | + |
| 182 | + |
| 183 | +class Generator(tf.keras.Model): |
| 184 | + def __init__(self, batch_size): |
| 185 | + """Simple generator with dense feedforward layers.""" |
| 186 | + self.batch_size = batch_size |
| 187 | + |
| 188 | + def build_model(self, input_shape, dim, data_dim): |
| 189 | + input_ = Input(shape=input_shape, batch_size=self.batch_size) |
| 190 | + x = Dense(dim, activation='relu')(input_) |
| 191 | + x = Dense(dim * 2, activation='relu')(x) |
| 192 | + x = Dense(dim * 4, activation='relu')(x) |
| 193 | + x = Dense(data_dim)(x) |
| 194 | + return Model(inputs=input_, outputs=x) |
| 195 | + |
| 196 | +class Critic(tf.keras.Model): |
| 197 | + def __init__(self, batch_size): |
| 198 | + """Simple critic with dense feedforward and dropout layers.""" |
| 199 | + self.batch_size = batch_size |
| 200 | + |
| 201 | + def build_model(self, input_shape, dim): |
| 202 | + input_ = Input(shape=input_shape, batch_size=self.batch_size) |
| 203 | + x = Dense(dim * 4, activation='relu')(input_) |
| 204 | + x = Dropout(0.1)(x) |
| 205 | + x = Dense(dim * 2, activation='relu')(x) |
| 206 | + x = Dropout(0.1)(x) |
| 207 | + x = Dense(dim, activation='relu')(x) |
| 208 | + x = Dense(1)(x) |
| 209 | + return Model(inputs=input_, outputs=x) |
0 commit comments