python knn模型_kNN模型(Python3.x环境)
#!/usr/bin/env python#-*- coding:utf-8 -*-#Author:Leslie Dang
from numpy import *
importmatplotlibimportmatplotlib.pyplot as pltfrom pylab importmpl
mpl.rcParams['font.sans-serif'] = ['FangSong'] #指定默認字體
mpl.rcParams['axes.unicode_minus'] = False #解決保存圖像是負號'-'顯示為方塊的問題
defclassify0(inX,dataSet,labels,k):#inX為預測樣本,dataSet為訓練樣本,labels為訓練樣本標簽,k為最近鄰的數目。
dataSetSize = dataSet.shape[0] #訓練樣本行數
#距離計算
diffMat = tile(inX,(dataSetSize,1)) -dataSet#tile(A,(a,b))功能是將數組A重復(a行b列)次,構成一個新的數組
sqDiffMat = diffMat**2sqDistances= sqDiffMat.sum(axis=1)#sum(axis=1)表示延矩陣水平方向求和
distances=sqDistances**0.5
#獲取距離排序后的索引排序
sortedDistIndicies =distances.argsort()#獲取前K個樣本的label頻次統計結果,將匯總結果放在classCount字典中。
classCount ={}for i inrange(k):
voteIlabel=labels[sortedDistIndicies[i]]#通過索引獲取對應的標注
classCount[voteIlabel] = classCount.get(voteIlabel,0)+1
#字典dict.get(key, default=None)函數返回指定鍵的值,如果值不在字典中返回默認值。
#對獲得的字典進行排序
sortedClassCount =sorted(classCount.items(),
key= lambda x:x[1],reverse=True)#iteritems()方法已經廢除了。在3.x里用 items()替換iteritems() ,可以用于for來循環遍歷。
return sortedClassCount[0][0] #返回距離最近的前k個樣本的label最多的類別名稱
deffile2matrix(filename):#處理文本文件,沒有表頭的、包含標簽的樣本數據。
#處理后,返回樣本特征矩陣、樣本標簽列表
fileRead=open(filename)
arrayOfLines=fileRead.readlines()
numOfLines=len(arrayOfLines)
returnMat= zeros((numOfLines,3))
classLabelVector=[]
index=0for line inarrayOfLines:
line=line.strip()
listFromLine= line.split('\t')#print('listFromLine:',listFromLine)
#獲取樣本行特征
returnMat[index,:] = listFromLine[0:3]#獲取樣本行標簽
classLabelVector.append(listFromLine[-1])
index+= 1
returnreturnMat,classLabelVector#returnMat為array格式,classLabelVector為list格式。
defautoNorm(dataSet):#將一列數據處理成[0,1]的歸一化值。
#返回歸一化數組、極差值、最小值。
minVals =dataSet.min(0)#參數0可以使函數從列中選取最小值,而不是選取當前行的最小值。
maxVals =dataSet.max(0)
ranges= maxVals-minVals
normSet=zeros(shape(dataSet))
rows=dataSet.shape[0]#所有樣本值減去最小值
normSet = dataSet - tile(minVals,(rows,1))#再除以樣本的區間值,實現歸一化。
normSet = normSet/tile(ranges,(rows,1))returnnormSet ,ranges ,minValsdefdatingClass(fileName,k):#函數名中不能加test字眼,不然pycharm調用不了這個函數。
#測試代碼
hoRatio = 0.30returnMat,classLebel=file2matrix(fileName)
normMat,ranges,minVals=autoNorm(returnMat)
m=normMat.shape[0]
numTestVecs= int(m*hoRatio)print('測試集樣本數:',numTestVecs)
errorCount= 0.0
for i inrange(numTestVecs):
classifierResult=classify0(normMat[i,:],normMat[numTestVecs:m,:],classLebel[numTestVecs:m],k)print('The classifier came back with: %d,the real answer is: %d' %(int(classifierResult), int(classLebel[i])))if (int(classifierResult) !=int(classLebel[i])):
errorCount+= 1.0
print('The total error rate is: %f'%(errorCount/float(numTestVecs)))return errorCount/float(numTestVecs)if __name__ == '__main__':
fileName= 'datingTestSet2.txt'k=[]
errorRate=[]for i in range(1,21):
k.append(i)
errorRate.append(datingClass(fileName,i)*100)
fig=plt.figure()
ax= fig.add_subplot(111)
ax.plot(k, errorRate)
plt.xlabel('k值')
plt.ylabel('KNN模型測試錯誤率(%)')
plt.title('KNN模型')
plt.show()
總結
以上是生活随笔為你收集整理的python knn模型_kNN模型(Python3.x环境)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 字符流读取,乱码问题
- 下一篇: Python算法学习教程