开始使用免费开始使用

创建训练集与测试集特征

在拟合线性模型之前,我们需要为特征添加常数项,以便模型包含截距。

我们还要创建训练集和测试集特征。这样可以在训练数据集上拟合模型,并在测试数据集上评估性能。我们始终要在模型未见过的数据上检查表现,以确保没有过拟合,即过于精确地记忆了训练数据中的模式。

对于这样的时间序列,通常将最早的数据作为训练集,将最新的数据作为测试集。这样可以在最新数据上评估模型性能,更贴近对未来未见数据进行预测的真实场景。

本练习是课程的一部分

Python 金融机器学习

查看课程

练习说明

  • 以别名 sm 导入 statsmodels.api 库。
  • 使用 statsmodels 的 .add_constant() 函数为变量 features 添加常数项。
  • 使用 featurestargets.shape[0] 属性,设置 train_size 为数据点总数(行数)的 85%。
  • 使用 train_size 和 Python 索引(例如 [start:stop]),将 linear_featurestargets 划分为训练集与测试集。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Import the statsmodels.api library with the alias sm
___

# Add a constant to the features
linear_features = sm.____(features)

# Create a size for the training set that is 85% of the total number of samples
train_size = int(0.85 * ____)
train_features = linear_features[:train_size]
train_targets = targets[____]
test_features = linear_features[train_size:]
test_targets = targets[train_size:]
print(linear_features.shape, train_features.shape, test_features.shape)
编辑并运行代码