監督學習-KNN最鄰近分類算法

分類(Classification)指的是從數據中選出已經分好類的訓練集,在該訓練集上運用數據挖掘分類的技術建立分類模型,從而對沒有分類的數據進行分類的分析方法。

分類問題的應用場景:用于將事物打上一個標簽,通常結果為離散值。例如判斷一副圖片上的動物是一只貓還是一只狗,分類通常是建立在回歸之上。

基本的分類方法—KNN最鄰近分類算法,簡稱KNN,最簡單的機器學習算法之一。

核心邏輯:在距離空間里,如果一個樣本的最接近的K個鄰居里,絕大多數屬于某個類別,則該樣本也屬于這個類別。

?

?

給定電影分類樣例,預測某一電影的分類。

from sklearn import neighbors  #導入模塊
import warnings
warnings.filterwarnings('ignore') #不發出警告

df = pd.DataFrame({'name':['北京遇上西雅圖','喜歡你','瘋狂動物城','戰狼2','力王','敢死隊'],'fight':[3,2,1,101,99,98],'kiss':[104,100,81,10,5,2],'type':['love','love','love','action','action','action']})
love = df[df['type']] == 'love']
action = df[df['type']== 'action']
plt.scatter(love['fight'],love['kiss'],color = 'red',label = 'love')  # 類型為愛情的電影做紅色散點圖
plt.scatter(action['fight'],action['kiss'],color = 'green',label='action')  # 類型為動作片的電影做綠色散點圖
plt.legend()knn = neighbors.KNeighborsClassifier()  # 創建KNN最鄰近分類模型
knn.fit(df[['fight','kiss']],df['type'])  # 給模型導入數據

k = knn.predict([[18, 90]])  # 預測數據,參數需要是二維的
print('預測電影類型為%s'%k,type(k))  # 預測電影類型為['love'],<class 'numpy.ndarray'>
plt.scatter(18,90,color = 'blue',marker='x',label=k) 
plt.text(18,90,'《你的名字》',color='blue') 

?

另外隨機生成一組數據,用上面的knn分類模型進行分類

df2 = pd.DataFrame(np.random.rand(100,2)*80,columns=['fight','kiss'])
df2['predictType'] = knn.predict(df2)plt.scatter(love['fight'],love['kiss'],color = 'red',label = 'love')  
plt.scatter(action['fight'],action['kiss'],color = 'green',label='action')
plt.legend()plt.scatter(df2[df2['predictType']=='love']['fight'],df2[df2['predictType']=='love']['kiss'],color = 'red',label = 'love',marker='x')  
plt.scatter(df2[df2['predictType']=='action']['fight'],df2[df2['predictType']=='action']['kiss'],color = 'green',label='action',marker='x')df2.head()

? ? ?

?

案例2:植物分類

from sklearn import datasets
iris = datasets.load_iris()
print(iris.data[:5])  #類型為<class 'sklearn.utils.Bunch'>,數據部分為一個二維數組
print(iris.feature_names)
print(iris.target_names) 
# print(iris.target) #表示每一個數據所屬的分類,分類用數字表示,結果為數組# [[5.1 3.5 1.4 0.2]
#  [4.9 3.  1.4 0.2]
#  [4.7 3.2 1.3 0.2]
#  [4.6 3.1 1.5 0.2]
#  [5.  3.6 1.4 0.2]]
#['sepal length (cm)','sepal width (cm)','petal length (cm)','petal width (cm)'],表示分類特征:萼片長度、萼片寬度、花瓣長度、花瓣寬度
#['setosa' 'versicolor' 'virginica'],表示分類名稱

?

構建DataFrame方便查看數據,并使用數字分類和名稱分類分別構建模型

