# How to compute the standard error of the estimate for a model (in Python, using statsmodels)

See all solutions.

One measure of the goodness of fit of a model is the standard error of its estimates. If the actual values are $y_i$ and the estimates are $\hat y_i$, the definition of this quantity is as follows, for $n$ data points.

$\sigma_{\text{est}} = \sqrt{ \frac{ \sum (y_i-\hat y_i)^2 }{ n } }$

If we’ve fit a linear model, how do we compute the standard error of its estimates?

## Solution

Let’s assume that you already fit the linear model, as shown in the code below. This one uses a small amount of fake data, but it’s just an example. See also how to fit a linear model to two columns of data.

1
2
3
4
5
6
7
8
# Below is the fake data as an example. You can replace with your real data.
x = [  34,   9,  78,  60,  22,  45,  83,  59,  25 ]
y = [ 126, 347, 298, 309, 450, 187, 266, 385, 400 ]

# Use statsmodels to build a linear regression model
import statsmodels.api as sm
model = sm.OLS( y, x ).fit()


The standard error is shown as part of the model summary, reported by statsmodels’s built-in summary function. See the column entitled “std err” in the output below.

1
model.summary()

1
2
/opt/conda/lib/python3.10/site-packages/scipy/stats/_stats_py.py:1736: UserWarning: kurtosistest only valid for n>=20 ... continuing anyway, n=9
warnings.warn("kurtosistest only valid for n>=20 ... continuing "

Dep. Variable: R-squared: y 0.063 OLS -0.071 Least Squares 0.4693 Mon, 24 Jul 2023 0.515 20:38:01 -53.705 9 111.4 7 111.8 1 nonrobust
coef std err t P>|t| [0.025 0.975] 354.0822 76.733 4.614 0.002 172.638 535.526 -1.0090 1.473 -0.685 0.515 -4.492 2.474
 Omnibus: Durbin-Watson: 2.324 1.618 0.313 1.079 -0.832 0.583 2.674 112

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

If we need to extract just the estimates or their standard errors, we can use code like the following.

1
model.params # just the model coefficients

1
array([354.0822479 ,  -1.00901261])

1
model.bse # just the standard errors of those estimates

1
array([76.73277161,  1.47293931])


The standard error of the estimate for the intercept is is 76.73277161 and the standard error of the estimate for the slope is 1.47293931.