การหาค่าเหมาะสมด้วย gradient
กำหนดให้มี loss function คือ \(y = x^{2}\) ซึ่งต้องการหาค่าต่ำสุด โดยคำนวณความชันด้วย operation GradientTape() ที่ค่า x ต่าง ๆ ถ้าความชันเป็นบวก ให้ลดค่า x เพื่อลด loss และถ้าความชันเป็นลบ ให้เพิ่มค่า x แทน นี่คือหลักการทำงานของ gradient descent

ในทางปฏิบัติ TensorFlow มี operation ระดับสูงสำหรับทำ gradient descent โดยอัตโนมัติ อย่างไรก็ตาม ในแบบฝึกหัดนี้จะคำนวณความชันที่ค่า x เท่ากับ -1, 1 และ 0 ด้วยตนเอง โดยใช้ operation ต่อไปนี้: GradientTape(), multiply() และ Variable()
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
TensorFlow เบื้องต้นใน Python
คำแนะนำการฝึกหัด
- กำหนด
xเป็นตัวแปรที่มีค่าเริ่มต้นเป็นx0 - กำหนด loss function
yให้เท่ากับxคูณxโดยไม่ใช้ operator overloading - กำหนดให้ฟังก์ชันคืนค่า gradient ของ
yเทียบกับx
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
def compute_gradient(x0):
# Define x as a variable with an initial value of x0
x = ____(x0)
with GradientTape() as tape:
tape.watch(x)
# Define y using the multiply operation
y = ____
# Return the gradient of y with respect to x
return tape.gradient(____, ____).numpy()
# Compute and print gradients at x = -1, 1, and 0
print(compute_gradient(-1.0))
print(compute_gradient(1.0))
print(compute_gradient(0.0))