exercise.py 11 KB

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