exercise.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. """
  2. Class for testing the performance of Generative Adversarial Networks
  3. in generating synthetic samples for datasets with a minority class.
  4. """
  5. import numpy as np
  6. import pandas as pd
  7. import seaborn as sns
  8. from sklearn.decomposition import PCA
  9. from sklearn.preprocessing import StandardScaler
  10. import matplotlib.pyplot as plt
  11. from library.dataset import DataSet, TrainTestData
  12. from library.testers import lr,knn, gb, TestResult
  13. class Exercise:
  14. """
  15. Exercising a test for a minority class extension class.
  16. """
  17. def __init__(self, testFunctions=None, shuffleFunction=None, numOfSlices=5, numOfShuffles=5):
  18. """
  19. Creates a instance of this class.
  20. *testFunctions* is a dictionary /(String : Function)/ of functions for testing
  21. a generated dataset. The functions have the signature:
  22. /(TrainTestData, TrainTestData) -> TestResult/
  23. *shuffleFunction* is either None or a function /numpy.array -> numpy.array/
  24. that shuffles a given array.
  25. *numOfSlices* is an integer > 0. The dataset given for the run function
  26. will be divided in such many slices.
  27. *numOfShuffles* is an integer > 0. It gives the number of exercised tests.
  28. The GAN will be trained and tested (numOfShuffles * numOfSlices) times.
  29. """
  30. self.numOfSlices = int(numOfSlices)
  31. self.numOfShuffles = int(numOfShuffles)
  32. self.shuffleFunction = shuffleFunction
  33. self.debug = print
  34. self.testFunctions = testFunctions
  35. if self.testFunctions is None:
  36. self.testFunctions = {
  37. "LR": lr,
  38. "GB": gb,
  39. "KNN": knn
  40. }
  41. self.results = { name: [] for name in self.testFunctions }
  42. # Check if the given values are in valid range.
  43. if self.numOfSlices < 0:
  44. raise AttributeError(f"Expected numOfSlices to be > 0 but got {self.numOfSlices}")
  45. if self.numOfShuffles < 0:
  46. raise AttributeError(f"Expected numOfShuffles to be > 0 but got {self.numOfShuffles}")
  47. def run(self, gan, dataset):
  48. """
  49. Exercise all tests for a given GAN.
  50. *gan* is a implemention of library.interfaces.GanBaseClass.
  51. It defines the GAN to test.
  52. *dataset* is a library.dataset.DataSet that contains the majority class
  53. (dataset.data0) and the minority class (dataset.data1) of data
  54. for training and testing.
  55. """
  56. # Check if the given values are in valid range.
  57. if len(dataset.data1) > len(dataset.data0):
  58. raise AttributeError(
  59. "Expected class 1 to be the minority class but class 1 is bigger than class 0.")
  60. # Reset results array.
  61. self.results = { name: [] for name in self.testFunctions }
  62. # If a shuffle function is given then shuffle the data before the
  63. # exercise starts.
  64. if self.shuffleFunction is not None:
  65. self.debug("-> Shuffling data")
  66. for _n in range(3):
  67. dataset.shuffleWith(self.shuffleFunction)
  68. # Repeat numOfShuffles times
  69. self.debug("### Start exercise for synthetic point generator")
  70. for shuffleStep in range(self.numOfShuffles):
  71. stepTitle = f"Step {shuffleStep + 1}/{self.numOfShuffles}"
  72. self.debug(f"\n====== {stepTitle} =======")
  73. # If a shuffle function is given then shuffle the data before the next
  74. # exercise starts.
  75. if self.shuffleFunction is not None:
  76. self.debug("-> Shuffling data")
  77. dataset.shuffleWith(self.shuffleFunction)
  78. # Split the (shuffled) data into numOfSlices slices.
  79. # dataSlices is a list of TrainTestData instances.
  80. #
  81. # If numOfSlices=3 then the data will be splited in D1, D2, D3.
  82. # dataSlices will contain:
  83. # [(train=D2+D3, test=D1), (train=D1+D3, test=D2), (train=D1+D2, test=D3)]
  84. self.debug("-> Spliting data to slices")
  85. dataSlices = TrainTestData.splitDataToSlices(dataset, self.numOfSlices)
  86. # Do a exercise for every slice.
  87. for (sliceNr, sliceData) in enumerate(dataSlices):
  88. sliceTitle = f"Slice {sliceNr + 1}/{self.numOfSlices}"
  89. self.debug(f"\n------ {stepTitle}: {sliceTitle} -------")
  90. self._exerciseWithDataSlice(gan, sliceData)
  91. self.debug("### Exercise is done.")
  92. for (n, name) in enumerate(self.results):
  93. stats = None
  94. for (m, result) in enumerate(self.results[name]):
  95. stats = result.addMinMaxAvg(stats)
  96. (mi, mx, avg) = TestResult.finishMinMaxAvg(stats)
  97. self.debug("")
  98. self.debug(f"-----[ {avg.title} ]-----")
  99. self.debug("maximum:")
  100. self.debug(str(mx))
  101. self.debug("")
  102. self.debug("average:")
  103. self.debug(str(avg))
  104. self.debug("")
  105. self.debug("minimum:")
  106. self.debug(str(mi))
  107. def _exerciseWithDataSlice(self, gan, dataSlice):
  108. """
  109. Runs one test for the given gan and dataSlice.
  110. *gan* is a implemention of library.interfaces.GanBaseClass.
  111. It defines the GAN to test.
  112. *dataSlice* is a library.dataset.TrainTestData instance that contains
  113. one data slice with training and testing data.
  114. """
  115. # Start over with a new GAN instance.
  116. self.debug("-> Reset the GAN")
  117. gan.reset()
  118. # Train the gan so it can produce synthetic samples.
  119. self.debug("-> Train generator for synthetic samples")
  120. gan.train(dataSlice.train)
  121. # Count how many syhthetic samples are needed.
  122. numOfNeededSamples = dataSlice.train.size0 - dataSlice.train.size1
  123. # Add synthetic samples (generated by the GAN) to the minority class.
  124. if numOfNeededSamples > 0:
  125. self.debug(f"-> create {numOfNeededSamples} synthetic samples")
  126. newSamples = gan.generateData(numOfNeededSamples)
  127. # Print out an overview of the new dataset.
  128. plotCloud(dataSlice.train.data0, dataSlice.train.data1, newSamples)
  129. dataSlice.train = DataSet(
  130. data0=dataSlice.train.data0,
  131. data1=np.concatenate((dataSlice.train.data1, newSamples))
  132. )
  133. # Test this dataset with every given test-function.
  134. # The results are printed out and stored to the results dictionary.
  135. for testerName in self.testFunctions:
  136. self.debug(f"-> test with '{testerName}'")
  137. testResult = (self.testFunctions[testerName])(dataSlice)
  138. self.debug(str(testResult))
  139. self.results[testerName].append(testResult)
  140. def saveResultsTo(self, fileName):
  141. avgResults = {}
  142. with open(fileName, "w") as f:
  143. for (n, name) in enumerate(self.results):
  144. if n > 0:
  145. f.write("---\n")
  146. f.write(name + "\n")
  147. isFirst = True
  148. stats = None
  149. for (m, result) in enumerate(self.results[name]):
  150. if isFirst:
  151. isFirst = False
  152. f.write("Nr.;" + result.csvHeading() + "\n")
  153. stats = result.addMinMaxAvg(stats)
  154. f.write(f"{m + 1};" + result.toCSV() + "\n")
  155. (mi, mx, avg) = TestResult.finishMinMaxAvg(stats)
  156. f.write(f"max;" + mx.toCSV() + "\n")
  157. f.write(f"avg;" + avg.toCSV() + "\n")
  158. f.write(f"min;" + mi.toCSV() + "\n")
  159. avgResults[name] = avg
  160. return avgResults
  161. def plotCloud(data0, data1, dataNew):
  162. """
  163. Does a PCA analysis of the given data and plot the both important axis.
  164. """
  165. # Normalizes the data.
  166. data_t = StandardScaler().fit_transform(np.concatenate([data0, data1, dataNew]))
  167. # Run the PCA analysis.
  168. pca = PCA(n_components=2)
  169. pc = pca.fit_transform(data_t)
  170. # Create a DataFrame for plotting.
  171. result = pd.DataFrame(data=pc, columns=['PCA0', 'PCA1'])
  172. result['Cluster'] = np.concatenate([
  173. np.zeros(len(data0)),
  174. np.zeros(len(data1)) + 1,
  175. np.zeros(len(dataNew)) + 2
  176. ])
  177. # Plot the analysis results.
  178. sns.set( font_scale=1.2)
  179. sns.lmplot( x="PCA0", y="PCA1",
  180. data=result,
  181. fit_reg=False,
  182. hue='Cluster', # color by cluster
  183. legend=False,
  184. scatter_kws={"s": 3}, palette="Set1") # specify the point size
  185. plt.legend(title='', loc='upper left', labels=['0', '1', '2'])
  186. plt.show()