ตั้งค่า Linear Regression
Linear regression แบบตัวแปรเดียวจะระบุความสัมพันธ์ระหว่าง feature หนึ่งตัวกับ tensor เป้าหมาย ในแบบฝึกหัดนี้ เราจะใช้ขนาดพื้นที่ดินและราคาของอสังหาริมทรัพย์ โดยจะแปลงค่า tensor ทั้งสองเป็น logarithm ธรรมชาติตามที่อธิบายในวิดีโอ ซึ่งพร้อมใช้งานในชื่อ price_log และ size_log
ในแบบฝึกหัดนี้ คุณจะกำหนดโมเดลและฟังก์ชัน loss จากนั้นประเมินค่า loss function ด้วยค่า intercept และ slope สองชุดที่แตกต่างกัน โดยค่าที่โมเดลพยากรณ์คำนวณจาก intercept + features*slope นอกจากนี้ keras.losses.mse() พร้อมใช้งานแล้ว และ slope กับ intercept ถูกกำหนดเป็นตัวแปรไว้แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
TensorFlow เบื้องต้นใน Python
คำแนะนำการฝึกหัด
- กำหนดฟังก์ชันที่คืนค่าที่พยากรณ์สำหรับ linear regression โดยใช้
intercept,featuresและslopeโดยไม่ใช้add()หรือmultiply() - เพิ่มตัวแปรของโมเดล ได้แก่
interceptและslopeเป็นอาร์กิวเมนต์ในloss_function()ให้ครบถ้วน - คำนวณ mean squared error โดยใช้
targetsและpredictions
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Define a linear regression model
def linear_regression(intercept, slope, features = size_log):
return ____
# Set loss_function() to take the variables as arguments
def loss_function(____, ____, features = size_log, targets = price_log):
# Set the predicted values
predictions = linear_regression(intercept, slope, features)
# Return the mean squared error loss
return keras.losses.____
# Compute the loss for different slope and intercept values
print(loss_function(0.1, 0.1).numpy())
print(loss_function(0.1, 0.5).numpy())