基于kNN算法改进约会网站的配对效果
基于kNN算法实现手写体数字识别
改进约会网站
。
import numpy as np
import matplotlib.pyplot as plt
import os
import operator
def file2matrix(filename):
fr = open(filename)#读取文件
arrayLine = fr.readlines()#读文件
number = len(arrayLine)
featureMat = np.zeros((number,3))#特征矩阵
classLabelVector = []#类别标签向量
index = 0
for line in arrayLine:
line = line.strip()
line = line.split('\t')
featureMat[index,:] = line[0:3]
if line[-1] == 'didntLike':
classLabelVector.append(0)
elif line[-1] == 'smallDoses':
classLabelVector.append(1)
elif line[-1] == 'largeDoses':
classLabelVector.append(2)
index += 1
return featureMat,classLabelVector
def autoNorm(dataSet):
minVals = dataSet.min(0)
maxVals = dataSet.max(0)
ranges = maxVals - minVals
normDataset = np.zeros(np.shape(dataSet))
m = dataSet.shape[0]
normDataset = dataSet - np.tile(minVals,(m,1))
normDataset = normDataset/np.tile(ranges,(m,1))
return normDataset,ranges,minVals
def kNNClassify(inX, dataSet, labels, k):
dataSetSize = dataSet.shape[0]
diffMat = np.tile(inX,(dataSetSize,1)) - dataSet
sqDiffMat = diffMat**2
sqDistances = sqDiffMat.sum(axis = 1)
distances = sqDistances**0.5#求距离
sortedDistindex = distances.argsort()#排序
classCount = {}
w = []
for i in range(k):
w.append((distances[sortedDistindex[k-1]]-distances[sortedDistindex[i]])/(distances[sortedDistindex[k-1]]-distances[sortedDistindex[0]]))
voteIlabel = labels[sortedDistindex[i]]
classCount[voteIlabel] = classCount.get(voteIlabel,0)+1#判断k个点的类别
sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)
return sortedClassCount[0][0]
def datingClassTest():
filename = "E:/data1/kNN_Dating/datingTestSet.txt"
datingDataMat, datingLabels = file2matrix(filename)
normMat, ranges, minVals = autoNorm(datingDataMat)
m = normMat.shape[0]
hoRatio = 0.10
numTestVecs = int(m * hoRatio)
errorCount = 0
for i in range(numTestVecs):
classifierResult = kNNClassify(normMat[i,:], normMat[numTestVecs:m,:],datingLabels[numTestVecs:m], 3)
print("分类结果:%d\t真实类别:%d" % (classifierResult, datingLabels[i]))
if classifierResult != datingLabels[i]:
errorCount += 1.0
print("错误率:%f%%" %(errorCount/float(numTestVecs)*100))
if __name__ == '__main__':
datingClassTest()
手写体数字识别
。
import numpy as np
import matplotlib.pyplot as plt
import os
import operator
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])
return returnVect
def loadTrainData(path):
hwLabels = []
index = 0
files = os.listdir(path)
hwMat = np.zeros((len(files),1024))
for file in files:
hwLabels.append(int(file.split('_')[0]))
hwMat[index,:]=img2vector(path.split('/')[0] + '/' + path.split('/')[1] + '/' + file)
index += 1
return hwMat,hwLabels
def kNNClassify(inX, dataSet, labels, k):
dataSetSize = dataSet.shape[0]
diffMat = np.tile(inX,(dataSetSize,1)) - dataSet
sqDiffMat = diffMat**2
sqDistances = sqDiffMat.sum(axis = 1)
distances = sqDistances**0.5#求距离
sortedDistindex = distances.argsort()#排序
classCount = {}
for i in range(k):
voteIlabel = labels[sortedDistindex[i]]
classCount[voteIlabel] = classCount.get(voteIlabel,0)+1#判断k个点的类别
sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)
return sortedClassCount[0][0]
def handwritingClassTest():
path='kNN_hand_writing/trainingDigits'
hwMat,hwLabels = loadTrainData(path)
errorCount = 0
test_hwMat,test_hwLabels = loadTrainData('kNN_hand_writing/testDigits')
numTestVes = len(test_hwMat)
for i in range(numTestVes):
classifierResult = kNNClassify(test_hwMat[i,:],hwMat,hwLabels ,3)
print("分类结果:%d\t真实类别:%d" % (classifierResult, test_hwLabels[i]))
if classifierResult != test_hwLabels[i]:
errorCount += 1
print("总共错了%d个数据\n错误率为%f%%" % (errorCount, errorCount/float(numTestVes)*100))
if __name__=='__main__':
handwritingClassTest()
改进约会网站的配对效果
读取数据
对于.txt文件的读取方式是
fr = open(filename)#读取文件
arrayLine = fr.readlines()#读文件
处理数据
将数据转变为特征矩阵和对应的分类标签向量。我们知道机器是无法识别英文的所以我们需要将英文标签转变为数字使机器能够识别。
即:
if line[-1] == 'didntLike':
classLabelVector.append(0)
elif line[-1] == 'smallDoses':
classLabelVector.append(1)
elif line[-1] == 'largeDoses':
classLabelVector.append(2)
数据归一化处理
我们通常将数据转化为0-1区间上的值
公式为 x =(t - min)/(max-min)
下面展示一些内容。
dataSet.min(0)列最小值
np.tile(a,(2))函数的作用就是将函数将函数沿着X轴扩大两倍。如果扩大倍数只有一个,默认为X轴
np.tile(a,(2,1))第一个参数为Y轴扩大倍数,第二个为X轴扩大倍数。
kNN核心算法实现
KNN的核心算法讲解可以参考链接: https://blog.csdn.net/LOVE_105/article/details/112607352.
测试数据
最后就是读取数据,进行测试,根据真实值判断错误率。
手写体数字识别
处理数据
因为在kNN算法中,每个点都是用向量表示的。而手写体数字数据为32X32的二维数据格式,所以我们需要将其转换为一维数组,即表示成一个向量。
for i in range(32):
lineStr = fr.readline()
for j in range(32):
returnVect[0,32*i+j] = int(lineStr[j])
return returnVect
之后的操作与改进约会网站的配对效果的操作相同。