數學建模:2.監督學習--分類分析- KNN最鄰近分類算法


 1.分類分析

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

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

本文主要講基本的分類方法 ----- KNN最鄰近分類算法 

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

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

 

 

2. KNN最鄰近分類的python實現方法

最鄰近分類的python實現方法

在距離空間里,如果一個樣本的最接近的k個鄰居里,絕大多數屬於某個類別,則該樣本也屬於這個類別

電影分類 / 植物分類

  2.1電影分類

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
% matplotlib inline
#  案例一:電影數據分類

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

data = pd.DataFrame({'name':['北京遇上西雅圖','喜歡你','瘋狂動物城','戰狼2','力王','敢死隊'],
                  'fight':[3,2,1,101,99,98],
                  'kiss':[104,100,81,10,5,2],
                  'type':['Romance','Romance','Romance','Action','Action','Action']})
print(data)
print('-------')
#  創建數據

plt.scatter(data[data['type'] == 'Romance']['fight'], data[data['type'] == 'Romance']['kiss'], color = 'r',marker = 'o',label = 'Romance')
plt.scatter(data[data['type'] == 'Action']['fight'],data[data['type'] == 'Action']['kiss'],color = 'g',marker = 'o',label = 'Action')
plt.grid()
plt.legend()

 data[data['type'] == 'Romance']['fight'] # 3 2 1
 data[data['type'] == 'Romance']['kiss'] #104 100 81

knn = neighbors.KNeighborsClassifier()   # 取得knn分類器
knn.fit(data[['fight','kiss']], data['type'])

print('預測電影類型為:', knn.predict([18, 90]))
# 加載數據,構建KNN分類模型
# 預測未知數據

plt.scatter(18,90,color = 'r',marker = 'x',label = 'Romance')
plt.ylabel('kiss')
plt.xlabel('fight')
plt.text(18,90,'《你的名字》',color = 'r')
# 繪制圖表

data2 = pd.DataFrame(np.random.randn(100, 2)*50, columns = ['fight', 'kiss'])
data2['typetest'] = knn.predict(data2)

plt.scatter(data[data['type'] == 'Romance']['fight'],data[data['type'] == 'Romance']['kiss'],color = 'r',marker = 'o',label = 'Romance')
plt.scatter(data[data['type'] == 'Action']['fight'],data[data['type'] == 'Action']['kiss'],color = 'g',marker = 'o',label = 'Action')
plt.grid()
plt.legend() #做一個可視化
plt.scatter(data2[data2['typetest'] == 'Romance']['fight'],data2[data2['typetest'] == 'Romance']['kiss'],color = 'r',marker = 'x',label = 'Romance')
plt.scatter(data2[data2['typetest'] == 'Action']['fight'],data2[data2['typetest'] == 'Action']['kiss'],color = 'g',marker = 'x',label = 'Action')
# plt.legend()
plt.ylabel('kiss')
plt.xlabel('fight')
# 繪制圖表
data2.head()

 

  2.2植物分類 

# 案例二:植物分類

from sklearn import datasets
iris = datasets.load_iris()
print(iris.keys())
print('數據長度為:%i條' % len(iris['data']))
# 導入數據

print(iris.feature_names)
print(iris.target_names)
#print(iris.target)
print(iris.data[:5])
# 150個實例數據
# feature_names - 特征分類:萼片長度,萼片寬度,花瓣長度,花瓣寬度  → sepal length, sepal width, petal length, petal width
# 目標類別:Iris setosa, Iris versicolor, Iris virginica. 
data = pd.DataFrame(iris.data, columns = iris.feature_names)
data['target'] = iris.target
iris.target
data.head()

knn = neighbors.KNeighborsClassifier()
knn.fit(iris.data, iris.target) #構建一個分類模型

prt_data = knn.predict([0.2, 0.1, 0.3, 0.4]) #array([0]) 
prt_data

 

ty = pd.DataFrame({'target':[0, 1, 2], 
                  'target_names':iris.target_names})


iris.target

df = pd.merge(data, ty, on = 'target')

df.head()

knn = neighbors.KNeighborsClassifier()
# knn.fit(iris.data, iris.target) #構建一個分類模型
knn.fit(iris.data, df['target_names']) #監督學習一定要有它的特征量和目標值
prt_data = knn.predict([0.2, 0.1, 0.3, 0.4]) #做預測
prt_data

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM