| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503 |
- import numpy as np
- import matplotlib.pyplot as plt
- from library.interfaces import GanBaseClass
- from library.dataset import DataSet
- from library.timing import timing
- from keras.layers import Dense, Input, Multiply, Flatten, Conv1D, Reshape
- from keras.models import Model
- from keras import backend as K
- from tqdm import tqdm
- import tensorflow as tf
- from tensorflow.keras.optimizers import Adam
- from tensorflow.keras.layers import Lambda
- from sklearn.utils import shuffle
- from library.NNSearch import NNSearch
- import warnings
- warnings.filterwarnings("ignore")
- def repeat(x, times):
- return [x for _i in range(times)]
- def create01Labels(totalSize, sizeFirstHalf):
- labels = repeat(np.array([1,0]), sizeFirstHalf)
- labels.extend(repeat(np.array([0,1]), totalSize - sizeFirstHalf))
- return np.array(labels)
- class NextConvGeN(GanBaseClass):
- """
- This is the ConvGeN class. ConvGeN is a synthetic point generator for imbalanced datasets.
- """
- def __init__(self, n_feat, neb=5, gen=None, neb_epochs=10, fdc=None, maj_proximal=False, debug=False):
- self.isTrained = False
- self.n_feat = n_feat
- self.neb = neb
- self.nebInitial = neb
- self.genInitial = gen
- self.gen = gen if gen is not None else self.neb
- self.neb_epochs = neb_epochs
- self.loss_history = None
- self.debug = debug
- self.minSetSize = 0
- self.conv_sample_generator = None
- self.maj_min_discriminator = None
- self.maj_proximal = maj_proximal
- self.cg = None
- self.canPredict = True
- self.fdc = fdc
- self.lastProgress = (-1,-1,-1)
-
- self.timing = { n: timing(n) for n in [
- "Train", "BMB", "NbhSearch", "NBH", "GenSamples", "Fit", "FixType"
- ] }
- if self.neb is not None and self.gen is not None and self.neb > self.gen:
- raise ValueError(f"Expected neb <= gen but got neb={neb} and gen={gen}.")
- def reset(self, data):
- """
- Creates the network.
- *dataSet* is a instance of /library.dataset.DataSet/ or None.
- It contains the training dataset.
- It is used to determine the neighbourhood size if /neb/ in /__init__/ was None.
- """
- self.isTrained = False
- if data is not None:
- nMinoryPoints = data.shape[0]
- if self.nebInitial is None:
- self.neb = nMinoryPoints
- else:
- self.neb = min(self.nebInitial, nMinoryPoints)
- else:
- self.neb = self.nebInitial
- self.gen = self.genInitial if self.genInitial is not None else self.neb
- ## instanciate generator network and visualize architecture
- self.conv_sample_generator = self._conv_sample_gen()
- ## instanciate discriminator network and visualize architecture
- self.maj_min_discriminator = self._maj_min_disc()
- ## instanciate network and visualize architecture
- self.cg = self._convGeN(self.conv_sample_generator, self.maj_min_discriminator)
- self.lastProgress = (-1,-1,-1)
- if self.debug:
- print(f"neb={self.neb}, gen={self.gen}")
- print(self.conv_sample_generator.summary())
- print('\n')
-
- print(self.maj_min_discriminator.summary())
- print('\n')
- print(self.cg.summary())
- print('\n')
- def train(self, data, discTrainCount=5):
- """
- Trains the Network.
- *dataSet* is a instance of /library.dataset.DataSet/. It contains the training dataset.
-
- *discTrainCount* gives the number of extra training for the discriminator for each epoch. (>= 0)
- """
- if data.shape[0] <= 0:
- raise AttributeError("Train: Expected data class 1 to contain at least one point.")
- self.timing["Train"].start()
- # Store size of minority class. This is needed during point generation.
- self.minSetSize = data.shape[0]
- normalizedData = data
- if self.fdc is not None:
- normalizedData = self.fdc.normalize(data)
-
- print(f"|N| = {normalizedData.shape}")
- print(f"|D| = {data.shape}")
-
- self.timing["NbhSearch"].start()
- # Precalculate neighborhoods
- self.nmbMin = NNSearch(self.neb).fit(haystack=normalizedData)
- self.nmbMin.basePoints = data
- self.timing["NbhSearch"].stop()
- # Do the training.
- self._rough_learning(data, discTrainCount)
-
- # Neighborhood in majority class is no longer needed. So save memory.
- self.isTrained = True
- self.timing["Train"].stop()
- def generateDataPoint(self):
- """
- Returns one synthetic data point by repeating the stored list.
- """
- return (self.generateData(1))[0]
- def generateData(self, numOfSamples=1):
- """
- Generates a list of synthetic data-points.
- *numOfSamples* is a integer > 0. It gives the number of new generated samples.
- """
- if not self.isTrained:
- raise ValueError("Try to generate data with untrained network.")
- ## roughly claculate the upper bound of the synthetic samples to be generated from each neighbourhood
- synth_num = (numOfSamples // self.minSetSize) + 1
- ## generate synth_num synthetic samples from each minority neighbourhood
- synth_set=[]
- for i in range(self.minSetSize):
- synth_set.extend(self._generate_data_for_min_point(i, synth_num))
- ## extract the exact number of synthetic samples needed to exactly balance the two classes
- synth_set = np.array(synth_set[:numOfSamples])
-
- return synth_set
- def predictReal(self, data):
- """
- Uses the discriminator on data.
-
- *data* is a numpy array of shape (n, n_feat) where n is the number of datapoints and n_feat the number of features.
- """
- prediction = self.maj_min_discriminator.predict(data)
- return np.array([x[0] for x in prediction])
- # ###############################################################
- # Hidden internal functions
- # ###############################################################
- # Creating the Network: Generator
- def _conv_sample_gen(self):
- """
- The generator network to generate synthetic samples from the convex space
- of arbitrary minority neighbourhoods
- """
- ## takes minority batch as input
- min_neb_batch = Input(shape=(self.neb, self.n_feat,))
- ## using 1-D convolution, feature dimension remains the same
- x = Conv1D(self.n_feat, 3, activation='relu')(min_neb_batch)
- ## flatten after convolution
- x = Flatten()(x)
- ## add dense layer to transform the vector to a convenient dimension
- x = Dense(self.neb * self.gen, activation='relu')(x)
- ## again, witching to 2-D tensor once we have the convenient shape
- x = Reshape((self.neb, self.gen))(x)
- ## column wise sum
- s = K.sum(x, axis=1)
- ## adding a small constant to always ensure the column sums are non zero.
- ## if this is not done then during initialization the sum can be zero.
- s_non_zero = Lambda(lambda x: x + .000001)(s)
- ## reprocals of the approximated column sum
- sinv = tf.math.reciprocal(s_non_zero)
- ## At this step we ensure that column sum is 1 for every row in x.
- ## That means, each column is set of convex co-efficient
- x = Multiply()([sinv, x])
- ## Now we transpose the matrix. So each row is now a set of convex coefficients
- aff=tf.transpose(x[0])
- ## 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
- synth=tf.matmul(aff, min_neb_batch)
- ## 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
- model = Model(inputs=min_neb_batch, outputs=synth)
- opt = Adam(learning_rate=0.001)
- model.compile(loss='mean_squared_logarithmic_error', optimizer=opt)
- return model
- # Creating the Network: discriminator
- def _maj_min_disc(self):
- """
- the discriminator is trained in two phase:
- first phase: while training ConvGeN the discriminator learns to differentiate synthetic
- minority samples generated from convex minority data space against
- the borderline majority samples
- second phase: after the ConvGeN generator learns to create synthetic samples,
- it can be used to generate synthetic samples to balance the dataset
- and then rettrain the discriminator with the balanced dataset
- """
- ## takes as input synthetic sample generated as input stacked upon a batch of
- ## borderline majority samples
- samples = Input(shape=(self.n_feat,))
-
- ## passed through two dense layers
- y = Dense(250, activation='relu')(samples)
- y = Dense(125, activation='relu')(y)
- y = Dense(75, activation='relu')(y)
-
- ## two output nodes. outputs have to be one-hot coded (see labels variable before)
- output = Dense(2, activation='sigmoid')(y)
-
- ## compile model
- model = Model(inputs=samples, outputs=output)
- opt = Adam(learning_rate=0.0001)
- model.compile(loss='binary_crossentropy', optimizer=opt)
- return model
- # Creating the Network: ConvGeN
- def _convGeN(self, generator, discriminator):
- """
- for joining the generator and the discriminator
- conv_coeff_generator-> generator network instance
- maj_min_discriminator -> discriminator network instance
- """
- ## by default the discriminator trainability is switched off.
- ## Thus training ConvGeN means training the generator network as per previously
- ## trained discriminator network.
- discriminator.trainable = False
- ## input receives a neighbourhood minority batch
- ## and a proximal majority batch concatenated
- batch_data = Input(shape=(2, self.gen, self.n_feat,))
-
- ## extract minority batch
- min_batch = Lambda(lambda x: x[:, 0, : ,:], name="SplitForGen")(batch_data)
-
- ## extract majority batch
- maj_batch = Lambda(lambda x: x[:, 1, :, :], name="SplitForDisc")(batch_data)
- maj_batch = tf.reshape(maj_batch, (-1, self.n_feat), name="ReshapeForDisc")
-
- ## pass minority batch into generator to obtain convex space transformation
- ## (synthetic samples) of the minority neighbourhood input batch
- conv_samples = generator(min_batch)
- conv_samples = tf.reshape(conv_samples, (-1, self.n_feat), name="ReshapeGenOutput")
- ## pass samples into the discriminator to know its decisions
- conv_samples = discriminator(conv_samples)
- maj_batch = discriminator(maj_batch)
-
- ## concatenate the decisions
- output = tf.concat([conv_samples, maj_batch],axis=0)
-
- ## note that, the discriminator will not be traied but will make decisions based
- ## on its previous training while using this function
- model = Model(inputs=batch_data, outputs=output)
- opt = Adam(learning_rate=0.0001)
- model.compile(loss='mse', optimizer=opt)
- return model
- # Create synthetic points
- def _generate_data_for_min_point(self, index, synth_num):
- """
- generate synth_num synthetic points for a particular minoity sample
- synth_num -> required number of data points that can be generated from a neighbourhood
- data_min -> minority class data
- neb -> oversampling neighbourhood
- index -> index of the minority sample in a training data whose neighbourhood we want to obtain
- """
- runs = int(synth_num / self.neb) + 1
- synth_set = []
- for _run in range(runs):
- batch = self.nmbMin.getNbhPointsOfItem(index)
- synth_batch = self.conv_sample_generator.predict(tf.reshape(batch, (1, self.neb, self.n_feat)), batch_size=self.neb)
- synth_batch = self.correct_feature_types(batch, synth_batch[0])
- synth_set.extend(synth_batch)
- return synth_set[:synth_num]
- # Training
- def _rough_learning(self, data, discTrainCount):
- generator = self.conv_sample_generator
- discriminator = self.maj_min_discriminator
- convGeN = self.cg
- loss_history = [] ## this is for stroring the loss for every run
- minSetSize = len(data)
- nLabels = 2 * self.gen
- labels = np.array(create01Labels(nLabels, self.gen))
- labelsGeN = np.array([labels])
-
-
- def createSamples(min_idx):
- self.timing["NBH"].start()
- ## generate minority neighbourhood batch for every minority class sampls by index
- min_batch_indices = shuffle(self.nmbMin.neighbourhoodOfItem(min_idx))
- min_batch = self.nmbMin.getPointsFromIndices(min_batch_indices)
- ## generate random proximal majority batch
- maj_batch = self._BMB(min_batch_indices)
- self.timing["NBH"].stop()
- self.timing["GenSamples"].start()
- ## generate synthetic samples from convex space
- ## of minority neighbourhood batch using generator
- conv_samples = generator.predict(np.array([min_batch]), batch_size=self.neb)
- conv_samples = tf.reshape(conv_samples, shape=(self.gen, self.n_feat))
- self.timing["GenSamples"].stop()
- self.timing["FixType"].start()
- ## Fix feature types
- conv_samples = self.correct_feature_types_tf(min_batch, conv_samples)
- self.timing["FixType"].stop()
- ## concatenate them with the majority batch
- conv_samples = [conv_samples, maj_batch]
- return conv_samples
- def trainDiscriminator(samples):
- concat_samples = tf.concat(samples, axis=0)
- self.timing["Fit"].start()
- ## switch on discriminator training
- discriminator.trainable = True
- ## train the discriminator with the concatenated samples and the one-hot encoded labels
- discriminator.fit(x=concat_samples, y=labels, verbose=0, batch_size=20)
- ## switch off the discriminator training again
- discriminator.trainable = False
- self.timing["Fit"].stop()
-
- for neb_epoch_count in range(self.neb_epochs):
- if discTrainCount > 0:
- for n in range(discTrainCount):
- for min_idx in range(minSetSize):
- self.progressBar([(neb_epoch_count + 1) / self.neb_epochs, n / discTrainCount, (min_idx + 1) / minSetSize])
- trainDiscriminator(createSamples(min_idx))
- for min_idx in range(minSetSize):
- self.progressBar([(neb_epoch_count + 1) / self.neb_epochs, 1.0, (min_idx + 1) / minSetSize])
- samples = createSamples(min_idx)
- trainDiscriminator(samples)
- ## use the complete network to make the generator learn on the decisions
- ## made by the previous discriminator training
- samples = np.array([samples])
- gen_loss_history = convGeN.fit(samples, y=labelsGeN, verbose=0, batch_size=nLabels)
- ## store the loss for the step
- loss_history.append(gen_loss_history.history['loss'])
- if self.debug:
- run_range = range(1, len(loss_history) + 1)
- plt.rcParams["figure.figsize"] = (16,10)
- plt.xticks(fontsize=20)
- plt.yticks(fontsize=20)
- plt.xlabel('runs', fontsize=25)
- plt.ylabel('loss', fontsize=25)
- plt.title('Rough learning loss for discriminator', fontsize=25)
- plt.plot(run_range, loss_history)
- plt.show()
- self.conv_sample_generator = generator
- self.maj_min_discriminator = discriminator
- self.cg = convGeN
- self.loss_history = loss_history
- def _BMB(self, min_idxs):
- ## Generate a borderline majority batch
- ## data_maj -> majority class data
- ## min_idxs -> indices of points in minority class
- ## gen -> convex combinations generated from each neighbourhood
- self.timing["BMB"].start()
- indices = [i for i in range(self.minSetSize) if i not in min_idxs]
- r = np.array([ [x.astype(np.float32) for x in self.nmbMin.basePoints[i]] for i in shuffle(indices)[0:self.gen]])
- self.timing["BMB"].stop()
- return r
- def retrainDiscriminitor(self, data, labels):
- self.maj_min_discriminator.trainable = True
- labels = np.array([ [x, 1 - x] for x in labels])
- self.maj_min_discriminator.fit(x=data, y=labels, batch_size=20, epochs=self.neb_epochs)
- self.maj_min_discriminator.trainable = False
- def progressBar(self, x):
- x = [int(v * 10) for v in x]
- if True not in [self.lastProgress[i] != x[i] for i in range(len(self.lastProgress))]:
- return
-
- def bar(v):
- r = ""
- for n in range(10):
- if n > v:
- r += " "
- else:
- r += "="
- return r
-
- s = [bar(v) for v in x]
- print(f"[{s[0]}] [{s[1]}] [{s[2]}]", end="\r")
-
- def correct_feature_types(self, batch, synth_batch):
- if self.fdc is None:
- return synth_batch
- def bestMatchOf(referenceValues, value):
- best = referenceValues[0]
- d = abs(best - value)
- for x in referenceValues:
- dx = abs(x - value)
- if dx < d:
- best = x
- d = dx
- return best
- synth_batch = list(synth_batch)
- for i in (self.fdc.nom_list or []):
- referenceValues = list(set(list(batch[:, i].numpy())))
- for x in synth_batch:
- y = x[i]
- x[i] = bestMatchOf(referenceValues, y)
- for i in (self.fdc.ord_list or []):
- referenceValues = list(set(list(batch[:, i].numpy())))
- for x in synth_batch:
- x[i] = bestMatchOf(referenceValues, x[i])
- return np.array(synth_batch)
-
- def correct_feature_types_tf(self, batch, synth_batch):
- if self.fdc is None:
- return synth_batch
-
- def bestMatchOf(referenceValues, value):
- if referenceValues is not None:
- best = referenceValues[0]
- d = abs(best - value)
- for x in referenceValues:
- dx = abs(x - value)
- if dx < d:
- best = x
- d = dx
- return best
- else:
- return value
-
- def correctVector(referenceLists, v):
- return np.array([bestMatchOf(referenceLists[i], v[i]) for i in range(len(v))])
-
- referenceLists = [None for _ in range(self.n_feat)]
- for i in (self.fdc.nom_list or []):
- referenceLists[i] = list(set(list(batch[:, i].numpy())))
- for i in (self.fdc.ord_list or []):
- referenceLists[i] = list(set(list(batch[:, i].numpy())))
- return Lambda(lambda x: np.array([correctVector(referenceLists, y) for y in x]))(synth_batch)
|