SciPy Linear Regression in Python (Step by Step)

SciPy linear regression takes one function call, scipy.stats.linregress(x, y). It fits a straight line through your data and hands back the slope, the intercept, and a few numbers that tell you how good the line is.

In ten steps, I fit it to made-up data, hours studied against exam score. Then I check the fit with R-squared, put a confidence interval on the slope, plot the leftover errors, add a second input, and cross-check the answer with NumPy and scikit-learn.

Regression shows up in my Big Data Analytics master’s at SDSU. I used a neural network for it in one of my final projects, before the AI boom, when you built and tested your own models. This post pulls that together with notes from a machine learning course on Udemy.

The example is mine, study hours against score. Every code block runs top to bottom on Python 3.13.8, NumPy 2.5.4, SciPy 1.18.1, matplotlib 3.11.2 and scikit-learn 1.9.1, and the output shown is what it printed.

What is linear regression?

Linear regression predicts a number, called the dependent variable y, from one or more inputs, called independent variables x. It’s a form of supervised learning, because you train it on examples where the right answer is known. It assumes the relationship is a straight line.

y = b0 + b1 * x + e
  • b0 is the intercept, the predicted y when x is zero.
  • b1 is the slope, how much y changes when x goes up by one.
  • e is the error, everything about y that x doesn’t explain.

You already do this in your head. Say you earned $10,000 two years ago and $20,000 last year. If you guess $30,000 for this year, you just drew a line through two points and extended it.

The model answers two questions. Is there a linear relationship between x and y? And, with several inputs, which one matters most?

It has a big catch. It only works when the relationship really is roughly linear.

And it will never predict every point exactly. The error term is there for a reason.

What do you need before you start?

You need three things.

  • Python 3.12 or newer. The current NumPy and SciPy releases require it.
  • A terminal.
  • Basic Python. If arrays are new to you, start with my NumPy tutorial.

The ten steps at a glance

Steps 1 to 6 fit the line and use it. Steps 7 to 10 check it, extend it, and keep you out of the usual traps.

  1. Install NumPy, SciPy and matplotlib in a virtual environment.
  2. Make practice data with a known answer.
  3. Fit the line with scipy.stats.linregress.
  4. Check the fit with R-squared.
  5. Put a confidence interval on the slope.
  6. Predict new scores, and know when not to.
  7. Plot the line and the residuals.
  8. Add a second input with multiple linear regression.
  9. Cross-check with NumPy polyfit and scikit-learn.
  10. Avoid the common linregress mistakes.

Step 1. Install NumPy, SciPy and matplotlib

Make a virtual environment first. That’s a private folder of packages for one project, so nothing here clashes with the rest of your Python setup. Any Python from 3.12 up works in place of python3.13.

python3.13 -m venv .venv
source .venv/bin/activate
pip install numpy scipy matplotlib

NumPy holds the data, SciPy does the regression, and matplotlib draws the charts. Step 9 adds scikit-learn.

Step 2. Make practice data with a known answer

Practice on data where you already know the true slope, so you can tell whether SciPy got it right. I generated 100 fake students so I’d know the true answer. Hours studied is normally distributed around 20. Each hour adds 1.1 points to the score, which is out of 100.

There’s also a second input, exercises completed, that adds 0.7 points per exercise, plus random noise.

For now I’ll ignore exercises and regress score on hours alone. Exercises come back in Step 8.

import numpy as np
from scipy import stats

rng = np.random.default_rng(1)

hours = rng.normal(20, 6, 100)
exercises = rng.normal(15, 4, 100)
score = 25 + 1.1 * hours + 0.7 * exercises + rng.normal(0, 4, 100)

print(f"hours: min {hours.min():.1f}, max {hours.max():.1f}")
print(f"score: min {score.min():.1f}, max {score.max():.1f}")
hours: min 3.7, max 32.7
score: min 39.2, max 75.4

default_rng(1) fixes the random numbers, so you get exactly these students every time you run it.

Step 3. Fit the line with scipy.stats.linregress

One call does the whole SciPy linear regression. linregress returns a result object, and each number lives on it as an attribute.

res = stats.linregress(hours, score)

print(f"slope {res.slope:.3f}  intercept {res.intercept:.3f}  r {res.rvalue:.3f}  r2 {res.rvalue ** 2:.3f}")
print(f"p {res.pvalue:.2e}  stderr {res.stderr:.3f}  intercept_stderr {res.intercept_stderr:.3f}")
slope 1.077  intercept 35.103  r 0.770  r2 0.593
p 7.28e-21  stderr 0.090  intercept_stderr 1.820

