Manually implement gradient descent to fit a straight line
Manually implement gradient descent to fit a straight line
Without sklearn, use gradient descent from scratch to fit (y = wx + b), and observe how the loss decreases step by step.
After learning this case study, you will understand: you don't need a closed-form solution; as long as you know how to calculate the gradient, the parameters will automatically converge to the optimal value.
Real-life introduction
**Shooting practice—adjusting the angle a little each time
You are shooting from outside the three-point line. The first shot is too far left—next time, adjust slightly to the right. The second shot is too far right—adjust slightly to the left again. After each shot, you look at the deviation and adjust your posture in the direction that reduces the deviation.
Machine learning training is exactly the same: after calculating a prediction value each time, we look at the difference between it and the true value (loss), and then adjust the parameters in the direction of reducing the difference (gradient descent). Repeating this hundreds of times, the posture is set.
Intuitive understanding
Our goal is to find a straight line (y = wx + b) that passes as close as possible to all data points. (w) is the slope, (b) is the intercept, and loss = the average of the squares of the vertical distances from all points to the line (MSE).
If we start from (w=0, b=0), the line is flat, and the loss is large. Gradient descent will tell us: "w should increase, and b should also increase," and then we follow that. After repeating 100 times, the line will pass through the data points.
Mathematical definition
[ L(w, b) = \frac{1}{n}\sum_{i=1}^{n}(wx_i + b - y_i)^2 ] [ \frac{\partial L}{\partial w} = \frac{2}{n}\sum_{i=1}^{n}(wx_i + b - y_i) \cdot x_i, \quad \frac{\partial L}{\partial b} = \frac{2}{n}\sum_{i=1}^{n}(wx_i + b - y_i) ] [ w \leftarrow w - \eta \cdot \frac{\partial L}{\partial w}, \quad b \leftarrow b - \eta \cdot \frac{\partial L}{\partial b} ]
Python hands-on practice
Example
import
numpy
as
np
np.
random
.
seed
(
0
)
Generate noisy linear data: true y = 2x + 1
n
=
60
x
=
np.
random
.
uniform
(
3
,
3
,
n
)
y
=
2
- x +
1
- np.
random
.
randn
(
60
)
0.8
Manual gradient function (partial derivatives with respect to w and b respectively)
def
compute_gradients
(
w
,
b
,
x
,
y
)
:
y_pred
=
w * x + b
error
=
y_pred - y
Predicted value - True value
dw
=
np.
mean
(
2
- error * x
)
dL/dw
db
=
np.
mean
(
2
- error
)
dL/db
return
dw
,
db
Gradient descent main loop
w
,
b
=
0.0
,
0.0
Initial parameters are intentionally set to 0
lr
=
0.05
epochs
=
100
(
"RUNOOB gradient descent process (true values w=2, b=1):"
)
for
epoch
in
range
(
epochs
)
:
y_pred
=
w * x + b
loss
=
np.
mean
(
(
y_pred - y
)
**
2
)
dw
,
db
=
compute_gradients
(
w
,
b
,
x
,
y
)
w -
=
lr * dw
b -
=
lr * db
if
epoch %
20
==
0
:
(
f
" epoch {epoch:3d} loss={loss:.4f} w={w:.3f} b={b:.3f}"
)
(
f
"\nRUNOOB Final: w={w:.3f}, b={b:.3f} (True w=2, b=1)"
)
(
f
"Fit line: y = {w:.2f}x + {b:.2f}"
)
Original prompt (Chinese, left untranslated)
RUNOOB 梯度下降过程 (真实值 w=2, b=1):
epoch 0 loss=13.4515 w=0.790 b=0.057
epoch 20 loss=0.9165 w=1.868 b=0.785
epoch 40 loss=0.7316 w=1.949 b=0.918
epoch 60 loss=0.7083 w=1.971 b=0.956
epoch 80 loss=0.7055 w=1.977 b=0.967
epoch 100 loss=0.7052 w=1.979 b=0.970
RUNOOB 最终: w=1.979, b=0.970 (真实 w=2, b=1)
拟合直线: y = 1.98x + 0.97
Application scenarios in AI
The code skeleton of this case is the template for all deep learning training: forward pass to predict values -> calculate loss -> backpropagation to find gradients -> update parameters -> repeat. optimizer.step() and loss.backward() in PyTorch automate this process.