使用 sklearn.model_selection 中的 train_test_split 将数据划分为训练集和测试集
在此步骤中,我们将准备数据以进行训练过程。机器学习的一个关键部分是在模型从未见过的数据上进行评估。为此,我们将数据集拆分为两部分:训练集和测试集。模型将从训练集中学习,然后我们将使用测试集来查看其性能如何。
首先,我们需要将特征(输入变量,X)与目标(我们想要预测的值,y)分开。在我们的例子中,X 将是除 MedHouseVal 之外的所有列,而 y 将是 MedHouseVal 列。
然后,我们将使用 sklearn.model_selection 中的 train_test_split 函数来执行拆分。
将以下代码追加到你的 main.py 文件中。
from sklearn.model_selection import train_test_split
## Prepare the data
X = california_df.drop('MedHouseVal', axis=1) ## Features (input variables)
y = california_df['MedHouseVal'] ## Target variable (what we want to predict)
## Split the data into training and testing sets
## test_size=0.2: Reserve 20% of data for testing, 80% for training
## random_state=42: Ensures reproducible splits (same result every run)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
## Print the shapes of the new datasets to confirm the split
print("\n--- Data Split ---")
print("X_train shape:", X_train.shape) ## Training features
print("X_test shape:", X_test.shape) ## Test features
print("y_train shape:", y_train.shape) ## Training target values
print("y_test shape:", y_test.shape) ## Test target values
现在,请再次从终端运行脚本:
python3 main.py
你将在 DataFrame 下方看到新创建的训练集和测试集的形状打印出来。这证实了数据已正确拆分。
--- Data Split ---
X_train shape: (16512, 8)
X_test shape: (4128, 8)
y_train shape: (16512,)
y_test shape: (4128,)