Code Explanation:
1. Importing Libraries
import statsmodels.api as sm
import numpy as np
numpy is used for numerical operations and creating arrays.
statsmodels.api is a Python package used for statistical modeling — especially regression.
2. Defining Data
x = np.array([1, 2, 3, 4, 5])
y = np.array([3, 6, 9, 12, 15])
x is the independent variable.
y is the dependent variable.
From a quick look: y = 3 * x — it’s a perfect linear relationship.
3. Adding Intercept to X
X = sm.add_constant(x)
This adds a column of ones to x so the model can estimate an intercept term (bias).
Now X becomes a 2D array:
[[1. 1.]
[1. 2.]
[1. 3.]
[1. 4.]
[1. 5.]]
First column = constant (intercept)
Second column = original x values
4. Fitting the OLS Model
model = sm.OLS(y, X).fit()
This runs Ordinary Least Squares (OLS) regression using:
y as the dependent variable
X (with constant) as the independent variable(s)
.fit() estimates the parameters (intercept and slope)
5. Accessing the Slope
print(model.params[1])
model.params returns the regression coefficients:
[intercept, slope]
model.params[1] extracts the slope of the line.
Since the data is perfectly linear (y = 3x), the slope should be exactly 3.0.
Final Output
>>> 3.0
This confirms the slope is 3, matching the relationship between x and y.
0 Comments:
Post a Comment