convGAN.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from library.interfaces import GanBaseClass
  4. from library.dataset import DataSet
  5. from keras.layers import Dense, Input, Multiply, Flatten, Conv1D, Reshape
  6. from keras.models import Model
  7. from keras import backend as K
  8. from tqdm import tqdm
  9. import tensorflow as tf
  10. from tensorflow.keras.optimizers import Adam
  11. from tensorflow.keras.layers import Lambda
  12. from library.NNSearch import NNSearch
  13. import warnings
  14. warnings.filterwarnings("ignore")
  15. def repeat(x, times):
  16. return [x for _i in range(times)]
  17. def create01Labels(totalSize, sizeFirstHalf):
  18. labels = repeat(np.array([1,0]), sizeFirstHalf)
  19. labels.extend(repeat(np.array([0,1]), totalSize - sizeFirstHalf))
  20. return np.array(labels)
  21. class ConvGAN(GanBaseClass):
  22. """
  23. This is a toy example of a GAN.
  24. It repeats the first point of the training-data-set.
  25. """
  26. def __init__(self, n_feat, neb=5, gen=5, neb_epochs=10, withMajorhoodNbSearch=False, debug=False):
  27. self.isTrained = False
  28. self.n_feat = n_feat
  29. self.neb = neb
  30. self.gen = gen
  31. self.neb_epochs = 10
  32. self.loss_history = None
  33. self.debug = debug
  34. self.minSetSize = 0
  35. self.conv_sample_generator = None
  36. self.maj_min_discriminator = None
  37. self.withMajorhoodNbSearch = withMajorhoodNbSearch
  38. self.cg = None
  39. if neb > gen:
  40. raise ValueError(f"Expected neb <= gen but got neb={neb} and gen={gen}.")
  41. def reset(self):
  42. """
  43. Resets the trained GAN to an random state.
  44. """
  45. self.isTrained = False
  46. ## instanciate generator network and visualize architecture
  47. self.conv_sample_generator = self._conv_sample_gen()
  48. ## instanciate discriminator network and visualize architecture
  49. self.maj_min_discriminator = self._maj_min_disc()
  50. ## instanciate network and visualize architecture
  51. self.cg = self._convGAN(self.conv_sample_generator, self.maj_min_discriminator)
  52. if self.debug:
  53. print(self.conv_sample_generator.summary())
  54. print('\n')
  55. print(self.maj_min_discriminator.summary())
  56. print('\n')
  57. print(self.cg.summary())
  58. print('\n')
  59. def train(self, dataSet):
  60. """
  61. Trains the GAN.
  62. It stores the data points in the training data set and mark as trained.
  63. *dataSet* is a instance of /library.dataset.DataSet/. It contains the training dataset.
  64. We are only interested in the first *maxListSize* points in class 1.
  65. """
  66. if dataSet.data1.shape[0] <= 0:
  67. raise AttributeError("Train: Expected data class 1 to contain at least one point.")
  68. # Store size of minority class. This is needed during point generation.
  69. self.minSetSize = dataSet.data1.shape[0]
  70. # Precalculate neighborhoods
  71. self.nmbMin = NNSearch(self.neb).fit(haystack=dataSet.data1)
  72. if self.withMajorhoodNbSearch:
  73. self.nmbMaj = NNSearch(self.neb).fit(haystack=dataSet.data0, needles=dataSet.data1)
  74. else:
  75. self.nmbMaj = None
  76. # Do the training.
  77. self._rough_learning(dataSet.data1, dataSet.data0)
  78. # Neighborhood in majority class is no longer needed. So save memory.
  79. self.nmbMaj = None
  80. self.isTrained = True
  81. def generateDataPoint(self):
  82. """
  83. Returns one synthetic data point by repeating the stored list.
  84. """
  85. return (self.generateData(1))[0]
  86. def generateData(self, numOfSamples=1):
  87. """
  88. Generates a list of synthetic data-points.
  89. *numOfSamples* is a integer > 0. It gives the number of new generated samples.
  90. """
  91. if not self.isTrained:
  92. raise ValueError("Try to generate data with untrained Re.")
  93. ## roughly claculate the upper bound of the synthetic samples to be generated from each neighbourhood
  94. synth_num = (numOfSamples // self.minSetSize) + 1
  95. ## generate synth_num synthetic samples from each minority neighbourhood
  96. synth_set=[]
  97. for i in range(self.minSetSize):
  98. synth_set.extend(self._generate_data_for_min_point(i, synth_num))
  99. ## extract the exact number of synthetic samples needed to exactly balance the two classes
  100. synth_set = np.array(synth_set[:numOfSamples])
  101. return synth_set
  102. # ###############################################################
  103. # Hidden internal functions
  104. # ###############################################################
  105. # Creating the GAN
  106. def _conv_sample_gen(self):
  107. """
  108. the generator network to generate synthetic samples from the convex space
  109. of arbitrary minority neighbourhoods
  110. """
  111. ## takes minority batch as input
  112. min_neb_batch = Input(shape=(self.n_feat,))
  113. ## reshaping the 2D tensor to 3D for using 1-D convolution,
  114. ## otherwise 1-D convolution won't work.
  115. x = tf.reshape(min_neb_batch, (1, self.neb, self.n_feat), name=None)
  116. ## using 1-D convolution, feature dimension remains the same
  117. x = Conv1D(self.n_feat, 3, activation='relu')(x)
  118. ## flatten after convolution
  119. x = Flatten()(x)
  120. ## add dense layer to transform the vector to a convenient dimension
  121. x = Dense(self.neb * self.gen, activation='relu')(x)
  122. ## again, witching to 2-D tensor once we have the convenient shape
  123. x = Reshape((self.neb, self.gen))(x)
  124. ## row wise sum
  125. s = K.sum(x, axis=1)
  126. ## adding a small constant to always ensure the row sums are non zero.
  127. ## if this is not done then during initialization the sum can be zero.
  128. s_non_zero = Lambda(lambda x: x + .000001)(s)
  129. ## reprocals of the approximated row sum
  130. sinv = tf.math.reciprocal(s_non_zero)
  131. ## At this step we ensure that row sum is 1 for every row in x.
  132. ## That means, each row is set of convex co-efficient
  133. x = Multiply()([sinv, x])
  134. ## Now we transpose the matrix. So each column is now a set of convex coefficients
  135. aff=tf.transpose(x[0])
  136. ## We now do matrix multiplication of the affine combinations with the original
  137. ## minority batch taken as input. This generates a convex transformation
  138. ## of the input minority batch
  139. synth=tf.matmul(aff, min_neb_batch)
  140. ## finally we compile the generator with an arbitrary minortiy neighbourhood batch
  141. ## as input and a covex space transformation of the same number of samples as output
  142. model = Model(inputs=min_neb_batch, outputs=synth)
  143. opt = Adam(learning_rate=0.001)
  144. model.compile(loss='mean_squared_logarithmic_error', optimizer=opt)
  145. return model
  146. def _maj_min_disc(self):
  147. """
  148. the discriminator is trained intwo phase:
  149. first phase: while training GAN the discriminator learns to differentiate synthetic
  150. minority samples generated from convex minority data space against
  151. the borderline majority samples
  152. second phase: after the GAN generator learns to create synthetic samples,
  153. it can be used to generate synthetic samples to balance the dataset
  154. and then rettrain the discriminator with the balanced dataset
  155. """
  156. ## takes as input synthetic sample generated as input stacked upon a batch of
  157. ## borderline majority samples
  158. samples = Input(shape=(self.n_feat,))
  159. ## passed through two dense layers
  160. y = Dense(250, activation='relu')(samples)
  161. y = Dense(125, activation='relu')(y)
  162. ## two output nodes. outputs have to be one-hot coded (see labels variable before)
  163. output = Dense(2, activation='sigmoid')(y)
  164. ## compile model
  165. model = Model(inputs=samples, outputs=output)
  166. opt = Adam(learning_rate=0.0001)
  167. model.compile(loss='binary_crossentropy', optimizer=opt)
  168. return model
  169. def _convGAN(self, generator, discriminator):
  170. """
  171. for joining the generator and the discriminator
  172. conv_coeff_generator-> generator network instance
  173. maj_min_discriminator -> discriminator network instance
  174. """
  175. ## by default the discriminator trainability is switched off.
  176. ## Thus training the GAN means training the generator network as per previously
  177. ## trained discriminator network.
  178. discriminator.trainable = False
  179. ## input receives a neighbourhood minority batch
  180. ## and a proximal majority batch concatenated
  181. batch_data = Input(shape=(self.n_feat,))
  182. ##- print(f"GAN: 0..{self.neb}/{self.gen}..")
  183. ## extract minority batch
  184. min_batch = Lambda(lambda x: x[:self.neb])(batch_data)
  185. ## extract majority batch
  186. maj_batch = Lambda(lambda x: x[self.gen:])(batch_data)
  187. ## pass minority batch into generator to obtain convex space transformation
  188. ## (synthetic samples) of the minority neighbourhood input batch
  189. conv_samples = generator(min_batch)
  190. ## concatenate the synthetic samples with the majority samples
  191. new_samples = tf.concat([conv_samples, maj_batch],axis=0)
  192. ##- new_samples = tf.concat([conv_samples, conv_samples, conv_samples, conv_samples],axis=0)
  193. ## pass the concatenated vector into the discriminator to know its decisions
  194. output = discriminator(new_samples)
  195. ##- output = Lambda(lambda x: x[:2 * self.gen])(output)
  196. ## note that, the discriminator will not be traied but will make decisions based
  197. ## on its previous training while using this function
  198. model = Model(inputs=batch_data, outputs=output)
  199. opt = Adam(learning_rate=0.0001)
  200. model.compile(loss='mse', optimizer=opt)
  201. return model
  202. # Create synthetic points
  203. def _generate_data_for_min_point(self, index, synth_num):
  204. """
  205. generate synth_num synthetic points for a particular minoity sample
  206. synth_num -> required number of data points that can be generated from a neighbourhood
  207. data_min -> minority class data
  208. neb -> oversampling neighbourhood
  209. index -> index of the minority sample in a training data whose neighbourhood we want to obtain
  210. """
  211. runs = int(synth_num / self.neb) + 1
  212. synth_set = []
  213. for _run in range(runs):
  214. batch = self.nmbMin.getNbhPointsOfItem(index)
  215. synth_batch = self.conv_sample_generator.predict(batch)
  216. synth_set.extend(synth_batch)
  217. return synth_set[:synth_num]
  218. # Training
  219. def _rough_learning(self, data_min, data_maj):
  220. generator = self.conv_sample_generator
  221. discriminator = self.maj_min_discriminator
  222. GAN = self.cg
  223. loss_history = [] ## this is for stroring the loss for every run
  224. min_idx = 0
  225. neb_epoch_count = 1
  226. labels = tf.convert_to_tensor(create01Labels(2 * self.gen, self.gen))
  227. for step in range(self.neb_epochs * len(data_min)):
  228. ## generate minority neighbourhood batch for every minority class sampls by index
  229. min_batch_indices = self.nmbMin.neighbourhoodOfItem(min_idx)
  230. min_batch = self.nmbMin.getPointsFromIndices(min_batch_indices)
  231. min_idx = min_idx + 1
  232. ## generate random proximal majority batch
  233. maj_batch = self._BMB(data_maj, min_batch_indices)
  234. ## generate synthetic samples from convex space
  235. ## of minority neighbourhood batch using generator
  236. conv_samples = generator.predict(min_batch)
  237. ## concatenate them with the majority batch
  238. concat_sample = tf.concat([conv_samples, maj_batch], axis=0)
  239. ## switch on discriminator training
  240. discriminator.trainable = True
  241. ## train the discriminator with the concatenated samples and the one-hot encoded labels
  242. discriminator.fit(x=concat_sample, y=labels, verbose=0)
  243. ## switch off the discriminator training again
  244. discriminator.trainable = False
  245. ## use the GAN to make the generator learn on the decisions
  246. ## made by the previous discriminator training
  247. ##- print(f"concat sample shape: {concat_sample.shape}/{labels.shape}")
  248. gan_loss_history = GAN.fit(concat_sample, y=labels, verbose=0)
  249. ## store the loss for the step
  250. loss_history.append(gan_loss_history.history['loss'])
  251. if self.debug and ((step + 1) % 10 == 0):
  252. print(f"{step + 1} neighbourhood batches trained; running neighbourhood epoch {neb_epoch_count}")
  253. if min_idx == len(data_min) - 1:
  254. if self.debug:
  255. print(f"Neighbourhood epoch {neb_epoch_count} complete")
  256. neb_epoch_count = neb_epoch_count + 1
  257. min_idx = 0
  258. if self.debug:
  259. run_range = range(1, len(loss_history) + 1)
  260. plt.rcParams["figure.figsize"] = (16,10)
  261. plt.xticks(fontsize=20)
  262. plt.yticks(fontsize=20)
  263. plt.xlabel('runs', fontsize=25)
  264. plt.ylabel('loss', fontsize=25)
  265. plt.title('Rough learning loss for discriminator', fontsize=25)
  266. plt.plot(run_range, loss_history)
  267. plt.show()
  268. self.conv_sample_generator = generator
  269. self.maj_min_discriminator = discriminator
  270. self.cg = GAN
  271. self.loss_history = loss_history
  272. ## convGAN
  273. def _BMB(self, data_maj, min_idxs):
  274. ## Generate a borderline majority batch
  275. ## data_maj -> majority class data
  276. ## min_idxs -> indices of points in minority class
  277. ## gen -> convex combinations generated from each neighbourhood
  278. if self.nmbMaj is not None:
  279. return self.nmbMaj.neighbourhoodOfItemList(min_idxs, maxCount=self.gen)
  280. else:
  281. return tf.convert_to_tensor(
  282. data_maj[np.random.randint(len(data_maj), size=self.gen)]
  283. )