
在建立機器學習模型之前,針對不同的預測目標,會有不同類型的機器學習模型,主要分成三大類型,分別是:
- 回歸模型(Regression Model)
- 分類模型(Classification Model)
- 分群模型(Clustering Model)
對於上述三種類型的任務,麥特會進行三種簡單資料集的介紹,那我們就開始建立有趣的機器學習模型吧!
回歸模型(Regression Model)
建立回歸模型的任務目標,是希望能夠預測出一個定值,比如說預測股票的價格、明天的天氣溫度預測、或是病患的血糖值預測,接下來麥特會介紹開的玩具資料集 load_diabetes(),這個資料集是紀錄糖尿病患者的生化指標以及血糖值水平,我們要建立的回歸模型就是預測血糖值,下面會使用python來示範如何建構回歸模型。
# 載入需要使用到的資源
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
# 載入糖尿病資料集,X是資料集的特徵,y是要預測的標籤
diabetes_X, diabetes_y = datasets.load_diabetes(return_X_y=True)
# Use only one feature
diabetes_X = diabetes_X[:, np.newaxis, 2]
# 將資料集分為訓練集和測試集,測試集為load_diabetes資料中最後的20筆資料
# X為資料的特徵項目,y為資料的預測目標(血糖值)
X_train = diabetes_X[:-20]
X_test = diabetes_X[-20:]
y_train = diabetes_y[:-20]
y_test = diabetes_y[-20:]
# 建立一個線性回歸模型
reg = linear_model.LinearRegression()
# 使用fit訓練模型
reg.fit(X_train, y_train)
# 使用predict進行預測
y_pred = reg.predict(X_test)
# 評估模型性能
print("Mean squared error: %.2f" % mean_squared_error(y_test, y_pred))
print("Coefficient of determination (R^2): %.2f" % r2_score(y_test, y_pred))
# 視覺化結果
plt.scatter(X_test, y_test, color='black')
plt.plot(X_test, y_pred, color='blue', linewidth=3)
plt.xlabel('特徵值')
plt.ylabel('血糖值')
plt.title('糖尿病患者血糖預測')
plt.show()
# 測試集資料進行預測後的評估指標(MSE以及R^2)
Mean squared error: 2548.07
Coefficient of determination (R^2): 0.47

進行回歸模型的預測後,會發現線性回歸預測就是藍線部分,對應到y軸就是測試集資料當中的血糖值,建立回歸模型的目標是希望一條線可以越貼近所有的黑點,而評估此模型的好壞,則是會計算預測值與實際血糖值之間的差異,也就是MSE,以及預測值與藍色線貼近的程度會使用R^2做為評估指標。
分類模型(Classification Model)
第二個使用K-最近鄰分類器模型進行鳶尾花資料集的分類預測,鳶尾花資料集會有三種不同類型的花:山鳶尾Setosa、變色鳶尾Versicolor、維吉尼亞鴛尾Virginica。
# 載入需要使用到的套件
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
import seaborn as sns
# 載入iris資料集
iris = load_iris()
# X是iris資料的特徵項目
X = iris.data
# y是iris資料預測標籤,包含Setosa, Versicolor, Virginica三個品種的花卉
y = iris.target
# 將資料集分為訓練集和測試集,比例為80:20
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=28)
# 建立K-最近鄰分類器模型,最近鄰數量設定為3
knn = KNeighborsClassifier(n_neighbors=3)
# 使用fit訓練模型
knn.fit(X_train, y_train)
# 使用predict進行預測
y_pred = knn.predict(X_test)
# 評估模型性能
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
# 視覺化原始測試集標籤
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap='viridis', edgecolor='k', s=50)
plt.title('原始Iris分類結果')
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
# 視覺化KNN預測結果
plt.subplot(1, 2, 2)
plt.scatter(X_test[:, 0], X_test[:, 1], c=y_pred, cmap='viridis', edgecolor='k', s=50)
plt.title('KNN預測結果')
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.tight_layout()
plt.show()
Accuracy: 0.9666666666666667
Classification Report:
precision recall f1-score support
0 1.00 1.00 1.00 9
1 1.00 0.91 0.95 11
2 0.91 1.00 0.95 10
accuracy 0.97 30
macro avg 0.97 0.97 0.97 30
weighted avg 0.97 0.97 0.97 30

最後輸出的結果,左邊部分是原始鳶尾花資料集的資料分布圖,而中間是測試集的經過預測後的分類結果,對於分類模型,我們通常會使用準確度(Accuracy)、混淆矩陣(Confusion Matrix)等等指標來評估模型,我們可以看到最終模型的準確度為96.67%,是相當高的準確度唷!
分群模型(Clustering Model)
接下來我們使用kmeans模型進行鳶尾花資料集的分群預測,以及使用不同評估分群模型效能的指數來觀察模型的預測結果。
# 載入需要使用到的套件
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score, davies_bouldin_score, calinski_harabasz_score
# 載入iris資料集
iris = load_iris()
X = iris.data
y = iris.target
# 執行 K-means 分群,分為3個群
kmeans = KMeans(n_clusters=3, random_state=28)
y_kmeans = kmeans.fit_predict(X)
# 計算輪廓分數評估分群效果
silhouette_avg = silhouette_score(X, y_kmeans)
print("Silhouette Score: {:.3f}".format(silhouette_avg))
# 計算 Davies-Bouldin 指數
db_score = davies_bouldin_score(X, y_kmeans)
print("Davies-Bouldin Score: {:.3f}".format(db_score))
# 計算 Calinski-Harabasz 指數
ch_score = calinski_harabasz_score(X, y_kmeans)
print("Calinski-Harabasz Score: {:.3f}".format(ch_score))
# 視覺化K-means分群結果
plt.figure(figsize=(8, 6))
plt.scatter(X[:, 0], X[:, 1], c=y_kmeans, cmap='viridis', edgecolor='k', s=50)
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=200, c='red', marker='*', edgecolor='k')
plt.title('K-means 分群結果')
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.show()
Silhouette Score: 0.553
Davies-Bouldin Score: 0.662
Calinski-Harabasz Score: 561.628

分群模型在訓練的時候,是沒有使用到真實標籤的(y),所以訓練玩模型並預測,只會得到類別型的預測答案(0, 1, 2),而在評估分群模型的結果時,就會依據每個資料分布的近似程度,來作為模型學習的標準,例如輪廓分數(silhouette)、Davies-Bouldin指數、Calinski-Harabasz指數等等,星星造型的圖例表示不同族群的中心位置。
結論
本次顯示所有程式碼的內容,都有提供程式碼在我的colab,只要登入你的google帳號,就可以在線上執行本次的所有程式,希望本次的教學可以讓大家對於建立機器學習模型有初步的了解,後面麥特會在進一步介紹有關於回歸、分類、分群模型的評估指標方法,讓我們持續在資料當中探險吧!