Here’s what each number means. The SciPy docs list them all.

  • slope, 1.077. Each extra hour of study goes with about one more point. That’s close to the 1.1 I built in. It says “goes with”, not “causes”.
  • intercept, 35.103. The predicted score at zero hours. Nobody in this data studied less than 3.7 hours, so don’t read too much into it.
  • r, 0.770. The correlation between hours and score.
  • p, 7.28e-21. The p-value for a test where the starting assumption is that the slope is zero. A tiny value means that if the true slope were zero, you would almost never see a slope this large by chance.
  • stderr, 0.090. The standard error of the slope, a measure of how much it would wobble if you drew new students.
  • intercept_stderr, 1.820. The same thing for the intercept.

Older tutorials unpack the result into five names instead. That still works, because the result also acts like a tuple of five values.

slope, intercept, r_value, p_value, std_err = stats.linregress(hours, score)
print(f"slope {slope:.3f}  intercept {intercept:.3f}")
slope 1.077  intercept 35.103

The SciPy docs point out the catch. The five-name style leaves out intercept_stderr, so use the object when you need it.

Step 4. Check the fit with R-squared

R-squared, also called the coefficient of determination, says how much of the variation in y your line captures. Here it’s 0.593, so the line explains about 59% of the spread in scores. The rest is everything else, like exercises, sleep or a lucky guess.

SciPy’s docs confirm the shortcut. The square of rvalue is the coefficient of determination. But the formula is worth seeing once.

R-squared = 1 - (sum of squared errors) / (sum of squared distances from the mean)

The bottom part is the total variation in scores around their own average. The top part is what the line failed to explain. Here it is in code, with a small predict() function you’ll reuse.

def predict(x):
    return res.slope * x + res.intercept

sse = np.sum((score - predict(hours)) ** 2)
sst = np.sum((score - score.mean()) ** 2)
print("1 - sse/sst =", round(1 - sse / sst, 3))
1 - sse/sst = 0.593

Same number. Two ways to read it.

  • 0 means the line explains nothing. 1 means it explains everything. A low value is a poor fit. A high value is a good one.
  • It isn’t strictly stuck between 0 and 1. On new data, or for a model fitted without an intercept, R-squared can go negative. That means the model does worse than just guessing the average.

A high R-squared doesn’t prove your model is right. It just says the line follows the data you fitted it to.

How does least squares find the line?

The method is called ordinary least squares, or OLS. It picks the slope and intercept that make the total squared error as small as possible.

The error for one student is the actual score minus the predicted one. Then we square it, for two reasons.

  1. A prediction can miss high or low. Squaring makes every miss positive, so misses can’t cancel each other out.
  2. Squaring punishes big misses far more than small ones.

Squaring doesn’t guarantee a better model. It just defines what “best line” means.

You never have to do the math, because Python does it. But knowing what’s under the hood helps. The answer has a closed form, and for one input it looks like this.

slope     = r * (standard deviation of y) / (standard deviation of x)
intercept = mean of y - slope * mean of x

I checked it against SciPy.

slope_hand = res.rvalue * score.std() / hours.std()
intercept_hand = score.mean() - slope_hand * hours.mean()
print("by hand:", round(slope_hand, 3), round(intercept_hand, 3))
by hand: 1.077 35.103

Identical. So OLS gets its answer in one step.

std() here is NumPy’s population standard deviation, which divides by N. Sample standard deviation, which divides by N minus 1, gives the same slope, because the two versions cancel out in the ratio. My NumPy standard deviation post covers that ddof setting.

Some tutorials show the line inching toward the data over many iterations. That’s gradient descent, which is how neural networks are trained, and it isn’t needed for a straight line.

I use it in my overfitting vs underfitting post if you want to see it running.

Step 5. Put a confidence interval on the slope

A slope of 1.077 is one estimate from one set of students. A confidence interval gives the range the true slope probably sits in.

The recipe comes from the example in SciPy’s linregress docs, and the t-value comes from scipy.stats.t. Look up a t-value for 95% with 98 degrees of freedom, which is 100 students minus the 2 numbers the line estimates. Multiply it by the standard error, then add and subtract.

from scipy.stats import t

