class AnomalyModel: def __init__(self, trainingSet, anomalyMethod = "KNN", h = None ): self.method = anomalyMethod if self.method == "online": self.h = h if self.method == "centroid": self.h = Util.centroid( trainingSet ) if self.method == "medoid": self.h = Util.medoid( trainingSet ) if self.method == "IGNG": self.h = IGNG( radius = PARAMS["R"] ) # IGNG.estimate_radius( trainingSet ) self.h.train( trainingSet ) # print len( self.h.get_nodes_positions() ), len(trainingSet) if self.method == "GNG": self.h = GNG(period = 50) self.h.train( trainingSet ) if self.method == "KNN": self.h = NearestNeighbors(algorithm='ball_tree', metric='euclidean').fit(trainingSet) if self.method == "RNN": self.h = NearestNeighbors(algorithm='ball_tree', metric='euclidean').fit(trainingSet) if self.method == "SVM": self.h = svm.OneClassSVM(nu=PARAMS["NU"], kernel="rbf", gamma=PARAMS["GAMMA"]).fit(trainingSet) def getAnomalyScore(self, x, inversed = False): if self.method == "online": alpha_m = self.h.getNearestDist(x) # alpha_m = self.h.getNearestDistToMature(x) if inversed == True: alpha_m = 1. / alpha_m if self.method == "centroid": alpha_m = Util.dist(x, self.h) if inversed == True: alpha_m = 1. / alpha_m if self.method == "medoid": alpha_m = Util.dist(x, self.h) if inversed == True: alpha_m = 1. / alpha_m if self.method == "IGNG": alpha_m = self.h.getNearestDist(x) if inversed == True: alpha_m = 1. / alpha_m if self.method == "GNG": alpha_m = self.h.getNearestDist(x) if inversed == True: alpha_m = 1. / alpha_m if self.method == "KNN": distances, indices = self.h.kneighbors( x, n_neighbors = PARAMS["K"] ) alpha_m = sum( distances[0] ) if inversed == True: alpha_m = 1. / alpha_m if self.method == "RNN": distances, indices = self.h.radius_neighbors(x, radius = PARAMS["R"]) alpha_m = 1. / ( 1. + sum( [ 1./di for di in distances[0] if di != 0 ] ) ) if inversed == True: alpha_m = 1. / alpha_m if self.method == "SVM": alpha_m = -1. * self.h.decision_function(x)[0][0] if inversed == True: alpha_m = -1. * alpha_m return alpha_m