data = pd.DataFrame(iris.data, columns = iris.feature_names)  #構建DataFrame方便查看
data['target'] = iris.target
print(data.head())
print('----------------------------')d = pd.DataFrame({'target':[0, 1, 2],'target_names':iris.target_names})
print(d.head())
print('----------------------------')data = pd.merge(data,d,on='target')  #最終形成的DataFrame包含四個分類特征、分類數值、分裂名稱
print(data.head())
print('----------------------------')knn1 = neighbors.KNeighborsClassifier()  
knn1.fit(iris.data,iris.target)  #使用分類數值構建模型
t1 = knn1.predict([[0.1,0.2,0.3,0.4]])
print('所在分類(數字表示)為',t1)knn2 = neighbors.KNeighborsClassifier()
knn2.fit(iris.data,data['target_names']) #使用分類名稱構建模型
t2 = knn2.predict([[0.1,0.2,0.3,0.4]])
print('所在分類(名稱表示)為',t2)  
# 上述輸出結果
#
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target # 0 5.1 3.5 1.4 0.2 0 # 1 4.9 3.0 1.4 0.2 0 # 2 4.7 3.2 1.3 0.2 0 # 3 4.6 3.1 1.5 0.2 0 # 4 5.0 3.6 1.4 0.2 0 # ---------------------------- # target target_names # 0 0 setosa # 1 1 versicolor # 2 2 virginica # ---------------------------- # sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target target_names # 0 5.1 3.5 1.4 0.2 0 setosa # 1 4.9 3.0 1.4 0.2 0 setosa # 2 4.7 3.2 1.3 0.2 0 setosa # 3 4.6 3.1 1.5 0.2 0 setosa # 4 5.0 3.6 1.4 0.2 0 setosa # ---------------------------- # 所在分類(數字表示)為 [0] # 所在分類(名稱表示)為 ['setosa']

?

轉載于:https://www.cnblogs.com/Forever77/p/11385689.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391598.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391598.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391598.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

istio 和 kong_如何啟動和運行Istio

istio 和 kongby Chris Cooney克里斯庫尼(Chris Cooney) 如何啟動和運行Istio (How to get Istio up and running) 而一旦完成&#xff0c;您就可以做的瘋狂的事情。 (And the crazy stuff you can do once it is.) The moment you get Istio working on your cluster, it fee…

js練習--貪吃蛇(轉)

最近一直在看javascript&#xff0c;但是發現不了動力。就開始想找動力&#xff0c;于是在網上找到了一個用js寫的貪吃蛇游戲。奈何還不會用git&#xff0c;就只能先這樣保存著。哈哈哈&#xff0c;這也算第一篇博客了&#xff0c;以后會堅持用自己的代碼寫博客的&#xff0c;下…

bzoj千題計劃169:bzoj2463: [中山市選2009]誰能贏呢?

http://www.lydsy.com/JudgeOnline/problem.php?id2463 n為偶數時&#xff0c;一定可以被若干個1*2 矩形覆蓋 先手每次從矩形的一端走向另一端&#xff0c;后手每次走向一個新的矩形 所以先手必勝 n為奇數時&#xff0c;先手走完一步后&#xff0c;剩下同n為偶數 所以先手必敗…

無監督學習-主成分分析和聚類分析

聚類分析&#xff08;cluster analysis&#xff09;是將一組研究對象分為相對同質的群組&#xff08;clusters&#xff09;的統計分析技術&#xff0c;即將觀測對象的群體按照相似性和相異性進行不同群組的劃分&#xff0c;劃分后每個群組內部各對象相似度很高&#xff0c;而不…

struts實現分頁_在TensorFlow中實現點Struts

struts實現分頁If you want to get started on 3D Object Detection and more specifically on Point Pillars, I have a series of posts written on it just for that purpose. Here’s the link. Also, going through the Point Pillars paper directly will be really help…

封裝jQuery下載文件組件