ts = abs(t.ppf(0.05 / 2, len(hours) - 2))
print(f"t value {ts:.3f}")
print(f"slope 95% CI: {res.slope - ts * res.stderr:.3f} to {res.slope + ts * res.stderr:.3f}")
print(f"intercept 95% CI: {res.intercept - ts * res.intercept_stderr:.2f} to {res.intercept + ts * res.intercept_stderr:.2f}")
t value 1.984
slope 95% CI: 0.898 to 1.255
intercept 95% CI: 31.49 to 38.71

The slope’s range, 0.898 to 1.255, contains the true 1.1 I built in. That’s what you want to see.

The intercept needs care. The true value for this one-input line isn’t 25, because the line also soaks up exercises at their average of 15. So the true intercept here is 25 + 0.7 × 15, or 35.5, and that sits inside 31.49 to 38.71.

What 95% means is easy to get wrong. If you repeated this with fresh students many times, about 95% of the ranges built this way would contain the true slope.

If you only care whether the slope is positive, linregress also takes alternative="greater" for a one-sided p-value. The docs list it with the other options.

Step 6. Predict new scores

Multiply the input by the slope and add the intercept. That’s what predict() from Step 4 does. Here’s a student who studies 30 hours, and one who studies 100.

print("30 hours ->", round(predict(30), 1))
print("100 hours ->", round(predict(100), 1))
30 hours -> 67.4
100 hours -> 142.8

The first answer is reasonable. 30 hours sits inside the range of the data, which ran up to 32.7.

The second answer is nonsense. A score of 142.8 isn’t possible on a test out of 100.

The math worked perfectly. The line just has no idea that scores stop at 100, and it has never seen anyone study for 100 hours.

Only trust predictions inside the range you fitted.

Step 7. Plot the line and the residuals

A residual is one student’s miss, the actual score minus the predicted one. Plotting them is how you check that a straight line suits the data at all.

residuals = score - predict(hours)

print("residuals average to zero:", np.isclose(residuals.mean(), 0))
print(f"residual std {residuals.std():.2f}")
print(f"biggest misses {residuals.min():.1f} and {residuals.max():.1f}")
print(f"residuals vs exercises r {np.corrcoef(residuals, exercises)[0, 1]:.2f}")
residuals average to zero: True
residual std 4.55
biggest misses -9.2 and 13.9
residuals vs exercises r 0.60

The residuals average to zero, which least squares with an intercept always guarantees. The typical miss is about 4.55 points.

The last line matters most. The misses aren’t random noise. They track exercises, the input we left out, with a correlation of 0.60.

This matplotlib code draws both charts side by side.

import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))

ax1.scatter(hours, score)
ax1.plot(hours, predict(hours), c="r")
ax1.set_xlabel("Hours studied")
ax1.set_ylabel("Score")

ax2.scatter(predict(hours), residuals)
ax2.axhline(0, c="r")
ax2.set_xlabel("Predicted score")
ax2.set_ylabel("Residual")

plt.show()

The two charts below show the same data, drawn from the run’s output.

Hours studied vs exam score, with the fitted line 100 made-up students. Scores rise with hours studied. The fitted line runs from about 39 points at 3.7 hours to about 70 points at 32.7 hours, with a slope of 1.077 points per hour. 30 40 50 60 70 80 0 5 10 15 20 25 30 35 Hours studied Score (out of 100) Fitted line, slope 1.077
The 100 practice students from Step 2 and the line linregress fitted through them. The line only covers the hours in the data, 3.7 to 32.7.
Rendered with Python from the run's output.
Residuals vs predicted score The miss for each of the 100 students, actual score minus predicted score, plotted against the predicted score. The points scatter above and below the zero line with no curve or funnel shape. The biggest misses are -9.2 and 13.9 points. -15 -10 -5 0 5 10 15 40 50 60 70 80 Predicted score Residual (points) Zero miss
Each dot is one student's miss. Above the line, the student scored higher than the line predicted. Below it, lower. A random cloud like this one means a straight line suits the data.
Rendered with Python from the run's output.

The residual plot looks like a random cloud, and that’s a good sign. A curve in the dots would mean the relationship bends, and a funnel would mean the misses grow as scores rise.

But a residual plot only shows patterns along the axis you plotted. The exercises signal was invisible here and obvious in the correlation. So also check the residuals against inputs you left out.

Step 8. Add a second input

Multiple linear regression uses two or more inputs. Add exercises completed to the model and it becomes this.

score = b0 + b1 * hours + b2 * exercises

Can SciPy do multiple linear regression?

Not with linregress, which takes a single x. Now there are three numbers to estimate. NumPy’s least squares solver, np.linalg.lstsq, does the job for any number of inputs, once you add a column of ones so the model gets an intercept.

