Nicolás P
Nicolás P

Reputation: 51

Residual standard error of a regression in python

Does anyone know a command or a way to obtain the residual standard error of a regression or standard error of a regression?

I use the following commands to get the coefficients and the R-squared, I would like to learn one command like these for the standard error of the regression:

#For the coefficients:
model = smf.OLS(y, X).fit()
print(model.params)

#For the R-squared:
model = smf.OLS(y, X).fit()
print(model.rsquared)

I will be really grateful to the person that can help me with this issue.

Upvotes: 4

Views: 12287

Answers (3)

To get Residual Standard Error (RSE) of a regression model in python's statsmodels library, you can simply apply the standard deviation method with the degree of freedom equal to the number of predictors (p) + 1 as below:

model = sm.OLS(y, X).fit()
model.resid.std(ddof=X.shape[1])

Upvotes: 3

rahul-ahuja
rahul-ahuja

Reputation: 1424

For a smf.ols fit

# Residual Standard Error of the model
np.sqrt(fitted_model.scale)

Upvotes: 4

Swain Subrat Kumar
Swain Subrat Kumar

Reputation: 523

RSE is an estimate of the standard deviation of error. You can go like this:

import math
import numpy as np


def RSE(y_true, y_predicted):
    """
    - y_true: Actual values
    - y_predicted: Predicted values
    """
    y_true = np.array(y_true)
    y_predicted = np.array(y_predicted)
    RSS = np.sum(np.square(y_true - y_predicted))

    rse = math.sqrt(RSS / (len(y_true) - 2))
    return rse


if __name__ == "__main__":
    y_true = [1, 2, 3]
    y_predicted = [2, 3, 4]
    print(RSE(y_true, y_predicted))

Upvotes: 0

Related Questions