exercise.py 8.8 KB

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