Skip to content
Justice Tech School

Least Squares Fit

lstsq fits the best line through noisy points. polyfit does the same for polynomials.

Example
x = np.array([0, 1, 2, 3]); y = np.array([1, 3, 5, 7])
slope, intercept = np.polyfit(x, y, 1)
print(round(slope, 2), round(intercept, 2))
print(np.polyval([slope, intercept], 4).round(1))

Result

2.0 1.0
9.0

Exercise

Fit a line.

np.(x, y, 1)

Quiz Test

What does polyval do?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.