国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python使用knn實(shí)現(xiàn)特征向量分類

2020-01-04 13:41:58
字體:
供稿:網(wǎng)友

這是一個(gè)使用knn把特征向量進(jìn)行分類的demo。

Knn算法的思想簡單說就是:看輸入的sample點(diǎn)周圍的k個(gè)點(diǎn)都屬于哪個(gè)類,哪個(gè)類的點(diǎn)最多,就把sample歸為哪個(gè)類。也就是說,訓(xùn)練集是一些已經(jīng)被手動打好標(biāo)簽的數(shù)據(jù),knn會根據(jù)你打好的標(biāo)簽來挖掘同類對象的相似點(diǎn),從而推算sample的標(biāo)簽。

Knn算法的準(zhǔn)確度受k影響較大,可能需要寫個(gè)循環(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ù)  '''距離計(jì)算'''  diffMat=tile(sample,(dataSetSize,1))-dataSet     #樣本與原先所有樣本的差值矩陣  sqDiffMat=diffMat**2   #差值矩陣平方  sqDistances=sqDiffMat.sum(axis=1)    #計(jì)算每一行上元素的和  distances=sqDistances**0.5  #開方  sortedDistIndicies=distances.argsort()   #按distances中元素進(jìn)行升序排序后得到的對應(yīng)下標(biāo)的列表  '''選擇距離最小的k個(gè)點(diǎn)'''  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í)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。


注:相關(guān)教程知識閱讀請移步到python教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 宜君县| 拉萨市| 沂南县| 绥德县| 绥江县| 永济市| 苍南县| 德昌县| 建昌县| 右玉县| 新郑市| 福泉市| 古浪县| 醴陵市| 报价| 阜南县| 芜湖市| 临江市| 民和| 高邮市| 紫云| 双牌县| 新安县| 沙河市| 收藏| 封开县| 旬邑县| 静乐县| 郧西县| 哈密市| 乳山市| 金川县| 青川县| 遂川县| 莆田市| 寻乌县| 镇康县| 新巴尔虎左旗| 博爱县| 马边| 沭阳县|