pecon.regression.OLS#
- class pecon.regression.OLS#
Bases:
objectSimple Ordinary Least Squares (OLS) regression for a single independent variable.
This class implements simple linear regression with one predictor (x) and one dependent variable (y). It calculates the slope (beta) and intercept (alpha) using the classical OLS formulas:
\[\beta = \frac{\sum (x - \bar{x}) (y - \bar{y})}{\sum (x - \bar{x})^2}\]\[\alpha = \bar{y} - \beta \bar{x}\]- x#
The independent variable (predictor). Must be 1-dimensional.
- Type:
array-like
- y#
The dependent variable (response). Must be 1-dimensional.
- Type:
array-like
- beta#
Estimated slope of the regression line. Calculated after calling fit().
- Type:
float
- alpha#
Estimated intercept of the regression line. Calculated after calling fit().
- Type:
float
- r#
Sample correlation coefficient between x and y.
- Type:
float
- p#
Two-tailed p-value for testing non-correlation between x and y.
- Type:
float
- fitted#
Flag indicating whether the model has been fitted.
- Type:
bool
- Raises:
ValueError – If x or y are not 1-dimensional arrays of the same length.
Warning – Warns if the independent variable has zero variance, which makes beta undefined.
Example
>>> import numpy as np >>> from pecon.regression import OLS >>> x = np.array([2, 4, 6, 8]) >>> y = np.array([1, 5, 2, 7]) >>> model = OLS(x, y) >>> model.fit() >>> model.summary() beta = 0.75 alpha = 0.0 r = 0.408 p = 0.6
- fit()#
Fit the Ordinary Least Squares (OLS) model.
Computes the slope (beta) and intercept (alpha) of the regression line using the closed-form OLS solution. Also computes the sample correlation coefficient and its two-tailed p-value.
Notes
The estimates are given by:
\[ \begin{align}\begin{aligned}\beta = \frac{\sum (x - \bar{x})(y - \bar{y})} {\sum (x - \bar{x})^2}\\\alpha = \bar{y} - \beta \bar{x}\end{aligned}\end{align} \]After calling this method, the following attributes are available:
beta: slope coefficientalpha: interceptr: correlation coefficientp: p-value for testing non-correlationfitted: set toTrue
- Raises:
ValueError – If the independent variable has zero variance.
- summary()#
Print a summary of the fitted OLS regression.
Displays the estimated coefficients and correlation statistics in a human-readable format. This method requires the model to be fitted first.
Output#
- beta
Estimated slope coefficient.
- alpha
Estimated intercept.
- r
Sample correlation coefficient.
- p
Two-tailed p-value for testing non-correlation.
- raises RuntimeError:
If the model has not been fitted. Call
fit()first.