exercise.py 11 KB

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