-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTestKnn.py
51 lines (36 loc) · 1.27 KB
/
TestKnn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from PythonKnn import PythonKnn
# Load the IRIS dataset, as in the labs
# uncomment this if you use jupyter
# %matplotlib inline
from sklearn import datasets
import numpy as np
import matplotlib.pyplot as plt
#import k-nn classifier
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score
import operator
iris = datasets.load_iris()
#view a description of the dataset (uncomment next line to do so)
#print(iris.DESCR)
#Set X equal to features, Y equal to the targets
X=iris.data
y=iris.target
mySeed=1234567
#initialize random seed generator
np.random.seed(mySeed)
#we add some random noise to our data to make the task more challenging
X=X+np.random.normal(0,0.5,X.shape)
np.random.seed(mySeed)
indices= np.random.permutation(X.shape[0])
bins=np.array_split(indices,2) # we just need a training and testing set here
foldTrain=bins[0]
foldTest=bins[1]
knn=PythonKnn(10, 'euclidean')
knn.fit(X[foldTrain], y[foldTrain])
y_pred=knn.predict(X[foldTest])
a = np.where(y_pred != y[foldTest])
print("accuracy: ", knn.accuracy(y[foldTest],y_pred))
# print(knn.confMat(y[foldTest],y_pred,len(np.unique(y))))