# How to compute R-squared for a simple linear model (in Python, using SciPy)

## Task

Letâ€™s say we have fit a linear model to two columns of data, one for a single independent variable $x$ and the other for a single dependent variable $y$. How can we compute $R^2$ for that model, to measure its goodness of fit?

Related tasks:

## Solution

We assume you have already fit a linear model to the data, as in the code below, which is explained fully in a separate task, how to fit a linear model to two columns of data.

1
2
3
4

import scipy.stats as stats
xs = [ 393, 453, 553, 679, 729, 748, 817 ]
ys = [ 24, 25, 27, 36, 55, 68, 84 ]
model = stats.linregress( xs, ys )

The $R$ value is part of the model object that `stats.linregress`

returns.

1

model.rvalue

1

0.8949574425541466

You can compute $R^2$ just by squaring it.

1

model.rvalue ** 2

1

0.8009488239830586

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (ncarter@bentley.edu)