python使用knn實現(xiàn)特征向量分類
這是一個使用knn把特征向量進行分類的demo。
Knn算法的思想簡單說就是:看輸入的sample點周圍的k個點都屬于哪個類,哪個類的點最多,就把sample歸為哪個類。也就是說,訓(xùn)練集是一些已經(jīng)被手動打好標(biāo)簽的數(shù)據(jù),knn會根據(jù)你打好的標(biāo)簽來挖掘同類對象的相似點,從而推算sample的標(biāo)簽。
Knn算法的準(zhǔn)確度受k影響較大,可能需要寫個循環(huán)試一下選出針對不同數(shù)據(jù)集的最優(yōu)的k。
至于如何拿到特征向量,可以參考之前的博文。
代碼:
#-*- coding: utf-8 -*-
__author__ = 'Rossie'
from numpy import *
import operator
'''構(gòu)造數(shù)據(jù)'''
def createDataSet():
characters=array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
labels=['A','A','B','B']
return characters,labels
'''從文件中讀取數(shù)據(jù),將文本記錄轉(zhuǎn)換為矩陣,提取其中特征和類標(biāo)'''
def file2matrix(filename):
fr=open(filename)
arrayOLines=fr.readlines()
numberOfLines=len(arrayOLines) #得到文件行數(shù)
returnMat=zeros((numberOfLines,3)) #創(chuàng)建以零填充的numberOfLines*3的NumPy矩陣
classLabelVector=[]
index=0
for line in arrayOLines: #解析文件數(shù)據(jù)到列表
line=line.strip()
listFromLine=line.split('\t')
returnMat[index, :]=listFromLine[0:3]
classLabelVector.append(listFromLine[-1])
index+=1
return returnMat,classLabelVector #返回特征矩陣和類標(biāo)集合
'''歸一化數(shù)字特征值到0-1范圍'''
'''輸入為特征值矩陣'''
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
def classify(sample,dataSet,labels,k):
dataSetSize=dataSet.shape[0] #數(shù)據(jù)集行數(shù)即數(shù)據(jù)集記錄數(shù)
'''距離計算'''
diffMat=tile(sample,(dataSetSize,1))-dataSet #樣本與原先所有樣本的差值矩陣
sqDiffMat=diffMat**2 #差值矩陣平方
sqDistances=sqDiffMat.sum(axis=1) #計算每一行上元素的和
distances=sqDistances**0.5 #開方
sortedDistIndicies=distances.argsort() #按distances中元素進行升序排序后得到的對應(yīng)下標(biāo)的列表
'''選擇距離最小的k個點'''
classCount={}
for i in range(k):
voteIlabel=labels[sortedDistIndicies[i]]
classCount[voteIlabel]=classCount.get(voteIlabel,0)+1
'''從大到小排序'''
sortedClassCount=sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)
return sortedClassCount[0][0]
'''針對約會網(wǎng)站數(shù)據(jù)的測試代碼'''
def datingClassTest():
hoRatio=0.20 #測試樣例數(shù)據(jù)比例
datingDataMat,datingLabels=file2matrix('datingTestSet1.txt')
normMat, ranges, minVals=autoNorm(datingDataMat)
m =normMat.shape[0]
numTestVecs=int(m*hoRatio)
errorCount=0.0
k=4
for i in range(numTestVecs):
classifierResult=classify(normMat[i, : ],normMat[numTestVecs:m, : ],datingLabels[numTestVecs:m],k)
print("The classifier came back with: %s, thereal answer is: %s" %(classifierResult, datingLabels[i]))
if(classifierResult!= datingLabels [i] ) :
errorCount += 1.0
print("the total error rate is: %f" % (errorCount/float(numTestVecs)))
def main():
sample=[0,0]#簡單樣本測試
sampleText = [39948,6.830795,1.213342]#文本中向量樣本測試
k=3
group,labels=createDataSet()
label1=classify(sample,group,labels,k)#簡單樣本的分類結(jié)果
fileN = "datingTestSet.txt"
matrix,label = file2matrix(fileN)
label2 =classify(sampleText,matrix,label,k)#文本樣本的分類結(jié)果
print("ClassifiedLabel of the simple sample:"+label1)
print("Classified Label of the textsample:"+label2)
if __name__=='__main__':
main()
#datingClassTest()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python3+PyQt5實現(xiàn)使用剪貼板做復(fù)制與粘帖示例
本篇文章主要介紹了python3+PyQt5實現(xiàn)使用剪貼板做復(fù)制與粘帖示例,具有一定的參考價值,有興趣的可以了解一下。2017-01-01
Python腳本開發(fā)中的命令行參數(shù)及傳參示例詳解
這篇文章主要為大家介紹了Python腳本開發(fā)中的命令行參數(shù)及傳參示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07
使用python創(chuàng)建極坐標(biāo)平面的示例代碼
PolarPlane 是 Manim(一個用于數(shù)學(xué)動畫的Python庫)中的一個類,用于創(chuàng)建極坐標(biāo)平面,與笛卡爾坐標(biāo)系不同,極坐標(biāo)系是基于角度和半徑來定位點的,本文就給大家介紹如何用python創(chuàng)建極坐標(biāo)平面,需要的朋友可以參考下2024-08-08

