一、线性回归的基本要素
1、模型定义
建立基于输入来计算输出x1和x2来计算输出 y 的表达式,也就是模型(model)。顾名思义,线性回归假设输出与各个输入之间是线性关系:
2、损失函数
通常选择使用平方差作为损失函数:
3、优化算法
当模型和损失函数形式较为简单时,上面的误差最小化问题的解可以直接用公式表达出来。这类解叫作解析解(analytical solution)。本次使用的线性回归和平方误差刚好属于这个范畴。然而,大多数深度学习模型并没有解析解,只能通过优化算法有限次迭代模型参数来尽可能降低损失函数的值。这类解叫作数值解(numerical solution)。
在求数值解的优化算法中,小批量随机梯度下降(mini-batch stochastic gradient descent)在深度学习中被广泛使用。它的算法很简单:先选取一组模型参数的初始值,如随机选取;接下来对参数进行多次迭代,使每次迭代都可能降低损失函数的值。在每次迭代中,先随机均匀采样一个由固定数目训练数据样本所组成的小批量(mini-batch)BB,然后求小批量中数据样本的平均损失有关模型参数的导数(梯度),最后用此结果与预先设定的一个正数的乘积作为模型参数在本次迭代的减小量。
代码实现(注解)
import tensorflow as tf
print(tf.__version__) # 采用tensorflow2.1.0版本
from matplotlib import pyplot as plt
import random
num_inputs = 2 # 共有两个特征
num_examples = 1000 # 共有1000条数据
true_w = [2, -3.4] # 线性回归模型真是权重, w1=2 w2=-3.4
true_b = 4.2 # 线性回归的偏差
features = tf.random.normal((num_examples, num_inputs), stddev=1) # 生成数据
labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b # 生成标签
labels += tf.random.normal(labels.shape, stddev=0.01) # 对标签增加服从均值为0、标准差为0.01的正态分布的噪音
# 噪声代表了数据集中无意义的干扰
def set_figsize(figsize=(3.5, 2.5)): # 展示数据图像
plt.rcParams['figure.figsize'] = figsize
set_figsize()
plt.scatter(features[:, 1], labels, 1)
plt.show()
def data_iter(batch_size, features, labels): # 读取数据
num_examples = len(features)
indices = list(range(num_examples))
random.shuffle(indices) # 打乱数据
for i in range(0, num_examples, batch_size):
j = indices[i: min(i + batch_size, num_examples)]
yield tf.gather(features, axis=0, indices=j), tf.gather(labels, axis=0, indices=j)
# 每次返回 batch_size (批量大小)个随机样本的特征和标签
batch_size = 10
# 读取第一个小批量数据样本并打印。每个批量的特征形状为(10, 2),分别对应批量大小和输入个数;标签形状为批量大小
for X, y in data_iter(batch_size, features, labels):
print(X, y)
break
# 将权重初始化成均值为0、标准差为0.01的正态随机数,偏差则初始化成0
w = tf.Variable(tf.random.normal((num_inputs, 1), stddev=0.01))
b = tf.Variable(tf.zeros((1,)))
def linreg(X, w, b): # 线性回归的矢量计算表达式
return tf.matmul(X, w) + b # tf.matmul 做乘法
def squared_loss(y_hat, y): # 平方损失来定义线性回归的损失函数
return (y_hat - tf.reshape(y, y_hat.shape)) ** 2 / 2
def sgd(params, lr, batch_size, grads): # 小批量随机梯度下降算法
"""Mini-batch stochastic gradient descent."""
for i, param in enumerate(params):
param.assign_sub(lr * grads[i] / batch_size)
# 自动求梯度模块计算得来的梯度是一个批量样本的梯度和。我们将它除以批量大小来得到平均值
# 训练模型
lr = 0.03 # 超参数
num_epochs = 3
net = linreg
loss = squared_loss
for epoch in range(num_epochs):
for X, y in data_iter(batch_size, features, labels):
with tf.GradientTape() as t:
t.watch([w, b])
l = loss(net(X, w, b), y)
grads = t.gradient(l, [w, b]) # 计算小批量随机梯度
sgd([w, b], lr, batch_size, grads)
train_l = loss(net(features, w, b), labels)
print('epoch %d, loss %f' % (epoch + 1, tf.reduce_mean(train_l)))
数据图像:
输出:
tf.Tensor(
[[-0.34988216 1.7806039 ]
[-1.8917446 -0.13573697]
[-0.17453413 -0.34349066]
[ 0.5370717 1.1191437 ]
[-0.01104847 0.38538134]
[ 0.33266178 0.6521724 ]
[-0.33420295 -1.5981245 ]
[-0.70956767 -1.2573007 ]
[ 0.8754746 -1.1428775 ]
[-0.10740936 0.494466 ]], shape=(10, 2), dtype=float32) tf.Tensor(
[-2.5482752 0.8646454 5.0283184 1.4668634 2.8685973 2.6552503
8.958068 7.057969 9.846524 2.3113618], shape=(10,), dtype=float32)
epoch 1, loss 0.028413
epoch 2, loss 0.000093
epoch 3, loss 0.000049
代码实现(无注解)
import tensorflow as tf
print(tf.__version__)
from matplotlib import pyplot as plt
import random
num_inputs = 2
num_examples = 1000
true_w = [2, -3.4]
true_b = 4.2
features = tf.random.normal((num_examples, num_inputs), stddev=1)
labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b
labels += tf.random.normal(labels.shape, stddev=0.01)
def set_figsize(figsize=(3.5, 2.5)):
plt.rcParams['figure.figsize'] = figsize
set_figsize()
plt.scatter(features[:, 1], labels, 1)
plt.show()
def data_iter(batch_size, features, labels):
num_examples = len(features)
indices = list(range(num_examples))
random.shuffle(indices)
for i in range(0, num_examples, batch_size):
j = indices[i: min(i + batch_size, num_examples)]
yield tf.gather(features, axis=0, indices=j), tf.gather(labels, axis=0, indices=j)
batch_size = 10
for X, y in data_iter(batch_size, features, labels):
print(X, y)
break
w = tf.Variable(tf.random.normal((num_inputs, 1), stddev=0.01))
b = tf.Variable(tf.zeros((1,)))
def linreg(X, w, b):
return tf.matmul(X, w) + b
def squared_loss(y_hat, y):
return (y_hat - tf.reshape(y, y_hat.shape)) ** 2 / 2
def sgd(params, lr, batch_size, grads):
"""Mini-batch stochastic gradient descent."""
for i, param in enumerate(params):
param.assign_sub(lr * grads[i] / batch_size)
lr = 0.03
num_epochs = 3
net = linreg
loss = squared_loss
for epoch in range(num_epochs):
for X, y in data_iter(batch_size, features, labels):
with tf.GradientTape() as t:
t.watch([w, b])
l = loss(net(X, w, b), y)
grads = t.gradient(l, [w, b])
sgd([w, b], lr, batch_size, grads)
train_l = loss(net(features, w, b), labels)
print('epoch %d, loss %f' % (epoch + 1, tf.reduce_mean(train_l)))