python使用knn實現特徵向量分類

2022-09-27 09:36:14 字數 3528 閱讀 9302

這是乙個使用knn把特徵向量進行分類的demo。

knn演算法的思想簡單說就是:看輸入的sample點周圍的k個點都屬於哪個類,哪個類的點最多,就把sample歸為哪個類。也就是說,訓練集是一些已經被手動打好標籤的資料,knn會根據你打好的標籤來挖掘同類物件的相似點,從而推算sample的標籤。

knn演算法的準確度受k影響較大,可能需要寫個迴圈試一下選出針對不同資料集的最優的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)) #建立以零填充的numberoflines*3的numpy矩陣

classlabelvector=

index=0

for line in arrayolines: #解析檔案資料到列表

www.cppcns.com 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=datase程式設計客棧t.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 rawww.cppcns.comnge(k):

voteilabel=labels[sorteddistindicies[i]]

classcount[voteilabel]=classcount.get(voteilabel,0)+1

'''從大到小排序'''

sortetkfmxkdclasscount=sorted(classcount.items(),key=operator.itemgetter(1),reverse=true)

return sortedclasscount[0][0]

'''針對約會**資料的測試**'''

def datingclasstest():

horatio=0.20 #測試樣例資料比例

datingdata程式設計客棧mat,datinglabels=file2matrix('datingtestset1.txt')

normmat, ranges, minvals=autonorm(datingdatamat)

m =normmat.shape[0]

numtestvecs=int(m*horatio)

errorcount=0.0

k=4for 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=3group,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 ****** sample:"+label1)

print("classified label of the textsample:"+label2)

if __name__=='__main__':

main()

#datingclasstest()

本文標題: python使用knn實現特徵向量分類

本文位址:

Python實現KNN演算法

from numpy import import operator def creatdataset group array 1.0,1.1 1.0,1.0 0,0 0,0.1 lables a a b b return group,lables def classify0 inx,dataset,...

python實現knn演算法

importnumpyasnp importoperator defcreatedataset group np.array 1.0 1.1 1.0 1.0 0.0 0.0 0.0 0.1 labels a a b b returngroup,labels 分類演算法 inx待分類的點 defcla...

Python實現KNN回歸

knn演算法不僅可以用於分類,還可以用於回歸。通過找出乙個樣本的k個最近鄰居,將這些鄰居的屬性的平均值賦給該樣本,就可以得到該樣本的屬性。以下是knn回歸 calendar strategy knn.py 中用到的部分 x np.array x y np.array y x x.reshape 1,...