日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

机器学习笔记1(K-近邻算法)

發布時間:2023/12/10 编程问答 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 机器学习笔记1(K-近邻算法) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

人生苦短,我用Python

K-近鄰算法:簡單來說,K-近鄰算法就是采用測量不同特征值之間的距離方法進行分類

  • 優點:精度高、對異常值不敏感、無數據輸入假定
  • 缺點:計算復雜度高、空間復雜度高
  • 適用范圍:數值型、標稱型

工作原理:

存在一個樣本數據集合,也稱作訓練樣本集,并且樣本集中每個數據都存在標簽,即我們知道樣本集中每一個數據與所屬分類的對應關系。輸入沒有標簽的新數據后,將新數據的每個特征與樣本集中數據對應的特征進行比較,然后算法提取樣本集中特征最相似的數據(最近鄰)的分類標簽。一般來說,我們只選擇樣本集中前K個最相似的數據,這就是K-近鄰算法中K的出處,通常K是不大于20的整數。最后,選擇K個最相似數據中出現次數最多的分類,作為新數據的分類。

K-近鄰算法的一般流程:

  • 收集數據:可以使用任何方法。
  • 準備數據:距離計算所需要的數值,最好是結構化的數據格式。
  • 分析數據:可以使用任何方法。
  • 訓練算法:此步驟不適用于K-近鄰算法。
  • 測試算法:計算錯誤率。
  • 使用算法:首先需要輸入樣本數據和結構化的輸出結果,然后運行K-近鄰算法判定輸入數據分別屬于哪個分類,最后應用對計算出的分類執行后續的處理。
  • 實施KNN分類算法--偽代碼

    對未知類別屬性的數據集中的每個點依次執行以下操作:

  • 計算已知類別數據集中的點與當前點之間的距離;
  • 按照距離遞增次序排序;
  • 選取與當前點距離最小的K個點;
  • 確定前K個點所在類別的出現頻率;
  • 返回前K個點出現頻率最高的類別作為當前點的預測分類;
  • 計算兩個向量點之間的距離公式--歐式距離公式:

    例如:點(0,0)與(1,2)之間的距離計算為:

    sqrt((1-0)**2+(2-0)**2)

    代碼實現:

    import numpy as np import operator """ def CreateDataSet():group=np.array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])labels=['A','A','B','B']return group,labels print(CreateDataSet()) """ """ inX--用于分類的輸入向量 dataSet--輸入的訓練樣本集 labels--標簽向量 k--用于選擇最近鄰居的數目 其中標簽向量的元素數目和矩陣dataSet的行數相同 """ def classify(inX,dataSet,labels,k):dataSetSize=dataSet.shape[0] #獲得訓練樣本集的行數#將輸入向量在列方向重復一次,在行方向上dataSize次,并與訓練樣本集dataSet相減diffMat=np.tile(inX,(dataSetSize,1))-dataSetprint("diffMat:")print(diffMat)#將相減后的集合進行平方運算sqDiffMat=diffMat**2print("sqDiffMat:")print(sqDiffMat)#對平方后的集合進行相加運算--按行相加sqDistances=sqDiffMat.sum(axis=1)print("sqDistances:")print(sqDistances)#對相加后的數據開平方,得到輸入向量與每個訓練樣本集之間的距離值distances=np.sqrt(sqDistances)print("distances")print(distances)#返回數組從小到大的索引值--排序sortedDistIndicies=np.argsort(distances)print("sortedDistIndicies")print(sortedDistIndicies)classCount={}for i in range(k):voteIlabel=labels[sortedDistIndicies[i]]print("voteIlabel"+str(i))print(voteIlabel)classCount[voteIlabel]=classCount.get(voteIlabel,0)+1print("classCount"+str(i))print(classCount)sortedClassCount=sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)print("sortedClassCount:")print(sortedClassCount)return sortedClassCount[0][0]if __name__=='__main__':#訓練樣本集group = np.array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])#標簽向量labels = ['A', 'A', 'B', 'B']#輸入向量inX=[0,0]#用于選擇最近鄰居的數目k=3result=classify(inX,group,labels,k)print(result)""" 輸出值: diffMat: [[-1. -1.1][-1. -1. ][ 0. 0. ][ 0. -0.1]] sqDiffMat: [[ 1. 1.21][ 1. 1. ][ 0. 0. ][ 0. 0.01]] sqDistances: [ 2.21 2. 0. 0.01] distances [ 1.48660687 1.41421356 0. 0.1 ] sortedDistIndicies [2 3 1 0] voteIlabel0 B classCount0 {'B': 1} voteIlabel1 B classCount1 {'B': 2} voteIlabel2 A classCount2 {'B': 2, 'A': 1} sortedClassCount: [('B', 2), ('A', 1)] BProcess finished with exit code 0 """復制代碼

    測試結果:

    輸入[0,0],經過測試后,返回的結果是B,也就是說[0,0]這個輸入向量通過K-近鄰算法分類后歸為B類


    示例:使用K-近鄰算法改進約會網站的配對效果

  • 收集數據:提供文本文件
  • 準備數據:使用Python解析文本文件
  • 分析數據:使用Matplotlib畫二維擴散圖
  • 訓練算法:此步驟不適用與K-近鄰算法
  • 測試算法:使用海倫提供的部分數據作為測試樣本
  • 測試樣本和非測試的區別在于:測試樣本是已經完成分類的數據,如果預測分類與實際類別不同,則標記為一個錯誤。
  • 使用算法:產生簡單的命令行程序,然后可以輸入一些特征數據以判斷對方是否是自己喜歡的類型
  • 準備數據:從文本文件中解析數據

    文本樣本數據特征:

    • 每年獲得的飛行常客里程數
    • 玩視頻游戲所耗時間的百分比
    • 每周消費的冰淇淋公升數

    將文本記錄轉換為numpy數據的解析程序:

    def file2matrix(filename):# 打開文件fr = open(filename, 'r', encoding='utf-8')# 按行讀取數據arrayOLines = fr.readlines()# 獲取數據的行數numberOfLines = len(arrayOLines)# 創建以0填充的矩陣returnMat = np.zeros((numberOfLines, 3))print(returnMat)classLabelVector = []index = 0for line in arrayOLines:print(line)# 截取掉所有回車字符line = line.strip()print(line)# 以'\t'將line分割成一個元素列表listFromLine = line.split('\t')# 選取前三個元素,存儲到特征矩陣中returnMat[index, :] = listFromLine[0:3]# 選取最后一個元素存儲到標簽向量中classLabelVector.append(int(listFromLine[-1]))index += 1return returnMat, classLabelVector datingDataMat,datingLabels=file2matrix('D:\liuguojiang_Python\city_58\city_58\datingTestSet2.txt') fig=plt.figure() plt.title('K-') plt.xlabel('fly') plt.ylabel('consume') ax=fig.add_subplot(111)ax.scatter(datingDataMat[:,0],datingDataMat[:,1],15.0*np.array(datingLabels),15.0*np.array(datingLabels)) plt.show()復制代碼

    特別說明:代碼中的資源文件可以在此處下載:LiuGuoJiang/machinelearninginaction

    解析文本數據并用散點圖展示:


    準備數據:歸一化數值

    任選樣本數據中一行數據,計算距離時,因為飛行常客里程數比較大,所以對最后計算結果影響過大,所以需要對數據做歸一化處理。如將取值范圍處理為0~1或者-1~1之間。下面的公式可以將任意取值范圍的特征值轉化為0~1區間內的值:

    newValue=(oldValue-min)/(max-min)

    • 其中min和max分別是數據集中的最小特征值和最大特征值。

    歸一化特征值函數:

    def autoNorm(dataSet):#選取列的最小值minVals=dataSet.min(0)#選取列的最大值maxVals=dataSet.max(0)#列的最大值與最小值做減法ranges=maxVals-minVals#normDataSet=np.zeros([dataSet.shape[0],dataSet.shape[1]])print(normDataSet)#取出dataSet的行數m=dataSet.shape[0]#np.tile(minVals,(m,1))將minVals在 列上重復一次,在行上重復m次normDataSet=dataSet-np.tile(minVals,(m,1)) #(oldValue-min)normDataSet=normDataSet/np.tile(ranges,(m,1)) #(oldValue-min)/(max-min)return normDataSet,ranges,minValsnormDataSet,ranges,minVals=autoNorm(datingDataMat) print(normDataSet)復制代碼

    測試算法:機器學習算法一個很重要的工作就是評估算法的正確率,通常我們只提供已有數據的90%作為訓練樣本來訓練分類器,而使用其余的10%數據去測試分類器,檢測分類器的正確率。10%數據應該是隨機選擇的。

    分類器的測試代碼:

    def datingClassUnitTest():hoRatio=0.10datingDataMat, datingLabels = file2matrix('D:\liuguojiang_Python\city_58\city_58\datingTestSet2.txt')print(datingDataMat)normDataSet, ranges, minVals = autoNorm(datingDataMat)print(normDataSet)m=normDataSet.shape[0]numTestVecs=int(m*hoRatio)print("numTestVecs")print(numTestVecs)errorCount=0.0for i in range(numTestVecs):classifierResult=classify(normDataSet[i,:],normDataSet[numTestVecs:m,:],datingLabels[numTestVecs:m],3)print("the classfier came back with:{},the real answer is:{}".format(classifierResult,datingLabels[i]))if (classifierResult!=datingLabels[i]):errorCount+=1.0print("the total error rate is:{}".format(errorCount/float(numTestVecs)))the classfier came back with:3,the real answer is:3 the classfier came back with:2,the real answer is:2 the classfier came back with:1,the real answer is:1 ......... the classfier came back with:1,the real answer is:1 the classfier came back with:3,the real answer is:3 the classfier came back with:3,the real answer is:3 the classfier came back with:2,the real answer is:2 the classfier came back with:1,the real answer is:1 the classfier came back with:3,the real answer is:1 the total error rate is:0.05復制代碼

    分類器處理數據集的錯誤率是5%,即代表此分類器可以幫助對象判定分類。

    編寫可以讓用戶輸入自己需要判斷的輸入向量,通過該分類器幫助用戶判斷屬于哪一分類:

    def classifyPerson():resultList = ['not at all', 'in small doses', 'in large doses']percentTats = float(input( \"percentage of time spent playing video games?"))ffMiles = float(input("frequent flier miles earned per year?"))iceCream = float(input("liters of ice cream consumed per year?"))datingDataMat, datingLabels = file2matrix('D:\liuguojiang_Python\city_58\city_58\datingTestSet2.txt')normDataSet, ranges, minVals = autoNorm(datingDataMat)inArr = np.array([ffMiles, percentTats, iceCream, ])classifierResult = classify((inArr - \minVals) / ranges, normDataSet, datingLabels, 3)print("You will probably like this person: {}".format(resultList[classifierResult - 1])) if __name__=='__main__':classifyPerson()""" return: percentage of time spent playing video games?10 frequent flier miles earned per year?10000 liters of ice cream consumed per year?0.5 You will probably like this person: in small doses """復制代碼

    總結:

  • 定義K-近鄰算法程序。
  • 定義將文本數據集處理成二維數組的函數,便于處理。
  • 為消除某一特征數值過大對結果判定的影響,定義歸一化數值函數,公式:(oldValue-min)/(max-min)
  • 定義測試算法函數,用于測試分類器的錯誤率是否滿足使用要求。
  • 定義可以讓用戶輸入的代碼,輸入輸入向量,用于判定分類

  • 總結

    以上是生活随笔為你收集整理的机器学习笔记1(K-近邻算法)的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。