데이터 표준화하기
K-nearest neighbors(KNN)와 neural networks 같은 일부 모델은 스케일링된 데이터에서 더 잘 작동해요. 따라서 데이터를 표준화하겠습니다.
또한 feature importance에 따라 중요하지 않은 변수(요일)를 제거하기 위해 .iloc[]로 features DataFrame을 인덱싱하겠습니다. KNN은 거리를 사용해 비슷한 점을 찾아 예측하므로, 값의 스케일이 큰 feature가 작은 feature를 압도하게 됩니다. 스케일링은 이를 바로잡아 줍니다.
sklearn의 scale()은 평균을 0, 표준편차를 1로 맞추는 표준화를 수행해요. 이상적으로는 학습 데이터에는 StandardScaler의 fit_transform()을, 테스트 데이터에는 fit()을 사용해야 하지만, 여기서는 코드가 15줄로 제한되어 있어 scale()을 사용합니다.
데이터를 스케일링한 뒤에는 히스토그램을 그려서 제대로 적용되었는지 확인하겠습니다.
이 연습은 강의의 일부입니다
Python으로 배우는 금융 분야 Machine Learning
연습 안내
.iloc을 사용해 학습/테스트 features에서 요일 feature를 제거하세요(요일은 마지막 4개 feature예요).- 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()