เทรน neural network ด้วย custom loss function
ต่อไปจะนำ custom loss function ที่สร้างไว้มาใช้งาน ซึ่งช่วยให้ปรับพฤติกรรมของโมเดลให้เหมาะกับปัญหาได้ โดยโมเดลจะพยายามเรียนรู้ทิศทางการเคลื่อนไหวของราคาให้ถูกต้องอย่างน้อยที่สุด สิ่งที่ต้องทำคือกำหนดอาร์กิวเมนต์ loss ใน .compile() ให้เป็นชื่อฟังก์ชันของเรา คือ sign_penalty จากนั้นตรวจสอบค่า training loss อีกครั้งเพื่อให้แน่ใจว่าค่าเริ่มนิ่งแล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Machine Learning สำหรับการเงินด้วย Python
คำแนะนำการฝึกหัด
- กำหนด
input_dimของ neural network layer แรกให้เท่ากับจำนวนคอลัมน์ของscaled_train_featuresโดยใช้ property.shape[1] - ใช้ custom loss function
sign_penaltyใน.compile()ของmodel_2 - พล็อตค่า loss จาก
historyที่ได้จากการเทรน โดยค่า loss อยู่ที่history.history['loss']
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Create the model
model_2 = Sequential()
model_2.add(Dense(100, input_dim=____, activation='relu'))
model_2.add(Dense(20, activation='relu'))
model_2.add(Dense(1, activation='linear'))
# Fit the model with our custom 'sign_penalty' loss function
model_2.compile(optimizer='adam', loss=____)
history = model_2.fit(scaled_train_features, train_targets, epochs=25)
plt.plot(____)
plt.title('loss:' + str(round(history.history['loss'][-1], 6)))
plt.show()