人工智能实践:Tensorflow2.0笔记 北京大学MOOC(2-2)
说明
本文内容整理自中国大学MOOC “北京大学-人工智能实践:Tensorflow笔记” 课程,部分内容可能在原笔记内容上进行了修改,转载请注明出处。
授课老师:曹健
中国大学MOOC 人工智能实践:Tensorflow笔记课程链接
本讲目标:学会神经网络优化过程,使用正则化减少过拟合,使用优化器更新网络参数
本节内容:本节将讨论神经网络优化过程中 “过拟合与欠拟合” 的概念,并简述通过正则化缓解过拟合的方法。
二、缓解“欠拟合”与“过拟合”问题
1. 欠拟合与过拟合
机器学习 过程中模型利用训练集中进行学习,在测试集中对样本进行预测。
模型对训练集数据的误差称为 经验误差,对测试集数据的误差称为 泛化误差。
模型对训练集以外样本的预测能力称为模型的泛化能力。
欠拟合(underfitting) 和 过拟合(overfitting) 是模型泛化能力不高的两种常见原因,都是模型学习能力与数据复杂度不匹配的情况。
欠拟合常常在模型学习能力比较弱,而数据复杂度较高的场景出现,由于模型学习能力不足,不能有效学习数据集的一般规律,导致模型泛化能力较弱。
过拟合常常在模型学习能力过强的场景中出现,由于模型学习能力太强,把训练集中单个样本的特点都能学习到,并将其作为一般规律,同样也导致模型泛化能力较弱。
以下图组形象地表现了欠拟合、正确拟合、过拟合三种情况:
图1 机器学习中的欠拟合、正确拟合、过拟合情况示意图
欠拟合在训练集和测试集上能力都较差,而过拟合则在训练集能较好学习数据的特征,在测试集上预测能力较差。
2. 缓解“欠拟合与过拟合”的思路
欠拟合的解决方法:
· 增加输入特征项:给网络更多维度的输入特征;
· 增加网络参数:扩展网络规模,增加网络深度,提升模型表达力;
· 减少正则化参数
过拟合的解决方法:
· 数据清洗:减少数据集中的噪声,使数据集更纯净;
· 增大训练集:让模型见到更多的数据;
· 采用正则化
· 增大正则化参数
3. 使用正则化缓解过拟合问题
3.1 相关概念
正则化是一种通用、有效地缓解过拟合问题的方法。
正则化在损失函数中引入模型复杂度指标,利用给W加权值 ,弱化了训练数据的噪声(一般不正则化b)。
采用正则化方法后损失函数的形式为: l o s s = l o s s ( y与y_ ) + REGULARIZER × l o s s ( w ) loss=loss(\text{y与y\_})+\operatorname{REGULARIZER}\times loss(w) loss=loss(y与y_)+REGULARIZER×loss(w)式中:
l o s s ( y与y_ ) ~~~loss(\text{y与y\_}) loss(y与y_) 指模型中所有参数的损失函数,如:交叉熵、均方误差等;
REGULARIZER ~~~\operatorname{REGULARIZER} REGULARIZER 用超参数REGULARIZER给出参数 w w w在总 l o s s loss loss中的比例,即正则化的权重;
l o s s ( w ) ~~~loss(w) loss(w) 指需要正则化的参数。
3.2 常用的正则化方法 及 代码实现
3.2.1 L1正则化
定义
:
l
o
s
s
L
1
(
w
)
=
∑
i
∣
w
i
∣
loss_{L1}(w)=\sum_i|w_i|
lossL1(w)=i∑∣wi∣L1正则化的特点
:
L1正则化大概率会使很多参数变为零,因此该方法可通过稀疏参数,即减少参数的数量,降低复杂度。
代码实现
:
由于在tensorflow新版本中不存在已经实现好的L1正则化函数,故自行实现如下:
loss_regularization = tf.reduce_sum(tf.abs(w1))
举例如下:
# L1正则化
#输入:
import tensorflow as tf
tf.random.set_seed(100) #seed: 随机数种子
REGULARIZER = 0.03 #正则化权重
loss_regularization_l1 = []
w1 = tf.Variable(tf.random.normal([2, 1]), dtype=tf.float32)
print("w1=\n",w1)
loss_regularization_l1.append(tf.reduce_sum(tf.abs(w1)))
# 求和
loss_regularization_l1 = tf.reduce_sum(loss_regularization_l1)
print("loss_regularization_l1=\n",loss_regularization_l1)
输出:
w1=
<tf.Variable 'Variable:0' shape=(2, 1) dtype=float32, numpy= array([[ 0.16052227],[-1.6597689 ]], dtype=float32)>
loss_regularization_l1=
tf.Tensor(1.8202912, shape=(), dtype=float32)
3.2.2 L2正则化
定义
:
l
o
s
s
L
2
(
w
)
=
∑
i
∣
w
i
2
∣
loss_{L2}(w)=\sum_i|w^2_i|
lossL2(w)=i∑∣wi2∣L2正则化的特点
:
L2正则化会使参数很接近零但不为零,因此该方法可通过 减小参数值的大小降低复杂度。
代码实现
:
在tensorflow中存在已经实现好的L2正则化函数:tf.nn.l2_loss
tf.nn.l2_loss( t, name=None )
功能: 计算不含 sqrt 的张量的 L2 范数的一半,简单的可以理解成张量中的每一个元素进行平方,然后求和,最后乘以1/2。
参数:
·t
: 张量,元素类型是half, bfloat16, float32, float64之一.
·name
: 操作的别名(可选).
返回:与 t 相同类型的张量.
可自行实现为:tf.nn.l2_loss(w) = sum(w ** 2) / 2
举例如下:
#输入:
import tensorflow as tf
tf.random.set_seed(100) #seed: 随机数种子
REGULARIZER = 0.03 #正则化权重
loss_regularization_l2 = []
w1 = tf.Variable(tf.random.normal([2, 1]), dtype=tf.float32)
print("w1=\n",w1)
print("sum(w1 ** 2)/2=\n",sum(w1 ** 2) / 2 )
print("tf.nn.l2_loss(w1)=\n",tf.nn.l2_loss(w1) )
# tf.nn.l2_loss(w)=sum(w ** 2) / 2
loss_regularization_l2.append(tf.nn.l2_loss(w1))
# 求和
loss_regularization_l2 = tf.reduce_sum(loss_regularization_l2)
print("loss_regularization_l2=\n",loss_regularization_l2)
输出:
w1=
<tf.Variable 'Variable:0' shape=(2, 1) dtype=float32, numpy= array([[ 0.16052227],[-1.6597689 ]], dtype=float32)>
sum(w1 ** 2)/2=
tf.Tensor([1.3903002], shape=(1,), dtype=float32)
tf.nn.l2_loss(w1)=
tf.Tensor(1.3903002, shape=(), dtype=float32)
loss_regularization_l2=
tf.Tensor(1.3903002, shape=(), dtype=float32)
3.3 使用不同正则化函数的实例对比
为进一步理解正则化函数的作用,体现不同正则化函数对神经网络预测结果的影响,以下引入一个例子进行对比。
背景:已知一系列点的坐标x,y和其对应的标签0或1;
说明:部分坐标数据及点的分布情况如下图所示(标签1记为红色,标签2记为蓝色):
图2 部分坐标数据及点的分布情况 完整数据已上传到 dot.csv。
目标:绘制图中红色和蓝色点的分界线。
思路:
1.先用神经网络拟合出输入特征x、y与标签的函数关系;
2.生成网格覆盖这些点,将网格交点(也即是横纵坐标)作为输入送入训练好的神经网络;
3.神经网络为每个坐标输出一个预测值;
4.将神经网络输出为0.5的线标出颜色,即为0和1,也即是红点和蓝点的区分线。
3.3.1 不使用正则化函数时的代码实现
首先,不考虑正则化函数,实现以上思路,代码如下(使用两层神经网络):
### 读入红蓝点,画出分割线,不包含正则化
# 导入所需模块
import tensorflow as tf
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
# 读入数据/标签 生成x_train y_train
df = pd.read_csv('dot.csv')
x_data = np.array(df[['x', 'y']])
y_data = np.array(df['p'])
x_train = x_data
y_train = y_data.reshape(-1, 1)
Y_c = [['red' if y else 'blue'] for y in y_train]
# 转换x的数据类型,否则后面矩阵相乘时会因数据类型问题报错
x_train = tf.cast(x_train, tf.float32)
y_train = tf.cast(y_train, tf.float32)
# from_tensor_slices函数切分传入的张量的第一个维度,生成相应的数据集,使输入特征和标签值一一对应
train_db = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(32)
# 生成神经网络的参数,输入层为2个神经元,隐藏层为11个神经元,1层隐藏层,输出层为1个神经元
# 用tf.Variable()保证参数可训练
w1 = tf.Variable(tf.random.normal([2, 11]), dtype=tf.float32)
b1 = tf.Variable(tf.constant(0.01, shape=[11]))
w2 = tf.Variable(tf.random.normal([11, 1]), dtype=tf.float32)
b2 = tf.Variable(tf.constant(0.01, shape=[1]))
lr = 0.005 # 学习率
epoch = 5000 # 循环轮数
# 训练部分
for epoch in range(epoch):
for step, (x_train, y_train) in enumerate(train_db):
with tf.GradientTape() as tape: # 记录梯度信息
h1 = tf.matmul(x_train, w1) + b1 # 记录神经网络乘加运算
h1 = tf.nn.relu(h1)
y = tf.matmul(h1, w2) + b2
# 采用均方误差损失函数mse = mean(sum(y-out)^2)
loss = tf.reduce_mean(tf.square(y_train - y))
# 计算loss对各个参数的梯度
variables = [w1, b1, w2, b2]
grads = tape.gradient(loss, variables)
# 实现梯度更新
# w1 = w1 - lr * w1_grad
w1.assign_sub(lr * grads[0])
b1.assign_sub(lr * grads[1])
w2.assign_sub(lr * grads[2])
b2.assign_sub(lr * grads[3])
# 每200个epoch,打印loss信息
if epoch % 20 == 0:
print('epoch:', epoch, 'loss:', float(loss))
# 预测部分
print("*******predict*******")
# xx在-3到3之间以步长为0.01,yy在-3到3之间以步长0.01,生成间隔数值点
xx, yy = np.mgrid[-3:3:.1, -3:3:.1]
# 将xx, yy拉直,并合并配对为二维张量,生成二维坐标点
grid = np.c_[xx.ravel(), yy.ravel()]
grid = tf.cast(grid, tf.float32)
# 将网格坐标点喂入神经网络,进行预测,probs为输出
probs = []
for x_predict in grid:
# 使用训练好的参数进行预测
h1 = tf.matmul([x_predict], w1) + b1
h1 = tf.nn.relu(h1)
y = tf.matmul(h1, w2) + b2 # y为预测结果
probs.append(y)
# 取第0列给x1,取第1列给x2
x1 = x_data[:, 0]
x2 = x_data[:, 1]
# probs的shape调整成xx的样子
probs = np.array(probs).reshape(xx.shape)
plt.scatter(x1, x2, color=np.squeeze(Y_c))
# 把坐标xx yy和对应的值probs放入contour函数,给probs值为0.5的所有点上色 plt.show()后 显示的是红蓝点的分界线
plt.contour(xx, yy, probs, levels=[.5])
plt.show()
程序迭代5000轮后绘制的图像如图3 所示:
图3 不使用正则化函数时神经网络预测的红蓝点分界线
分析:从绘制的结果来看,黑色曲线大致分隔了红蓝色点,完成了程序要求。但曲线轮廓不够平滑,存在过拟合现象。
3.3.2 使用L1正则化函数时的代码实现
在以上代码的基础上,加入L1正则化函数,全部代码如下:
### 读入红蓝点,画出分割线,包含L1正则化
# 导入所需模块
import tensorflow as tf
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
# 读入数据/标签 生成x_train y_train
df = pd.read_csv('dot.csv')
x_data = np.array(df[['x', 'y']])
y_data = np.array(df['p'])
x_train = x_data
y_train = y_data.reshape(-1, 1)
Y_c = [['red' if y else 'blue'] for y in y_train]
# 转换x的数据类型,否则后面矩阵相乘时会因数据类型问题报错
x_train = tf.cast(x_train, tf.float32)
y_train = tf.cast(y_train, tf.float32)
# from_tensor_slices函数切分传入的张量的第一个维度,生成相应的数据集,使输入特征和标签值一一对应
train_db = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(32)
# 生成神经网络的参数,输入层为2个神经元,隐藏层为11个神经元,1层隐藏层,输出层为1个神经元
# 用tf.Variable()保证参数可训练
w1 = tf.Variable(tf.random.normal([2, 11]), dtype=tf.float32)
b1 = tf.Variable(tf.constant(0.01, shape=[11]))
w2 = tf.Variable(tf.random.normal([11, 1]), dtype=tf.float32)
b2 = tf.Variable(tf.constant(0.01, shape=[1]))
lr = 0.005 # 学习率
epoch = 5000 # 循环轮数
REGULARIZER = 0.03 # 正则化权重
# 训练部分
for epoch in range(epoch):
for step, (x_train, y_train) in enumerate(train_db):
with tf.GradientTape() as tape: # 记录梯度信息
h1 = tf.matmul(x_train, w1) + b1 # 记录神经网络乘加运算
h1 = tf.nn.relu(h1)
y = tf.matmul(h1, w2) + b2
# 采用均方误差损失函数mse = mean(sum(y-out)^2)
loss_mse = tf.reduce_mean(tf.square(y_train - y))
# 添加l1正则化
loss_regularization_l1 = []
loss_regularization_l1.append(tf.reduce_sum(tf.abs(w1)))
loss_regularization_l1.append(tf.reduce_sum(tf.abs(w2)))
# 求和
loss_regularization_l1 = tf.reduce_sum(loss_regularization_l1)
loss = loss_mse + REGULARIZER * loss_regularization_l1
# 计算loss对各个参数的梯度
variables = [w1, b1, w2, b2]
grads = tape.gradient(loss, variables)
# 实现梯度更新
# w1 = w1 - lr * w1_grad
w1.assign_sub(lr * grads[0])
b1.assign_sub(lr * grads[1])
w2.assign_sub(lr * grads[2])
b2.assign_sub(lr * grads[3])
# 每200个epoch,打印loss信息
if epoch % 20 == 0:
print('epoch:', epoch, 'loss:', float(loss))
# 预测部分
print("*******predict*******")
# xx在-3到3之间以步长为0.01,yy在-3到3之间以步长0.01,生成间隔数值点
xx, yy = np.mgrid[-3:3:.1, -3:3:.1]
# 将xx, yy拉直,并合并配对为二维张量,生成二维坐标点
grid = np.c_[xx.ravel(), yy.ravel()]
grid = tf.cast(grid, tf.float32)
# 将网格坐标点喂入神经网络,进行预测,probs为输出
probs = []
for x_predict in grid:
# 使用训练好的参数进行预测
h1 = tf.matmul([x_predict], w1) + b1
h1 = tf.nn.relu(h1)
y = tf.matmul(h1, w2) + b2 # y为预测结果
probs.append(y)
# 取第0列给x1,取第1列给x2
x1 = x_data[:, 0]
x2 = x_data[:, 1]
# probs的shape调整成xx的样子
probs = np.array(probs).reshape(xx.shape)
plt.scatter(x1, x2, color=np.squeeze(Y_c))
# 把坐标xx yy和对应的值probs放入contour函数,给probs值为0.5的所有点上色 plt.show()后 显示的是红蓝点的分界线
plt.contour(xx, yy, probs, levels=[.5])
plt.show()
程序迭代5000轮后绘制的图像如图4 所示:
图4 使用L1正则化函数时神经网络预测的红蓝点分界线
分析:使用L1正则化函数后,分隔红蓝色点的黑色曲线比未使用正则化函数时轮廓更平滑,有效缓解了过拟合现象。
3.3.3 使用L2正则化函数时的代码实现
在以上代码的基础上,加入L2正则化函数,全部代码如下:
### 读入红蓝点,画出分割线,包含L2正则化
# 导入所需模块
import tensorflow as tf
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
# 读入数据/标签 生成x_train y_train
df = pd.read_csv('dot.csv')
x_data = np.array(df[['x', 'y']])
y_data = np.array(df['p'])
x_train = x_data
y_train = y_data.reshape(-1, 1)
Y_c = [['red' if y else 'blue'] for y in y_train]
# 转换x的数据类型,否则后面矩阵相乘时会因数据类型问题报错
x_train = tf.cast(x_train, tf.float32)
y_train = tf.cast(y_train, tf.float32)
# from_tensor_slices函数切分传入的张量的第一个维度,生成相应的数据集,使输入特征和标签值一一对应
train_db = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(32)
# 生成神经网络的参数,输入层为2个神经元,隐藏层为11个神经元,1层隐藏层,输出层为1个神经元
# 用tf.Variable()保证参数可训练
w1 = tf.Variable(tf.random.normal([2, 11]), dtype=tf.float32)
b1 = tf.Variable(tf.constant(0.01, shape=[11]))
w2 = tf.Variable(tf.random.normal([11, 1]), dtype=tf.float32)
b2 = tf.Variable(tf.constant(0.01, shape=[1]))
lr = 0.005 # 学习率
epoch = 5000 # 循环轮数
REGULARIZER = 0.03 # 正则化权重
# 训练部分
for epoch in range(epoch):
for step, (x_train, y_train) in enumerate(train_db):
with tf.GradientTape() as tape: # 记录梯度信息
h1 = tf.matmul(x_train, w1) + b1 # 记录神经网络乘加运算
h1 = tf.nn.relu(h1)
y = tf.matmul(h1, w2) + b2
# 采用均方误差损失函数mse = mean(sum(y-out)^2)
loss_mse = tf.reduce_mean(tf.square(y_train - y))
# 添加l2正则化
loss_regularization_l2 = []
loss_regularization_l2.append(tf.nn.l2_loss(w1))
loss_regularization_l2.append(tf.nn.l2_loss(w2))
# 求和
loss_regularization_l2 = tf.reduce_sum(loss_regularization_l2)
loss = loss_mse + REGULARIZER * loss_regularization_l2
# 计算loss对各个参数的梯度
variables = [w1, b1, w2, b2]
grads = tape.gradient(loss, variables)
# 实现梯度更新
# w1 = w1 - lr * w1_grad
w1.assign_sub(lr * grads[0])
b1.assign_sub(lr * grads[1])
w2.assign_sub(lr * grads[2])
b2.assign_sub(lr * grads[3])
# 每200个epoch,打印loss信息
if epoch % 20 == 0:
print('epoch:', epoch, 'loss:', float(loss))
# 预测部分
print("*******predict*******")
# xx在-3到3之间以步长为0.01,yy在-3到3之间以步长0.01,生成间隔数值点
xx, yy = np.mgrid[-3:3:.1, -3:3:.1]
# 将xx, yy拉直,并合并配对为二维张量,生成二维坐标点
grid = np.c_[xx.ravel(), yy.ravel()]
grid = tf.cast(grid, tf.float32)
# 将网格坐标点喂入神经网络,进行预测,probs为输出
probs = []
for x_predict in grid:
# 使用训练好的参数进行预测
h1 = tf.matmul([x_predict], w1) + b1
h1 = tf.nn.relu(h1)
y = tf.matmul(h1, w2) + b2 # y为预测结果
probs.append(y)
# 取第0列给x1,取第1列给x2
x1 = x_data[:, 0]
x2 = x_data[:, 1]
# probs的shape调整成xx的样子
probs = np.array(probs).reshape(xx.shape)
plt.scatter(x1, x2, color=np.squeeze(Y_c))
# 把坐标xx yy和对应的值probs放入contour函数,给probs值为0.5的所有点上色 plt.show()后 显示的是红蓝点的分界线
plt.contour(xx, yy, probs, levels=[.5])
plt.show()
程序迭代5000轮后绘制的图像如图5所示:
图5 使用L2正则化函数时神经网络预测的红蓝点分界线
分析:使用L2正则化函数后,分隔红蓝色点的黑色曲线同样比未使用正则化函数时轮廓更平滑,有效缓解了过拟合现象。
传送门
上一节讨论了神经网络复杂度、学习率策略、激活函数、损失函数等神经网络优化过程中需要的部分概念。
人工智能实践:Tensorflow2.0笔记 北京大学MOOC(2-1)
下一讲将介绍神经网络参数优化器的有关概念,并介绍五种常用的神经网络参数优化器。
人工智能实践:Tensorflow2.0笔记 北京大学MOOC(2-3)<未完工待续。。。>