众所周知,线性回归(Linear Regression)是最常见的机器学习算法之一,简单但超级实用。线性回归旨在用线性方程来拟合数据分布,在数据量小计算速度要求高的地方是神经网络的最佳替代品。
LR的一般表现形式为:
y
=
w
⃗
T
x
⃗
+
b
y = vec{w}^Tvec{x} + b
y=w
Tx
+b
通常,LR优化方式可以通过构建均方误差损失函数,得到一个凸函数,计算导数为0的位置来确定
w
⃗
vec{w}
w
和
b
b
b,如周志华老师西瓜书里描述的那样。
在工程上,我们可以把LR当做一个简易的神经网络来对待,用梯度下降算法就可以优化。本文提供一个梯度下降算法优化LR的实验例子,有助于加深大家对LR以及梯度下降的理解。
假设有一个绝对正确的函数
y
=
f
(
x
⃗
;
w
⃗
,
b
)
=
w
⃗
T
x
⃗
+
b
y=f(vec{x};vec{w},b)=vec{w}^Tvec{x}+b
y=f(x
;w
,b)=w
Tx
+b,每输入一个
x
⃗
vec{x}
x
都可以得到一个准确的
y
y
y。那么,咱们只需要得到最真实的
w
⃗
vec{w}
w
和
b
b
b即可。假设最真实的
w
⃗
=
[
3
,
1
,
4
,
1
,
5
,
9
,
2
,
6
]
vec{w}=[3,1,4,1,5,9,2,6]
w
=[3,1,4,1,5,9,2,6],最真实的
b
=
3.7
b=3.7
b=3.7。
初始化
w
⃗
vec{w}
w
和
b
b
b为随机数,通过大量样本的梯度反传来修正
w
⃗
vec{w}
w
和
b
b
b到真实的值。
实验环境:
python3.7
numpy >=1.15.1
先申明,以下代码为本人原创,借用最好在评论中告知我。
########################################################
# @author: MuZhan
# @contact: levio.pku@gmail.com
# experiment: using GD to optimize Linear Regression
# To fit `y=w*x+b`, where x and w are multi-dim vectors.
########################################################
import numpy as np
# initial setting
np.random.seed(10)
epochs = 30
lr = .1 # learning rate
w_ = np.array([3, 1, 4, 1, 5, 9, 2, 6]) # the ground truth w
b_ = 3.7 # the ground truth b
SAMPLE_NUM = 100
x_dim = len(w_)
# preparing random (x, y) pairs
print('preparing data...')
x_list = []
y_list = []
for i in range(SAMPLE_NUM):
x = np.random.rand(x_dim)
y = w_.dot(x) + b_
x_list.append(x)
y_list.append(y)
# init w
np.random.seed(10)
w = np.random.rand(x_dim)
# init b
b = 1
# training
print('training...')
for e in range(epochs):
print('epoch: ', e, end='t')
sum_loss = 0
for i in range(len(x_list)):
x = x_list[i]
y_ = y_list[i]
y = w.dot(x) + b
loss = (y - y_) ** 2
sum_loss += loss
# use Gradient Descent to update parameters
w = w - 2 * lr * (y - y_) * x
b = b - 2 * lr * (y - y_)
print('loss: ', sum_loss)
print('Ground Truth w: ', w_, end='t')
print('learned w: ', w)
print('Ground Trueh b: ', b_, end='t')
print('learned b: ', b)



