convGAN2.py 15 KB

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