Gradient Boosting (Visualization)

2.4.6

Gradient Boosting (Visualization)

อัปเดต 2020-04-08 อ่าน 1 นาที
สรุป
  • สรุปเป้าหมาย สมมติฐาน และเงื่อนไขที่เหมาะสมของวิธีนี้.
  • ตรวจสอบว่ากฎการอัปเดตหรือเกณฑ์การแบ่งส่งผลต่อพฤติกรรมโมเดลอย่างไร.
  • ใช้ตัวอย่างโค้ดเพื่อกำหนดแนวทางปรับพารามิเตอร์อย่างเป็นรูปธรรม.

สัญชาตญาณ #

การมอง Gradient Boosting แบบทีละขั้น ควรเข้าใจผ่านสมมติฐาน กลไกการปรับปรุงโมเดล และรูปแบบความผิดพลาดบนข้อมูลจริง เพื่อให้เลือกโมเดลและปรับพารามิเตอร์ได้อย่างเหมาะสม.

คำอธิบายโดยละเอียด #

1. ฝึกโมเดลและดูเส้นพยากรณ์สุดท้าย #

n_samples = 500
X = np.linspace(-10, 10, n_samples)[:, np.newaxis]
noise = np.random.rand(X.shape[0]) * 10
y = (np.sin(X).ravel()) * 10 + 10 + noise

n_estimators = 10
learning_rate = 0.5
reg = GradientBoostingRegressor(
    n_estimators=n_estimators,
    learning_rate=learning_rate,
)
reg.fit(X, y)

y_pred = reg.predict(X)

plt.figure(figsize=(20, 10))
plt.scatter(X, y, c="k", marker="x", label="train")
plt.plot(X, y_pred, c="r", label="final prediction")
plt.axhline(y=np.mean(y), color="gray", linestyle=":", label="initial model")
plt.legend(); plt.show()

เส้นสีเทาคือโมเดลเริ่มต้น (ค่าเฉลี่ย) ส่วนสีแดงคือผลหลังบวกต้นไม้ 10 ต้น


2. ดูว่าต้นไม้แต่ละต้นเพิ่มอะไร #

fig, ax = plt.subplots(figsize=(20, 10))
temp = np.zeros(n_samples) + np.mean(y)

for i in range(n_estimators):
    res = reg.estimators_[i][0].predict(X) * learning_rate
    ax.bar(X.flatten(), res, bottom=temp, label=f"tree {i+1}", alpha=0.05)
    temp += res

plt.scatter(X.flatten(), y, c="k", marker="x", label="train")
plt.plot(X, y_pred, c="r", linewidth=1, label="final prediction")
plt.legend(); plt.show()

แท่งสีจาง = ผลของต้นไม้แต่ละต้น เมื่อบวกทีละก้อนจะได้เส้นสีแดง


3. ดูพัฒนาการหลังเพิ่มต้นไม้ทีละต้น #

for i in range(5):
    fig, ax = plt.subplots(figsize=(20, 10))
    plt.title(f"หลังเพิ่ม {i+1} ต้น")
    temp = np.zeros(n_samples) + np.mean(y)

    for j in range(i + 1):
        res = reg.estimators_[j][0].predict(X) * learning_rate
        ax.bar(X.flatten(), res, bottom=temp, alpha=0.05)
        temp += res

    plt.scatter(X.flatten(), y, c="k", marker="x")
    plt.plot(X, temp, c="r", linewidth=1.2, label="prediction")
    plt.legend(); plt.show()

จะเห็นว่าเส้นพยากรณ์เริ่มจากค่าเฉลี่ย → เพิ่มต้นไม้แต่ละต้นแล้วค่อย ๆ โค้งตามข้อมูล → พอต้นไม้พอเพียงก็ได้เส้นสีแดงสุดท้าย