#! /usr/bin/python import numpy import sys import os sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)),os.pardir)) import helperFunctions import activeLearningGPLinKprototype class Classifier(activeLearningGPLinKprototype.ClassifierPrototype): def __init__(self, sigmaN = 0.00178, useDensity = True, configFile = None): activeLearningGPLinKprototype.ClassifierPrototype.__init__(self, sigmaN=sigmaN, configFile=configFile) self.useDensity = helperFunctions.getConfig(configFile, 'activeLearning', 'useDensity', useDensity, 'bool', True) # x.shape = (number of samples, feat dim) def calcEMOC(self, x, allX=None, kAll=None, sigmaF=None): if allX is None: allX = numpy.append(self.X, x, axis=0) if kAll is None: kAll = numpy.dot(allX,allX.T) k = kAll[0:self.X.shape[0],self.X.shape[0]:] if sigmaF is None: selfK = numpy.asmatrix(numpy.diag(kAll[self.X.shape[0]:,self.X.shape[0]:])).T sigmaF = self.calcSigmaF(x, k, selfK) containsNoise = (self.yUni == -1).any() infY = self.infer(x, containsNoise, k) probs = self.calcProbs(x, infY, sigmaF) term1 = 1.0 / (self.sigmaN + sigmaF) term2 = numpy.asmatrix(numpy.ones((self.X.shape[0] + 1,x.shape[0]))) * (-1.0) term2[0:self.X.shape[0],:] = numpy.linalg.solve(numpy.add(self.K, numpy.identity(self.X.shape[0], dtype=numpy.float32)*self.sigmaN), k) pro = numpy.absolute(infY - 1) contra = numpy.absolute(infY + 1) term3 = numpy.repeat(numpy.sum(contra,axis=1),contra.shape[1],axis=1) term3 = numpy.add(numpy.subtract(term3,contra),pro) scores = numpy.asmatrix(numpy.zeros((x.shape[0],1))) for cls in range(infY.shape[1]): diffAlpha = numpy.multiply(numpy.repeat(numpy.multiply(term1,term3[:,cls]), term2.shape[0], axis=1),term2.T) change = numpy.dot(diffAlpha[:,:-1],kAll[0:self.X.shape[0],:]) change = numpy.add(change, numpy.multiply(numpy.repeat(diffAlpha[:,-1], kAll.shape[0], axis=1),kAll[self.X.shape[0]:,:])) scores = numpy.add(scores, numpy.multiply(probs[:,cls],numpy.sum(numpy.absolute(change),axis=1))) return scores def getDensity(self, sim): return numpy.sum(sim, axis=1) / float(sim.shape[1]) def getDiversity(self, sim): return 1.0 / numpy.max(sim, axis=1) # x.shape = (feat dim, number of samples) def calcAlScores(self, x): allX = numpy.append(self.X, x, axis=0) kAll = numpy.dot(allX,allX.T) k = kAll[0:self.X.shape[0],self.X.shape[0]:] selfK = numpy.asmatrix(numpy.diag(kAll[self.X.shape[0]:,self.X.shape[0]:])).T sigmaF = self.calcSigmaF(x, k, selfK) alScores = self.calcEMOC(x, allX=allX, kAll=kAll, sigmaF=sigmaF) if self.useDensity: density = self.getDensity(kAll[self.X.shape[0]:,:]) alScores = numpy.multiply(alScores, density) return alScores