資料標準化
有些模型(例如 K-nearest neighbors,簡稱 KNN,和神經網路)在特徵縮放後表現會更好——所以我們要先把資料標準化。
我們也會依照特徵重要性,移除不重要的變數(星期幾),方法是用 .iloc[] 來索引特徵的 DataFrame。KNN 透過距離來尋找相似的點以進行預測,因此尺度較大的特徵會壓過尺度較小的特徵。把資料縮放可以解決這個問題。
sklearn 的 scale() 會進行標準化,將平均數設為 0、標準差設為 1。理想做法是對訓練資料用 StandardScaler 的 fit_transform(),對測試資料用 fit(),不過這裡受限於只能寫 15 行程式碼。
資料縮放完成後,我們會用直方圖來檢查是否生效。
本練習屬於課程
Python 金融 Machine Learning
練習說明
- 使用
.iloc從訓練/測試特徵中移除星期幾特徵(星期幾是最後 4 個特徵)。 - 使用 sklearn 的
scale()對train_features與test_features進行標準化;將結果分別存為scaled_train_features與scaled_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()