You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conditional_wgan_wrapper_exp1.py 10.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. from functools import partial
  2. import numpy as np
  3. from keras import backend as K
  4. from keras.layers import Input, RepeatVector, Multiply, Lambda, Permute
  5. from keras.layers.merge import _Merge
  6. from keras.models import Model
  7. from keras.optimizers import Adam, SGD
  8. from keras.losses import binary_crossentropy
  9. def wasserstein_loss(y_true, y_pred):
  10. return K.mean(-y_true * y_pred)
  11. def generator_recunstruction_loss(y_true, y_pred, enableTrain):
  12. def rescale_back_labels(labels):
  13. rescaled_back_labels = (labels / 2) + 0.5
  14. return rescaled_back_labels
  15. return binary_crossentropy(rescale_back_labels(y_true), rescale_back_labels(y_pred)) #* enableTrain
  16. global enable_train
  17. enable_train = Input(shape = (1,))
  18. global generator_recunstruction_loss_new
  19. generator_recunstruction_loss_new = partial(generator_recunstruction_loss, enableTrain = enable_train)
  20. generator_recunstruction_loss_new.__name__ = 'generator_recunstruction_loss_new'
  21. def gradient_penalty_loss(y_true, y_pred, averaged_samples, gradient_penalty_weight):
  22. """Calculates the gradient penalty loss for a batch of "averaged" samples.
  23. In Improved WGANs, the 1-Lipschitz constraint is enforced by adding a term to the loss function
  24. that penalizes the network if the gradient norm moves away from 1. However, it is impossible to evaluate
  25. this function at all points in the input space. The compromise used in the paper is to choose random points
  26. on the lines between real and generated samples, and check the gradients at these points. Note that it is the
  27. gradient w.r.t. the input averaged samples, not the weights of the discriminator, that we're penalizing!
  28. In order to evaluate the gradients, we must first run samples through the generator and evaluate the loss.
  29. Then we get the gradients of the discriminator w.r.t. the input averaged samples.
  30. The l2 norm and penalty can then be calculated for this gradient.
  31. Note that this loss function requires the original averaged samples as input, but Keras only supports passing
  32. y_true and y_pred to loss functions. To get around this, we make a partial() of the function with the
  33. averaged_samples argument, and use that for model training."""
  34. # first get the gradients:
  35. # assuming: - that y_pred has dimensions (batch_size, 1)
  36. # - averaged_samples has dimensions (batch_size, nbr_features)
  37. # gradients afterwards has dimension (batch_size, nbr_features), basically
  38. # a list of nbr_features-dimensional gradient vectors
  39. gradients = K.gradients(y_pred, averaged_samples)[0]
  40. # compute the euclidean norm by squaring ...
  41. gradients_sqr = K.square(gradients)
  42. # ... summing over the rows ...
  43. gradients_sqr_sum = K.sum(gradients_sqr,
  44. axis=np.arange(1, len(gradients_sqr.shape)))
  45. # ... and sqrt
  46. gradient_l2_norm = K.sqrt(gradients_sqr_sum)
  47. # compute lambda * (1 - ||grad||)^2 still for each single sample
  48. gradient_penalty = gradient_penalty_weight * K.square(1 - gradient_l2_norm)
  49. # return the mean as loss over all the batch samples
  50. return K.mean(gradient_penalty)
  51. def WGAN_wrapper(generator, discriminator, generator_input_shape, discriminator_input_shape, discriminator_input_shape2,
  52. batch_size, gradient_penalty_weight, embeddings):
  53. BATCH_SIZE = batch_size
  54. GRADIENT_PENALTY_WEIGHT = gradient_penalty_weight
  55. def set_trainable_state(model, state):
  56. for layer in model.layers:
  57. layer.trainable = state
  58. model.trainable = state
  59. class RandomWeightedAverage(_Merge):
  60. """Takes a randomly-weighted average of two tensors. In geometric terms, this outputs a random point on the line
  61. between each pair of input points.
  62. Inheriting from _Merge is a little messy but it was the quickest solution I could think of.
  63. Improvements appreciated."""
  64. def _merge_function(self, inputs):
  65. weights = K.random_uniform((BATCH_SIZE, 1))
  66. print(inputs[0])
  67. return (weights * inputs[0]) + ((1 - weights) * inputs[1])
  68. # The generator_model is used when we want to train the generator layers.
  69. # As such, we ensure that the discriminator layers are not trainable.
  70. # Note that once we compile this model, updating .trainable will have no effect within it. As such, it
  71. # won't cause problems if we later set discriminator.trainable = True for the discriminator_model, as long
  72. # as we compile the generator_model first.
  73. def mul(input):
  74. embedds = K.variable(np.expand_dims(embeddings.T, 0), dtype='float32')
  75. batch_size = K.shape(input)[0]
  76. expanded_embed = K.tile(embedds, (batch_size, 1, 1))
  77. expanded_input = RepeatVector(100)(input)
  78. masked = Multiply()([expanded_embed, expanded_input])
  79. return K.permute_dimensions(masked, [0,2,1])
  80. set_trainable_state(discriminator, False)
  81. set_trainable_state(generator, True)
  82. #enable_train = Input(shape = (1,))
  83. generator_input = Input(shape=generator_input_shape)
  84. generator_layers = generator(generator_input)
  85. #masked_generator_layers = Lambda(mul)(generator_layers)
  86. #discriminator_noise_in = Input(shape=(1,))
  87. #input_seq_g = Input(shape = discriminator_input_shape2)
  88. discriminator_layers_for_generator= discriminator([generator_layers, generator_input])
  89. generator_model = Model(inputs=[generator_input, enable_train],
  90. outputs=[generator_layers, discriminator_layers_for_generator])
  91. # We use the Adam paramaters from Gulrajani et al.
  92. #global generator_recunstruction_loss_new
  93. #generator_recunstruction_loss_new = partial(generator_recunstruction_loss, enableTrain = enable_train)
  94. #generator_recunstruction_loss_new.__name__ = 'generator_RLN'
  95. loss = [generator_recunstruction_loss_new, wasserstein_loss]
  96. loss_weights = [10000, 1]
  97. generator_model.compile(optimizer=Adam(lr=1E-4, beta_1=0.9, beta_2=0.999, epsilon=1e-08),
  98. loss=loss, loss_weights=loss_weights)
  99. # Now that the generator_model is compiled, we can make the discriminator layers trainable.
  100. set_trainable_state(discriminator, True)
  101. set_trainable_state(generator, False)
  102. # The discriminator_model is more complex. It takes both real image samples and random noise seeds as input.
  103. # The noise seed is run through the generator model to get generated images. Both real and generated images
  104. # are then run through the discriminator. Although we could concatenate the real and generated images into a
  105. # single tensor, we don't (see model compilation for why).
  106. real_samples = Input(shape=discriminator_input_shape)
  107. input_seq = Input(shape = discriminator_input_shape2)
  108. generator_input_for_discriminator = Input(shape=generator_input_shape)
  109. generated_samples_for_discriminator = generator(generator_input_for_discriminator)
  110. #masked_real_samples = Lambda(mul)(real_samples)
  111. #masked_generated_samples_for_discriminator= Lambda(mul)(generated_samples_for_discriminator)
  112. discriminator_output_from_generator = discriminator([generated_samples_for_discriminator, generator_input_for_discriminator])
  113. discriminator_output_from_real_samples= discriminator([real_samples, input_seq])
  114. # We also need to generate weighted-averages of real and generated samples, to use for the gradient norm penalty.
  115. averaged_samples = RandomWeightedAverage()([real_samples, generated_samples_for_discriminator])
  116. average_seq = RandomWeightedAverage()([input_seq, generator_input_for_discriminator])
  117. # We then run these samples through the discriminator as well. Note that we never really use the discriminator
  118. # output for these samples - we're only running them to get the gradient norm for the gradient penalty loss.
  119. #print('hehehe')
  120. #print(averaged_samples)
  121. #masked_averaged_samples = Lambda(mul)(averaged_samples)
  122. averaged_samples_out = discriminator([averaged_samples, average_seq])
  123. # The gradient penalty loss function requires the input averaged samples to get gradients. However,
  124. # Keras loss functions can only have two arguments, y_true and y_pred. We get around this by making a partial()
  125. # of the function with the averaged samples here.
  126. partial_gp_loss = partial(gradient_penalty_loss,
  127. averaged_samples=averaged_samples,
  128. gradient_penalty_weight=GRADIENT_PENALTY_WEIGHT)
  129. partial_gp_loss.__name__ = 'gradient_penalty' # Functions need names or Keras will throw an error
  130. # Keras requires that inputs and outputs have the same number of samples. This is why we didn't concatenate the
  131. # real samples and generated samples before passing them to the discriminator: If we had, it would create an
  132. # output with 2 * BATCH_SIZE samples, while the output of the "averaged" samples for gradient penalty
  133. # would have only BATCH_SIZE samples.
  134. # If we don't concatenate the real and generated samples, however, we get three outputs: One of the generated
  135. # samples, one of the real samples, and one of the averaged samples, all of size BATCH_SIZE. This works neatly!
  136. discriminator_model = Model(inputs=[real_samples, generator_input_for_discriminator, input_seq],
  137. outputs=[discriminator_output_from_real_samples,
  138. discriminator_output_from_generator,
  139. averaged_samples_out])
  140. loss_weights2 = [1, 1, 1]
  141. # We use the Adam paramaters from Gulrajani et al. We use the Wasserstein loss for both the real and generated
  142. # samples, and the gradient penalty loss for the averaged samples.
  143. discriminator_model.compile(optimizer=SGD(clipvalue=0.01), # Adam(lr=4E-4, beta_1=0.9, beta_2=0.999, epsilon=1e-08),
  144. loss=[wasserstein_loss,
  145. wasserstein_loss,
  146. partial_gp_loss], loss_weights = loss_weights2)
  147. # set_trainable_state(discriminator, True)
  148. # set_trainable_state(generator, True)
  149. return generator_model, discriminator_model