exercise.py 9.7 KB

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