ML Linear Regression
Regression means predicting a number: a price, a temperature, a score. The simplest regression model draws the best straight line through the data points of a scatter plot and uses that line to predict new values. This is linear regression.
A straight line is described by two numbers:
y = slope * x + intercept- the slope says how much
ychanges whenxgrows by 1, - the intercept is the value of
ywhenxis 0.
"Best line" means the line that makes the squared vertical distances between the points and the line as small as possible (the least squares method).
Fitting a line with SciPy
scipy.stats.linregress is the quickest way to fit a line through two lists of numbers. We'll reuse the study-time data:
from scipy import stats
hours = [1, 2, 2.5, 3, 4, 4.5, 5, 6, 6.5, 7, 8, 9]
score = [52, 55, 61, 58, 67, 70, 68, 76, 79, 77, 85, 90]
result = stats.linregress(hours, score)
print(f"slope = {result.slope:.3f}")
print(f"intercept = {result.intercept:.3f}")
print(f"r = {result.rvalue:.3f}")slope = 4.737
intercept = 46.743
r = 0.987
Each extra hour of study adds roughly 4.7 points, and a student who doesn't study at all would be predicted to score about 47.
Drawing the line
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
hours = np.array([1, 2, 2.5, 3, 4, 4.5, 5, 6, 6.5, 7, 8, 9])
score = np.array([52, 55, 61, 58, 67, 70, 68, 76, 79, 77, 85, 90])
fit = stats.linregress(hours, score)
line = fit.slope * hours + fit.intercept
plt.scatter(hours, score, label="students")
plt.plot(hours, line, color="red", label="regression line")
plt.xlabel("Hours studied")
plt.ylabel("Exam score")
plt.legend()
plt.show()
print(f"Line drawn: score = {fit.slope:.2f} * hours + {fit.intercept:.2f}")Line drawn: score = 4.74 * hours + 46.74
Predicting new values
Once you know the slope and intercept, predicting is just arithmetic. A small function makes it reusable:
from scipy import stats
hours = [1, 2, 2.5, 3, 4, 4.5, 5, 6, 6.5, 7, 8, 9]
score = [52, 55, 61, 58, 67, 70, 68, 76, 79, 77, 85, 90]
fit = stats.linregress(hours, score)
def predict(h):
return fit.slope * h + fit.intercept
for h in [3.5, 5.5, 10]:
print(f"{h:4} hours -> predicted score {predict(h):.1f}") 3.5 hours -> predicted score 63.3
5.5 hours -> predicted score 72.8
10 hours -> predicted score 94.1
Be careful with extrapolation: predicting far outside the range you trained on (say 30 hours of study) would give a score above 100, which is impossible. A line has no idea where the real world stops.
How good is the fit? r and R²
The correlation r from linregress tells how well the line fits. Squaring it gives R² (the coefficient of determination): the share of the variation in y that the line explains. R² = 1 is a perfect fit; R² = 0 means the line explains nothing.
import numpy as np
from scipy import stats
rng = np.random.default_rng(4)
x = np.arange(20)
good = 3 * x + 5 + rng.normal(0, 2, size=20) # a clear line plus noise
bad = rng.normal(30, 10, size=20) # no relationship at all
for name, y in [("good", good), ("bad", bad)]:
fit = stats.linregress(x, y)
print(f"{name}: slope={fit.slope:6.2f} R^2={fit.rvalue ** 2:.3f}")good: slope= 3.00 R^2=0.983
bad: slope= 0.13 R^2=0.006
For the "bad" data the R² is close to zero: a line is the wrong tool there, and its predictions would be almost worthless.
The scikit-learn way
linregress handles one input variable. scikit-learn's LinearRegression works with any number of inputs and follows the same fit/predict pattern as every other model in the library. The input X must be two-dimensional (rows × features), even when there is just one feature:
import numpy as np
from sklearn.linear_model import LinearRegression
hours = np.array([1, 2, 2.5, 3, 4, 4.5, 5, 6, 6.5, 7, 8, 9])
score = np.array([52, 55, 61, 58, 67, 70, 68, 76, 79, 77, 85, 90])
X = hours.reshape(-1, 1) # 12 rows, 1 column
model = LinearRegression().fit(X, score)
print("slope: ", model.coef_.round(3))
print("intercept:", round(model.intercept_, 3))
print("R^2: ", round(model.score(X, score), 3))
print("predict 5.5 h:", model.predict([[5.5]]).round(1))slope: [4.737]
intercept: 46.743
R^2: 0.975
predict 5.5 h: [72.8]
The numbers match linregress. model.score() returns R² directly for regression models.
Go further: In the Machine Learning track, Linear Regression and the Normal Equation derives this fit with matrices and writes it from scratch in NumPy, and Linear Regression by Gradient Descent reaches the same line by iteration.
Test yourself
In y = 2.5 * x + 10, what is the predicted y for x = 4?
- 14
- 20
- 16.5
- 25
What does an R² value of 0.95 tell you?
- 95 % of predictions are exactly right
- The line explains about 95 % of the variation in y
- The slope is 0.95
- 5 % of the data are outliers
Why do we call hours.reshape(-1, 1) before LinearRegression().fit?
- To sort the data
- Because scikit-learn expects a 2-D array of rows × features
- To remove outliers
- To convert to integers