python-scipyHow do I use Python and SciPy to perform linear regression?
Linear regression is a statistical method used to find the relationship between two variables. With Python and SciPy, you can use the least-squares method to fit a linear regression model.
Example code
import scipy.stats as st
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
slope, intercept, r_value, p_value, std_err = st.linregress(x,y)
print("slope: %f intercept: %f" % (slope, intercept))
Output example
slope: 4.000000 intercept: 0.000000
Code explanation
import scipy.stats as st
imports the SciPy library.x = [1, 2, 3, 4, 5]
andy = [1, 4, 9, 16, 25]
creates two lists of data points.slope, intercept, r_value, p_value, std_err = st.linregress(x,y)
uses the SciPylinregress
function to fit a linear regression model to the data.print("slope: %f intercept: %f" % (slope, intercept))
prints the slope and intercept of the linear regression model.
Helpful links
- SciPy Documentation: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.linregress.html
- Python Tutorial: https://docs.python.org/3/tutorial/index.html
More of Python Scipy
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How do I create a 2D array of zeros using Python and NumPy?
- How can I check if a certain version of Python is compatible with SciPy?
- How can I use the "where" function in Python Numpy?
- How can I use Python and SciPy to solve an ordinary differential equation?
- How do I create a zero matrix using Python and Numpy?
- How can I use SciPy in Python with the help of W3Schools tutorials?
- How do I use the scipy ttest_ind function in Python?
- How do I use the NumPy transpose function in Python?
- How can I use Python Scipy to solve a Poisson equation?
See more codes...