Basic linear regression

Submitted by
kevindunn on 28 July 2011
Download
File
Update history
Revision 5 of 5: previous
Updated by
jeremy on 07 February 2016
Tags
# Calculates the linear regression model and plots the data # Limitations: only returns the most basic regression outputs from scipy import stats import numpy as np import pylab # Fit the model x = np.array([1, 2, 5, 7, 10, 15]) y = np.array([2, 6, 7, 9, 14, 19]) slope, intercept, r_value, p_value, slope_std_error = stats.linregress(x, y) # Calculate some additional outputs predict_y = intercept + slope * x pred_error = y - predict_y degrees_of_freedom = len(x) - 2 residual_std_error = np.sqrt(np.sum(pred_error**2) / degrees_of_freedom) # Plotting pylab.plot(x, y, 'o') pylab.plot(x, predict_y, 'k-') pylab.show()

Expected result: /media/images/201107/least-squares-screenshot_2.png

See the official Scipy documentation for details about linregress.

A more complete regression model can be obtained with the OLS function in the statsmodels library.

Please Sign in or Register to leave a comment

  • Creative Commons Zero. No rights reserved.
    Users have permission to do anything with the code and other material on this page. (More details)
  • Trademarks are property of their respective owners. Code and comments are owned by their respective posters. © 2013 All Rights Reserved