开始使用免费开始使用

数据标准化

某些模型(如 K 近邻(KNN)和神经网络)在输入数据经过缩放后表现更好——因此我们将对数据进行标准化。

我们还会根据特征重要性删除不重要的变量(星期几),方法是用 .iloc[] 对特征 DataFrame 进行索引。KNN 通过距离来寻找用于预测的相似点,因此量纲大的特征会压过量纲小的特征。对数据进行缩放可以解决这个问题。

sklearnscale() 会将数据标准化,把均值设为 0、标准差设为 1。理想情况下,我们会在训练数据上使用 StandardScalerfit_transform(),在测试数据上使用 fit(),但此处代码行数限制为 15 行。

完成缩放后,我们将通过绘制数据的直方图来检查是否生效。

本练习是课程的一部分

Python 金融机器学习

查看课程

练习说明

  • 使用 .iloc 从训练/测试特征中移除星期几特征(星期几是最后 4 个特征)。
  • 使用 sklearn 的 scale()train_featurestest_features 进行标准化;将结果分别保存为 scaled_train_featuresscaled_test_features
  • 在第一个子图(ax[0])上,绘制未缩放的 train_features 中 14 日 RSI 移动平均(索引为 [:, 2])的直方图。
  • 在第二个子图(ax[1])上,绘制标准化后的 14 日 RSI 移动平均的直方图。

交互式实操练习

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

from sklearn.preprocessing import scale

# Remove unimportant features (weekdays)
train_features = train_features.iloc[:, :-4]
test_features = test_features.____

# Standardize the train and test features
scaled_train_features = scale(train_features)
scaled_test_features = ____

# Plot histograms of the 14-day SMA RSI before and after scaling
f, ax = plt.subplots(nrows=2, ncols=1)
train_features.iloc[:, 2].hist(ax=____)
ax[1].hist(scaled_train_features[:, 2])
plt.show()
编辑并运行代码