NextConvGeN.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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 library.timing import timing
  6. from keras.layers import Dense, Input, Multiply, Flatten, Conv1D, Reshape
  7. from keras.models import Model
  8. from keras import backend as K
  9. from tqdm import tqdm
  10. import tensorflow as tf
  11. from tensorflow.keras.optimizers import Adam
  12. from tensorflow.keras.layers import Lambda
  13. from sklearn.utils import shuffle
  14. from library.NNSearch import NNSearch, randomIndices
  15. import warnings
  16. warnings.filterwarnings("ignore")
  17. def repeat(x, times):
  18. return [x for _i in range(times)]
  19. def create01Labels(totalSize, sizeFirstHalf):
  20. labels = repeat(np.array([1,0]), sizeFirstHalf)
  21. labels.extend(repeat(np.array([0,1]), totalSize - sizeFirstHalf))
  22. return np.array(labels)
  23. class NextConvGeN(GanBaseClass):
  24. """
  25. This is the ConvGeN class. ConvGeN is a synthetic point generator for imbalanced datasets.
  26. """
  27. def __init__(self, n_feat, neb=5, gen=None, neb_epochs=10, fdc=None, maj_proximal=False, debug=False):
  28. self.isTrained = False
  29. self.n_feat = n_feat
  30. self.neb = neb
  31. self.nebInitial = neb
  32. self.genInitial = gen
  33. self.gen = gen if gen is not None else self.neb
  34. self.neb_epochs = neb_epochs
  35. self.loss_history = None
  36. self.debug = debug
  37. self.minSetSize = 0
  38. self.conv_sample_generator = None
  39. self.maj_min_discriminator = None
  40. self.maj_proximal = maj_proximal
  41. self.cg = None
  42. self.canPredict = True
  43. self.fdc = fdc
  44. self.lastProgress = (-1,-1,-1)
  45. self.timing = { n: timing(n) for n in [
  46. "Train", "BMB", "NbhSearch", "NBH", "GenSamples", "Fit", "FixType"
  47. ] }
  48. if self.neb is not None and self.gen is not None and self.neb > self.gen:
  49. raise ValueError(f"Expected neb <= gen but got neb={neb} and gen={gen}.")
  50. def reset(self, data):
  51. """
  52. Creates the network.
  53. *dataSet* is a instance of /library.dataset.DataSet/ or None.
  54. It contains the training dataset.
  55. It is used to determine the neighbourhood size if /neb/ in /__init__/ was None.
  56. """
  57. self.isTrained = False
  58. if data is not None:
  59. nMinoryPoints = data.shape[0]
  60. if self.nebInitial is None:
  61. self.neb = nMinoryPoints
  62. else:
  63. self.neb = min(self.nebInitial, nMinoryPoints)
  64. else:
  65. self.neb = self.nebInitial
  66. self.gen = self.genInitial if self.genInitial is not None else self.neb
  67. ## instanciate generator network and visualize architecture
  68. self.conv_sample_generator = self._conv_sample_gen()
  69. ## instanciate discriminator network and visualize architecture
  70. self.maj_min_discriminator = self._maj_min_disc()
  71. ## instanciate network and visualize architecture
  72. self.cg = self._convGeN(self.conv_sample_generator, self.maj_min_discriminator)
  73. self.lastProgress = (-1,-1,-1)
  74. if self.debug:
  75. print(f"neb={self.neb}, gen={self.gen}")
  76. print(self.conv_sample_generator.summary())
  77. print('\n')
  78. print(self.maj_min_discriminator.summary())
  79. print('\n')
  80. print(self.cg.summary())
  81. print('\n')
  82. def train(self, data, discTrainCount=5, batchSize=32):
  83. """
  84. Trains the Network.
  85. *dataSet* is a instance of /library.dataset.DataSet/. It contains the training dataset.
  86. *discTrainCount* gives the number of extra training for the discriminator for each epoch. (>= 0)
  87. """
  88. if data.shape[0] <= 0:
  89. raise AttributeError("Train: Expected data class 1 to contain at least one point.")
  90. self.timing["Train"].start()
  91. # Store size of minority class. This is needed during point generation.
  92. self.minSetSize = data.shape[0]
  93. normalizedData = data
  94. if self.fdc is not None:
  95. normalizedData = self.fdc.normalize(data)
  96. print(f"|N| = {normalizedData.shape}")
  97. print(f"|D| = {data.shape}")
  98. self.timing["NbhSearch"].start()
  99. # Precalculate neighborhoods
  100. self.nmbMin = NNSearch(self.neb).fit(haystack=normalizedData)
  101. self.nmbMin.basePoints = np.array([ [x.astype(np.float32) for x in p] for p in data])
  102. self.timing["NbhSearch"].stop()
  103. # Do the training.
  104. self._rough_learning(data, discTrainCount, batchSize=batchSize)
  105. # Neighborhood in majority class is no longer needed. So save memory.
  106. self.isTrained = True
  107. self.timing["Train"].stop()
  108. def generateDataPoint(self):
  109. """
  110. Returns one synthetic data point by repeating the stored list.
  111. """
  112. return (self.generateData(1))[0]
  113. def generateData(self, numOfSamples=1):
  114. """
  115. Generates a list of synthetic data-points.
  116. *numOfSamples* is a integer > 0. It gives the number of new generated samples.
  117. """
  118. if not self.isTrained:
  119. raise ValueError("Try to generate data with untrained network.")
  120. ## roughly claculate the upper bound of the synthetic samples to be generated from each neighbourhood
  121. synth_num = (numOfSamples // self.minSetSize) + 1
  122. runs = (synth_num // self.gen) + 1
  123. ## Get a random list of all indices
  124. indices = randomIndices(self.minSetSize)
  125. ## generate all neighborhoods
  126. def neighborhoodGenerator():
  127. for index in indices:
  128. yield self.nmbMin.getNbhPointsOfItem(index)
  129. neighborhoods = (tf.data.Dataset
  130. .from_generator(neighborhoodGenerator, output_types=tf.float32)
  131. .repeat()
  132. )
  133. batch = neighborhoods.take(runs * self.minSetSize).batch(32)
  134. synth_batch = self.conv_sample_generator.predict(batch)
  135. n = 0
  136. synth_set = []
  137. for (x,y) in zip(neighborhoods, synth_batch):
  138. synth_set.extend(self.correct_feature_types(x.numpy(), y))
  139. n += len(y)
  140. if n >= numOfSamples:
  141. break
  142. ## extract the exact number of synthetic samples needed to exactly balance the two classes
  143. return np.array(synth_set[:numOfSamples])
  144. def predictReal(self, data):
  145. """
  146. Uses the discriminator on data.
  147. *data* is a numpy array of shape (n, n_feat) where n is the number of datapoints and n_feat the number of features.
  148. """
  149. prediction = self.maj_min_discriminator.predict(data)
  150. return np.array([x[0] for x in prediction])
  151. # ###############################################################
  152. # Hidden internal functions
  153. # ###############################################################
  154. # Creating the Network: Generator
  155. def _conv_sample_gen(self):
  156. """
  157. The generator network to generate synthetic samples from the convex space
  158. of arbitrary minority neighbourhoods
  159. """
  160. ## takes minority batch as input
  161. min_neb_batch = Input(shape=(self.neb, self.n_feat,))
  162. ## using 1-D convolution, feature dimension remains the same
  163. x = Conv1D(self.n_feat, 3, activation='relu')(min_neb_batch)
  164. ## flatten after convolution
  165. x = Flatten()(x)
  166. ## add dense layer to transform the vector to a convenient dimension
  167. x = Dense(self.neb * self.gen, activation='relu')(x)
  168. ## again, witching to 2-D tensor once we have the convenient shape
  169. x = Reshape((self.neb, self.gen))(x)
  170. ## column wise sum
  171. s = K.sum(x, axis=1)
  172. ## adding a small constant to always ensure the column sums are non zero.
  173. ## if this is not done then during initialization the sum can be zero.
  174. s_non_zero = Lambda(lambda x: x + .000001)(s)
  175. ## reprocals of the approximated column sum
  176. sinv = tf.math.reciprocal(s_non_zero)
  177. ## At this step we ensure that column sum is 1 for every row in x.
  178. ## That means, each column is set of convex co-efficient
  179. x = Multiply()([sinv, x])
  180. ## Now we transpose the matrix. So each row is now a set of convex coefficients
  181. aff=tf.transpose(x[0])
  182. ## We now do matrix multiplication of the affine combinations with the original
  183. ## minority batch taken as input. This generates a convex transformation
  184. ## of the input minority batch
  185. synth=tf.matmul(aff, min_neb_batch)
  186. ## finally we compile the generator with an arbitrary minortiy neighbourhood batch
  187. ## as input and a covex space transformation of the same number of samples as output
  188. model = Model(inputs=min_neb_batch, outputs=synth)
  189. opt = Adam(learning_rate=0.001)
  190. model.compile(loss='mean_squared_logarithmic_error', optimizer=opt)
  191. return model
  192. # Creating the Network: discriminator
  193. def _maj_min_disc(self):
  194. """
  195. the discriminator is trained in two phase:
  196. first phase: while training ConvGeN the discriminator learns to differentiate synthetic
  197. minority samples generated from convex minority data space against
  198. the borderline majority samples
  199. second phase: after the ConvGeN generator learns to create synthetic samples,
  200. it can be used to generate synthetic samples to balance the dataset
  201. and then rettrain the discriminator with the balanced dataset
  202. """
  203. ## takes as input synthetic sample generated as input stacked upon a batch of
  204. ## borderline majority samples
  205. samples = Input(shape=(self.n_feat,))
  206. ## passed through two dense layers
  207. y = Dense(250, activation='relu')(samples)
  208. y = Dense(125, activation='relu')(y)
  209. y = Dense(75, activation='relu')(y)
  210. ## two output nodes. outputs have to be one-hot coded (see labels variable before)
  211. output = Dense(2, activation='sigmoid')(y)
  212. ## compile model
  213. model = Model(inputs=samples, outputs=output)
  214. opt = Adam(learning_rate=0.0001)
  215. model.compile(loss='binary_crossentropy', optimizer=opt)
  216. return model
  217. # Creating the Network: ConvGeN
  218. def _convGeN(self, generator, discriminator):
  219. """
  220. for joining the generator and the discriminator
  221. conv_coeff_generator-> generator network instance
  222. maj_min_discriminator -> discriminator network instance
  223. """
  224. ## by default the discriminator trainability is switched off.
  225. ## Thus training ConvGeN means training the generator network as per previously
  226. ## trained discriminator network.
  227. discriminator.trainable = False
  228. # Shape of data: (batchSize, 2, gen, n_feat)
  229. # Shape of labels: (batchSize, 2 * gen, 2)
  230. ## input receives a neighbourhood minority batch
  231. ## and a proximal majority batch concatenated
  232. batch_data = Input(shape=(2, self.gen, self.n_feat,))
  233. # batch_data: (batchSize, 2, gen, n_feat)
  234. ## extract minority batch
  235. min_batch = Lambda(lambda x: x[:, 0, : ,:], name="SplitForGen")(batch_data)
  236. # min_batch: (batchSize, gen, n_feat)
  237. ## extract majority batch
  238. maj_batch = Lambda(lambda x: x[:, 1, :, :], name="SplitForDisc")(batch_data)
  239. # maj_batch: (batchSize, gen, n_feat)
  240. maj_batch = tf.reshape(maj_batch, (-1, self.n_feat), name="ReshapeForDisc")
  241. # maj_batch: (batchSize * gen, n_feat)
  242. ## pass minority batch into generator to obtain convex space transformation
  243. ## (synthetic samples) of the minority neighbourhood input batch
  244. conv_samples = generator(min_batch)
  245. # conv_batch: (batchSize, gen, n_feat)
  246. conv_samples = tf.reshape(conv_samples, (-1, self.n_feat), name="ReshapeGenOutput")
  247. # conv_batch: (batchSize * gen, n_feat)
  248. ## pass samples into the discriminator to know its decisions
  249. conv_samples = discriminator(conv_samples)
  250. conv_samples = tf.reshape(conv_samples, (-1, self.gen, 2), name="ReshapeGenDiscOutput")
  251. # conv_batch: (batchSize * gen, 2)
  252. maj_batch = discriminator(maj_batch)
  253. maj_batch = tf.reshape(maj_batch, (-1, self.gen, 2), name="ReshapeGenDiscOutput")
  254. # conv_batch: (batchSize * gen, 2)
  255. ## concatenate the decisions
  256. output = tf.concat([conv_samples, maj_batch],axis=1)
  257. # output: (batchSize, 2 * gen, 2)
  258. ## note that, the discriminator will not be traied but will make decisions based
  259. ## on its previous training while using this function
  260. model = Model(inputs=batch_data, outputs=output)
  261. opt = Adam(learning_rate=0.0001)
  262. model.compile(loss='mse', optimizer=opt)
  263. return model
  264. # Training
  265. def _rough_learning(self, data, discTrainCount, batchSize=32):
  266. generator = self.conv_sample_generator
  267. discriminator = self.maj_min_discriminator
  268. convGeN = self.cg
  269. loss_history = [] ## this is for stroring the loss for every run
  270. minSetSize = len(data)
  271. ## Create labels for one neighborhood training.
  272. nLabels = 2 * self.gen
  273. labels = np.array(create01Labels(nLabels, self.gen))
  274. labelsGeN = np.array([labels])
  275. def indexToBatches(min_idx):
  276. self.timing["NBH"].start()
  277. ## generate minority neighbourhood batch for every minority class sampls by index
  278. min_batch_indices = self.nmbMin.neighbourhoodOfItem(min_idx)
  279. min_batch = self.nmbMin.getPointsFromIndices(min_batch_indices)
  280. ## generate random proximal majority batch
  281. maj_batch = self._BMB(min_batch_indices)
  282. self.timing["NBH"].stop()
  283. return (min_batch, maj_batch)
  284. def createSamples(min_idx):
  285. min_batch, maj_batch = indexToBatches(min_idx)
  286. self.timing["GenSamples"].start()
  287. ## generate synthetic samples from convex space
  288. ## of minority neighbourhood batch using generator
  289. conv_samples = generator.predict(np.array([min_batch]), batch_size=self.neb)
  290. conv_samples = tf.reshape(conv_samples, shape=(self.gen, self.n_feat))
  291. self.timing["GenSamples"].stop()
  292. self.timing["FixType"].start()
  293. ## Fix feature types
  294. conv_samples = self.correct_feature_types(min_batch.numpy(), conv_samples)
  295. self.timing["FixType"].stop()
  296. ## concatenate them with the majority batch
  297. conv_samples = [conv_samples, maj_batch]
  298. return conv_samples
  299. def genSamplesForDisc():
  300. for min_idx in range(minSetSize):
  301. yield createSamples(min_idx)
  302. def genSamplesForGeN():
  303. for min_idx in range(minSetSize):
  304. yield indexToBatches(min_idx)
  305. def unbatch(rows):
  306. def fn():
  307. for row in rows:
  308. for part in row:
  309. for x in part:
  310. yield x
  311. return fn
  312. def genLabels():
  313. for min_idx in range(minSetSize):
  314. for x in labels:
  315. yield x
  316. padd = np.zeros((self.gen - self.neb, self.n_feat))
  317. discTrainCount = 1 + max(0, discTrainCount)
  318. for neb_epoch_count in range(self.neb_epochs):
  319. self.progressBar([(neb_epoch_count + 1) / self.neb_epochs, 0.5, 0.5])
  320. ## Training of the discriminator.
  321. #
  322. # Get all neighborhoods and synthetic points as data stream.
  323. a = tf.data.Dataset.from_generator(genSamplesForDisc, output_types=tf.float32).repeat().take(discTrainCount * self.minSetSize)
  324. a = tf.data.Dataset.from_generator(unbatch(a), output_types=tf.float32)
  325. # Get all labels as data stream.
  326. b = tf.data.Dataset.from_tensor_slices(labels).repeat()
  327. # Zip data and matching labels together for training.
  328. samples = tf.data.Dataset.zip((a, b)).batch(batchSize * 2 * self.gen)
  329. # train the discriminator with the concatenated samples and the one-hot encoded labels
  330. self.timing["Fit"].start()
  331. discriminator.trainable = True
  332. discriminator.fit(x=samples, verbose=0)
  333. discriminator.trainable = False
  334. self.timing["Fit"].stop()
  335. ## use the complete network to make the generator learn on the decisions
  336. ## made by the previous discriminator training
  337. #
  338. # Get all neighborhoods as data stream.
  339. a = (tf.data.Dataset
  340. .from_generator(genSamplesForGeN, output_types=tf.float32)
  341. .map(lambda x: [[tf.concat([x[0], padd], axis=0), x[1]]]))
  342. # Get all labels as data stream.
  343. b = tf.data.Dataset.from_tensor_slices(labelsGeN).repeat()
  344. # Zip data and matching labels together for training.
  345. samples = tf.data.Dataset.zip((a, b)).batch(batchSize)
  346. # Train with the data stream. Store the loss for later usage.
  347. gen_loss_history = convGeN.fit(samples, verbose=0, batch_size=batchSize)
  348. loss_history.append(gen_loss_history.history['loss'])
  349. ## When done: print some statistics.
  350. if self.debug:
  351. run_range = range(1, len(loss_history) + 1)
  352. plt.rcParams["figure.figsize"] = (16,10)
  353. plt.xticks(fontsize=20)
  354. plt.yticks(fontsize=20)
  355. plt.xlabel('runs', fontsize=25)
  356. plt.ylabel('loss', fontsize=25)
  357. plt.title('Rough learning loss for discriminator', fontsize=25)
  358. plt.plot(run_range, loss_history)
  359. plt.show()
  360. ## When done: print some statistics.
  361. self.loss_history = loss_history
  362. def _BMB(self, min_idxs):
  363. ## Generate a borderline majority batch
  364. ## data_maj -> majority class data
  365. ## min_idxs -> indices of points in minority class
  366. ## gen -> convex combinations generated from each neighbourhood
  367. self.timing["BMB"].start()
  368. indices = randomIndices(self.minSetSize, outputSize=self.gen, indicesToIgnore=min_idxs)
  369. r = self.nmbMin.basePoints[indices]
  370. self.timing["BMB"].stop()
  371. return r
  372. def retrainDiscriminitor(self, data, labels):
  373. self.maj_min_discriminator.trainable = True
  374. labels = np.array([ [x, 1 - x] for x in labels])
  375. self.maj_min_discriminator.fit(x=data, y=labels, batch_size=20, epochs=self.neb_epochs)
  376. self.maj_min_discriminator.trainable = False
  377. def progressBar(self, x):
  378. x = [int(v * 10) for v in x]
  379. if True not in [self.lastProgress[i] != x[i] for i in range(len(self.lastProgress))]:
  380. return
  381. def bar(v):
  382. r = ""
  383. for n in range(10):
  384. if n > v:
  385. r += " "
  386. else:
  387. r += "="
  388. return r
  389. s = [bar(v) for v in x]
  390. print(f"[{s[0]}] [{s[1]}] [{s[2]}]", end="\r")
  391. def correct_feature_types(self, batch, synth_batch):
  392. if self.fdc is None:
  393. return synth_batch
  394. def bestMatchOf(referenceValues, value):
  395. if referenceValues is not None:
  396. best = referenceValues[0]
  397. d = abs(best - value)
  398. for x in referenceValues:
  399. dx = abs(x - value)
  400. if dx < d:
  401. best = x
  402. d = dx
  403. return best
  404. else:
  405. return value
  406. def correctVector(referenceLists, v):
  407. return np.array([bestMatchOf(referenceLists[i], v[i]) for i in range(len(v))])
  408. referenceLists = [None for _ in range(self.n_feat)]
  409. for i in (self.fdc.nom_list or []):
  410. referenceLists[i] = list(set(list(batch[:, i])))
  411. for i in (self.fdc.ord_list or []):
  412. referenceLists[i] = list(set(list(batch[:, i])))
  413. # print(batch.shape, synth_batch.shape)
  414. return Lambda(lambda x: np.array([correctVector(referenceLists, y) for y in x]))(synth_batch)