Last active
April 4, 2022 10:07
-
-
Save netsatsawat/3f00d048c85cd1ee5c955e39e3498ff1 to your computer and use it in GitHub Desktop.
Example of single linear regression (closed form equation)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import statsmodels.api as sm | |
from sklearn.linear_model import LinearRegression | |
# generate sample data (single linear) | |
X = 2 * np.random.rand(200, 1) | |
y = 1.2 * X + 1 + 0.8 * np.random.randn(200, 1) | |
X_ = sm.add_constant(X) # add constant for intercept computation | |
print('Method 1: matrix formulation') | |
print(np.dot(np.linalg.inv(np.dot(X_.T, X_)), np.dot(X_.T, y))) | |
# statsmodels lib | |
model = sm.OLS(y, X_).fit() | |
print('Method 2: statsmodels') | |
print(f'{model.params}') | |
# LinearRegression | |
print('Method 3: sklearn.linear_model.LinearRegression') | |
lr_model = LinearRegression(fit_intercept=True) | |
lr_model.fit(X, y) | |
print(f'Intercept: {lr_model.intercept_}, coeff: {lr_model.coef_}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment