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

首頁 > 編程 > Python > 正文

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

2020-02-16 00:19:39
字體:
來源:轉載
供稿:網友

這是一個使用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:       #解析文件數據到列表    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()            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 扶绥县| 玛纳斯县| 惠来县| 镇康县| 元江| 通化市| 毕节市| 兴隆县| 桐城市| 青浦区| 平南县| 富顺县| 鹤峰县| 星子县| 新沂市| 东兴市| 长宁县| 秭归县| 萍乡市| 盐山县| 嘉定区| 来宾市| 林西县| 武城县| 南华县| 同心县| 九江市| 运城市| 龙泉市| 绍兴市| 山西省| 唐山市| 体育| 泸水县| 利津县| 西乡县| 高雄市| 奉新县| 灵山县| 即墨市| 庄浪县|