Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Matplotlib에서 statsmodels 선형 회귀(OLS)를 깔끔하게 플롯하는 방법은 무엇입니까?

<시간/>

비선형 곡선을 사용하지만 선형 데이터를 사용하여 statsmodels 선형 회귀(OLS)를 그릴 수 있습니다.

단계

  • Figure 크기를 설정하고 서브플롯 사이와 주변의 패딩을 조정합니다.

  • 새 것을 만들려면 seed()를 사용할 수 있습니다. 방법.

  • 샘플 및 시그마 변수의 수를 초기화합니다.

  • 선형 데이터 포인트 x, X, 베타, t_true 생성 , y 및 해상도 numpy를 사용합니다.

  • 해상도 일반적인 최소제곱 클래스 인스턴스입니다.

  • 표준편차를 계산합니다. 예측을 위한 신뢰 구간은 일반 GLS가 아닌 WLS와 OLS에 적용됩니다. 즉, 독립적이지만 동일하게 분포하지 않는 관측값입니다.

  • subplot()을 사용하여 Figure와 서브플롯 세트 생성 방법.

  • plot()을 사용하여 모든 곡선을 플로팅합니다. (x, y), (x, y_true), (x, res.fittedvalues), (x, iv_u)가 있는 메서드 및 (x, iv_l) 데이터 포인트.

  • 줄거리에 범례를 배치하십시오.

  • 그림을 표시하려면 show()를 사용하세요. 방법.

예시

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()

출력

Matplotlib에서 statsmodels 선형 회귀(OLS)를 깔끔하게 플롯하는 방법은 무엇입니까?