def mainSVML(): q = 12 t1 = time.time() alpha_star, k, total_fun_eval, total_jac_eval, opt_obj = f.SVMlight( Xtr, Ytr, C, gamma, q) total_time = time.time() - t1 b_star = f.find_b_star(alpha_star, Xtr, Ytr, C, gamma) y_pred = f.predict(alpha_star, b_star, Xtr, Ytr, Xtst, gamma) test_acc = f.acc_score(y_pred, Ytst) ytrpred = f.predict(alpha_star, b_star, Xtr, Ytr, Xtr, gamma) #print("Main train accuracy: ", f.acc_score(ytrpred, Ytr)) output = open("output_homework2_28.txt", "a") # instead of 99, number of the team output.write("\nHomework 2, question 2") output.write("\nTraining objective function," + "%f" % opt_obj) output.write("\nTest accuracy," + "%f" % test_acc) output.write("\nTraining computing time," + "%f" % total_time) output.write("\nOuter iterations," + "%i" % k) output.write("\nFunction evaluations," + "%i" % total_fun_eval) output.write("\nGradient evaluations," + "%i" % total_jac_eval) output.close()
def main(): t = time.time() alpha_star, res = f.find_alpha_star(Xtr, Ytr, C, gamma) totalTime = time.time() - t b_star = f.find_b_star(alpha_star, Xtr, Ytr, C, gamma) #print("b_star: ", b_star) ytstpred = f.predict(alpha_star, b_star, Xtr, Ytr, Xtst, gamma) ytrpred = f.predict(alpha_star, b_star, Xtr, Ytr, Xtr, gamma) test_accuracy = f.acc_score(ytstpred, Ytst) #print("Main train accuracy: ",f.acc_score(ytrpred,Ytr)) output = open("output_homework2_28.txt", "a") # instead of 99, number of the team output.write("Homework 2, question 1") output.write("\nTraining objective function," + "%f" % res.fun) output.write("\nTest accuracy," + "%f" % test_accuracy) output.write("\nTraining computing time," + "%f" % totalTime) output.write("\nFunction evaluations," + "%i" % res.nfev) output.write("\nGradient evaluations," + "%i" % res.njev) output.close()
def main(): #Set up argument parser for console input parser = argparse.ArgumentParser(description='Predict category of flower') parser.add_argument('image_path', help='path of image to be analyzed') parser.add_argument( 'checkpoint_dir', help= 'directory containing /checkpoint.pth with pre-trained model to be used for prediction' ) parser.add_argument('--top_k', help='number of top K most likely classes', default=1, type=int) parser.add_argument('--category_names', help='Select JSON file') parser.add_argument('--gpu', help='Enable GPU', action='store_true') args = parser.parse_args() #Load pre-trained model from checkpoint loaded_model, optimizer, criterion, epochs = fu.load_checkpoint( args.checkpoint_dir + '/checkpoint.pth') #Set mode device = torch.device( 'cuda' if torch.cuda.is_available() and args.gpu == True else 'cpu') print('Device is: ', device) #Inference calculation probs, classes = fu.predict(args.image_path, loaded_model, args.top_k, device, args.category_names) print(probs) print(classes)
def mainMVP(): t = time.time() alpha_star, objective_value, i = f.MVP(Xtr, Ytr, C, gamma) total_time = time.time() - t b_star = f.find_b_star(alpha_star, Xtr, Ytr, C, gamma) ytrpred = f.predict(alpha_star, b_star, Xtr, Ytr, Xtr, gamma) ytstpred = f.predict(alpha_star, b_star, Xtr, Ytr, Xtst, gamma) test_accuracy = f.acc_score(ytstpred, Ytst) #print("Main train accuracy: ", f.acc_score(ytrpred, Ytr)) output = open("output_homework2_28.txt", "a") # instead of 99, number of the team output.write("\nHomework 2, question 3") output.write("\nTraining objective function," + "%f" % objective_value) output.write("\nTest accuracy," + "%f" % test_accuracy) output.write("\nTraining computing time," + "%f" % total_time) output.write("\nOuter iterations," + "%i" % i) output.close()
data_np = loadtxt() X = data_np[:, 0:2] Y = data_np[:, 2] m, n = np.shape(X) init_theta = np.zeros((n + 1, )) X = np.c_[np.ones((m, )), X] print(init_theta) cost = costFunction(init_theta, X, Y) grad = gradFunction(init_theta, X, Y) print('Cost at initial theta (zeros): ', cost) print('Gradient at initial theta (zeros): ', grad) _ = input('Press [Enter] to continue.') #minimize the castFunction by scipy.optimize.minimize result = op.minimize(costFunction, x0=init_theta, method='BFGS', jac=gradFunction, args=(X, Y)) theta = result.x print(theta) plotDecisonBoundary(theta, X, Y) #predict by training data p = predict(theta, X) #print(data_np[:,2]) one_sum = np.sum(p == Y) Accuracy = one_sum / np.size(X, 0) print('Accuracy:', Accuracy)
# Load the path to images path = str(sys.argv[1]) num = random.choice(os.listdir(path)) image = random.choice(os.listdir(f'{path}/{num}')) im_pth = f"{path}/{num}/{image}" print(im_pth) # Open images and apply transformations im = Image.open(im_pth) cropped_image, np_image_final = function.process_image(im) # Predict classes top_classes, top_proba = function.predict(im_pth, model, topk=int(results.top_k)) # Print results with open(results.category_names, 'r') as f: labels_to_name = json.load(f) names_proba = [] i = 0 for classes in list(top_classes[0]): names_proba.append({ "name": labels_to_name[str(classes)], "proba": top_proba.item(i) }) i = i + 1 names_proba_df = pd.DataFrame(names_proba)
@author: 29132 """ import numpy as np import scipy.io as scio from DisplayData import displayData from function import predict input_layer_size = 400 #20x20 Input Images of Digits num_labels = 10 #=========== Part 1: Loading and Visualizing Data ============= print("Loading and Visualizing Data ...") data = scio.loadmat('ex3data1.mat') X = data['X'] y = data['y'] m = np.size(y) for i in range(m): y[i] -= 1 #Randomly select: 100 data points to display rand_indices = np.arange(m) np.random.shuffle(rand_indices) sel = X[rand_indices[0:100], :] displayData(sel) #================ Part 2: Loading Pameters ================ print('Loading Saved Neural Network Parameters ...') data1 = scio.loadmat('ex3weights.mat') Theta1 = data1['Theta1'] Theta2 = data1['Theta2'] pred = predict(Theta1, Theta2, X, y) print('Training Set Accuracy: ', pred)
help="pass in your data directory here", default='/home/workspace/aipnd-project/flowers/test/1/image_06752.jpg', required=False) parser.add_argument("-epochs", "--epochs", type=int, help="number of training iteration", default=2, required=False) parser.add_argument("-lr", "--learn_rate", type=float, help="the learning rate", default=0.0001, required=False) parser.add_argument("-topk", "--topks", type=int, help="number of top match results", default=5, required=False) args = parser.parse_args() test = args.file_path epochs = args.epochs lr = args.learn_rate topk = args.topks # Load the label mapping with open('/home/workspace/aipnd-project/cat_to_name.json', 'r') as c: cat_to_name = json.load(c) # Return the classification of the input and its probability result = (f.predict(test, model, cat_to_name, topk)) # Print the result print(np.reshape(result[1:], (2, len(result[1])))) print("\nThe top match flower category is " + result[1][0] + " with a probability of " + result[2][0])