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

การหาค่าเหมาะสมด้วย gradient

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

The image shows a plot of y equals x squared. It also shows the gradient at x equals -1, x equals 0, and x equals 1.

ในทางปฏิบัติ 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))
แก้ไขและรันโค้ด