print("Output file {} cannot be created".format(file_name)) sys.exit(1) # Write header for output file f_out.write('{}\t{}\t{}\t{}\n'.format('Value of k', 'Accuracy', 'Precision', 'Recall')) ############################## KNN algorithm #################################### # Create the k-NN object. knn = KNNClassifier(train_X[:, 1:], train_y[:, 1:], metric='euclidean') # Iterate through all possible values of k: for k in range(min_k, max_k + 1): knn.set_k(k) # 1. Perform KNN training and classify all the test points. In this step, you will # obtain a prediction for each test point. y_pred = [] for i in range(test_X.shape[0]): result = knn.predict(test_X[i, 1:]) if result: y_pred.append(result) else: knn.set_k(k - 1) y_pred.append(knn.predict(test_X[i, 1:])) knn.set_k(k)