简介:本文介绍了在机器学习项目中如何有效划分数据集为训练集、验证集和测试集,并通过Python代码示例展示了这一过程的实现,帮助读者理解数据划分的重要性及操作方法。
在机器学习项目中,合理划分数据集是确保模型泛化能力的重要步骤。通常,我们会将数据集分为三部分:训练集(Training Set)、验证集(Validation Set)和测试集(Test Set)。训练集用于训练模型,验证集用于调整模型参数(如超参数调优),测试集则用于评估模型的最终性能。
这里我们使用Python的sklearn.model_selection模块中的train_test_split函数进行随机划分,并通过自定义函数实现分层划分。
from sklearn.model_selection import train_test_splitfrom sklearn.datasets import load_iris# 加载Iris数据集data = load_iris()X = data.datay = data.target# 划分数据集X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.3, random_state=42)X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)print(f'训练集样本数: {len(X_train)}, 验证集样本数: {len(X_val)}, 测试集样本数: {len(X_test)}')
对于分层划分,我们可以使用StratifiedShuffleSplit或者自定义函数。
from sklearn.model_selection import StratifiedShuffleSplit# 使用StratifiedShuffleSplit进行分层划分sss = StratifiedShuffleSplit(n_splits=1, test_size=0.3, random_state=42)for train_index, test_index in sss.split(X, y):X_train, X_temp = X[train_index], X[test_index]y_train, y_temp = y[train_index], y[test_index]# 进一步将temp数据集划分为验证集和测试集X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)print(f'训练集样本数: {len(X_train)}, 验证集样本数: {len(X_val)}, 测试集样本数: {len(X_test)}')
train_test_split中设置random_state参数可以确保每次划分的结果相同,便于复现。通过合理的数据划分,我们可以更准确地评估模型的性能,提高模型的泛化能力。希望本文能帮助你更好地理解和实践数据划分的过程。