X = np.column_stack([np.ones_like(hours), hours, exercises])
coef, *_ = np.linalg.lstsq(X, score, rcond=None)
b0, b1, b2 = coef
print(f"b0 {b0:.3f} b1 {b1:.3f} b2 {b2:.3f}")

pred = X @ coef
r2 = 1 - np.sum((score - pred) ** 2) / sst
print("multiple r2", round(r2, 3))
print("30h, 15 ex ->", round(b0 + b1 * 30 + b2 * 15, 1))
print(f"hours vs exercises r {np.corrcoef(hours, exercises)[0, 1]:.2f}")
b0 24.737 b1 1.091 b2 0.686
multiple r2 0.739
30h, 15 ex -> 67.8
hours vs exercises r -0.03

The estimates land close to the truth I built in, 25, 1.1 and 0.7. R-squared jumps from 0.593 to 0.739, because exercises really do matter in this data.

Each hour now adds about 1.09 points with exercises held fixed. Hours and exercises are almost uncorrelated here, at -0.03, which is why the one-input slope of 1.077 was already close to the truth.

In real data, inputs usually overlap, and leaving one out shifts the slope of the other.

SciPy has its own least squares solver too, scipy.linalg.lstsq, and it gives the same answer.

from scipy import linalg

coef_scipy, *_ = linalg.lstsq(X, score)
print("scipy.linalg.lstsq", coef_scipy.round(3))
scipy.linalg.lstsq [24.737  1.091  0.686]

One warning. Adding an input can never lower R-squared on the data you fitted, even if that input is pure noise.

So a rising R-squared isn’t proof that a new variable belongs. Check on data the model hasn’t seen, which is the whole point of the overfitting vs underfitting comparison.

Step 9. Cross-check with NumPy polyfit and scikit-learn

A SciPy linear regression isn’t the only way to get this line, and checking one tool against another is a cheap way to catch a mistake. For a NumPy linear regression without SciPy, np.polyfit fits a polynomial, and degree 1 is a straight line, a linear fit.

print("polyfit", np.polyfit(hours, score, 1).round(3))
polyfit [ 1.077 35.103]

polyfit returns the highest power first, so that’s the slope and then the intercept. They match linregress to three decimals.

NumPy’s docs call polyfit part of the old polynomial API, and they prefer numpy.polynomial for new code. Here’s the newer call.

from numpy.polynomial import Polynomial

line = Polynomial.fit(hours, score, 1).convert()
print("Polynomial.fit", line.coef.round(3))
Polynomial.fit [35.103  1.077]

Same line, opposite order. Polynomial lists the lowest power first, so the intercept comes before the slope. .convert() matters too, because without it the coefficients are for a rescaled version of hours.

Many tutorials on this topic use scikit-learn’s LinearRegression instead. Install it into the same environment.

pip install scikit-learn

Then fit the same data.

from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit(hours.reshape(-1, 1), score)
print(f"slope {model.coef_[0]:.3f}  intercept {model.intercept_:.3f}  r2 {model.score(hours.reshape(-1, 1), score):.3f}")
print("30 hours ->", round(model.predict([[30]])[0], 1))
slope 1.077  intercept 35.103  r2 0.593
30 hours -> 67.4

scikit-learn wants the inputs as a 2D array, with one row per student and one column per input. That’s why hours gets reshaped. Multiple regression is the same call with two columns.

X2 = np.column_stack([hours, exercises])
multi = LinearRegression().fit(X2, score)
print(f"b0 {multi.intercept_:.3f}  b1 {multi.coef_[0]:.3f}  b2 {multi.coef_[1]:.3f}  r2 {multi.score(X2, score):.3f}")
b0 24.737  b1 1.091  b2 0.686  r2 0.739

Every tool lands on the same slope and intercept, and scikit-learn’s R-squared matches too. So which one should you use?

Tool Inputs Best for
scipy.stats.linregress One A line plus its p-value and standard errors
np.polyfit or Polynomial.fit One Just the coefficients, or a curve
np.linalg.lstsq or scipy.linalg.lstsq Many Several inputs as plain arrays
scikit-learn LinearRegression Many A model inside a bigger workflow

linregress is the only one here that hands you the p-value and standard errors directly. scikit-learn has the same fit and predict pattern as the classifier in my KNN tutorial, so train and test splits and cross-validation work the same way. The LinearRegression docs list its options, and my sklearn linear regression tutorial builds that whole workflow on real NFL Combine data.

