def predict_third_set(gram_train, gram_test, y_label, scale=20000, max_iter=1, lambd=0.00001): gram_train = gram_train[0] + gram_train[1] + gram_train[2] gram_test = gram_test[0] + gram_test[1] + gram_test[2] krl = KRL(gram_m=gram_train / scale, max_iter=max_iter, lambd=lambd) krl.fit(np.array(y_label)) y_pred_krl = krl.predict(gram_test / scale) clf = SVM(gram_m=gram_train) clf.fit(np.array(y_label)) y_pred_svm = clf.predict(gram_test) y_pred = np.sign(y_pred_svm + y_pred_krl) return y_pred
Y_test) = imdb.load_data(num_words=max_features) X_train = sequence.pad_sequences(X_train, maxlen=maxlen) X_test = sequence.pad_sequences(X_test, maxlen=maxlen) model = Sequential() model.add(Embedding(max_features, 128)) model.add(LSTM(128, dropout=0.5, recurrent_dropout=0.5)) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) print("Train...") model.fit(X_train, Y_train, batch_size=batch_size, epochs=15) score, accuracy = model.evaluate(X_test, Y_test, batch_size=batch_size) print('Test score: {0}'.format(score)) print('Test accuracy: {0}'.format(accuracy)) if sys.argv[1] != 'rnn': print("SVM: {0}".format(SVM(X_train, Y_train, X_test, Y_test))) print("Naive Bayes: {0}".format( nultinomialNB(X_train, Y_train, X_test, Y_test))) print("Logistic Regression: {0}".format( LR(X_train, Y_train, X_test, Y_test))) print("Fully connected Neural Net: {0}".format( NN(X_train, Y_train, X_test, Y_test)))
X2_test = test_data_mat_2[0].str.split(' ').values for i , lst in enumerate(X2_test): X2_test[i] = np.array([float(x) for x in lst]) X2_test = np.vstack(X2_test) X3_test = test_data_mat_3[0].str.split(' ').values for i , lst in enumerate(X3_test): X3_test[i] = np.array([float(x) for x in lst]) X3_test= np.vstack(X3_test) if config.Kernel == 'linear': print("-- This will take few milliseconds per dataset to compute the kernel matrix --\n") if config.classifier =='SVM': classifier = SVM(kernel_name=config.Kernel, kernel=linear_kernel, C=20) elif config.classifier =='RIDGE': classifier = Ridge_Classifier(lam = 1e-8, kernel_name=config.Kernel, kernel=linear_kernel, loss_func=log_rg_loss) elif config.Kernel == 'rbf': print("-- This will take few milliseconds per dataset to compute the kernel matrix --\n") if config.classifier =='SVM': classifier = SVM(kernel_name=config.Kernel, kernel=rbf_kernel, C=20) elif config.classifier =='RIDGE': classifier = Ridge_Classifier(lam = 1e-8, kernel_name=config.Kernel, kernel=rbf_kernel, loss_func=log_rg_loss) else: classifier = None print("Kernel not found") if classifier!=None:
def main(args): # Create algorithm objects lbp = LBP() detector = FaceDetector() svm = SVM() knn = KNearest() # Get subjects to train the svm on imgs = [ '/home/arthur/Downloads/lfw_funneled/Gian_Marco/Gian_Marco_0001.jpg', '/home/arthur/Downloads/lfw_funneled/Micky_Ward/Micky_Ward_0001.jpg', '/home/arthur/Downloads/lfw_funneled/Ziwang_Xu/Ziwang_Xu_0001.jpg', '/home/arthur/Downloads/lfw_funneled/Zhu_Rongji/Zhu_Rongji_0001.jpg' ] # Load the subjects and extract their features hists, labels = load_subjects(imgs, detector, lbp) # Transform to np arrays samples = np.array(hists, dtype=np.float32) labels = np.array(labels, dtype=np.int) # Train classifiers svm.train(samples, labels) knn.train(samples, labels) # Check which mode the app is running in (image vs. video) if args.image is not None: # Read the image from the file path provided img = cv2.imread(args.image, 0) # Check the image exists if img is not None: # Run face recognition algorithm classify_snapshot(img, detector, lbp, knn) else: print('The image could not be found...') return # Establish connection to camera cap = cv2.VideoCapture(0) # Continuously grab the next frame from the camera while cap.isOpened(): # Capture frame-by-frame ret, frame = cap.read() # Start timer for performance logging start = time.time() # Convert frame to gray scale for face detector gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Detect a face in the frame and crop the image face_coords = detector.detect(gray) face = detector.crop_face(gray, face_coords) # Check we have detected a face if face is not None: # Apply LBP operator to get feature descriptor hist, bins = lbp.run(face, False) # Convert the LBP descriptor to numpy array for opencv classifiers test_sample = np.array([hist], dtype=np.float32) # Get the class of id of the closest neighbour and its distance dist, class_id = knn.predict(test_sample) # Draw the face if found util.draw_face(dist, class_id, frame, face_coords) # util.segment_face(frame) # Processing finished end = time.time() # Write the fps to the video util.write_fps(start, end, frame) # Display the resulting frame cv2.imshow('frame', frame) # Check if we should stop the application if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows()
import sys import os import numpy as np import math import cv2 from plyfile import PlyData from LBP import LBP, LocalBinaryPatterns from classifiers import SVM, KNearest # todo test the classifier # todo validate on a 80/20 split lbp = LBP() svm = SVM() knn = KNearest() hists = [] labels = [] def main(photoface_dir): traverse(photoface_dir, describe_face) samples = np.array(hists, dtype=np.float32) ids = np.array(labels, dtype=np.int) # Train classifiers svm.train(samples, ids) knn.train(samples, ids)
nb.predict(data_test_compact) print("Predict the EVAL set") y_preds = nb.predict(data_eval_compact)['y_preds'] make_submission_data(y_preds, 'nb_1214.csv') # run Perceptron ----------------------- perceptron = Perceptron(r=0.1, margin=0.01, n_epoch=20) perceptron.fit(data_train) print("Predict the TEST set") perceptron.predict(data_test, perceptron.weights[-1]) print("Predict the EVAL set") y_preds = perceptron.predict(data_eval, perceptron.weights[-1])['y_preds'] make_submission_data(y_preds, 'perceptron.csv') # run SVM svm = SVM(r=0.01, c=1, n_epoch=17) svm.fit(data_train) print("Predict the TEST set") svm.predict(data_test, svm.weights[-1]) print("Predict the EVAL set") y_preds = svm.predict(data_eval, svm.weights[-1])['y_preds'] make_submission_data(y_preds, 'svm.csv') # run Logistic ----------------------------- logistic = Logistic(r=0.01, sigma=100, n_epoch=10) logistic.fit(data_train) print("Predict the TEST set") logistic.predict(data_test, logistic.weights[-1]) print("Preidict the EVAL set") y_preds = logistic.predict(data_eval, logistic.weights[-1])['y_preds'] make_submission_data(y_preds, 'logistic.csv')