一行 Python 代碼搞定訓練分類或回歸模型
自動機器學習(Auto-ML)是指自動化數據科學模型開發流水線的組件。AutoML 減少了數據科學家的工作量,并加快了工作流程。AutoML 可用于自動化各種流水線組件,包括數據理解,EDA,數據處理,模型訓練,超參數調整等。
在本文中,我們將討論如何使用開放源碼的 Python 庫 LazyPredict 來自動化模型訓練過程。
什么是 LazyPredict ?
LazyPredict 是一個開源的 Python 庫,它自動化了模型培訓流水線并加快了工作流。LazyPredict 為一個分類數據集訓練了大約30個分類模型,為一個回歸數據集訓練了大約40個回歸模型。
Lazypredicate 返回訓練好的模型以及它的性能指標,而不需要編寫很多代碼。我們可以比較每個模型的性能指標,并優化最佳模型以進一步提高性能。
安裝
可以通過以下方式從 PyPl 庫安裝 LazyPredict:
pip install lazypredict
安裝完成后,可導入庫進行分類和回歸模型的自動訓練。
from lazypredict.Supervised import LazyRegressor, LazyClassifier
用法
Lazypredicate 同時支持分類和回歸問題,因此我們將進行這兩個任務的演示:
波士頓住房(回歸)和泰坦尼克號(分類)數據集用于演示 LazyPredict 庫。
() 分類任務:
LazyPredict 的使用非常直觀,類似于 scikit-learn。首先,為分類任務創建一個估計器 LazyClassifier 的實例。可以通過自定義指標進行評估,默認情況下,每個模型都會根據準確度、ROC AUC 分數、F1 分數進行評估。
在進行 lazypredict 預測模型訓練之前,必須讀取數據集并對其進行處理以使其適合訓練。
import pandas as pd
from sklearn.model_selection import train_test_split
# Read the titanic dataset
df_cls = pd.read_csv("titanic.csv")
df_cls = df_cls.drop(['PassengerId','Name','Ticket', 'Cabin'], axis=1)
# Drop instances with null records
df_cls = df_cls.dropna()
# feature processing
df_cls['Sex'] = df_cls['Sex'].replace({'male':1, 'female':0})
df_cls['Embarked'] = df_cls['Embarked'].replace({'S':0, 'C':1, 'Q':2})
# Creating train test split
y = df_cls['Survived']
X = df_cls.drop(columns=['Survived'], axis=1)
# Call train test split on the data and capture the results
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=0.2)
經過處理將數據拆分為訓練測試數據后,我們可以使用 LazyPredict 進行模型訓練。
# LazyClassifier Instance and fiting data
cls= LazyClassifier(ignore_warnings=False, custom_metric=None)
models, predictions = cls.fit(X_train, X_test, y_train, y_test)
(2)回歸任務:
類似于分類模型訓練,lazypredicate 提供了用于回歸數據集的自動模型訓練。實現類似于分類任務,只是對實例 LazyRegressor 進行了更改。
import pandas as pd
from sklearn.model_selection import train_test_split
# read the data
column_names = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV']
df_reg = pd.read_csv("housing.csv", header=None, delimiter=r"\s+", names=column_names)
# Creating train test split
y = df_reg['MEDV']
X = df_reg.drop(columns=['MEDV'], axis=1)
# Call train_test_split on the data and capture the results
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=0.2)
reg = LazyRegressor(ignore_warnings=False, custom_metric=None)
models, predictions = reg.fit(X_train, X_test, y_train, y_test)
從以上性能指標來看,AdaBoost 分類器是分類任務的最佳執行模型,而 GradientBoostingRegressor 模型是回歸任務的最佳執行模型。
總結
在本文中,我們討論了 LazyPredict 庫的實現,該庫可以在幾行 Python 代碼中訓練大約70個分類和回歸模型。這是一個非常方便的工具,因為它提供了模型執行情況的總體圖像,并且可以比較每個模型的性能。
每個模型都使用其默認參數進行訓練,因為它不執行超參數調整。選擇性能最佳的模型后,開發人員可以調整模型以進一步提高性能。