Last updated

Linear Regression

Definition: Linear regression finds the straight line that best fits your data. Once you have the line, you can predict new values along it. It is the "hello world" of machine learning.

Example — fit a line and predict

np.polyfit(x, y, 1) finds the best line (degree 1). It returns the slope and intercept of y = slope*x + intercept:

import numpy as np
import matplotlib.pyplot as plt
x = np.array([1, 2, 3, 4, 5, 6])
y = np.array([5, 7, 9, 11, 13, 15])

slope, intercept = np.polyfit(x, y, 1)
print("slope:", round(slope, 2), "intercept:", round(intercept, 2))

prediction = slope * 7 + intercept
print("Predicted y when x = 7:", round(prediction, 2))

plt.scatter(x, y)
plt.plot(x, slope * x + intercept, color="red")
plt.title("Linear Regression")

What the line means

The red line is the model. The slope says how much y changes for each step in x; the intercept is y when x is 0. Prediction is just reading a point off the line.

💡 Try it: change a y value to break the perfect pattern, then re-run — watch the line shift to the new best fit.

Try it Yourself
Output

          
Ad · responsive