1、正则化与偏差-方差分解
1.1 Regularization
Regularization:减小方差的策略;
误差可分解为偏差,方差与噪声之和,即误差=偏差+方差+噪声之和;
偏差度量了学习算法的期望预测与真实结果的偏离程度,即刻画了学习算法本身的拟合能力;
方差度量了同样大小的训练集的变动所导致的学习性能的变化,即刻画了数据扰动所造成的影响;
噪声则表达了在当前任务上任何学习算法所能达到的期望泛化误差的下界;
下面通过一个线性回归的例子理解方差和偏差的概念:
假如现在有一个一元线性回归,如图,训练集是蓝色的点,测试集是红色的点,假如有一个模型能够很好地拟合训练集,如下如所示:
但是该模型在测试集的效果比较差,这就是一个典型的高方差,也就是过拟合现象。正则化策略的目的就是降低方差,减小过拟合的发生。
下面了解一下降低过拟合的正则化策略,这里主要学习L1和L2正则化策略。
1.2 损失函数
损失函数:衡量模型输出与真实标签的差异
损失函数:
Loss=f(y^?,y)代价函数:
Cost=N1?i∑N?f(y^?i?,yi?)目标函数:
Obj=Cost+Regularization Term
L1 Regularization Term:
i∑N?∣wi?∣L2 Regularization Term:
i∑N?∣wi2?∣
在分析L!和L2正则化的时候,经常看到下面这个图:
左图为L1正则化,右图为L2正则化,图中的彩色圆圈是损失函数的等高线,也就是公式中的cost,这里假设模型是一个二元模型,有两个参数
w1?和
w2?。左图中的黑色矩阵表示正则化的等高线,右图和左图的图形意义一样。
1.3 L2 Regularization
L2 Regularization = weight decay(权重衰减)
目标函数(Objective Function):
Obj=Cost+Regularization Term假设目标函数为
Obj=Loss+2λ??i∑N?wi2?权重更新公式为
wi+1?=wi???wi??Obj?=wi???wi??Loss?可以得到L2正则化的权重更新为
wi+1?=wi???wi??Obj?=wi??(?wi??Loss?+λ?wi?)公式化简为
wi+1?=wi??(1?λ)??wi??Loss?因为公式中存在
wi??(1?λ),因此L2正则化也称为权重衰减。
现在通过代码看一下在一元线性模型上weight decay(L2正则化)的具体作用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | import torch import torch.nn as nn import matplotlib.pyplot as plt from common_tools import set_seed from torch.utils.tensorboard import SummaryWriter set_seed(1) # 设置随机种子 n_hidden = 200 max_iter = 2000 disp_interval = 200 lr_init = 0.01 # ============================ step 1/5 数据 ============================ def gen_data(num_data=10, x_range=(-1, 1)): w = 1.5 train_x = torch.linspace(*x_range, num_data).unsqueeze_(1) train_y = w*train_x + torch.normal(0, 0.5, size=train_x.size()) test_x = torch.linspace(*x_range, num_data).unsqueeze_(1) test_y = w*test_x + torch.normal(0, 0.3, size=test_x.size()) return train_x, train_y, test_x, test_y train_x, train_y, test_x, test_y = gen_data(x_range=(-1, 1)) # ============================ step 2/5 模型 ============================ class MLP(nn.Module): def __init__(self, neural_num): super(MLP, self).__init__() self.linears = nn.Sequential( nn.Linear(1, neural_num), nn.ReLU(inplace=True), nn.Linear(neural_num, neural_num), nn.ReLU(inplace=True), nn.Linear(neural_num, neural_num), nn.ReLU(inplace=True), nn.Linear(neural_num, 1), ) def forward(self, x): return self.linears(x) net_normal = MLP(neural_num=n_hidden) net_weight_decay = MLP(neural_num=n_hidden) # ============================ step 3/5 优化器 ============================ optim_normal = torch.optim.SGD(net_normal.parameters(), lr=lr_init, momentum=0.9) optim_wdecay = torch.optim.SGD(net_weight_decay.parameters(), lr=lr_init, momentum=0.9, weight_decay=1e-2) # ============================ step 4/5 损失函数 ============================ loss_func = torch.nn.MSELoss() # ============================ step 5/5 迭代训练 ============================ writer = SummaryWriter(comment='_test_tensorboard', filename_suffix="12345678") for epoch in range(max_iter): # forward pred_normal, pred_wdecay = net_normal(train_x), net_weight_decay(train_x) loss_normal, loss_wdecay = loss_func(pred_normal, train_y), loss_func(pred_wdecay, train_y) optim_normal.zero_grad() optim_wdecay.zero_grad() loss_normal.backward() loss_wdecay.backward() optim_normal.step() optim_wdecay.step() if (epoch+1) % disp_interval == 0: # 可视化 for name, layer in net_normal.named_parameters(): writer.add_histogram(name + '_grad_normal', layer.grad, epoch) writer.add_histogram(name + '_data_normal', layer, epoch) for name, layer in net_weight_decay.named_parameters(): writer.add_histogram(name + '_grad_weight_decay', layer.grad, epoch) writer.add_histogram(name + '_data_weight_decay', layer, epoch) test_pred_normal, test_pred_wdecay = net_normal(test_x), net_weight_decay(test_x) # 绘图 plt.scatter(train_x.data.numpy(), train_y.data.numpy(), c='blue', s=50, alpha=0.3, label='train') plt.scatter(test_x.data.numpy(), test_y.data.numpy(), c='red', s=50, alpha=0.3, label='test') plt.plot(test_x.data.numpy(), test_pred_normal.data.numpy(), 'r-', lw=3, label='no weight decay') plt.plot(test_x.data.numpy(), test_pred_wdecay.data.numpy(), 'b--', lw=3, label='weight decay') plt.text(-0.25, -1.5, 'no weight decay loss={:.6f}'.format(loss_normal.item()), fontdict={'size': 15, 'color': 'red'}) plt.text(-0.25, -2, 'weight decay loss={:.6f}'.format(loss_wdecay.item()), fontdict={'size': 15, 'color': 'red'}) plt.ylim((-2.5, 2.5)) plt.legend(loc='upper left') plt.title("Epoch: {}".format(epoch+1)) plt.show() plt.close() |
在Pytorch中,weight_decay是在优化器中实现的,在代码中构建了两个优化器,一个优化器不带有正则化,一个优化器带有正则化。
代码输出的结果如下所示: