数据划分
为了正确评估模型,通常会将数据划分为训练集和测试集。训练集用于构建模型,测试集用于评估模型。该划分是随机进行的,但当目标变量的发生率较低时,可能需要进行分层抽样(stratify),也就是确保训练集和测试集中目标的比例相同。
在本练习中,您将使用分层抽样来划分数据,并验证训练集和测试集具有相同的目标发生率。train_test_split 方法已导入,X 和 y 这两个 DataFrame 已在您的工作区中可用。
本练习是课程的一部分
Python 预测分析入门
练习说明
- 使用
train_test_split方法对这些 DataFrame 进行分层划分。确保训练集与测试集大小相同,且目标发生率一致。 - 计算训练集的目标发生率。即训练集中目标数量除以训练集观测数。
- 计算测试集的目标发生率。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Load the partitioning module
from sklearn.model_selection import train_test_split
# Create DataFrames with variables and target
X = basetable.drop("target", 1)
y = basetable["target"]
# Carry out 50-50 partititioning with stratification
X_train, X_test, y_train, y_test = ____(X, y, test_size = ____, stratify = ____)
# Create the final train and test basetables
train = pd.concat([X_train, y_train], axis=1)
test = pd.concat([X_test, y_test], axis=1)
# Check whether train and test have same percentage targets
print(round(sum(train[____])/len(____), 2))
print(round(sum(test[____])/len(____), 2))