Sitemap

[ML101] 模型訓練從0開始

7 min readSep 9, 2024

今天來講講一個模型的誕生

  1. 資料採集
  2. 資料處理
  3. [本篇]模型訓練與評估
  4. 上線 (內容太充實了下堂課再來講講吧- 有興趣的可以先回去翻翻streamlit,猜猜看可以怎麼用)

現在我們資料已經準備好了,也知道遇到模型無法處理的字串資料可以用哪些方法處理。接下來就來開train吧。相信已經很多人摩拳擦掌已久了吧。

接續一開始的Iris dataset來試試看tree這個模型能不能把它分類分好吧,首先我們照第一講的內容,先把資料載好

from sklearn.datasets import load_iris

data = load_iris()
columns = data['feature_names']
X = data['data']
y = data['target']

機器學習訓練最重要的就是:我們不能看著答案背答案,我們希望模型可以通過一部分的題目與答案學到一種答題技巧。接下來看見沒有看過的問題,也能通過"訓練期間"掌握的答題技巧來回答出正確的答案

所以我們需要分出training與testing 兩個資料集

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

print(X_train.shape, y_train.shape)
Press enter or click to view image in full size

準備好訓練資料接下來就可以開始訓練 下面示範tree 這個模型

from sklearn.tree import DecisionTreeClassifier


tree = DecisionTreeClassifier()
tree.fit(X_train, y_train)
y_pred = tree.predict(X_test)
Press enter or click to view image in full size

接下來就是評估模型能力的時間

我們可以通過confusion_matrix, classification_report 來衡量模型的水準

可以看到這個模型透過樹分類可以在測試集拿到完美的結果

左下角就是三個類別 在對角線上就是預測正確。

Press enter or click to view image in full size

所以三種類別都讓模型全部答對了。好像沒有換模型的必要了(笑),不過我還是示範一下好了

Press enter or click to view image in full size

想要新增SVM模型呢 也非常簡單

Press enter or click to view image in full size

想使用xgboost也是pip install後用一樣的方式使用

pip install xgboost
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.svm import SVC
from xgboost import XGBClassifier

models = [
XGBClassifier(learning_rate =0.1,
n_estimators=1000,
max_depth=7,
min_child_weight=1,
gamma=0,
subsample=0.8,
colsample_bytree=0.8,
objective='multi:softprob', #'binary:logistic'
nthread=8,
eval_metric='auc',
seed=42),
SVC(),
DecisionTreeClassifier(),
RandomForestClassifier(),
]

for cls in models:
print('processing', cls)
cls.fit(X_train, y_train)
y_pred = cls.predict(X_test)
print(classification_report(y_test, y_pred, zero_division=1))
print(confusion_matrix(y_test, y_pred))
Press enter or click to view image in full size

最終的code就如上所示,認真的孩子也許會問,怎麼其它模型都看起來很簡單,這個xgboost自己夾帶了好多私貨。 這些看起來很複雜長長一串的參數,就是後續進階課程會討論到的超參數調教的範疇,目前可以把這些值當作默認值先貼上。唯獨需要注意,這裡是多輸出的分類,所以我切換成objective=’multi:softprob’, 如果是binary的時候記得切換成後面那個,我也貼心的留在註解了。

說到binary,我們就拿tree與svc來介紹一下切換成binary model可以怎麼做吧

from sklearn.metrics import confusion_matrix, classification_report
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC


flower_types = ["Iris-Setosa", "Iris-Versicolour","Iris-Virginica"]

models = [SVC(), DecisionTreeClassifier()]

for cls in models:
print('processing', cls)
for flower_idx, flower_type in enumerate(flower_types):
print('processing', flower_type)
X_train, X_test, y_train, y_test = train_test_split(X, y==flower_idx, test_size=0.2, random_state=42)
cls.fit(X_train, y_train)
y_pred = cls.predict(X_test)
print(classification_report(y_test, y_pred, zero_division=1, target_names=['not_'+flower_type, flower_type]))
print(confusion_matrix(y_test, y_pred))
Press enter or click to view image in full size

關鍵在於y==flower_idx這個命令,我僅找出label為我目前要train的row 標記為true, 其他我都標記為false.這樣就可以在for迴圈內輕鬆做出binary dataset

以上就是今天的內容,接下來下一篇再帶大家練習用今天學到的內容來訓練鐵達尼號資料集吧~

--

--

Even Pan
Even Pan

Written by Even Pan

Technical blogger who like to held hands-on ml workshops. Fast-paced learner and highly interested in the latest technologies.

No responses yet