如何在 Python 中使用 scikit-learn 庫將資料集拆分為訓練集和測試集?
Scikit-learn,通常稱為 sklearn,是 Python 中用於實現機器學習演算法的庫。它功能強大且健壯,因為它提供了各種工具來執行統計建模。
這包括使用 Python 中功能強大且穩定的介面進行分類、迴歸、聚類、降維等等。基於 Numpy、SciPy 和 Matplotlib 庫構建。
在將輸入資料傳遞給機器學習演算法之前,必須將其拆分為訓練資料集和測試資料集。
一旦資料擬合到所選模型,輸入資料集就會在這個模型上進行訓練。在訓練過程中,模型從資料中學習。
它還學習對新資料進行泛化。測試資料集在模型訓練期間不會被使用。
一旦所有超引數都已調整,並且最佳權重已設定,測試資料集就會提供給機器學習演算法。
此資料集用於檢查演算法在新資料上的泛化程度。讓我們看看如何使用 scikit-learn 庫來拆分資料。
示例
from sklearn.datasets import load_iris
my_data = load_iris()
X = my_data.data
y = my_data.target
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 = 2
)
print("The dimensions of the features of training data ")
print(X_train.shape)
print("The dimensions of the features of test data ")
print(X_test.shape)
print("The dimensions of the target values of training data ")
print(y_train.shape)
print("The dimensions of the target values of test data ")
print(y_test.shape)輸出
The dimensions of the features of training data (120, 4) The dimensions of the features of test data (30, 4) The dimensions of the target values of training data (120,) The dimensions of the target values of test data (30,)
解釋
- 匯入所需的包。
- 為此所需的資料集也載入到環境中。
- 從資料集中分離特徵和目標值。
- 訓練資料和測試資料分別以 80% 和 20% 的比例進行拆分。
- 這意味著 20% 的資料將用於檢查模型在新資料上的泛化程度。
- 這些拆分以及資料的維度將列印到控制檯上。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP