NextConvGeN.py 17 KB

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