activeLearningGPLinKprototype.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. #! /usr/bin/python
  2. import numpy
  3. import sys
  4. import os
  5. sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)),os.pardir))
  6. import helperFunctions
  7. class ClassifierPrototype:
  8. def __init__(self, sigmaN = 0.00178, configFile=None, probSampleRuns=1000):
  9. self.sigmaN = helperFunctions.getConfig(configFile, 'activeLearning', 'sigmaN', sigmaN, 'float', True)
  10. self.probSampleRuns = helperFunctions.getConfig(configFile, 'activeLearning', 'probSampleRuns', probSampleRuns, 'float', True)
  11. self.K = []
  12. self.alpha = []
  13. self.X = []
  14. self.y = []
  15. self.yBin = []
  16. self.yUni = []
  17. def checkModel(self):
  18. if not numpy.all(numpy.isfinite(self.K)):
  19. raise Exception('not numpy.all(numpy.isfinite(self.K))')
  20. if not numpy.all(numpy.isfinite(self.alpha)):
  21. raise Exception('not numpy.all(numpy.isfinite(self.alpha))')
  22. if not numpy.all(numpy.isfinite(self.X)):
  23. raise Exception('not numpy.all(numpy.isfinite(self.X))')
  24. if not numpy.all(numpy.isfinite(self.y)):
  25. raise Exception('not numpy.all(numpy.isfinite(self.y))')
  26. def train2(self, X, y, sigmaN=None):
  27. self.train(X[0,:],y[0,:],sigmaN)
  28. for idx in range(1,X.shape[0]):
  29. self.update(X[idx,:],y[idx,:])
  30. # X.shape = (number of samples, feat dim), y.shape = (number of samples, 1)
  31. def train(self, X, y, sigmaN=None):
  32. if sigmaN is not None:
  33. self.sigmaN = sigmaN
  34. self.X = X
  35. self.y = y
  36. self.yUni = numpy.asmatrix(numpy.unique(numpy.asarray(self.y)))
  37. tmpVec = numpy.asmatrix(numpy.empty([self.y.shape[0],1]))
  38. self.yBin = numpy.asmatrix(numpy.empty([self.y.shape[0],self.yUni.shape[1]]))
  39. for cls in range(self.yUni.shape[1]):
  40. mask = (self.y == self.yUni[0,cls])
  41. tmpVec[mask == True] = 1
  42. tmpVec[mask == False] = -1
  43. self.yBin[:,cls] = tmpVec
  44. self.K = numpy.dot(X,X.T)
  45. self.alpha = numpy.linalg.solve(numpy.add(self.K, numpy.identity(self.X.shape[0], dtype=numpy.float)*self.sigmaN), self.yBin)
  46. self.checkModel()
  47. # x.shape = (1, feat dim), y.shape = (1, 1)
  48. def update(self, x, y):
  49. # update for known classes
  50. binY = numpy.asmatrix(numpy.ones((1,self.alpha.shape[1])))*(-1)
  51. if self.alpha.shape[1] > 1:
  52. binY[0,numpy.asarray(numpy.squeeze(numpy.asarray(y==self.yUni)))] = 1
  53. elif y==self.yUni:
  54. binY[0,0] = 1
  55. # get new kernel columns
  56. k = numpy.dot(self.X,x.T)
  57. selfK = numpy.sum(numpy.multiply(x,x), axis=1)
  58. # get score of new sample
  59. infY = self.infer(x, k=k)
  60. # update alpha
  61. term1 = 1.0 / (self.sigmaN + self.calcSigmaF(x, k, selfK).item(0))
  62. term2 = numpy.asmatrix(numpy.ones((self.X.shape[0] + 1,x.shape[0])), dtype=numpy.float)*(-1.0)
  63. term2[0:self.X.shape[0],:] = numpy.linalg.solve(numpy.add(self.K, numpy.identity(self.X.shape[0], dtype=numpy.float)*self.sigmaN), k)
  64. term3 = infY - binY
  65. self.alpha = numpy.add(numpy.append(self.alpha, numpy.zeros((1,self.alpha.shape[1])), axis=0), numpy.dot(numpy.dot(term1,term2),term3))
  66. # update K
  67. self.K = numpy.append(numpy.append(self.K, k, axis=1), numpy.append(k.T, selfK, axis=1), axis=0)
  68. # update samples
  69. self.X = numpy.append(self.X, x, axis=0)
  70. self.y = numpy.append(self.y, y, axis=0)
  71. # update binary labels for knwon class
  72. if (self.yUni == y).any():
  73. mask = (y == self.yUni)
  74. tmpVec = numpy.empty([self.yBin.shape[1], 1])
  75. tmpVec[mask.T == True] = 1
  76. tmpVec[mask.T == False] = -1
  77. self.yBin = numpy.append(self.yBin, tmpVec.T, axis=0)
  78. # create labels and alpha for new class
  79. else:
  80. # create bigger matrices
  81. tmpyBin = numpy.asmatrix(numpy.empty([self.yBin.shape[0] + 1, self.yBin.shape[1] + 1]))
  82. tmpAlpha = numpy.asmatrix(numpy.empty([self.alpha.shape[0], self.alpha.shape[1] + 1]))
  83. # index of new class
  84. tmpIdx = -1
  85. # check all knwon classes
  86. for cls in range(self.yUni.shape[1]):
  87. # just copy all classes with lower label
  88. if y > self.yUni[0,cls]:
  89. tmpyBin[0:-1,cls] = self.yBin[:,cls]
  90. tmpyBin[tmpyBin.shape[0] - 1,cls] = -1
  91. tmpAlpha[:,cls] = self.alpha[:,cls]
  92. tmpIdx = cls
  93. # copy classes with higher label to shiftet position
  94. else: # y < self.yUni[cls]
  95. tmpyBin[0:-1,cls + 1] = self.yBin[:,cls]
  96. tmpyBin[tmpyBin.shape[0] - 1,cls + 1] = -1
  97. tmpAlpha[:,cls + 1] = self.alpha[:,cls]
  98. # add new binary label vector for new class
  99. tmpyBin[0:-1,tmpIdx + 1] = -1
  100. tmpyBin[tmpyBin.shape[0] - 1,tmpIdx + 1] = 1
  101. # set new binary matrix and append new label
  102. self.yBin = tmpyBin
  103. self.yUni = numpy.sort(numpy.append(self.yUni, y, axis=1))
  104. # train new alpha for new class
  105. tmpAlpha[:,tmpIdx + 1] = numpy.linalg.solve(numpy.add(self.K, numpy.identity(self.X.shape[0], dtype=numpy.float)*self.sigmaN), self.yBin[:,tmpIdx + 1])
  106. self.alpha = tmpAlpha
  107. self.checkModel()
  108. # X.shape = (number of samples, feat dim), loNoise = {0,1}
  109. def infer(self, x, loNoise=False, k=None):
  110. if k is None:
  111. k = numpy.dot(self.X,x.T)
  112. loNoise = loNoise and (self.yUni == -1).any()
  113. pred = numpy.asmatrix(numpy.dot(k.T,self.alpha[:,int(loNoise):]))
  114. if not numpy.all(numpy.isfinite(pred)):
  115. raise Exception('not numpy.all(numpy.isfinite(pred))')
  116. return pred
  117. # X.shape = (number of samples, feat dim)
  118. def test(self, x, loNoise=False):
  119. loNoise = loNoise and (self.yUni == -1).any()
  120. return self.yUni[0,numpy.argmax(self.infer(x, loNoise), axis=1) + int(loNoise)]
  121. # X.shape = (number of samples, feat dim)
  122. def calcSigmaF(self, x, k=None, selfK=None):
  123. if k is None:
  124. k = numpy.dot(self.X,x.T)
  125. if selfK is None:
  126. selfK = numpy.sum(numpy.multiply(x,x), axis=1)
  127. sigmaF = numpy.subtract(selfK, numpy.sum(numpy.multiply(numpy.linalg.solve(numpy.add(self.K, numpy.identity(self.X.shape[0], dtype=numpy.float)*self.sigmaN), k),k).T, axis=1))
  128. if not numpy.all(numpy.isfinite(sigmaF)):
  129. raise Exception('not numpy.all(numpy.isfinite(sigmaF))')
  130. return sigmaF
  131. # X.shape = (number of samples, feat dim)
  132. def calcProbs(self, x, mu=None, sigmaF=None, nmb=None):
  133. # set number of sampling iterations
  134. if nmb is None:
  135. nmb = self.probSampleRuns
  136. # get mu and sigma
  137. if mu is None:
  138. mu = self.infer(x)
  139. if sigmaF is None:
  140. sigmaF = self.calcSigmaF(x)
  141. # prepare
  142. probs = numpy.asmatrix(numpy.zeros(mu.shape))
  143. for idx in range(nmb):
  144. draws = numpy.asmatrix(numpy.random.randn(mu.shape[0],mu.shape[1]))
  145. draws = numpy.add(numpy.multiply(draws, numpy.repeat(sigmaF, draws.shape[1], axis=1)), mu)
  146. maxIdx = numpy.argmax(draws, axis=1)
  147. idxs = (range(len(maxIdx)),numpy.squeeze(maxIdx))
  148. probs[idxs] = probs[idxs] + 1
  149. # convert absolute to relative amount
  150. return probs/float(nmb)
  151. # x.shape = (feat dim, number of samples)
  152. def calcAlScores(self, x):
  153. return None
  154. # x.shape = (feat dim, number of samples)
  155. def getAlScores(self, x):
  156. alScores = self.calcAlScores(x)
  157. if not numpy.all(numpy.isfinite(alScores)):
  158. raise Exception('not numpy.all(numpy.isfinite(alScores))')
  159. if alScores.shape[0] != x.shape[0] or alScores.shape[1] != 1:
  160. raise Exception('alScores.shape[0] != x.shape[0] or alScores.shape[1] != 1')
  161. return alScores
  162. # x.shape = (feat dim, number of samples)
  163. def chooseSample(self, x):
  164. return numpy.argmax(self.getAlScores(x), axis=0).item(0)