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

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