การอัปเดต weights หลายครั้ง
คราวนี้จะลองอัปเดต weights หลายรอบ เพื่อปรับปรุงโมเดลอย่างเห็นได้ชัด และสังเกตว่าการทำนายดีขึ้นแค่ไหนในแต่ละรอบ
เพื่อให้โค้ดเป็นระเบียบ มีฟังก์ชัน get_slope() ที่โหลดไว้แล้ว รับ input_data, target, และ weights เป็น argument รวมถึงฟังก์ชัน get_mse() ที่รับ argument ชุดเดียวกัน ส่วน input_data, target, และ weights ก็ถูกโหลดไว้ให้แล้วเช่นกัน
โครงข่ายนี้ไม่มี hidden layer ใด ๆ โดยรับข้อมูลจาก input (3 โหนด) แล้วส่งตรงไปยัง output node เลย สังเกตว่า weights เป็น array เดียว
นอกจากนี้ยังโหลด matplotlib.pyplot ไว้ให้แล้ว และกราฟประวัติค่า error จะแสดงผลหลังจากทำขั้นตอน gradient descent เสร็จสิ้น
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Introduction to Deep Learning in Python
คำแนะนำการฝึกหัด
- ใช้
forloop เพื่ออัปเดต weights แบบวนซ้ำ:- คำนวณค่า slope โดยใช้ฟังก์ชัน
get_slope() - อัปเดต weights โดยใช้ learning rate เท่ากับ
0.01 - คำนวณค่า mean squared error (
mse) จาก weights ที่อัปเดตแล้ว โดยใช้ฟังก์ชันget_mse() - เพิ่มค่า
mseเข้าไปในmse_hist
- คำนวณค่า slope โดยใช้ฟังก์ชัน
- กด ส่งคำตอบ เพื่อแสดงกราฟของ
mse_histแล้วสังเกตว่าเห็นแนวโน้มอะไร
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
n_updates = 20
mse_hist = []
# Iterate over the number of updates
for i in range(n_updates):
# Calculate the slope: slope
slope = ____(____, ____, ____)
# Update the weights: weights
weights = ____ - ____ * ____
# Calculate mse with new weights: mse
mse = ____(____, ____, ____)
# Append the mse to mse_hist
____
# Plot the mse history
plt.plot(mse_hist)
plt.xlabel('Iterations')
plt.ylabel('Mean Squared Error')
plt.show()