เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การ Standardize ข้อมูล

โมเดลบางประเภท เช่น K-nearest neighbors (KNN) และ neural network ทำงานได้ดีขึ้นเมื่อใช้ข้อมูลที่ผ่านการ scale แล้ว ดังนั้นเราจะ standardize ข้อมูลของเรากัน

นอกจากนี้ เราจะลบตัวแปรที่ไม่สำคัญออก (วันในสัปดาห์) ตามค่า feature importances โดย index DataFrame ของ features ด้วย .iloc[] เนื่องจาก KNN ใช้ระยะทางในการหาจุดที่ใกล้เคียงสำหรับการพยากรณ์ feature ที่มีค่าขนาดใหญ่จึงมีน้ำหนักมากกว่า feature ที่มีค่าขนาดเล็ก การ scale ข้อมูลช่วยแก้ปัญหานี้ได้

ฟังก์ชัน scale() ของ sklearn จะ standardize ข้อมูล โดยปรับค่าเฉลี่ยให้เป็น 0 และส่วนเบี่ยงเบนมาตรฐานให้เป็น 1 ในอุดมคติเราควรใช้ StandardScaler ร่วมกับ fit_transform() บนข้อมูล training และใช้ fit() บนข้อมูล test แต่เนื่องจากมีข้อจำกัดที่ 15 บรรทัด เราจะใช้วิธีนี้แทน

เมื่อ scale ข้อมูลเสร็จแล้ว เราจะตรวจสอบว่าได้ผลถูกต้องหรือไม่โดยการพล็อต histogram ของข้อมูล

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Machine Learning สำหรับการเงินด้วย Python

ดูคอร์ส

คำแนะนำการฝึกหัด

  • ลบ features วันในสัปดาห์ออกจาก features ชุด train และ test โดยใช้ .iloc (features วันในสัปดาห์อยู่ที่ 4 ตัวสุดท้าย)
  • Standardize train_features และ test_features โดยใช้ scale() ของ sklearn แล้วเก็บ features ที่ผ่านการ scale ไว้ในตัวแปร scaled_train_features และ scaled_test_features
  • พล็อต histogram ของ 14-day RSI moving average (index ที่ [:, 2]) จาก train_features ที่ยังไม่ได้ scale บน subplot แรก (ax[0])
  • พล็อต histogram ของ 14-day RSI moving average ที่ผ่านการ standardize แล้วบน subplot ที่สอง (ax[1])

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

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()
แก้ไขและรันโค้ด