import numpy as np from sklearn.svm import SVC class AlgorithmSVM(): # method: AlgorithmSVM::constructor # # arguments: # win_input: GUI input display # win_output: GUI output display # win_log: GUI process log # # return: none # def __init__(self, win_input, win_output, win_log, maxiter, gamma): # create class data # AlgorithmSVM.__CLASS_NAME__ = self.__class__.__name__ # copy the inputs into class data # self.input_d = win_input self.output_d = win_output self.log_d = win_log self.gamma = gamma self.maxiter = maxiter # method: AlgorithmSVM::initialize # # arguments: None # # return: True # # initialize variables for SVM # def initialize(self, data): # initialize variables # self.data = data self.classes = len(self.data) self.svm = SVC(gamma=self.gamma, max_iter=self.maxiter) self.X = np.empty((0,0)) return True # method: AlgorithmSVM::run_algo # # arguments: None # # return: True # # run algorithm steps # def run_algo(self, data): # calc everything and display stats self.initialize(data) self.compute_vectors() self.draw_vectors() return True def create_labels(self): labels = [] count = 0 d = self.input_d.class_info for i in d: total_samples = len(d[i][1]) labels = labels + [count]*total_samples count +=1 labels = np.array(labels) return labels def compute_vectors(self): labels = self.create_labels() data = np.vstack((self.data)) self.svm.fit(data,labels) self.support_vectors = self.svm.support_vectors_ def draw_vectors(self): self.input_d.canvas.axes.scatter(self.support_vectors[:,0], self.support_vectors[:,1], facecolors='none',edgecolor='black', s =8) return True def predict(self, ax, X): X = np.concatenate(X, axis=0) X = np.reshape(X, (-1, 2)) res = (ax.canvas.axes.get_xlim()[1] - ax.canvas.axes.get_ylim()[0]) / 100 x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, res), np.arange(y_min, y_max, res)) Z = self.svm.predict(np.c_[xx.ravel(),yy.ravel()]) Z = Z.reshape(xx.shape) return xx, yy, Z def prediction_classifier(self,data): data = np.array([data]) prediction = self.svm.predict(data) return prediction[0]