พยากรณ์ด้วยโมเดลถั่วเหลืองบนข้อมูลทดสอบ
ในแบบฝึกหัดนี้ จะนำโมเดลถั่วเหลืองจากแบบฝึกหัดก่อนหน้า (model.lin และ model.gam ที่โหลดไว้แล้ว) มาใช้กับข้อมูลใหม่: soybean_test
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Supervised Learning ใน R: การถดถอย
คำแนะนำการฝึกหัด
- สร้างคอลัมน์
soybean_test$pred.linโดยใช้ค่าพยากรณ์จากโมเดลเชิงเส้นmodel.lin - สร้างคอลัมน์
soybean_test$pred.gamโดยใช้ค่าพยากรณ์จากโมเดล GAMmodel.gam- สำหรับโมเดล GAM ฟังก์ชัน
predict()จะคืนค่าเป็น matrix ดังนั้นให้ใช้as.numeric()เพื่อแปลงเป็น vector
- สำหรับโมเดล GAM ฟังก์ชัน
- เติมช่องว่างเพื่อใช้
pivot_longer()รวมคอลัมน์ค่าพยากรณ์ให้เป็นคอลัมน์ค่าเดียวชื่อpredโดยมีคอลัมน์คีย์ชื่อmodeltypeแล้วกำหนดชื่อ data frame แบบยาวนี้ว่าsoybean_long - คำนวณและเปรียบเทียบค่า RMSE ของทั้งสองโมเดล
- โมเดลไหนให้ผลดีกว่ากัน?
- รันโค้ดเพื่อเปรียบเทียบค่าพยากรณ์ของแต่ละโมเดลกับน้ำหนักใบจริง
- กราฟ scatter plot ของ
weightตามฟังก์ชันของTime - กราฟจุดและเส้นของค่าพยากรณ์ (
pred) ตามฟังก์ชันของTime - สังเกตว่าโมเดลเชิงเส้นบางครั้งพยากรณ์น้ำหนักติดลบ โมเดล GAM เป็นเช่นนั้นด้วยหรือไม่?
- กราฟ scatter plot ของ
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# soybean_test is available
summary(soybean_test)
# Get predictions from linear model
soybean_test$pred.lin <- ___(___, newdata = ___)
# Get predictions from gam model
soybean_test$pred.gam <- ___(___(___, newdata = ___))
# Pivot the predictions into a "long" dataset
soybean_long <- soybean_test %>%
pivot_longer(cols = c(___, ___), names_to = ___, values_to = ___)
# Calculate the rmse
soybean_long %>%
mutate(residual = weight - pred) %>% # residuals
group_by(modeltype) %>% # group by modeltype
summarize(rmse = ___(___(___))) # calculate the RMSE
# Compare the predictions against actual weights on the test data
soybean_long %>%
ggplot(aes(x = Time)) + # the column for the x axis
geom_point(aes(y = weight)) + # the y-column for the scatterplot
geom_point(aes(y = pred, color = modeltype)) + # the y-column for the point-and-line plot
geom_line(aes(y = pred, color = modeltype, linetype = modeltype)) + # the y-column for the point-and-line plot
scale_color_brewer(palette = "Dark2")