-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkNN.py
213 lines (172 loc) · 6.84 KB
/
kNN.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# -*- coding: utf-8 -*-
"""
kNN: k Nearest Neighbors
Input: inX: vector to compare to existing dataset (1xN)
dataSet: size m data set of known vectors (NxM)
labels: data set labels (1xM vector)
k: number of neighbors to use for comparison (should be an odd number)
Output: the most popular class label
@author: zhlei99
"""
from numpy import *
import numpy as np
import operator
import importlib
import kNN
from os import listdir
#importlib.reload(sys)
from matplotlib import *
import matplotlib.pyplot as plt
def createDataSet():
group=np.array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
labels = ['A','A','B','B']
return group, labels
def classify0(inX, dataSet, labels, k):
"""
kNN algorithm
"""
#get dataSet number of row Vector
dataSetSize = dataSet.shape[0]
#construct an array by repeating inX the number of times given by (dataSetSize,1)
#the times of line is dataSetSize, the times of columns is 1
#calculate distance
diffMat = np.tile(inX, (dataSetSize, 1)) - dataSet
sqDiffMat = diffMat**2
sqDistances = sqDiffMat.sum(axis=1)
distances = sqDistances**0.5
#return the indices that would sort this array
sorteDistIndicies = distances.argsort()
#select the smallest k points
classCount={}
for i in range(k):
voteIlabel = labels[sorteDistIndicies[i]]
#get :D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
#sorted
sortedClassCount = sorted(classCount.items(),
key = operator.itemgetter(1), reverse = True) #After f = itemgetter(2), the call f(r) returns r[2]
#return predictive lable
print
return sortedClassCount[0][0]
def file2matrix(filename):
"""
date conversion
"""
fr = open(filename)
arrayOLines = fr.readlines()
numberOfLines = len(arrayOLines)
#creat NumPy matrix
returnMat = np.zeros((numberOfLines,3))
classLabelVector = []
index = 0
#label change int
classLabelDict = {'largeDoses':3, 'smallDoses':2,'didntLike':1}
#Text data parsing
for line in arrayOLines:
line = line.strip()
listFromLine = line.split('\t')
returnMat[index,:] = listFromLine[0:3]
# change label into int type
classLabelVector.append(classLabelDict.get(listFromLine[-1]))
index += 1
fr.close()
return returnMat, classLabelVector
def showDataMap(inX, inY, datingLabels):
"""
show data map scatter 二维图
"""
fig = plt.figure()
ax = fig.add_subplot(111)
# ax.scatter(inX, inY)
ax.scatter(inX, inY, s=15.0 * np.array(datingLabels), c=15.0* np.array(datingLabels))
plt.show()
def autoNorm(dataSet):
"""
#normalized data
"""
minVals = dataSet.min(0)
maxVals = dataSet.max(0)
ranges = maxVals - minVals
normDataSet = np.zeros(np.shape(dataSet))
m = np.shape(dataSet)[0]
normDataSet = dataSet - np.tile(minVals, (m, 1))
normDataSet = normDataSet /np.tile(ranges , (m , 1))
return normDataSet, ranges, minVals
def datingClassTest():
"""
test calssfier error rate
"""
hoRatio = 0.10
datingDataMat, datingLabels = file2matrix('datingTestSet.txt')
normMat, ranges, minVals = kNN.autoNorm(datingDataMat)
m =normMat.shape[0]
numTestVecs = int(m*hoRatio)
errorCount = 0.0
for i in range(numTestVecs):
classifierResult = classify0(normMat[i,:],normMat[numTestVecs:m,:], \
datingLabels[numTestVecs:m],3)
print ("the classfierResult came back with %d ,the real answer is : %d"\
%(classifierResult, datingLabels[i]))
if (classifierResult != datingLabels[i]): errorCount += 1.0
print ("the total error rate is : %f" %(errorCount/float(numTestVecs)))
def classifyPerson():
"""
imput someone information and predicts how much she will like this person
"""
resultList = ['not at all','in small doses','in large doses']
percentTats = float (input(\
"percentage of time spent playing video games?"))
ffMiles = float(input("frequent fliter miles earned per year?"))
iceCream = float(input("liters of ice cream consumed per year?"))
datingDataMat, datingLabels = file2matrix('datingTestSet.txt')
normMat, ranges, minVals = kNN.autoNorm(datingDataMat)
classifierResult = kNN.classify0([ffMiles, percentTats, iceCream ],normMat, \
datingLabels,3)
print ("you will probably like this person : %s" %(resultList[classifierResult - 1]))
"""
handwriting recognition with out kNN classifier,we'll be working only with the digits 0-9
"""
def img2vector(filename):
returnVect = np.zeros((1,1024))
fr = open(filename)
for i in range(32):
lineStr = fr.readline()
for j in range(32):
returnVect[0,32*i+j] = int(lineStr[j])
fr.close()
return returnVect
def handwritingClassTest():
hwLabels = [] #get contents of directory
trainingFileList = listdir('./digits/trainingDigits')
m = len(trainingFileList)
trainingMat = np.zeros((m,1024))
for i in range(m):
fileNameStr = trainingFileList[i] #process class num from filename
fileStr = fileNameStr.split(".")[0]
classNumStr = int(fileStr.split('_')[0])
hwLabels.append(classNumStr)
trainingMat[i,:] = img2vector('./digits/trainingDigits/%s' %fileNameStr)
# print (type(trainingMat[i,:]))
testFileList = listdir ('./digits/testDigits')
errorCount = 0.0
mTest = len(testFileList)
for i in range(mTest):
fileNameStr = testFileList[i]
fileStr = fileNameStr.split(".")[0]
classNumStr = int(fileStr.split('_')[0])
vectorUnderTest= img2vector('./digits/testDigits/%s' %fileNameStr)
classiferResult = classify0(vectorUnderTest, trainingMat , hwLabels, 3) #k= 5, rate=0.017970 k=3 rate =0.010571
print ("the classifier came back with:%d ,the real answer is : %d " \
%(classiferResult, classNumStr))
if (classiferResult != classNumStr):
errorCount +=1.0
print ("\n the total number of is : %d " % (errorCount))
print ("\nthe total error rate is : %f" % (errorCount/float(mTest)))
if __name__ == '__main__':
# datingDataMat,datingLabels = file2matrix('datingTestSet.txt')
# showDataMap(datingDataMat[:,1],datingDataMat[:,2], datingLabels)
# normDataSet, ranges, minVals = kNN.autoNorm(datingDataMat)
# kNN.datingClassTest()
# kNN.classifyPerson()
# testVector = kNN.img2vector('./digits/testDigits/0_13.txt')
kNN.handwritingClassTest()