SwadhyAI Notes

All Python notes

Linear Regression 📉

Predicting Values

Linear Regression is a statistical method used to create a linear model. It tries to find the relationship between variables to draw a straight line through them.

✨ Creating a Model

We use SciPy to calculate the key components of the line: slope and intercept.

python
import matplotlib.pyplot as plt
from scipy import stats

x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,111,86,103,87,94,78,77,85,86]

slope, intercept, r, p, std_err = stats.linregress(x, y)

def myfunc(x):
  return slope * x + intercept

mymodel = list(map(myfunc, x))

plt.scatter(x, y)
plt.plot(x, mymodel)
plt.show()

📊 R-Squared (The Fit)

It is important to know how well the relationship between the values of the x-axis and the values of the y-axis is.

The r value ranges from -1 to 1.

  • 0: No relationship. Linear regression cannot be used.
  • 1 or -1: 100% related. Perfect fit.
python
print(r) # -0.76 (Good fit, negative correlation)

✨ Pro Tip: Prediction

Once you have a good model (high r-value), you can predict future values:

python
speed = myfunc(10) # Predict speed of a 10-year-old car
print(speed)