def test_fit(self): seed = 666 file_ = "tests/files/libsvm/2" x, y = ds.load_svmlight_file(file_, (10, 300), 780, False) csvm = CascadeSVM(cascade_arity=3, max_iter=5, tol=1e-4, kernel='linear', c=2, gamma=0.1, check_convergence=True, random_state=seed, verbose=False) csvm.fit(x, y) self.assertTrue(csvm.converged) csvm = CascadeSVM(cascade_arity=3, max_iter=1, tol=1e-4, kernel='linear', c=2, gamma=0.1, check_convergence=False, random_state=seed, verbose=False) csvm.fit(x, y) self.assertFalse(csvm.converged) self.assertEqual(csvm.iterations, 1)
def test_score(self, collect): seed = 666 # negative points belong to class 1, positives to 0 p1, p2, p3, p4 = [1, 2], [2, 1], [-1, -2], [-2, -1] x = ds.array(np.array([p1, p4, p3, p2]), (2, 2)) y = ds.array(np.array([0, 1, 1, 0]).reshape(-1, 1), (2, 1)) csvm = CascadeSVM(cascade_arity=3, max_iter=10, tol=1e-4, kernel='rbf', c=2, gamma=0.1, check_convergence=True, random_state=seed, verbose=False) csvm.fit(x, y) # points are separable, scoring the training dataset should have 100% # accuracy x_test = ds.array(np.array([p1, p2, p3, p4]), (2, 2)) y_test = ds.array(np.array([0, 0, 1, 1]).reshape(-1, 1), (2, 1)) accuracy = csvm.score(x_test, y_test, collect) if not collect: accuracy = compss_wait_on(accuracy) self.assertEqual(accuracy, 1.0)
def test_predict(self): seed = 666 # negative points belong to class 1, positives to 0 p1, p2, p3, p4 = [1, 2], [2, 1], [-1, -2], [-2, -1] x = ds.array(np.array([p1, p4, p3, p2]), (2, 2)) y = ds.array(np.array([0, 1, 1, 0]).reshape(-1, 1), (2, 1)) csvm = CascadeSVM(cascade_arity=3, max_iter=10, tol=1e-4, kernel='linear', c=2, gamma=0.1, check_convergence=False, random_state=seed, verbose=False) csvm.fit(x, y) # p5 should belong to class 0, p6 to class 1 p5, p6 = np.array([1, 1]), np.array([-1, -1]) x_test = ds.array(np.array([p1, p2, p3, p4, p5, p6]), (2, 2)) y_pred = csvm.predict(x_test) l1, l2, l3, l4, l5, l6 = y_pred.collect() self.assertTrue(l1 == l2 == l5 == 0) self.assertTrue(l3 == l4 == l6 == 1)
def test_fit_default_gamma(self): """ Tests that the fit method converges when using gamma=auto on a toy dataset """ seed = 666 file_ = "tests/files/libsvm/2" x, y = ds.load_svmlight_file(file_, (10, 300), 780, False) csvm = CascadeSVM(cascade_arity=3, max_iter=5, tol=1e-4, kernel='linear', c=2, check_convergence=True, random_state=seed, verbose=False) csvm.fit(x, y) self.assertTrue(csvm.converged) csvm = CascadeSVM(cascade_arity=3, max_iter=1, tol=1e-4, kernel='linear', c=2, gamma=0.1, check_convergence=False, random_state=seed, verbose=False) csvm.fit(x, y) self.assertFalse(csvm.converged) self.assertEqual(csvm.iterations, 1)
def test_duplicates(self): """ Tests that C-SVM does not generate duplicate support vectors """ x = ds.array( np.array([[0, 1], [1, 1], [0, 1], [1, 2], [0, 0], [2, 2], [2, 1], [1, 0]]), (2, 2)) y = ds.array(np.array([1, 0, 1, 0, 1, 0, 0, 1]).reshape(-1, 1), (2, 1)) csvm = CascadeSVM(c=1, random_state=1, max_iter=100, tol=0) csvm.fit(x, y) csvm._collect_clf() self.assertEqual(csvm._clf.support_vectors_.shape[0], 6)
def test_decision_func(self): seed = 666 # negative points belong to class 1, positives to 0 # all points are in the x-axis p1, p2, p3, p4 = [0, 2], [0, 1], [0, -2], [0, -1] x = ds.array(np.array([p1, p4, p3, p2]), (2, 2)) y = ds.array(np.array([0, 1, 1, 0]).reshape(-1, 1), (2, 1)) csvm = CascadeSVM(cascade_arity=3, max_iter=10, tol=1e-4, kernel='rbf', c=2, gamma=0.1, check_convergence=False, random_state=seed, verbose=False) csvm.fit(x, y) # p1 should be equidistant to p3, and p2 to p4 x_test = ds.array(np.array([p1, p2, p3, p4]), (2, 2)) y_pred = csvm.decision_function(x_test) d1, d2, d3, d4 = y_pred.collect() self.assertTrue(np.isclose(abs(d1) - abs(d3), 0)) self.assertTrue(np.isclose(abs(d2) - abs(d4), 0)) # p5 and p6 should be in the decision function (distance=0) p5, p6 = np.array([1, 0]), np.array([-1, 0]) x_test = ds.array(np.array([p5, p6]), (1, 2)) y_pred = csvm.decision_function(x_test) d5, d6 = y_pred.collect() self.assertTrue(np.isclose(d5, 0)) self.assertTrue(np.isclose(d6, 0))
def test_fit_private_params(self): kernel = 'rbf' c = 2 gamma = 0.1 seed = 666 file_ = "tests/files/libsvm/2" x, y = ds.load_svmlight_file(file_, (10, 300), 780, False) csvm = CascadeSVM(kernel=kernel, c=c, gamma=gamma, random_state=seed) csvm.fit(x, y) self.assertEqual(csvm._clf_params['kernel'], kernel) self.assertEqual(csvm._clf_params['C'], c) self.assertEqual(csvm._clf_params['gamma'], gamma) kernel, c = 'linear', 0.3 csvm = CascadeSVM(kernel=kernel, c=c, random_state=seed) csvm.fit(x, y) self.assertEqual(csvm._clf_params['kernel'], kernel) self.assertEqual(csvm._clf_params['C'], c)
def test_sparse(self): """ Tests that C-SVM produces the same results with sparse and dense data""" seed = 666 train = "tests/files/libsvm/3" x_sp, y_sp = ds.load_svmlight_file(train, (10, 300), 780, True) x_d, y_d = ds.load_svmlight_file(train, (10, 300), 780, False) csvm_sp = CascadeSVM(random_state=seed) csvm_sp.fit(x_sp, y_sp) csvm_d = CascadeSVM(random_state=seed) csvm_d.fit(x_d, y_d) sv_d = csvm_d._clf.support_vectors_ sv_sp = csvm_sp._clf.support_vectors_.toarray() self.assertTrue(np.array_equal(sv_d, sv_sp)) coef_d = csvm_d._clf.dual_coef_ coef_sp = csvm_sp._clf.dual_coef_.toarray() self.assertTrue(np.array_equal(coef_d, coef_sp))
def main(): parser = argparse.ArgumentParser() parser.add_argument("--svmlight", help="read files in SVMLight format", action="store_true") parser.add_argument("-dt", "--detailed_times", help="get detailed execution times (read and fit)", action="store_true") parser.add_argument("-k", "--kernel", metavar="KERNEL", type=str, help="linear or rbf (default is rbf)", choices=["linear", "rbf"], default="rbf") parser.add_argument("-a", "--arity", metavar="CASCADE_ARITY", type=int, help="default is 2", default=2) parser.add_argument("-b", "--block_size", metavar="BLOCK_SIZE", type=str, help="two comma separated ints that represent the " "size of the blocks in which to divide the input " "data (default is 100,100)", default="100,100") parser.add_argument("-i", "--iteration", metavar="MAX_ITERATIONS", type=int, help="default is 5", default=5) parser.add_argument("-g", "--gamma", metavar="GAMMA", type=float, help="(only for rbf kernel) default is 1 / n_features", default=None) parser.add_argument("-c", metavar="C", type=float, default=1, help="Penalty parameter C of the error term. " "Default:1") parser.add_argument("-f", "--features", metavar="N_FEATURES", help="number of features of the input data " "(only for SVMLight files)", type=int, default=None, required=False) parser.add_argument("-t", "--test-file", metavar="TEST_FILE_PATH", help="test file path", type=str, required=False) parser.add_argument("-o", "--output_file", metavar="OUTPUT_FILE_PATH", help="output file path", type=str, required=False) parser.add_argument("--convergence", help="check for convergence", action="store_true") parser.add_argument("--dense", help="store data in dense format (only " "for SVMLight files)", action="store_true") parser.add_argument("train_data", help="input file in CSV or SVMLight format", type=str) parser.add_argument("-v", "--verbose", action="store_true") parser.add_argument("-s", "--shuffle", help="shuffle input data", action="store_true") args = parser.parse_args() train_data = args.train_data s_time = time.time() read_time = 0 if not args.gamma: gamma = "auto" else: gamma = args.gamma sparse = not args.dense bsize = args.block_size.split(",") block_size = (int(bsize[0]), int(bsize[1])) if args.svmlight: x, y = ds.load_svmlight_file(train_data, block_size, args.features, sparse) else: x = ds.load_txt_file(train_data, block_size) y = x[:, x.shape[1] - 2: x.shape[1] - 1] x = x[:, :x.shape[1] - 1] if args.shuffle: x, y = shuffle(x, y) if args.detailed_times: barrier() read_time = time.time() - s_time s_time = time.time() csvm = CascadeSVM(cascade_arity=args.arity, max_iter=args.iteration, c=args.c, gamma=gamma, check_convergence=args.convergence, verbose=args.verbose) csvm.fit(x, y) barrier() fit_time = time.time() - s_time out = [args.kernel, args.arity, args.part_size, csvm._clf_params["gamma"], args.c, csvm.iterations, csvm.converged, read_time, fit_time] if os.path.isdir(train_data): n_files = os.listdir(train_data) out.append(len(n_files)) if args.test_file: if args.svmlight: x_test, y_test = ds.load_svmlight_file(args.test_file, block_size, args.features, sparse) else: x_test = ds.load_txt_file(args.test_file, block_size) y_test = x_test[:, x_test.shape[1] - 1: x_test.shape[1]] x_test = x_test[:, :x_test.shape[1] - 1] out.append(compss_wait_on(csvm.score(x_test, y_test))) if args.output_file: with open(args.output_file, "ab") as f: wr = csv.writer(f) wr.writerow(out) else: print(out)