Chúng ta có thể vẽ hồi quy tuyến tính OLS của statsmodels với đường cong phi tuyến nhưng dữ liệu tuyến tính.
Các bước thực hiện
- Thiết lập kích thước hình và khoảng đệm.
- Tạo seed ngẫu nhiên bằng seed().
- Khởi tạo số mẫu và biến sigma.
- Tạo các điểm dữ liệu tuyến tính x, X, beta, t_true, y và res bằng NumPy.
- Res là instance của Ordinary Least Square.
- Tính độ lệch chuẩn. Khoảng tin cậy dự báo áp dụng cho WLS và OLS.
- Tạo hình và tập subplot bằng subplots().
- Vẽ các đường cong với dữ liệu (x, y), (x, y_true), (x, res.fittedvalues), (x, iv_u), (x, iv_l).
- Đặt legend trên biểu đồ.
- Hiển thị hình bằng show().
Ví dụ
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()
Kết quả
