4 examples of 'knn sklearn' in Python

Every line of 'knn sklearn' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
169def predict_knn(X_train, X_test, y_train, y_test):
170 clf=knn(n_neighbors=3)
171 print("knn started")
172 clf.fit(X_train,y_train)
173 y_pred=clf.predict(X_test)
174 calc_accuracy("K nearest neighbours",y_test,y_pred)
175 np.savetxt('submission_surf_knn.csv', np.c_[range(1,len(y_test)+1),y_pred,y_test], delimiter=',', header = 'ImageId,Label,TrueLabel', comments = '', fmt='%d')
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

24def trainKNN(trainData,trainLabel):
25 knn = neighbors.KNeighborsClassifier(n_neighbors=3,algorithm='ball_tree')
26 #print(type(trainData))
27 return knn.fit(trainData,trainLabel)
35def skl_knn(self, k):
36 """k: number of neighbors to use in classification
37 test_data: the data/targets used to test the classifier
38 stored_data: the data/targets used to classify the test_data
39 """
40 fifty_x, fifty_y = self.mk_dataset(50000)
41 test_img = [self.data[i] for i in self.indx[60000:70000]]
42 test_img1 = np.array(test_img)
43 test_target = [self.target[i] for i in self.indx[60000:70000]]
44 test_target1 = np.array(test_target)
45 self.classifier.fit(fifty_x, fifty_y)
46
47 y_pred = self.classifier.predict(test_img1)
48 pickle.dump(self.classifier, open('knn.sav', 'wb'))
49 print(classification_report(test_target1, y_pred))
50 print("KNN Classifier model saved as knn.sav!")
221def __init__(self, X, Y):
222 '''
223 :param X:
224 :param Y:
225 '''
226 self.model = KNeighborsClassifier(n_neighbors=3)
227 self.X = X
228 self.Y = Y

Related snippets