使用jQuery導出文檔文件 jQuery添加download組件 jQuery.download function(url, data, method){if( url && data ){data typeof data string ? data : paramEdit(data);     function paramEdit(obj){        var temStr "",tempStr"…

7.13. parallel - build and execute shell command lines from standard input in parallel

并行執行shell命令 $ sudo apt-get install parallel 例 7.5. parallel - build and execute shell command lines from standard input in parallel $ cat *.csv | parallel --pipe grep 13113 設置塊大小 $ cat *.csv | parallel --block 10M --pipe grep 131136688 原…

MySQL-InnoDB索引實現

聯合索引提高查詢效率的原理 MySQL會為InnoDB的每個表建立聚簇索引&#xff0c;如果表有索引會建立二級索引。聚簇索引以主鍵建立索引&#xff0c;如果沒有主鍵以表中的唯一鍵建立&#xff0c;唯一鍵也沒會以隱式的創建一個自增的列來建立。聚簇索引和二級索引都是一個b樹&…

Go語言-基本的http請求操作

Go發起GET請求 基本的GET請求 //基本的GET請求 package mainimport ("fmt""io/ioutil""net/http" )func main() {resp, err : http.Get("http://www.hao123.com")if err ! nil {fmt.Println(err)return}defer resp.Body.Close()body, …

釘釘設置jira機器人_這是當您機器學習JIRA票證時發生的事情

釘釘設置jira機器人For software developers, one of the most-debated and maybe even most-hated questions is “…and how long will it take?”. I’ve experienced those discussions myself, which oftentimes lacked precise information on the requirements. What I…

python的賦值與參數傳遞(python和linux切換)

1&#xff0c;python模式切回成linux模式------exit&#xff08;&#xff09; linux模式切換成python模式------python 2,在linux里運行python的復合語句&#xff08;得在linux創建.py文件&#xff09; touch le.py vim le.py----在le文件里輸入python語句 #!/usr/bin/python …

vscode 標準庫位置_如何在VSCode中使用標準

vscode 標準庫位置I use Visual Studio Code as my text editor. When I write JavaScript, I follow JavaScript Standard Style.Theres an easy way to integrate Standard in VS Code—with the vscode-standardjs plugin. I made a video for this some time ago if youre …

leetcode 1603. 設計停車系統

請你給一個停車場設計一個停車系統。停車場總共有三種不同大小的車位&#xff1a;大&#xff0c;中和小&#xff0c;每種尺寸分別有固定數目的車位。 請你實現 ParkingSystem 類&#xff1a; ParkingSystem(int big, int medium, int small) 初始化 ParkingSystem 類&#xf…

IBM量子計算新突破:成功構建50個量子比特原型機

本文來自AI新媒體量子位&#xff08;QbitAI&#xff09;IBM去年開始以云計算服務的形式提供量子計算能力。當時&#xff0c;IBM發布了包含5個量子比特的計算機。在短短18個月之后&#xff0c;IBM周五宣布&#xff0c;將發布包含20個量子比特的計算機。 IBM還宣布&#xff0c;該…

ChromeDriver與chrome對應關系

http://chromedriver.storage.googleapis.com/index.html 轉載于:https://www.cnblogs.com/gcgc/p/11387605.html

快速排序和快速選擇(quickSort and quickSelect)算法

排序算法&#xff1a;快速排序(quicksort)遞歸與非遞歸算法 TopK問題&#xff1a;快速選擇(quickSelect)算法 import java.util.*; import java.lang.*;public class Demo {// 非遞歸 using stackpublic static void quickSortStack(int[] nums, int left, int right) {if (lef…

小程序點擊地圖氣泡獲取氣泡_氣泡上的氣泡

小程序點擊地圖氣泡獲取氣泡Combining two colors that are two steps apart on the Color Wheel creates a Diad Color Harmony. This Color Harmony is one of the lesser used ones. I decided to cover it here to add variety to your options for colorizing visualizati…

leetcode 150. 逆波蘭表達式求值(棧)

根據 逆波蘭表示法&#xff0c;求表達式的值。 有效的算符包括 、-、*、/ 。每個運算對象可以是整數&#xff0c;也可以是另一個逆波蘭表達式。 說明&#xff1a; 整數除法只保留整數部分。 給定逆波蘭表達式總是有效的。換句話說&#xff0c;表達式總會得出有效數值且不存在…

WebLogic常見問題

myeclipseweblogic10的配置&#xff0c;配置成功 運行中可能失敗&#xff0c;由于weblogic10不穩定&#xff0c;重啟機器后可以使用了 web工程使用到hibernate3時可能出現問題 ClassNotFoundException: org.hibernate.hql.ast.HqlToken 參考http://blog.chinajavaworld.com/ent…

PopTheBubble —測量媒體偏差的產品創意

產品管理 (Product Management) A couple of months ago, I decided to try something new. The MVP Lab by Mozilla is an 8-week incubator for pre-startup teams to explore product concepts and, over the 8 weeks of the program, ship a minimum viable product that p…