怎么在python中使用sklearn實(shí)現(xiàn)一個(gè)KNN分類算法?針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡(jiǎn)單易行的方法。

實(shí)現(xiàn)步驟:通過選取與該點(diǎn)距離最近的k個(gè)樣本,在這k個(gè)樣本中哪一個(gè)類別的數(shù)量多,就把k歸為哪一類。
注意
該算法需要保存訓(xùn)練集的觀察值,以此判定待分類數(shù)據(jù)屬于哪一類
k需要進(jìn)行自定義,一般選取k<30
距離一般用歐氏距離,即 
通過sklearn對(duì)數(shù)據(jù)使用KNN算法進(jìn)行分類
代碼如下:
## 導(dǎo)入鳶尾花數(shù)據(jù)集 iris = datasets.load_iris() data = iris.data[:, :2] target = iris.target ## 區(qū)分訓(xùn)練集和測(cè)試集,75%的訓(xùn)練集和25%的測(cè)試集 train_data, test_data = train_test_split(np.c_[data, target]) ## 訓(xùn)練并預(yù)測(cè),其中選取k=15 clf = neighbors.KNeighborsClassifier(15, 'distance') clf.fit(train_data[:, :2], train_data[:, 2]) Z = clf.predict(test_data[:, :2]) print '準(zhǔn)確率:' ,clf.score(test_data[:, :2], test_data[:, 2]) colormap = dict(zip(np.unique(target), sns.color_palette()[:3])) plt.scatter(train_data[:, 0], train_data[:, 1], edgecolors=[colormap[x] for x in train_data[:, 2]],c='', s=80, label='all_data') plt.scatter(test_data[:, 0], test_data[:, 1], marker='^', color=[colormap[x] for x in Z], s=20, label='test_data') plt.legend() plt.show()
結(jié)果如下:

關(guān)于怎么在python中使用sklearn實(shí)現(xiàn)一個(gè)KNN分類算法問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
名稱欄目:怎么在python中使用sklearn實(shí)現(xiàn)一個(gè)KNN分類算法-創(chuàng)新互聯(lián)
網(wǎng)頁(yè)鏈接:http://www.chinadenli.net/article44/dhdehe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、網(wǎng)站設(shè)計(jì)、企業(yè)建站、網(wǎng)站營(yíng)銷、微信小程序、定制開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容