python使用knn實現特征向量分類
更新時間:2018年12月26日 11:41:35 作者:RossieSeven
這篇文章主要為大家詳細介紹了python使用knn實現特征向量分類,具有一定的參考價值,感興趣的小伙伴們可以參考一下
這是一個使用knn把特征向量進行分類的demo。
Knn算法的思想簡單說就是:看輸入的sample點周圍的k個點都屬于哪個類,哪個類的點最多,就把sample歸為哪個類。也就是說,訓練集是一些已經被手動打好標簽的數據,knn會根據你打好的標簽來挖掘同類對象的相似點,從而推算sample的標簽。
Knn算法的準確度受k影響較大,可能需要寫個循環(huán)試一下選出針對不同數據集的最優(yōu)的k。
至于如何拿到特征向量,可以參考之前的博文。
代碼:
#-*- coding: utf-8 -*-
__author__ = 'Rossie'
from numpy import *
import operator
'''構造數據'''
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
'''從文件中讀取數據,將文本記錄轉換為矩陣,提取其中特征和類標'''
def file2matrix(filename):
fr=open(filename)
arrayOLines=fr.readlines()
numberOfLines=len(arrayOLines) #得到文件行數
returnMat=zeros((numberOfLines,3)) #創(chuàng)建以零填充的numberOfLines*3的NumPy矩陣
classLabelVector=[]
index=0
for line in arrayOLines: #解析文件數據到列表
line=line.strip()
listFromLine=line.split('\t')
returnMat[index, :]=listFromLine[0:3]
classLabelVector.append(listFromLine[-1])
index+=1
return returnMat,classLabelVector #返回特征矩陣和類標集合
'''歸一化數字特征值到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] #數據集行數即數據集記錄數
'''距離計算'''
diffMat=tile(sample,(dataSetSize,1))-dataSet #樣本與原先所有樣本的差值矩陣
sqDiffMat=diffMat**2 #差值矩陣平方
sqDistances=sqDiffMat.sum(axis=1) #計算每一行上元素的和
distances=sqDistances**0.5 #開方
sortedDistIndicies=distances.argsort() #按distances中元素進行升序排序后得到的對應下標的列表
'''選擇距離最小的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]
'''針對約會網站數據的測試代碼'''
def datingClassTest():
hoRatio=0.20 #測試樣例數據比例
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)#簡單樣本的分類結果
fileN = "datingTestSet.txt"
matrix,label = file2matrix(fileN)
label2 =classify(sampleText,matrix,label,k)#文本樣本的分類結果
print("ClassifiedLabel of the simple sample:"+label1)
print("Classified Label of the textsample:"+label2)
if __name__=='__main__':
main()
#datingClassTest()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Python win32com 操作Exce的l簡單方法(必看)
下面小編就為大家?guī)硪黄狿ython win32com 操作Exce的l簡單方法(必看)。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
python多項式擬合之np.polyfit 和 np.polyld詳解
這篇文章主要介紹了python多項式擬合之np.polyfit 和 np.polyld的實例代碼,python數據擬合主要可采用numpy庫,庫的安裝可直接用pip install numpy等,需要的朋友跟隨小編一起學習吧2020-02-02
Python使用cx_Oracle模塊操作Oracle數據庫詳解
這篇文章主要介紹了Python使用cx_Oracle模塊操作Oracle數據庫,結合實例形式較為詳細的分析了cx_Oracle模塊的下載、安裝及針對Oracle數據庫的連接、執(zhí)行SQL語句、存儲過程等相關操作技巧,需要的朋友可以參考下2018-05-05

