機器學習 - 訓練與測試



在機器學習中,訓練測試分割是一種常用的評估機器學習模型效能的技術。訓練測試分割的基本思想是將可用資料分成兩個集合:訓練集和測試集。訓練集用於訓練模型,測試集用於評估模型的效能。

訓練測試分割非常重要,因為它允許我們測試模型在之前從未見過的資料上的表現。這一點很重要,因為如果我們在模型訓練時使用的資料上評估模型,那麼模型在訓練資料上可能表現良好,但在新資料上可能無法很好地泛化。

示例

在 Python 中,可以使用 sklearn.model_selection 模組中的 train_test_split 函式將資料分割成訓練集和測試集。以下是一個示例實現 -

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

# Load the iris dataset
data = load_iris()
X = data.data
y = data.target

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Create a logistic regression model and fit it to the training data
model = LogisticRegression()
model.fit(X_train, y_train)

# Evaluate the model on the testing data
accuracy = model.score(X_test, y_test)
print(f"Accuracy: {accuracy:.2f}")

在此示例中,我們載入 iris 資料集並使用 train_test_split 函式將其分割成訓練集和測試集。然後,我們建立一個邏輯迴歸模型並將其擬合到訓練資料上。最後,我們使用模型物件的 score 方法評估測試資料上的模型。

train_test_split 函式中的 test_size 引數指定應用於測試的資料比例。在此示例中,我們將其設定為 0.2,這意味著 20% 的資料將用於測試,而 80% 的資料將用於訓練。random_state 引數確保分割結果可重現,因此每次執行程式碼時都會獲得相同的分割結果。

輸出

執行此程式碼後,將產生以下輸出 -

Accuracy: 1.00

總的來說,訓練測試分割是評估機器學習模型效能的關鍵步驟。透過將資料分割成訓練集和測試集,我們可以確保模型不會過度擬合訓練資料,並且可以很好地泛化到新資料上。

廣告