3.1.6.6. Multiple Regression

Calculate using ‘statsmodels’ just the best fit, or all the corresponding statistical parameters.

Also shows how to make 3d plots.

# Original author: Thomas Haslwanter
import numpy as np
import matplotlib.pyplot as plt
import pandas
# For 3d plots. This import is necessary to have 3D plotting below
from mpl_toolkits.mplot3d import Axes3D
# For statistics. Requires statsmodels 5.0 or more
from statsmodels.formula.api import ols
# Analysis of Variance (ANOVA) on linear models
from statsmodels.stats.anova import anova_lm

Generate and show the data

x = np.linspace(-5, 5, 21)
# We generate a 2D grid
X, Y = np.meshgrid(x, x)
# To get reproducible values, provide a seed value
rng = np.random.default_rng(27446968)
# Z is the elevation of this 2D grid
Z = -5 + 3 * X - 0.5 * Y + 8 * np.random.normal(size=X.shape)
# Plot the data
ax = plt.figure().add_subplot(projection="3d")
surf = ax.plot_surface(X, Y, Z, cmap=plt.cm.coolwarm, rstride=1, cstride=1)
ax.view_init(20, -120)
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
plot regression 3d
Text(-0.10764513121260137, 0.009865032686848017, 'Z')

Multilinear regression model, calculating fit, P-values, confidence intervals etc.

# Convert the data into a Pandas DataFrame to use the formulas framework
# in statsmodels
# First we need to flatten the data: it's 2D layout is not relevant.
X = X.flatten()
Y = Y.flatten()
Z = Z.flatten()
data = pandas.DataFrame({"x": X, "y": Y, "z": Z})
# Fit the model
model = ols("z ~ x + y", data).fit()
# Print the summary
print(model.summary())
print("\nRetrieving manually the parameter estimates:")
print(model._results.params)
# should be array([-4.99754526, 3.00250049, -0.50514907])
# Perform analysis of variance on fitted linear model
anova_results = anova_lm(model)
print("\nANOVA results")
print(anova_results)
plt.show()
                            OLS Regression Results
==============================================================================
Dep. Variable: z R-squared: 0.527
Model: OLS Adj. R-squared: 0.525
Method: Least Squares F-statistic: 244.4
Date: Fri, 15 Sep 2023 Prob (F-statistic): 5.12e-72
Time: 19:08:02 Log-Likelihood: -1572.2
No. Observations: 441 AIC: 3150.
Df Residuals: 438 BIC: 3163.
Df Model: 2
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
Intercept -4.9921 0.409 -12.216 0.000 -5.795 -4.189
x 2.9435 0.135 21.809 0.000 2.678 3.209
y -0.4906 0.135 -3.635 0.000 -0.756 -0.225
==============================================================================
Omnibus: 0.978 Durbin-Watson: 1.878
Prob(Omnibus): 0.613 Jarque-Bera (JB): 1.020
Skew: -0.030 Prob(JB): 0.600
Kurtosis: 2.772 Cond. No. 3.03
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
Retrieving manually the parameter estimates:
[-4.99210364 2.9434951 -0.49062773]
ANOVA results
df sum_sq mean_sq F PR(>F)
x 1.0 35024.880591 35024.880591 475.621545 6.263349e-72
y 1.0 973.092684 973.092684 13.214145 3.108398e-04
Residual 438.0 32254.421306 73.640231 NaN NaN

Total running time of the script: (0 minutes 0.115 seconds)

Gallery generated by Sphinx-Gallery