convGAN.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. import os
  2. import math
  3. import random
  4. import numpy as np
  5. import pandas as pd
  6. import matplotlib.pyplot as plt
  7. import random
  8. from scipy import ndarray
  9. from sklearn.neighbors import NearestNeighbors
  10. from sklearn.decomposition import PCA
  11. from sklearn.metrics import confusion_matrix
  12. from sklearn.metrics import f1_score
  13. from sklearn.metrics import cohen_kappa_score
  14. from sklearn.metrics import precision_score
  15. from sklearn.metrics import recall_score
  16. from collections import Counter
  17. from imblearn.datasets import fetch_datasets
  18. from sklearn.preprocessing import StandardScaler
  19. import keras
  20. from keras.layers import Dense, Dropout, Input
  21. from keras.models import Model,Sequential
  22. from tqdm import tqdm
  23. from keras.layers.advanced_activations import LeakyReLU
  24. from tensorflow.keras.optimizers import Adam
  25. from keras import losses
  26. from keras import backend as K
  27. import tensorflow as tf
  28. import warnings
  29. warnings.filterwarnings("ignore")
  30. from sklearn.neighbors import KNeighborsClassifier
  31. from sklearn.ensemble import RandomForestClassifier
  32. from sklearn.ensemble import GradientBoostingClassifier
  33. from numpy.random import seed
  34. seed_num=1
  35. seed(seed_num)
  36. tf.random.set_seed(seed_num)
  37. from library.interfaces import GanBaseClass
  38. from library.dataset import DataSet
  39. from sklearn.utils import shuffle
  40. ## Import dataset
  41. data = fetch_datasets()['yeast_me2']
  42. ## Creating label and feature matrices
  43. labels_x=data.target ## labels of the data
  44. labels_x.shape
  45. features_x=data.data ## features of the data
  46. features_x.shape
  47. # Until now we have obtained the data. We divided it into training and test sets. we separated obtained seperate variables for the majority and miority classes and their labels for both sets.
  48. class ConvGAN(GanBaseClass):
  49. """
  50. This is a toy example of a GAN.
  51. It repeats the first point of the training-data-set.
  52. """
  53. def __init__(self, neb, gen, debug=True):
  54. self.isTrained = False
  55. self.neb = neb
  56. self.gen = gen
  57. self.loss_history = None
  58. self.debug = debug
  59. self.dataSet = None
  60. def reset(self):
  61. """
  62. Resets the trained GAN to an random state.
  63. """
  64. self.isTrained = False
  65. ## instanciate generator network and visualize architecture
  66. self.conv_sample_generator = conv_sample_gen()
  67. ## instanciate discriminator network and visualize architecture
  68. self.maj_min_discriminator = maj_min_disc()
  69. ## instanciate network and visualize architecture
  70. self.cg = convGAN(self.conv_sample_generator, self.maj_min_discriminator)
  71. def train(self, dataSet, neb_epochs=5):
  72. """
  73. Trains the GAN.
  74. It stores the data points in the training data set and mark as trained.
  75. *dataSet* is a instance of /library.dataset.DataSet/. It contains the training dataset.
  76. We are only interested in the first *maxListSize* points in class 1.
  77. """
  78. if dataSet.data1.shape[0] <= 0:
  79. raise AttributeError("Train: Expected data class 1 to contain at least one point.")
  80. self.dataSet = dataSet
  81. self._rough_learning(neb_epochs, dataSet.data1, dataSet.data0)
  82. self.isTrained = True
  83. def generateDataPoint(self):
  84. """
  85. Returns one synthetic data point by repeating the stored list.
  86. """
  87. return (self.generateData(1))[0]
  88. def generateData(self, numOfSamples=1):
  89. """
  90. Generates a list of synthetic data-points.
  91. *numOfSamples* is a integer > 0. It gives the number of new generated samples.
  92. """
  93. if not self.isTrained:
  94. raise ValueError("Try to generate data with untrained Re.")
  95. data_min = self.dataSet.data1
  96. data_maj = self.dataSet.data0
  97. neb = self.neb
  98. # ---
  99. ## roughly claculate the upper bound of the synthetic samples to be generated from each neighbourhood
  100. synth_num = (numOfSamples // len(data_min)) + 1
  101. ## generate synth_num synthetic samples from each minority neighbourhood
  102. synth_set=[]
  103. for i in range(len(data_min)):
  104. synth_set.extend(self.generate_data_for_min_point(data_min, i, synth_num))
  105. synth_set = synth_set[:numOfSamples] ## extract the exact number of synthetic samples needed to exactly balance the two classes
  106. return np.array(synth_set)
  107. # ###############################################################
  108. # Hidden internal functions
  109. # ###############################################################
  110. def _generate_data_for_min_point(self, data_min, index, synth_num, generator):
  111. """
  112. generate synth_num synthetic points for a particular minoity sample
  113. synth_num -> required number of data points that can be generated from a neighbourhood
  114. data_min -> minority class data
  115. neb -> oversampling neighbourhood
  116. index -> index of the minority sample in a training data whose neighbourhood we want to obtain
  117. """
  118. runs = int(synth_num / self.neb) + 1
  119. synth_set = []
  120. for run in range(runs):
  121. batch = self._NMB_guided(data_min, index)
  122. synth_batch = self.conv_sample_generator.predict(batch)
  123. for x in synth_batch:
  124. synth_set.append(x)
  125. return synth_set[:synth_num]
  126. # Training
  127. def _rough_learning(self, neb_epochs, data_min, data_maj):
  128. generator = self.conv_sample_generator
  129. discriminator = self.maj_min_discriminator
  130. GAN = self.cg
  131. loss_history=[] ## this is for stroring the loss for every run
  132. min_idx = 0
  133. neb_epoch_count = 1
  134. labels = []
  135. for i in range(2 * self.gen):
  136. if i < gen:
  137. labels.append(np.array([1,0]))
  138. else:
  139. labels.append(np.array([0,1]))
  140. labels = np.array(labels)
  141. labels = tf.convert_to_tensor(labels)
  142. for step in range(neb_epochs * len(data_min)):
  143. min_batch = self._NMB_guided(data_min, min_idx) ## generate minority neighbourhood batch for every minority class sampls by index
  144. min_idx = min_idx + 1
  145. maj_batch = self._BMB(data_min, data_maj) ## generate random proximal majority batch
  146. conv_samples = generator.predict(min_batch) ## generate synthetic samples from convex space of minority neighbourhood batch using generator
  147. concat_sample = tf.concat([conv_samples, maj_batch], axis=0) ## concatenate them with the majority batch
  148. discriminator.trainable = True ## switch on discriminator training
  149. discriminator.fit(x=concat_sample, y=labels, verbose=0) ## train the discriminator with the concatenated samples and the one-hot encoded labels
  150. discriminator.trainable = False ## switch off the discriminator training again
  151. gan_loss_history = GAN.fit(concat_sample, y=labels, verbose=0) ## use the GAN to make the generator learn on the decisions made by the previous discriminator training
  152. loss_history.append(gan_loss_history.history['loss']) ## store the loss for the step
  153. if self.debug and ((step + 1) % 10 == 0):
  154. print(f"{step + 1} neighbourhood batches trained; running neighbourhood epoch {neb_epoch_count}")
  155. if min_idx == len(data_min) - 1:
  156. if self.debug:
  157. print(f"Neighbourhood epoch {neb_epoch_count} complete")
  158. neb_epoch_count = neb_epoch_count + 1
  159. min_idx = 0
  160. if self.debug:
  161. run_range = range(1, len(loss_history) + 1)
  162. plt.rcParams["figure.figsize"] = (16,10)
  163. plt.xticks(fontsize=20)
  164. plt.yticks(fontsize=20)
  165. plt.xlabel('runs', fontsize=25)
  166. plt.ylabel('loss', fontsize=25)
  167. plt.title('Rough learning loss for discriminator', fontsize=25)
  168. plt.plot(run_range, loss_history)
  169. plt.show()
  170. self.conv_sample_generator = generator
  171. self.maj_min_discriminator = discriminator
  172. self.cg = GAN
  173. self.loss_history = loss_history
  174. ## convGAN
  175. def _BMB(self, data_min, data_maj):
  176. ## Generate a borderline majority batch
  177. ## data_min -> minority class data
  178. ## data_maj -> majority class data
  179. ## neb -> oversampling neighbourhood
  180. ## gen -> convex combinations generated from each neighbourhood
  181. neigh = NearestNeighbors(self.neb)
  182. n_feat = data_min.shape[1]
  183. neigh.fit(data_maj)
  184. bmbi = [
  185. neigh.kneighbors([data_min[i]], self.neb, return_distance=False)
  186. for i in range(len(data_min))
  187. ]
  188. bmbi = np.unique(np.array(bmbi).flatten())
  189. bmbi = shuffle(bmbi)
  190. return tf.convert_to_tensor(
  191. data_maj[np.random.randint(len(data_maj), size=self.gen)]
  192. )
  193. def _NMB_guided(self, data_min, index):
  194. ## generate a minority neighbourhood batch for a particular minority sample
  195. ## we need this for minority data generation
  196. ## we will generate synthetic samples for each training data neighbourhood
  197. ## index -> index of the minority sample in a training data whose neighbourhood we want to obtain
  198. ## data_min -> minority class data
  199. ## neb -> oversampling neighbourhood
  200. neigh = NearestNeighbors(self.neb)
  201. neigh.fit(data_min)
  202. nmbi = neigh.kneighbors([data_min[index]], self.neb, return_distance=False)
  203. nmbi = shuffle(nmbi)
  204. nmb = data_min[nmbi]
  205. nmb = tf.convert_to_tensor(nmb[0])
  206. return (nmb)
  207. def conv_sample_gen():
  208. ## the generator network to generate synthetic samples from the convex space of arbitrary minority neighbourhoods
  209. min_neb_batch = keras.layers.Input(shape=(n_feat,)) ## takes minority batch as input
  210. x=tf.reshape(min_neb_batch, (1,neb,n_feat), name=None) ## reshaping the 2D tensor to 3D for using 1-D convolution, otherwise 1-D convolution won't work.
  211. x= keras.layers.Conv1D(n_feat, 3, activation='relu')(x) ## using 1-D convolution, feature dimension remains the same
  212. x= keras.layers.Flatten()(x) ## flatten after convolution
  213. x= keras.layers.Dense(neb*gen, activation='relu')(x) ## add dense layer to transform the vector to a convenient dimension
  214. x= keras.layers.Reshape((neb,gen))(x)## again, witching to 2-D tensor once we have the convenient shape
  215. s=K.sum(x,axis=1) ## row wise sum
  216. s_non_zero=tf.keras.layers.Lambda(lambda x: x+.000001)(s) ## adding a small constant to always ensure the row sums are non zero. if this is not done then during initialization the sum can be zero
  217. sinv=tf.math.reciprocal(s_non_zero) ## reprocals of the approximated row sum
  218. x=keras.layers.Multiply()([sinv,x]) ## At this step we ensure that row sum is 1 for every row in x. That means, each row is set of convex co-efficient
  219. aff=tf.transpose(x[0]) ## Now we transpose the matrix. So each column is now a set of convex coefficients
  220. synth=tf.matmul(aff,min_neb_batch) ## We now do matrix multiplication of the affine combinations with the original minority batch taken as input. This generates a convex transformation of the input minority batch
  221. model = Model(inputs=min_neb_batch, outputs=synth) ## finally we compile the generator with an arbitrary minortiy neighbourhood batch as input and a covex space transformation of the same number of samples as output
  222. opt = Adam(learning_rate=0.001)
  223. model.compile(loss='mean_squared_logarithmic_error', optimizer=opt)
  224. return model
  225. def maj_min_disc():
  226. ## the discriminator is trained intwo phase:
  227. ## first phase: while training GAN the discriminator learns to differentiate synthetic minority samples generated from convex minority data space against the borderline majority samples
  228. ## second phase: after the GAN generator learns to create synthetic samples, it can be used to generate synthetic samples to balance the dataset
  229. ## and then rettrain the discriminator with the balanced dataset
  230. samples=keras.layers.Input(shape=(n_feat,)) ## takes as input synthetic sample generated as input stacked upon a batch of borderline majority samples
  231. y= keras.layers.Dense(250, activation='relu')(samples) ## passed through two dense layers
  232. y= keras.layers.Dense(125, activation='relu')(y)
  233. output= keras.layers.Dense(2, activation='sigmoid')(y) ## two output nodes. outputs have to be one-hot coded (see labels variable before)
  234. model = Model(inputs=samples, outputs=output) ## compile model
  235. opt = Adam(learning_rate=0.0001)
  236. model.compile(loss='binary_crossentropy', optimizer=opt)
  237. return model
  238. def convGAN(generator,discriminator):
  239. ## for joining the generator and the discriminator
  240. ## conv_coeff_generator-> generator network instance
  241. ## maj_min_discriminator -> discriminator network instance
  242. maj_min_disc.trainable=False ## by default the discriminator trainability is switched off.
  243. ## Thus training the GAN means training the generator network as per previously trained discriminator network.
  244. batch_data = keras.layers.Input(shape=(n_feat,)) ## input receives a neighbourhood minority batch and a proximal majority batch concatenated
  245. min_batch = tf.keras.layers.Lambda(lambda x: x[:neb])(batch_data) ## extract minority batch
  246. maj_batch = tf.keras.layers.Lambda(lambda x: x[neb:])(batch_data) ## extract majority batch
  247. conv_samples=generator(min_batch) ## pass minority batch into generator to obtain convex space transformation (synthetic samples) of the minority neighbourhood input batch
  248. new_samples=tf.concat([conv_samples,maj_batch],axis=0) ## concatenate the synthetic samples with the majority samples
  249. output=discriminator(new_samples) ## pass the concatenated vector into the discriminator to know its decisions
  250. ## note that, the discriminator will not be traied but will make decisions based on its previous training while using this function
  251. model = Model(inputs=batch_data, outputs=output)
  252. opt = Adam(learning_rate=0.0001)
  253. model.compile(loss='mse', optimizer=opt)
  254. return model
  255. ## this is the main training process where the GAn learns to generate appropriate samples from the convex space
  256. ## this is the first training phase for the discriminator and the only training phase for the generator.
  257. def rough_learning_predictions(discriminator,test_data_numpy,test_labels_numpy):
  258. ## after the first phase of training the discriminator can be used for classification
  259. ## it already learns to differentiate the convex minority points with majority points during the first training phase
  260. y_pred_2d=discriminator.predict(tf.convert_to_tensor(test_data_numpy))
  261. ## discretisation of the labels
  262. y_pred=np.digitize(y_pred_2d[:,0], [.5])
  263. ## prediction shows a model with good recall and less precision
  264. c=confusion_matrix(test_labels_numpy, y_pred)
  265. f=f1_score(test_labels_numpy, y_pred)
  266. pr=precision_score(test_labels_numpy, y_pred)
  267. rc=recall_score(test_labels_numpy, y_pred)
  268. k=cohen_kappa_score(test_labels_numpy, y_pred)
  269. print('Rough learning confusion matrix:', c)
  270. print('Rough learning f1 score', f)
  271. print('Rough learning precision score', pr)
  272. print('Rough learning recall score', rc)
  273. print('Rough learning kappa score', k)
  274. return c,f,pr,rc,k
  275. def generate_synthetic_data(gan, data_min, data_maj):
  276. ## roughly claculate the upper bound of the synthetic samples to be generated from each neighbourhood
  277. synth_num=((len(data_maj)-len(data_min))//len(data_min))+1
  278. ## generate synth_num synthetic samples from each minority neighbourhood
  279. synth_set = gan.generateData(synth_num)
  280. ovs_min_class=np.concatenate((data_min,synth_set),axis=0)
  281. ovs_training_dataset=np.concatenate((ovs_min_class,data_maj),axis=0)
  282. ovs_pca_labels=np.concatenate((np.zeros(len(data_min)),np.zeros(len(synth_set))+1,np.zeros(len(data_maj))+2))
  283. ovs_training_labels=np.concatenate((np.zeros(len(ovs_min_class))+1,np.zeros(len(data_maj))+0))
  284. ovs_training_labels_oh=[]
  285. for i in range(len(ovs_training_dataset)):
  286. if i<len(ovs_min_class):
  287. ovs_training_labels_oh.append(np.array([1,0]))
  288. else:
  289. ovs_training_labels_oh.append(np.array([0,1]))
  290. ovs_training_labels_oh=np.array(ovs_training_labels_oh)
  291. ovs_training_labels_oh=tf.convert_to_tensor(ovs_training_labels_oh)
  292. ## PCA visualization of the synthetic sata
  293. ## observe how the minority samples from convex space have optimal variance and avoids overlap with the majority
  294. pca = PCA(n_components=2)
  295. pca.fit(ovs_training_dataset)
  296. data_pca= pca.transform(ovs_training_dataset)
  297. ## plot PCA
  298. plt.rcParams["figure.figsize"] = (12,12)
  299. colors=['r', 'b', 'g']
  300. plt.xticks(fontsize=20)
  301. plt.yticks(fontsize=20)
  302. plt.xlabel('PCA1',fontsize=25)
  303. plt.ylabel('PCA2', fontsize=25)
  304. plt.title('PCA plot of oversampled data',fontsize=25)
  305. classes = ['minority', 'synthetic minority', 'majority']
  306. scatter=plt.scatter(data_pca[:,0], data_pca[:,1], c=ovs_pca_labels, cmap='Set1')
  307. plt.legend(handles=scatter.legend_elements()[0], labels=classes, fontsize=20)
  308. plt.show()
  309. return ovs_training_dataset, ovs_pca_labels, ovs_training_labels_oh
  310. def final_learning(discriminator, ovs_training_dataset, ovs_training_labels_oh, test_data_numpy, test_labels_numpy, num_epochs):
  311. print('\n')
  312. print('Final round training of the discrminator as a majority-minority classifier')
  313. print('\n')
  314. ## second phase training of the discriminator with balanced data
  315. history_second_learning=discriminator.fit(x=ovs_training_dataset,y=ovs_training_labels_oh, batch_size=20, epochs=num_epochs)
  316. ## loss of the second phase learning smoothly decreses
  317. ## this is because now the data is fixed and diverse convex combinations are no longer fed into the discriminator at every training step
  318. run_range=range(1,num_epochs+1)
  319. plt.rcParams["figure.figsize"] = (16,10)
  320. plt.xticks(fontsize=20)
  321. plt.yticks(fontsize=20)
  322. plt.xlabel('runs',fontsize=25)
  323. plt.ylabel('loss', fontsize=25)
  324. plt.title('Final learning loss for discriminator', fontsize=25)
  325. plt.plot(run_range, history_second_learning.history['loss'])
  326. plt.show()
  327. ## finally after second phase training the discriminator classifier has a more balanced performance
  328. ## meaning better F1-Score
  329. ## the recall decreases but the precision improves
  330. print('\n')
  331. y_pred_2d=discriminator.predict(tf.convert_to_tensor(test_data_numpy))
  332. y_pred=np.digitize(y_pred_2d[:,0], [.5])
  333. c=confusion_matrix(test_labels_numpy, y_pred)
  334. f=f1_score(test_labels_numpy, y_pred)
  335. pr=precision_score(test_labels_numpy, y_pred)
  336. rc=recall_score(test_labels_numpy, y_pred)
  337. k=cohen_kappa_score(test_labels_numpy, y_pred)
  338. print('Final learning confusion matrix:', c)
  339. print('Final learning f1 score', f)
  340. print('Final learning precision score', pr)
  341. print('Final learning recall score', rc)
  342. print('Final learning kappa score', k)
  343. return c,f,pr,rc,k
  344. def convGAN_train_end_to_end(training_data,training_labels,test_data,test_labels, neb, gen, neb_epochs,epochs_retrain_disc):
  345. ##minority class
  346. data_min=training_data[np.where(training_labels == 1)[0]]
  347. ##majority class
  348. data_maj=training_data[np.where(training_labels == 0)[0]]
  349. dataSet = DataSet(data0=data_maj, data1=data_min)
  350. gan = ConvGAN(neb, gen)
  351. gan.reset()
  352. ## instanciate generator network and visualize architecture
  353. conv_sample_generator = gan.conv_sample_generator
  354. print(conv_sample_generator.summary())
  355. print('\n')
  356. ## instanciate discriminator network and visualize architecture
  357. maj_min_discriminator = gan.maj_min_discriminator
  358. print(maj_min_discriminator.summary())
  359. print('\n')
  360. ## instanciate network and visualize architecture
  361. cg = gan.cg
  362. print(cg.summary())
  363. print('\n')
  364. print('Training the GAN, first round training of the discrminator as a majority-minority classifier')
  365. print('\n')
  366. ## train gan generator ## rough_train_discriminator
  367. gan.train(dataSet, neb_epochs)
  368. print('\n')
  369. ## rough learning results
  370. c_r,f_r,pr_r,rc_r,k_r = rough_learning_predictions(gan.maj_min_discriminator_r, test_data, test_labels)
  371. print('\n')
  372. ## generate synthetic data
  373. ovs_training_dataset, ovs_pca_labels, ovs_training_labels_oh = generate_synthetic_data(gan, data_min, data_maj)
  374. print('\n')
  375. ## final training results
  376. c,f,pr,rc,k=final_learning(gan.maj_min_discriminator, ovs_training_dataset, ovs_training_labels_oh, test_data, test_labels, epochs_retrain_disc)
  377. return ((c_r,f_r,pr_r,rc_r,k_r),(c,f,pr,rc,k))
  378. def unison_shuffled_copies(a, b,seed_perm):
  379. 'Shuffling the feature matrix along with the labels with same order'
  380. np.random.seed(seed_perm)##change seed 1,2,3,4,5
  381. assert len(a) == len(b)
  382. p = np.random.permutation(len(a))
  383. return a[p], b[p]
  384. ## specify parameters
  385. neb=gen=5 ##neb=gen required
  386. neb_epochs=10
  387. epochs_retrain_disc=50
  388. n_feat=len(features_x[1]) ## number of features
  389. ## Training
  390. np.random.seed(42)
  391. strata=5
  392. results=[]
  393. for seed_perm in range(strata):
  394. features_x,labels_x=unison_shuffled_copies(features_x,labels_x,seed_perm)
  395. ### Extracting all features and labels
  396. print('Extracting all features and labels for seed:'+ str(seed_perm)+'\n')
  397. ## Dividing data into training and testing datasets for 10-fold CV
  398. print('Dividing data into training and testing datasets for 10-fold CV for seed:'+ str(seed_perm)+'\n')
  399. label_1=list(np.where(labels_x == 1)[0])
  400. features_1=features_x[label_1]
  401. label_0=list(np.where(labels_x != 1)[0])
  402. features_0=features_x[label_0]
  403. a=len(features_1)//5
  404. b=len(features_0)//5
  405. fold_1_min=features_1[0:a]
  406. fold_1_maj=features_0[0:b]
  407. fold_1_tst=np.concatenate((fold_1_min,fold_1_maj))
  408. lab_1_tst=np.concatenate((np.zeros(len(fold_1_min))+1, np.zeros(len(fold_1_maj))))
  409. fold_2_min=features_1[a:2*a]
  410. fold_2_maj=features_0[b:2*b]
  411. fold_2_tst=np.concatenate((fold_2_min,fold_2_maj))
  412. lab_2_tst=np.concatenate((np.zeros(len(fold_1_min))+1, np.zeros(len(fold_1_maj))))
  413. fold_3_min=features_1[2*a:3*a]
  414. fold_3_maj=features_0[2*b:3*b]
  415. fold_3_tst=np.concatenate((fold_3_min,fold_3_maj))
  416. lab_3_tst=np.concatenate((np.zeros(len(fold_1_min))+1, np.zeros(len(fold_1_maj))))
  417. fold_4_min=features_1[3*a:4*a]
  418. fold_4_maj=features_0[3*b:4*b]
  419. fold_4_tst=np.concatenate((fold_4_min,fold_4_maj))
  420. lab_4_tst=np.concatenate((np.zeros(len(fold_1_min))+1, np.zeros(len(fold_1_maj))))
  421. fold_5_min=features_1[4*a:]
  422. fold_5_maj=features_0[4*b:]
  423. fold_5_tst=np.concatenate((fold_5_min,fold_5_maj))
  424. lab_5_tst=np.concatenate((np.zeros(len(fold_5_min))+1, np.zeros(len(fold_5_maj))))
  425. fold_1_trn=np.concatenate((fold_2_min,fold_3_min,fold_4_min,fold_5_min, fold_2_maj,fold_3_maj,fold_4_maj,fold_5_maj))
  426. lab_1_trn=np.concatenate((np.zeros(3*a+len(fold_5_min))+1,np.zeros(3*b+len(fold_5_maj))))
  427. fold_2_trn=np.concatenate((fold_1_min,fold_3_min,fold_4_min,fold_5_min,fold_1_maj,fold_3_maj,fold_4_maj,fold_5_maj))
  428. lab_2_trn=np.concatenate((np.zeros(3*a+len(fold_5_min))+1,np.zeros(3*b+len(fold_5_maj))))
  429. fold_3_trn=np.concatenate((fold_2_min,fold_1_min,fold_4_min,fold_5_min,fold_2_maj,fold_1_maj,fold_4_maj,fold_5_maj))
  430. lab_3_trn=np.concatenate((np.zeros(3*a+len(fold_5_min))+1,np.zeros(3*b+len(fold_5_maj))))
  431. fold_4_trn=np.concatenate((fold_2_min,fold_3_min,fold_1_min,fold_5_min,fold_2_maj,fold_3_maj,fold_1_maj,fold_5_maj))
  432. lab_4_trn=np.concatenate((np.zeros(3*a+len(fold_5_min))+1,np.zeros(3*b+len(fold_5_maj))))
  433. fold_5_trn=np.concatenate((fold_2_min,fold_3_min,fold_4_min,fold_1_min,fold_2_maj,fold_3_maj,fold_4_maj,fold_1_maj))
  434. lab_5_trn=np.concatenate((np.zeros(4*a)+1,np.zeros(4*b)))
  435. training_folds_feats=[fold_1_trn,fold_2_trn,fold_3_trn,fold_4_trn,fold_5_trn]
  436. testing_folds_feats=[fold_1_tst,fold_2_tst,fold_3_tst,fold_4_tst,fold_5_tst]
  437. training_folds_labels=[lab_1_trn,lab_2_trn,lab_3_trn,lab_4_trn,lab_5_trn]
  438. testing_folds_labels=[lab_1_tst,lab_2_tst,lab_3_tst,lab_4_tst,lab_5_tst]
  439. for i in range(5):
  440. print('\n')
  441. print('Executing fold: '+str(i+1))
  442. print('\n')
  443. r1,r2=convGAN_train_end_to_end(training_folds_feats[i],training_folds_labels[i],testing_folds_feats[i],testing_folds_labels[i], neb, gen, neb_epochs, epochs_retrain_disc)
  444. results.append(np.array([list(r1[1:]),list(r2[1:])]))
  445. results=np.array(results)
  446. ## Benchmark
  447. mean_rough=np.mean(results[:,0], axis=0)
  448. data_r={'F1-Score_r':[mean_rough[0]], 'Precision_r' : [mean_rough[1]], 'Recall_r' : [mean_rough[2]], 'Kappa_r': [mean_rough[3]]}
  449. df_r=pd.DataFrame(data=data_r)
  450. print('Rough training results:')
  451. print('\n')
  452. print(df_r)
  453. mean_final=np.mean(results[:,1], axis=0)
  454. data_f={'F1-Score_f':[mean_final[0]], 'Precision_f' : [mean_final[1]], 'Recall_f' : [mean_final[2]], 'Kappa_f': [mean_final[3]]}
  455. df_f=pd.DataFrame(data=data_f)
  456. print('Final training results:')
  457. print('\n')
  458. print(df_f)