การแสดงผลโมเดลถดถอยเชิงเส้น (OLS) จาก statsmodels พร้อมช่วงความเชื่อมั่น สามารถทำได้โดยใช้ wls_prediction_std คำนวณค่าคาดการณ์และช่วงความเชื่อมั่น แล้วพลอตพร้อมข้อมูลจริงและเส้นถดถอย
ขั้นตอนการทำงาน
- ตั้งค่า seed และสร้างข้อมูลเชิงเส้นพร้อม noise
- สร้างเมทริกซ์ออกแบบ (design matrix) X และพารามิเตอร์ beta
- คำนวณ y_true และเพิ่ม noise ได้ y
- ทำ OLS fit ด้วย
sm.OLS(y, X).fit() - คำนวณช่วงความเชื่อมั่นด้วย
wls_prediction_std - พลอตข้อมูล จริง เส้นถดถอย และช่วงความเชื่อมั่น
ตัวอย่างโค้ด
import numpy as np
from matplotlib import pyplot as plt
from statsmodels import api as sm
from statsmodels.sandbox.regression.predstd import wls_prediction_std
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
np.random.seed(9876789)
nsample = 50
sig = 0.5
x = np.linspace(0, 20, nsample)
X = np.column_stack((x, np.sin(x), (x - 5) ** 2, np.ones(nsample)))
beta = [0.5, 0.5, -0.02, 5.]
y_true = np.dot(X, beta)
y = y_true + sig * np.random.normal(size=nsample)
res = sm.OLS(y, X).fit()
prstd, iv_l, iv_u = wls_prediction_std(res)
fig, ax = plt.subplots()
ax.plot(x, y, 'o', label="data")
ax.plot(x, y_true, 'b-', label="True")
ax.plot(x, res.fittedvalues, 'r--.', label="OLS")
ax.plot(x, iv_u, 'r--')
ax.plot(x, iv_l, 'r--')
ax.legend(loc='best')
plt.show()
ผลลัพธ์
