Step-by-Step Breakdown
1. Import Required Libraries
import statsmodels.api as sm
import numpy as np
statsmodels.api is a Python library for statistical modeling, including Ordinary Least Squares (OLS) regression.
numpy is used for handling arrays.
2. Define Input Data
x = np.array([1, 2, 3, 4, 5])
y = np.array([3, 6, 9, 12, 15])
x represents the independent variable (predictor).
y represents the dependent variable (response).
The relationship follows a perfect linear pattern:
y=3x
This means the data is already perfectly aligned with a straight line.
3. Add Constant Term for Intercept
X = sm.add_constant(x)
sm.add_constant(x) adds a column of ones to x, which allows the regression model to estimate the intercept in the equation:
y=mx+c
After this step, X looks like:
[[1, 1],
[1, 2],
[1, 3],
[1, 4],
[1, 5]]
where:
The first column (all 1s) represents the intercept.
The second column is the original x values.
4. Fit the OLS Model
model = sm.OLS(y, X).fit()
sm.OLS(y, X).fit() performs Ordinary Least Squares (OLS) regression, which finds the best-fitting line by minimizing the sum of squared residuals.
5. Print the Slope (Coefficient)
print(model.params[1])
.params gives the estimated coefficients [intercept, slope].
model.params[1] extracts the slope (coefficient of x).
Final Output
3
0 Comments:
Post a Comment