def cross_validation(x, y, folds_number): avg = 0 precision = 0 recall = 0 fold_size = int(y.shape[0] / folds_number) for i in range(folds_number): train_x = np.concatenate((x[(i - 1) * fold_size:i * fold_size], x[(i + 1) * fold_size:(i + 2) * fold_size])) train_y = np.concatenate((y[(i - 1) * fold_size:i * fold_size], y[(i + 1) * fold_size:(i + 2) * fold_size])) test_x = x[i * fold_size:(i + 1) * fold_size] test_y = y[i * fold_size:(i + 1) * fold_size] clf = SVM() clf.fit(train_x, train_y) y_pred = clf.predict(test_x) avg += np.average(y_pred == test_y) precision += np.sum(np.bitwise_and(y_pred == 1, test_y == 1)) / np.sum(y_pred == 1) recall += np.sum(np.bitwise_and(y_pred == 1, test_y == 1)) / np.sum(test_y == 1) return avg / folds_number * 100, precision / folds_number, recall / folds_number
def test_blob_coefficients(self): X, y = generate_data("blobs") svm = SVM(C=1, rate=0.001, epochs=5000, kernel="linear") svm.fit(X, y) ref = np.array([3.8, -1.6, -1.0]) np.testing.assert_array_almost_equal(ref, svm.get_weights(), decimal=1)
def otimizar(self): # Definindo estado inicial da otimização estado_inicial = [ 2**np.random.uniform(low=-5.0, high=15.0 + 1), 2**np.random.uniform(low=-15.0, high=3.0 + 1), np.random.uniform(low=0.05, high=1.0) ] # Instanciando otimizador sp = SVMProblem(estado_inicial, self.X_treinamento, self.Y_treinamento) sp.steps = self.num_passos # Otimizando self.iniciar_tempo() resp, mae = sp.anneal() self.finalizar_tempo() # Extraindo os melhores hiperparametros C = resp[0] gamma = resp[1] epsilon = resp[2] # Treinando SVM final com os parâmetros encontrados self.svm = SVM(gamma, C, epsilon) self.svm.treinar(self.X_treinamento, self.Y_treinamento) self.svm.testar(self.X_teste, self.Y_teste)
def main(): # train_x, train_y, test_x, test_y = load_matrix2("data/data.csv", 1000, 1000, 49.1) train_x, train_y, test_x, test_y = load_matrix("data/sapirData.csv", 1100, 20) print('num of 1:', np.sum(test_y == 1)) #clf = svm.SVC(kernel='linear', C=0.01) clf = SVM() clf.fit(train_x, train_y) y_pred = clf.predict(test_x) res = np.average(y_pred == test_y) * 100 print('simple accurate: {:.2f}%'.format(res)) print('simple precision: {:.2f}'.format( np.sum(np.bitwise_and(y_pred == 1, test_y == 1)) / np.sum(y_pred == 1))) print('simple recall: {:.2f}'.format( np.sum(np.bitwise_and(y_pred == 1, test_y == 1)) / np.sum(test_y == 1))) accurate, precision, recall = cross_validation(train_x, train_y, 5) print( 'cross validation accurate: {:.2f}%\ncross validation precision: {:.2f}\ncross validation recall: {:.2f}' .format(accurate, precision, recall))
def Get_svm_model(parameter, X, y): svm = SVM() loss_histroy = svm.Train( X, y, parameter[1], 1, parameter[0], 200, 1500, True) VisualizeLoss(loss_histroy) input("Enter any key to predict...") return svm
def nonlinearSVM(): data = pd.read_csv("dataset/fourclass.csv") X = data[["x1", "x2"]].as_matrix() m, n = X.shape y = data["y"].as_matrix() h = 0.02 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, h), np.arange(y_min, y_max, h)) fig_idx = 1 for d in [10, 20, 30,40, 50, 60]: s = SVM(kernel="polynomial", degree=1) # s = svm.SVC(kernel='poly', degree=d, C=1.0).fit(X, y) # s = svm.SVC(kernel='rbf', gamma=0.7, C=1.0).fit(X, y) s.fit(X, y) Z = s.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # plt.subplot(3,2, fig_idx) # plt.title("Degree=1" %d) plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8) plt.scatter(X[:, 0], X[:, 1], c=y) fig_idx += 1 break plt.show()
def otimizar(self): # Definindo os parâmetros a serem utilizados parametros = { 'C': hp.uniform('C', -5, 15), 'gamma': hp.uniform('gamma', -15, 3), 'epsilon': hp.uniform('epsilon', 0.05, 1.0) } # Executando otimização dos parâmetros self.iniciar_tempo() resp = fmin(self.func_obj_bayesiana, parametros, algo=tpe.suggest, max_evals=self.num_chamadas) self.finalizar_tempo() # Extraindo os melhores hiperparametros C = 2.0**resp['C'] gamma = 2.0**resp['gamma'] epsilon = resp['epsilon'] # Treinando SVM final com os parâmetros encontrados self.svm = SVM(gamma, C, epsilon) self.svm.treinar(self.X_treinamento, self.Y_treinamento) self.svm.testar(self.X_teste, self.Y_teste)
def fit(self, X: np.ndarray, y: np.ndarray): # check if labels are integers labels = np.unique(y) for label in labels: if not label.is_integer(): raise ValueError(str(label) + " is not an integer value label") self.labels = np.array(labels, dtype=int) # re-arrange training set per labels in a dictionary X_arranged_list = collections.defaultdict(list) for index, x in enumerate(X): X_arranged_list[y[index]].append(x) # convert to numpy array the previous dictionary X_arranged_numpy = {} for index in range(len(self.labels)): X_arranged_numpy[index] = np.array(X_arranged_list[index]) for i in range(0, self.labels.shape[0] - 1): for j in range(i + 1, self.labels.shape[0]): current_X = np.concatenate((X_arranged_numpy[i], X_arranged_numpy[j])) current_y = np.concatenate((- np.ones((len(X_arranged_numpy[i]),), dtype=int), np.ones(len((X_arranged_numpy[j]),), dtype=int))) svm = SVM(kernel=self.kernel, gamma=self.gamma, deg=self.deg, r=self.r, C=self.C) svm.fit(current_X, current_y, verbosity=0) for sv in svm.sv_X: self.support_vectors.add(tuple(sv.tolist())) svm_tuple = (svm, self.labels[i], self.labels[j]) self.SVMs.append(svm_tuple) print('{0:d} support vectors found out of {1:d} data points'.format(len(self.support_vectors), len(X)))
def fit(self, X, y): n_samples, n_features = np.shape(X) # Initialize weights to 1/N w = np.full(n_samples, (1 / n_samples)) self.clfs = [] self.alphas = [] # Create classifiers for _ in range(self.n_clf): clf = SVM(rbf_kernel, 1.5) x_train, y_train = self.weighted_selection(X, y, w, 1) clf.fit(x_train, y_train) predictions = clf.predict(X) error = 1 - accuracy_score(predictions, y) if(error > 0.5): predictions *= -1 # Calculate alpha alpha = 0.5 * math.log((1.0 - error) / (error + 1e-10)) w *= np.exp(-alpha * y * predictions) # Normalize weights w /= np.sum(w) # Save classifier and alpha self.clfs.append(clf) self.alphas.append(alpha)
def get_svm_model(parameter, X, y): svm = SVM() loss_history = svm.train(X, y, parameter[1], 1, parameter[0], 200, 1500, True) VisualizeLoss(loss_history) input('Enter any key to predict...') return svm
def analyze(): def verify_structure(obj): if not obj: return False elif ("frames" not in obj) or ("username" not in obj): return False return True if not verify_structure(request.get_json()): print "verify structure" abort(401) user = User.query.filter_by(username=request.get_json()["username"]).first() if not user: abort(401) incidents = user.incidents machine = SVM(user.username, event_list_flatten(incidents), event_list_result_flatten(incidents)) event_list = [0.0] * 75 frames = request.get_json()["frames"] for each in sorted(frames, key=lambda frame: frame["batch_order"]): batch_order = each["batch_order"] event_list[batch_order * 3] = each["accel_x"] event_list[batch_order * 3 + 1] = each["accel_y"] event_list[batch_order * 3 + 2] = each["accel_z"] machine.classify(event_list) guess = bool(machine.labeled_new_data()) return json.dumps({"guess": guess, "content": request.get_json()}), 200
def otimizar(self): # Definindo os parâmetros a serem utilizados parametros = { 'C': loguniform.rvs(2**-5, 2**15, size=self.tamanho_grid), 'gamma': loguniform.rvs(2**-15, 2**3, size=self.tamanho_grid), 'epsilon': uniform.rvs(0.0, 1, size=self.tamanho_grid) } cv_ = ShuffleSplit(n_splits=1, test_size=0.1, train_size=0.9) # Executando otimização dos parâmetros self.iniciar_tempo() grid = GridSearchCV(estimator=SVR(kernel='rbf'), param_grid=parametros, scoring="neg_mean_absolute_error", cv=cv_, n_jobs=-1) grid.fit(self.X_treinamento, self.Y_treinamento) self.finalizar_tempo() # extraindo os melhores hiperparametros C = grid.best_params_['C'] gamma = grid.best_params_['gamma'] epsilon = grid.best_params_['epsilon'] # Treinando SVM final com os parâmetros encontrados self.svm = SVM(gamma, C, epsilon) self.svm.treinar(self.X_treinamento, self.Y_treinamento) self.svm.testar(self.X_teste, self.Y_teste)
def computeSVMCrossValidation(args, dict_algorithms): if (args.debug): print("Running svm...", end='') model = SVM(args) dict_algorithms["svm"] = model.computeCrossValidation() if (args.debug): print("ok!")
def svm_validate(data, kernel, svm_C, show_plot): plot = Plot() matrix_full = [[0, 0], [0, 0]] y_predict_arr = [] for i in range(len(data)): data.updateTrainTest(i) trainDots, trainClass = data.getDotsByMode('train', True) testDots, testClass = data.getDotsByMode('test', True) clf = SVM(kernel=kernel, C=svm_C) clf.fit(trainDots, trainClass) y_predict = clf.predict(testDots) y_predict_arr.append(y_predict[0]) if show_plot: plot.smv(trainDots[trainClass == 1], trainDots[trainClass == -1], clf, testDots[0], y_predict[0]) matrix = get_metrics(y_predict, testClass) matrix_full[0][0] += matrix[0][0] matrix_full[0][1] += matrix[0][1] matrix_full[1][0] += matrix[1][0] matrix_full[1][1] += matrix[1][1] return y_predict_arr, get_f_measure(matrix_full), matrix_full
def linearSVM(): iris = load_iris() X = iris.data[:100, :2] y = iris.target[:100] plt.scatter(X[:, 0], X[:, 1], c=y) plt.xlabel("Sepal Width") # plt.ylabel("Petal Length") plt.ylabel("Sepal Length") plt.title("Iris") x_min = int(min(X[:, 0])) - 1 x_max = int(max(X[:, 0])) + 1 s = SVM() s.fit(X, y) w, w_0, sp_idx = s.coef_ X_sp = X[sp_idx] y_sp = iris.target[sp_idx] plt.scatter(X_sp[:, 0], X_sp[:, 1], c="red") x = np.array([i for i in range(x_min, x_max)]) y = (-w_0 - x*w[0,0]) / w[1, 0] y_1 = (1-w_0 - x*w[0,0]) / w[1, 0] y_m_1 = (-1-w_0 - x*w[0,0]) / w[1, 0] plt.plot(x, y, label="Wx + W_0 = 0") plt.plot(x, y_1, label="Wx + W_0 = 1") plt.plot(x, y_m_1, label="Wx + W_0 = -1") plt.legend(loc=0, borderaxespad=0.) plt.show()
def train(self): weights = np.full(self.n_samples, 1 / self.n_samples) for i in trange(self.iterations): count = 0 error = np.inf while error > self.threshold: svm = SVM(self.train_data, self.test_data, self.train_labels, self.test_labels, 'rbf', 1, 1, True) error = 0 # print(self.n_samples) for i in range(self.n_samples): if self.train_labels[:, i] != svm.predicted_labels[i]: error = error + weights[i] if error > self.threshold: print(error) print("continuing...") continue svm.alpha = 0.5 * np.log((1.0 - error) / (error + 1e-10)) weights = np.exp(-1.0 * svm.alpha * self.train_labels.squeeze() * svm.predicted_labels.squeeze()) weights = weights / np.sum(weights) self.classifiers.append(svm)
def otimizar(self): # Definindo os parâmetros a serem utilizados parametros = { 'C': loguniform(2**-5, 2**15), 'gamma': loguniform(2**-15, 2**3), 'epsilon': uniform(0.0, 1) } cv_ = ShuffleSplit(n_splits=1, test_size=0.1, train_size=0.9) # Executando otimização dos parâmetros self.iniciar_tempo() randomSCV = RandomizedSearchCV(SVR(kernel='rbf'), parametros, scoring="neg_mean_absolute_error", cv=cv_, n_iter=self.num_combinacoes, n_jobs=-1) randomSCV.fit(self.X_treinamento, self.Y_treinamento) self.finalizar_tempo() # Identify optimal hyperparameter values C = randomSCV.best_params_['C'] gamma = randomSCV.best_params_['gamma'] epsilon = randomSCV.best_params_['epsilon'] # Treinando SVM final com os parâmetros encontrados self.svm = SVM(gamma, C, epsilon) self.svm.treinar(self.X_treinamento, self.Y_treinamento) self.svm.testar(self.X_teste, self.Y_teste)
def get_model_optimizer(args): model = SVM(c=args.c, penalty=args.penalty) if args.gpu >= 0: model.to_gpu() optimizer = optimizers.SGD(lr=args.lr) optimizer.setup(model) return model, optimizer
def test_fit(self): s = SVM(C=None) s.fit( np.array([[1, 2], [1, 1], [2, 1.5], [7, 8], [8, 6.5], [8, 7.5], [9, 7]]), np.array([-1, -1, -1, 1, 1, 1, 1])) np.testing.assert_allclose(s.w, np.array([0.1967213, 0.16393444]), rtol=1e-5) np.testing.assert_allclose(s.b, -1.6393436694251626, rtol=1e-5)
def test_text_training(self): X, y = get_text_data("text-data") svm = SVM(C=1, rate=0.001, epochs=100, kernel="text") svm.fit(X, y) predicted = svm.predict(X) print(y) print(predicted) errors = np.sum(predicted - y) self.assertEqual(errors, 0)
def run(self): while True: try: cg = self.work_queue.get_nowait() svm = SVM(sys.argv[1]) avg_acc = svm.cross_validate(cg[0],cg[1]) self.result_queue.put((cg[0], cg[1], avg_acc)) except Empty: return
def func_objetivo(self, arg): C_ = 2 ** (-5 + arg[0] * 20) gamma_ = 2 ** (-15 + arg[1] * 18) epsilon_ = abs(arg[2]) svm = SVM(gamma_, C_, epsilon_) svm.treinar(self.X_treinamento, self.Y_treinamento) return svm.mae_treinamento
def func_obj_bayesiana(self, params): C_ = 2.0**params['C'] gamma_ = 2.0**params['gamma'] epsilon_ = params['epsilon'] svm = SVM(gamma_, C_, epsilon_) svm.treinar(self.X_treinamento, self.Y_treinamento) return svm.mae_treinamento
def func_obj_pso(self, params): C_ = 2.0**params[0] gamma_ = 2.0**params[1] epsilon_ = params[2] svm = SVM(gamma_, C_, epsilon_) svm.treinar(self.X_treinamento, self.Y_treinamento) return svm.mae_treinamento
def _trainSvm(self, positiveLabel, negativeLabel, C = 2, toler = 0.0001): ''' ''' assert self.dataFileName is not None assert positiveLabel < negativeLabel dataSet = DigitDataSet() dataSet.load(self.dataFileName).map(positiveLabel, negativeLabel) svm = SVM() svm.train(dataSet, C, toler) return svm
def test_blob_prediction(self): X, y = generate_data("blobs") svm = SVM(C=1, rate=0.001, epochs=5000, kernel="linear") svm.fit(X, y) predicted = svm.predict(X) print(y) print(predicted) errors = np.sum(np.abs(predicted - y)) print(errors) self.assertLess(errors, 8)
def test_circle_prediction(self): X, y = generate_data("circle", n_samples=200) svm = SVM(C=1, rate=0.001, epochs=5000, kernel="rbf") svm.fit(X, y) predicted = svm.predict(X) print(y) print(predicted) errors = np.sum(np.abs(predicted - y)) print(errors) self.assertLess(errors, 20)
def example(num_samples=10, num_features=2, grid_size=20, filename="svm.pdf"): samples = np.array( np.random.normal(size=num_samples * num_features).reshape( num_samples, num_features)) labels = 2 * (samples.sum(axis=1) > 0) - 1.0 data_dict = build_data_dict(samples, labels) svm = SVM(data=data_dict, kernel=Kernel.linear(), c=0.1) svm.fit() plot(svm, samples, labels, grid_size, filename)
def mnist_svm_test(): # Create reader to load and save the training and test data reader = MNistReader() reader.load_training_data("./mnist-data/train-images.idx3-ubyte", "./mnist-data/train-labels.idx1-ubyte") reader.load_test_data("./mnist-data/t10k-images.idx3-ubyte", "./mnist-data/t10k-labels.idx1-ubyte") # Create SVM object svm = SVM() svm.isMnist() """ # Train and predict for binary svm logging.info("Running SVM for binary classification") #svm.train(reader.X, reader.Y, reader.X_test, reader.Y_test) logging.info("Saving binary results") #svm.results.to_excel(writer_mnist, sheet_name='binary') # MULTI CLASS SVM # Train and predict for binary svm logging.info("Multi Class SVM\n") # Train and predict for multi-class data using the linear svm from liblinear implementation # Train for multi-class single run with these objects liblinear implementation #svm.train(reader.X, reader.multiY, reader.X_test, reader.multiYtest, binary=False) logging.info("Saving multiclass liblinear results") #svm.results.to_excel(writer_mnist, sheet_name='multiclass-liblinear') # Train for multi-class single run with these objects using the libsvm implementation #svm.train(reader.X, reader.multiY, reader.X_test, reader.multiYtest, binary=False, linear=False) logging.info("Saving multiclass libsvm results") #svm.results.to_excel(writer_mnist, sheet_name='multiclass-libsvm') # Train for multi-class single run with these objects liblinear implementation KPCA-LDA svm.train(reader.X, reader.multiY, reader.X_test, reader.multiYtest, binary=False, decomposition=True, once=True) logging.info("Saving multiclass liblinear results with kpca-lda") svm.results.to_excel(writer_mnist, sheet_name='multiclass-liblinear-kpca-lda') # Train for multi-class single run with these objects using the libsvm implementation KPCA-LDA svm.train(reader.X, reader.multiY, reader.X_test, reader.multiYtest, binary=False, linear=False, decomposition=True, once=True, fileprefix='mnist_') logging.info("Saving multiclass libsvm results with kpca-lda") svm.results.to_excel(writer_mnist, sheet_name='multiclass-libsvm-kpca-lda') # KNN and NC nearest(reader.X, reader.Y, reader.X_test, reader.Y_test, reader.multiY, reader.multiYtest, writer_mnist, once=True, starcraft=False) """ clustering(reader.X, reader.Y, reader.X_test, reader.Y_test) # Write all the results writer_mnist.save()
def iterate(cself, svm, classes): cself.mention('Training SVM...') D = spdiag(classes) qp.update_H(D * K * D) qp.update_Aeq(classes.T) alphas, obj = qp.solve(cself.verbose) # Construct SVM from solution svm = SVM(kernel=self.kernel, gamma=self.gamma, p=self.p, verbose=self.verbose, sv_cutoff=self.sv_cutoff) svm._X = bs.instances svm._y = classes svm._alphas = alphas svm._objective = obj svm._compute_separator(K) svm._K = K cself.mention('Recomputing classes...') p_conf = svm._predictions[-bs.L_p:] pos_classes = np.vstack([_update_classes(part) for part in partition(p_conf, bs.pos_groups)]) new_classes = np.vstack([-np.ones((bs.L_n, 1)), pos_classes]) class_changes = round(np.sum(np.abs(classes - new_classes) / 2)) cself.mention('Class Changes: %d' % class_changes) if class_changes == 0: return None, svm return {'svm': svm, 'classes': new_classes}, None
def get_model_optimizer(args): model = SVM(c=args.c, penalty=args.penalty) if args.gpu >= 0: model.to_gpu() if args.penalty == 'L2': optimizer = optimizers.SGD(lr=args.lr) elif args.penalty == 'L1': optimizer = SGD(lr=args.lr) optimizer.setup(model) return model, optimizer
def predict_dataset(set_num, p): svm = SVM(partial(p_spectral_kernel_proj, p), 4**p, 1, data_sets[0][set_num], data_sets[1][set_num], data_sets[2][set_num]) svm.fit(1) result = svm.predict_Z() for i in range(len(result)): if result[i] == -1: result[i] = 0 return np.array([result]).T
def main(): data_path = './data' test_size_ratio = 0.1 loader = Data_Loader(data_path) # unshuffled split of data to train and test [train_img, train_labels, test_img, test_labels ] = [np.array(x) for x in loader.load_all_data(test_size_ratio)] # call SVM(train_img, train_labels, test_img, test_labels) train, test svm_classifier = SVM(train_img, train_labels, test_img, test_labels) svm_classifier.train()
def test_rbf_svm(): random_state = np.random.RandomState(0) n_samples = 100 X = np.empty((n_samples, 2)) X[:, 0] = np.linspace(0, 1, n_samples) X[:, 1] = random_state.randn(n_samples) y = np.sign(X[:, 1] - np.sin(2.0 * np.pi * np.sin(X[:, 0]))) svm = SVM(kernel="rbf", C=1.0, gamma=1.0, random_state=random_state) svm.fit(X, y) y_pred = svm.predict(X) assert_greater(accuracy_score(y, y_pred), 0.9)
def load(self): path = os.path.join('dump') assert os.path.exists(path) keySet = set() for each_path in os.listdir(path): key = each_path.split('.')[0] keySet.add(key) for key in keySet: svm = SVM() svm.load(os.path.join('dump', key)) self.svm_dict[key] = svm return self.svm_dict
def test_linear_svm(): random_state = np.random.RandomState(0) X = random_state.randn(10, 2) b = -0.2 w = np.array([0.5, -0.3]) y = np.sign(b + np.dot(X, w)) svm = SVM(kernel="linear", C=1.0, random_state=random_state) svm.fit(X, y) y_pred = svm.predict(X) assert_array_almost_equal(y, y_pred) assert_true(hasattr(svm, "coef_")) assert_true(hasattr(svm, "intercept_"))
def train_svm(dataset_loader, test_points, data_limit=0): input_, output = get_data_up_to_limit(dataset_loader, data_limit) input_, output = data_utils.construct_one_vs_all(input_, output, 0) (input_train, input_test, output_train, output_test) = data_utils.split(input_, output, test_points) #Run svm svm = SVM() svm.give_training_data(input_train, output_train) svm.train() svm.give_test_data(input_test, output_test) svm.analyze()
def test_trainSvm(self): return file = os.path.join('..', 'data', 'sample') trainer = Trainer(file) t_svm = trainer._trainSvm(5, 8) dataSet = DigitDataSet() dataSet.load(file).map(5, 8) svm = SVM() svm.train(dataSet, 2, 0.0001) m,n = dataSet.shape() for i in range(m): X = dataSet.getData(i) t_y = t_svm.predict(X) y = svm.predict(X) self.assertTrue(t_y == y)
def test_dump(self): data_path = os.path.join('..','data', 'sample') trainset = DigitDataSet() trainset.load(data_path).map(0, 7) m, n = trainset.shape() svm1 = SVM() svm1.train(trainset,2, 0.0001) svm1.dump('temp') svm2 = SVM() svm2.load('temp') for i in range(m): X = trainset.getData(i) y1 = svm1.predict(X) y2 = svm2.predict(X) self.assertTrue(y1 == y2)
def test_getSvm(self): return trainer = Trainer() trainer.load() svm1 = trainer.getSvmInstance(6, 7) dataSet = DigitDataSet() dataSet.load(os.path.join('..', 'data', 'sample')).map(6, 7) svm2 = SVM() svm2.train(dataSet, 2, 0.0001) m,n = dataSet.shape() for i in range(m): X = dataSet.getData(i) y1= svm1.predict(X) y2 = svm2.predict(X) self.assertTrue(y1 == y2)
def radial_SVM(): iris = load_iris() X = iris.data[:100, :2] y = iris.target[:100] plt.scatter(X[:, 0], X[:, 1], c=y) plt.xlabel("Sepal Width") plt.ylabel("Petal Length") plt.title("Iris") s = SVM(kernel="radial", gamma=0.9) s.fit(X, y) x_min, x_max = X[:, 0].min() - 5, X[:, 0].max() + 5 y_min, y_max = X[:, 1].min() - 5, X[:, 1].max() + 5 h = 0.02 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = s.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.9) plt.scatter(X[:, 0], X[:, 1], c=y) plt.show()
def test_smo(self): return data_path = os.path.join('..','data', 'sample') trainset = DigitDataSet() trainset.load(data_path).map(0, 7) svm = SVM() svm.train(trainset,2, 0.0001) testset = DigitDataSet() testset.load(os.path.join('..', 'data', 'sample')).map(0, 7) m,n = testset.shape() err = 0 for i in range(m): X = testset.getData(i) y = testset.getLabel(i) label = svm.predict(X) print(label, y) if label != y: err += 1 print(float(err) / m)
def main(): if len(sys.argv) < 3: usage() exit(1) else: model_file = sys.argv[1] if len(sys.argv) == 3: is_known = False test_file = sys.argv[2] else: test_file = sys.argv[3] is_known = True try: svm = SVM(test_file) svm.load_model(model_file) if is_known: ret = svm.predict_known() target = ret['target'] print "Accuracy Rate:%.2f%%"%(ret['acc'] * 100) else: target = svm.predict() print 'Classified Result:' classcified = {} for index, target in target.items(): if target not in classcified: classcified[target] = [] classcified[target].append(index+1) ''' for t,i in classcified.items(): print "class %g: "%(t), for j in i: print "%g, "%(j), print '' ''' print_class(classcified) except IOError, msg: print msg exit(1)
def iterate(cself, svm, selectors, instances, K): cself.mention('Training SVM...') alphas, obj = qp.solve(cself.verbose) # Construct SVM from solution svm = SVM(kernel=self.kernel, gamma=self.gamma, p=self.p, verbose=self.verbose, sv_cutoff=self.sv_cutoff) svm._X = instances svm._y = classes svm._alphas = alphas svm._objective = obj svm._compute_separator(K) svm._K = K cself.mention('Recomputing classes...') p_confs = svm.predict(bs.pos_instances) pos_selectors = bs.L_n + np.array([l + np.argmax(p_confs[l:u]) for l, u in slices(bs.pos_groups)]) new_selectors = np.hstack([neg_selectors, pos_selectors]) if selectors is None: sel_diff = len(new_selectors) else: sel_diff = np.nonzero(new_selectors - selectors)[0].size cself.mention('Selector differences: %d' % sel_diff) if sel_diff == 0: return None, svm elif sel_diff > 5: # Clear results to avoid a # bad starting point in # the next iteration qp.clear_results() cself.mention('Updating QP...') indices = (new_selectors,) K = K_all[indices].T[indices].T D = spdiag(classes) qp.update_H(D * K * D) return {'svm': svm, 'selectors': new_selectors, 'instances': bs.instances[indices], 'K': K}, None
import json from svm import SVM # Open all files: with open('ex2-vocabulary.json') as file: vocabulary = json.load(file) with open('ex2-train-vecs.json') as file: train_vecs = json.load(file) with open('ex2-validation-vecs.json') as file: valid_vecs = json.load(file) print("Building SVM...") svm = SVM(length=len(vocabulary)) print("Start Training...") # Train the svm: mistakes = svm.train(train_vecs) print('The svm missed %s%% classifications on the validation data.' % (svm.test(valid_vecs)*100) ) print('Writing weight vector on file.') with open('ex4.1-w_vec.json', 'w') as file: file.write(json.dumps(svm.w_vec)) with open('ex4.1-obj_vec.json', 'w') as file:
try: opts, args = getopt.getopt(sys.argv[1:], 'hc:g:') except getopt.GetoptError, msg: usage(msg) exit(1) for opt, val in opts: if opt == '-h': usage() exit() elif opt == '-c': param['cost'] = float(val) elif opt == '-g': param['gamma'] = float(val) if len(args) != 1: usage('Must specify scaled train data file') exit(1) try: svm = SVM(args[0]) svm.train(param['cost'], param['gamma']) svm.save_model() except IOError, msg: print msg exit(1) if __name__ == '__main__': main()
pylab.plot(point[0], point[1], 'go') else: pylab.plot(point[0], point[1], 'mo') if __name__ == "__main__": generate_new = False if generate_new: positive_points = generate_2d_points(5, 1, -1.5, 1, 0.5, 1) positive_points += generate_2d_points(5, 1, 1.5, 1, 0.5, 1) negative_points = generate_2d_points(10, -1, -0.5, 0.5, -0.5, 0.5) data = negative_points+positive_points random.shuffle(data) store_points(data, "points.txt") else: data = load_points("points.txt") print_data(data) clf = SVM('polynomial', with_slack=False, degree=2) clf.train(data) print_boundaries(clf) print_classification(clf) pylab.show()
import numpy as np import matplotlib.pyplot as plt from svm import SVM random_state = np.random.RandomState(0) n_samples = 20 X = random_state.rand(n_samples, 2) y = np.ones(n_samples) y[X[:, 0] + 0.1 * random_state.randn(n_samples) < 0.5] = -1.0 plt.figure() for i, C in enumerate([1e-3, 1.0, 1e3, np.inf]): svm = SVM(kernel="linear", C=C, random_state=random_state) svm.fit(X, y) xx = np.linspace(0, 1) a = -svm.coef_[0] / svm.coef_[1] yy = a * xx - svm.intercept_ / svm.coef_[1] plt.subplot(2, 2, 1 + i) plt.scatter(svm.support_vectors_[:, 0], svm.support_vectors_[:, 1], c="green", s=100) plt.scatter(X[:, 0], X[:, 1], c=y) plt.plot(xx, yy, 'k-') plt.title("$C = %g$" % C) plt.xlim(0, 1) plt.ylim(0, 1) plt.xticks(()) plt.yticks(())
import numpy as np import matplotlib.pyplot as plt from svm import SVM random_state = np.random.RandomState(0) n_samples = 20 X = random_state.rand(n_samples, 2) y = np.ones(n_samples) y[X[:, 0] + 0.1 * random_state.randn(n_samples) < 0.5] = -1.0 plt.figure() for i, C in enumerate([1.0, 1e1, 1e2, np.inf]): svm = SVM(kernel="rbf", C=C, gamma=10.0, random_state=random_state) svm.fit(X, y) X_grid, Y_grid = np.meshgrid(np.linspace(0, 1, 50), np.linspace(0, 1, 50)) X_test = np.vstack(map(np.ravel, (X_grid, Y_grid))).T Z_grid = svm.predict(X_test).reshape(X_grid.shape) plt.subplot(2, 2, 1 + i) plt.contourf(X_grid, Y_grid, Z_grid, alpha=0.3) plt.scatter(svm.support_vectors_[:, 0], svm.support_vectors_[:, 1], c="green", s=100) plt.scatter(X[:, 0], X[:, 1], c=y) plt.title("$C = %g$" % C) plt.xlim(0, 1) plt.ylim(0, 1) plt.xticks(()) plt.yticks(())
class SdA(object): """Stacked denoising auto-encoder class (SdA) A stacked denoising autoencoder model is obtained by stacking several dAs. The hidden layer of the dA at layer `i` becomes the input of the dA at layer `i+1`. The first layer dA gets as input the input of the SdA, and the hidden layer of the last dA represents the output. Note that after pretraining, the SdA is dealt with as a normal MLP, the dAs are only used to initialize the weights. """ def __init__( self, numpy_rng, theano_rng=None, n_ins=156*256, hidden_layers_sizes=[5000, 500], n_outs=10, corruption_levels=[0.1, 0.1] ): """ This class is made to support a variable number of layers. :type numpy_rng: numpy.random.RandomState :param numpy_rng: numpy random number generator used to draw initial weights :type theano_rng: theano.tensor.shared_randomstreams.RandomStreams :param theano_rng: Theano random generator; if None is given one is generated based on a seed drawn from `rng` :type n_ins: int :param n_ins: dimension of the input to the sdA :type n_layers_sizes: list of ints :param n_layers_sizes: intermediate layers size, must contain at least one value :type n_outs: int :param n_outs: dimension of the output of the network :type corruption_levels: list of float :param corruption_levels: amount of corruption to use for each layer """ self.sigmoid_layers = [] self.dA_layers = [] self.params = [] self.n_layers = len(hidden_layers_sizes) assert self.n_layers > 0 if not theano_rng: theano_rng = RandomStreams(numpy_rng.randint(2 ** 30)) # allocate symbolic variables for the data self.x = T.matrix('x') # the data is presented as rasterized images self.y = T.matrix('y',dtype="int32") # the labels are presented as 1D vector of # [int] labels # end-snippet-1 # The SdA is an MLP, for which all weights of intermediate layers # are shared with a different denoising autoencoders # We will first construct the SdA as a deep multilayer perceptron, # and when constructing each sigmoidal layer we also construct a # denoising autoencoder that shares weights with that layer # During pretraining we will train these autoencoders (which will # lead to chainging the weights of the MLP as well) # During finetunining we will finish training the SdA by doing # stochastich gradient descent on the MLP # start-snippet-2 for i in xrange(self.n_layers): # construct the sigmoidal layer # the size of the input is either the number of hidden units of # the layer below or the input size if we are on the first layer if i == 0: input_size = n_ins else: input_size = hidden_layers_sizes[i - 1] # the input to this layer is either the activation of the hidden # layer below or the input of the SdA if you are on the first # layer if i == 0: layer_input = self.x else: layer_input = self.sigmoid_layers[-1].output sigmoid_layer = HiddenLayer(rng=numpy_rng, input=layer_input, n_in=input_size, n_out=hidden_layers_sizes[i], activation=T.nnet.sigmoid) # add the layer to our list of layers self.sigmoid_layers.append(sigmoid_layer) # its arguably a philosophical question... # but we are going to only declare that the parameters of the # sigmoid_layers are parameters of the StackedDAA # the visible biases in the dA are parameters of those # dA, but not the SdA self.params.extend(sigmoid_layer.params) # Construct a denoising autoencoder that shared weights with this # layer dA_layer = dA(numpy_rng=numpy_rng, theano_rng=theano_rng, input=layer_input, n_visible=input_size, n_hidden=hidden_layers_sizes[i], W=sigmoid_layer.W, bhid=sigmoid_layer.b) self.dA_layers.append(dA_layer) # end-snippet-2 # We now need to add a logistic layer on top of the MLP self.svmLayer = SVM( input=self.sigmoid_layers[-1].output, n_in=hidden_layers_sizes[-1], n_out=n_outs ) self.params.extend(self.svmLayer.params) # construct a function that implements one step of finetunining # compute the cost for second phase of training, # defined as the negative log likelihood self.finetune_cost = self.svmLayer.cost(self.y) # compute the gradients with respect to the model parameters # symbolic variable that points to the number of errors made on the # minibatch given by self.x and self.y self.errors = self.svmLayer.errors(self.y) def pretraining_functions(self, train_set_x, batch_size): ''' Generates a list of functions, each of them implementing one step in trainnig the dA corresponding to the layer with same index. The function will require as input the minibatch index, and to train a dA you just need to iterate, calling the corresponding function on all minibatch indexes. :type train_set_x: theano.tensor.TensorType :param train_set_x: Shared variable that contains all datapoints used for training the dA :type batch_size: int :param batch_size: size of a [mini]batch :type learning_rate: float :param learning_rate: learning rate used during training for any of the dA layers ''' # index to a [mini]batch index = T.lscalar('index') # index to a minibatch corruption_level = T.scalar('corruption') # % of corruption to use learning_rate = T.scalar('lr') # learning rate to use # begining of a batch, given `index` batch_begin = index * batch_size # ending of a batch given `index` batch_end = batch_begin + batch_size pretrain_fns = [] for dA in self.dA_layers: # get the cost and the updates list cost, updates = dA.get_cost_updates(corruption_level, learning_rate) # compile the theano function fn = theano.function( inputs=[ index, theano.Param(corruption_level, default=0.2), theano.Param(learning_rate, default=0.1) ], outputs=cost, updates=updates, givens={ self.x: train_set_x[batch_begin: batch_end] } ) # append `fn` to the list of functions pretrain_fns.append(fn) return pretrain_fns def build_finetune_functions(self, datasets, batch_size, learning_rate): '''Generates a function `train` that implements one step of finetuning, a function `validate` that computes the error on a batch from the validation set, and a function `test` that computes the error on a batch from the testing set :type datasets: list of pairs of theano.tensor.TensorType :param datasets: It is a list that contain all the datasets; the has to contain three pairs, `train`, `valid`, `test` in this order, where each pair is formed of two Theano variables, one for the datapoints, the other for the labels :type batch_size: int :param batch_size: size of a minibatch :type learning_rate: float :param learning_rate: learning rate used during finetune stage ''' (train_set_x, train_set_y) = datasets[0] (valid_set_x, valid_set_y) = datasets[1] (test_set_x, test_set_y) = datasets[2] # compute number of minibatches for training, validation and testing print train_set_x.get_value(borrow=True).shape n_valid_batches = valid_set_x.get_value(borrow=True).shape[0] n_valid_batches /= batch_size n_test_batches = test_set_x.get_value(borrow=True).shape[0] n_test_batches /= batch_size index = T.lscalar('index') # index to a [mini]batch # compute the gradients with respect to the model parameters gparams = T.grad(self.finetune_cost, self.params) # compute list of fine-tuning updates updates = [ (param, param - gparam * learning_rate) for param, gparam in zip(self.params, gparams) ] train_fn = theano.function( inputs=[index], outputs=self.finetune_cost, updates=updates, givens={ self.x: train_set_x[ index * batch_size: (index + 1) * batch_size ], self.y: train_set_y[ index * batch_size: (index + 1) * batch_size ] }, name='train' ) test_score_i = theano.function( [index], self.errors, givens={ self.x: test_set_x[ index * batch_size: (index + 1) * batch_size ], self.y: test_set_y[ index * batch_size: (index + 1) * batch_size ] }, name='test' ) valid_score_i = theano.function( [index], self.errors, givens={ self.x: valid_set_x[ index * batch_size: (index + 1) * batch_size ], self.y: valid_set_y[ index * batch_size: (index + 1) * batch_size ] }, name='valid' ) # Create a function that scans the entire validation set def valid_score(): return [valid_score_i(i) for i in xrange(n_valid_batches)] # Create a function that scans the entire test set def test_score(): return [test_score_i(i) for i in xrange(n_test_batches)] return train_fn, valid_score, test_score
import matplotlib.pyplot as pyplot from svm import SVM Original_Data = numpy.array([ [3,3], [4,3], [1,1]]).transpose() Tag = numpy.array([ [+1], [+1], [-1]]).transpose() Tag = Tag.flatten() a = SVM(Original_Data, Tag) a.train() for i in range(Original_Data.shape[1]): if Tag[i] == +1: pyplot.plot(Original_Data[0][i], Original_Data[1][i], "or") else: pyplot.plot(Original_Data[0][i], Original_Data[1][i], "ob") x = numpy.arange(-5, +5, 0.01) pyplot.plot(x, -((a.W[1] * x + a.b)/a.W[0])) pyplot.show()
def __init__( self, numpy_rng, theano_rng=None, n_ins=156*256, hidden_layers_sizes=[5000, 500], n_outs=10, corruption_levels=[0.1, 0.1] ): """ This class is made to support a variable number of layers. :type numpy_rng: numpy.random.RandomState :param numpy_rng: numpy random number generator used to draw initial weights :type theano_rng: theano.tensor.shared_randomstreams.RandomStreams :param theano_rng: Theano random generator; if None is given one is generated based on a seed drawn from `rng` :type n_ins: int :param n_ins: dimension of the input to the sdA :type n_layers_sizes: list of ints :param n_layers_sizes: intermediate layers size, must contain at least one value :type n_outs: int :param n_outs: dimension of the output of the network :type corruption_levels: list of float :param corruption_levels: amount of corruption to use for each layer """ self.sigmoid_layers = [] self.dA_layers = [] self.params = [] self.n_layers = len(hidden_layers_sizes) assert self.n_layers > 0 if not theano_rng: theano_rng = RandomStreams(numpy_rng.randint(2 ** 30)) # allocate symbolic variables for the data self.x = T.matrix('x') # the data is presented as rasterized images self.y = T.matrix('y',dtype="int32") # the labels are presented as 1D vector of # [int] labels # end-snippet-1 # The SdA is an MLP, for which all weights of intermediate layers # are shared with a different denoising autoencoders # We will first construct the SdA as a deep multilayer perceptron, # and when constructing each sigmoidal layer we also construct a # denoising autoencoder that shares weights with that layer # During pretraining we will train these autoencoders (which will # lead to chainging the weights of the MLP as well) # During finetunining we will finish training the SdA by doing # stochastich gradient descent on the MLP # start-snippet-2 for i in xrange(self.n_layers): # construct the sigmoidal layer # the size of the input is either the number of hidden units of # the layer below or the input size if we are on the first layer if i == 0: input_size = n_ins else: input_size = hidden_layers_sizes[i - 1] # the input to this layer is either the activation of the hidden # layer below or the input of the SdA if you are on the first # layer if i == 0: layer_input = self.x else: layer_input = self.sigmoid_layers[-1].output sigmoid_layer = HiddenLayer(rng=numpy_rng, input=layer_input, n_in=input_size, n_out=hidden_layers_sizes[i], activation=T.nnet.sigmoid) # add the layer to our list of layers self.sigmoid_layers.append(sigmoid_layer) # its arguably a philosophical question... # but we are going to only declare that the parameters of the # sigmoid_layers are parameters of the StackedDAA # the visible biases in the dA are parameters of those # dA, but not the SdA self.params.extend(sigmoid_layer.params) # Construct a denoising autoencoder that shared weights with this # layer dA_layer = dA(numpy_rng=numpy_rng, theano_rng=theano_rng, input=layer_input, n_visible=input_size, n_hidden=hidden_layers_sizes[i], W=sigmoid_layer.W, bhid=sigmoid_layer.b) self.dA_layers.append(dA_layer) # end-snippet-2 # We now need to add a logistic layer on top of the MLP self.svmLayer = SVM( input=self.sigmoid_layers[-1].output, n_in=hidden_layers_sizes[-1], n_out=n_outs ) self.params.extend(self.svmLayer.params) # construct a function that implements one step of finetunining # compute the cost for second phase of training, # defined as the negative log likelihood self.finetune_cost = self.svmLayer.cost(self.y) # compute the gradients with respect to the model parameters # symbolic variable that points to the number of errors made on the # minibatch given by self.x and self.y self.errors = self.svmLayer.errors(self.y)
max_iter=20 w_vec_list = [] avg_train_err = [] avg_valid_err = [] print("Starting experiments...") for val in range(-9, 10): print(" Experiment with val=2**%s" % (val if val>=0 else ("(%s)" % val)) ) # Build a new svm: svm = SVM(w_vec=w_vec, lamb=2**val) # Train it num_erros = svm.train(train_vecs, max_iter=max_iter) # Save the weight vector: w_vec_list.append( svm.w_vec ) # Save the train data: avg_train_err.append( float(num_erros)/(max_iter*len(train_vecs)) ) # Save the validation data: avg_valid_err.append( svm.test(valid_vecs) ) min_err = sorted( zip(range(-9,10), avg_valid_err),