If your data follows a curve instead of a line, the SciPy docs point to scipy.optimize.curve_fit, which fits any function you write.

Step 10. Avoid the common linregress mistakes

Three mistakes come up again and again. Each one below ran on the same data.

A missing value turns everything into nan

Real data has gaps. If you load a CSV with pandas read_csv, empty cells arrive as NaN by default. Here one student’s hours go missing.

hours_gap = hours.copy()
hours_gap[0] = np.nan

print(f"default slope {stats.linregress(hours_gap, score).slope:.3f}")
print(f"omit slope    {stats.linregress(hours_gap, score, nan_policy='omit').slope:.3f}")
default slope nan
omit slope    1.071

With the default setting, one missing value makes every result nan, which stands for “not a number”. There’s no error and no warning. nan_policy="omit" skips that student and fits the other 99.

Two inputs in one array

linregress fits one x against one y. Hand it two inputs side by side and it refuses.

try:
    stats.linregress(np.column_stack([hours, exercises]), score)
except Exception as e:
    print(type(e).__name__, e)
ValueError Array shapes are incompatible for broadcasting.

The try and except just print the error instead of stopping the script. My Python exception handling post explains how they work.

That’s the friendly version. Stack the same two inputs as rows instead, and it runs.

rows = np.vstack([hours, exercises])
wrong = stats.linregress(rows, score)
print(np.shape(wrong.slope), wrong.slope[:3], wrong.rvalue[:3])
(100,) [0. 0. 0.] [nan nan nan]

No error, no warning, and 100 confident zeros. It fitted a line through each column of two points, where both y values are the same score, so every slope is 0 and every r is nan.

The axis setting doesn’t turn it into multiple regression either. With axis=1 it runs two separate one-input fits.

per_row = stats.linregress(rows, score, axis=1)
print("axis=1 slopes", per_row.slope.round(3))
axis=1 slopes [1.077 0.648]

The 1.077 is hours alone, and the 0.648 is exercises alone, not the 0.686 from Step 8. For several inputs at once, use Step 8.

Reading r as R-squared

rvalue is the correlation, not R-squared. Square it first.

print(f"r {res.rvalue:.3f}, r squared {res.rvalue ** 2:.3f}")
r 0.770, r squared 0.593

Reporting 0.770 as R-squared would overstate the fit. The line explains 59% of the spread, not 77%.

Where have I used regression for real?

In the SDSU program, my part of the BDA 594 final group project was about NFL special teams. We were given league data and asked to build new metrics for the specialists (punters, kickers, and long snappers). Then we ranked them, hoping to find something that could help a team perform better.

I preprocessed the exploratory data and built predictions for two things, the average distance a special teams player travels in one tracking frame, a tenth of a second, and their kick success rate in a game. The notebook’s comment called it distance per game, and my sklearn linear regression tutorial shows why it can’t be. My project write-up calls it a simple linear regression built as an artificial neural network. The code says otherwise. It was a small Keras network with three hidden layers of 4 ReLU neurons each, trained to predict a number.

A neural network with no hidden layers and no activation function really is linear regression, with one weight per input, one bias and a weighted sum. Mine had hidden layers and ReLU, which let it bend away from a straight line. So it was a neural network doing a regression task, not linear regression.

It was also fitted differently. The network nudges its weights a little on every pass, which is gradient descent, instead of using the closed-form formula from earlier.

I rebuilt that template with real data, and fixed its mistakes, in my Keras in Python tutorial.

Ranking real people from predicted values is where the warnings above stop being academic. R-squared tells you how much of the spread your line explains.

It doesn’t tell you whether a ranking is fair. And a prediction is only as good as the range the model was fitted on, so a player far outside that range gets a guess, not a prediction.

My grad projects are in this GitHub repo, with a short write-up of each one.

What should you remember about SciPy linear regression?

  • scipy.stats.linregress(x, y) gives you the slope, intercept, correlation, p-value and both standard errors in one call. Read them off the result object.
  • R-squared is rvalue squared, the share of variation your line explains. 1 - SSE/SST computes the same thing.
  • A 95% confidence interval is the slope plus or minus a t-value times stderr.
  • Predict inside your data’s range. Outside it, the line is guessing.
  • Plot the residuals, and check them against inputs you left out.
  • For more than one input, use np.linalg.lstsq, scipy.linalg.lstsq or scikit-learn’s LinearRegression.
  • Watch for nan results, and pass nan_policy="omit" when your data has gaps.

What’s the first thing you’d try to predict with a straight line?