工作原理:存在一個樣本數(shù)據(jù)集合,也稱作訓練樣本集耙饰,樣本集中每個數(shù)據(jù)都存在標簽摩瞎,即已知樣本集中每一數(shù)據(jù)與其所屬分類的對應(yīng)關(guān)系拴签。當輸入沒有標簽的新數(shù)據(jù)孝常, 將新數(shù)據(jù)的每個特征與樣本集中數(shù)據(jù)對應(yīng)的特征進行比較旗们,提取樣本集中特征最相似數(shù)據(jù)(最近鄰)的k個分類標簽(K-近鄰),最后選擇k個最相似數(shù)據(jù)中出現(xiàn)次數(shù)最多的分類构灸,作為新數(shù)據(jù)的分類上渴。
python代碼(python3版本):
from numpy import *
import operator
def createDataset():
group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
labels = ['A','A','B','B']
return group, labels
# K-近鄰算法
def classify0(inX, dataSet, labels, k):
dataSetSize=dataSet.shape[0]
diffMat=tile(inX, (dataSetSize,1))-dataSet
sqDiffMat=diffMat**2
# 每行元素相加
sqDistances=sqDiffMat.sum(axis=1)
distances=sqDistances**0.5
# 排序輸出其下標值
sortedDistIndicies=distances.argsort()
classCount={}
for i in range(k):
voteIlabel=labels[sortedDistIndicies[i]]
# 返回key為voteIlabel的value,如果沒有這個元素則返回0喜颁,有就加1
classCount[voteIlabel]=classCount.get(voteIlabel,0)+1
# operator.itemgetter(1)表示對第二個域進行排序稠氮,reverse=True表示倒序排序
sortedClassCount=sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)
return sortedClassCount[0][0]
# 將文本記錄轉(zhuǎn)換為numpy
def file2matrix(filename):
fr=open(filename)
arrayOLines=fr.readlines()
numberOfLines=len(arrayOLines)
# 用0填充二維數(shù)組,numberOfLines行3列
returnMat=zeros((numberOfLines,3))
classLabelVector=[]
index=0
for line in arrayOLines:
line=line.strip()
listFromLine=line.split('\t')
returnMat[index,:]=listFromLine[0:3]
classLabelVector.append(int(listFromLine[-1]))
index+=1
return returnMat,classLabelVector
# 歸一化特征值
def autoNorm(dataSet):
minVals=dataSet.min(0)
maxVals=dataSet.max(0)
ranges=maxVals-minVals
normDataSet=zeros(shape(dataSet))
m=dataSet.shape[0]
normDataSet=dataSet-tile(minVals,(m,1))
normDataSet=normDataSet/tile(ranges,(m,1))
return normDataSet,ranges,minVals
# 針對約會網(wǎng)站的測試
def datingClassTest():
hoRatio=0.10
datingDataMat,datingLabels=file2matrix('datingTestSet2.txt')
normMat,ranges,minVals=autoNorm(datingDataMat)
m=normMat.shape[0]
# 選出10%的數(shù)據(jù)進行測試
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 classifier 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: %.2f%%' % (errorCount/float(numTestVecs)*100))
# 預(yù)測函數(shù)
def classifyPerson():
resultList=['not at all','in small doses','in large doses']
percentTats=float(input('percentage of time spent playing video games?'))
ffMiles=float(input('frequent flier miles earned per year?'))
iceCream=float(input('liters of ice cream consumed per year?'))
datingDataMat,datingLabels=file2matrix('datingTestSet2.txt')
normMat,ranges,minVals=autoNorm(datingDataMat)
inArr=array([ffMiles,percentTats,iceCream])
classifierResult=classify0((inArr-minVals)/ranges,normMat,datingLabels,3)
print('you will probably like this person: ',resultList[classifierResult-1])
以上內(nèi)容均來自《機器學習實戰(zhàn)》