Pytorch学习笔记(深度之眼)(10)之正则化之weight_decay

1、正则化与偏差-方差分解

Regularization:减小方差的策略;

误差可分解为偏差,方差与噪声之和,即误差=偏差+方差+噪声之和;

偏差度量了学习算法的期望预测与真实结果的偏离程度,即刻画了学习算法本身的拟合能力;

方差度量了同样大小的训练集的变动所导致的学习性能的变化,即刻画了数据扰动所造成的影响;

噪声则表达了在当前任务上任何学习算法所能达到的期望泛化误差的下界;
Pytorch学习笔记(深度之眼)(10)之正则化之weight_decay_第1张图片该模型在测试集的效果比较差,这就是一个典型的高方差,也就是过拟合现象。正则化策略的目的就是降低方差,减小过拟合的发生。
Pytorch学习笔记(深度之眼)(10)之正则化之weight_decay_第2张图片Pytorch学习笔记(深度之眼)(10)之正则化之weight_decay_第3张图片Pytorch学习笔记(深度之眼)(10)之正则化之weight_decay_第4张图片左图为L1正则化,右图为L2正则化,图中的彩色圆圈是损失函数的等高线,也就是公式中的cost,这里假设模型是一个二元模型,有两个参数 w 1 w_1 w1​和 w 2 w_2 w2​。左图中的黑色矩阵表示正则化的等高线,右图和左图的图形意义一样

L2 Regularization

Pytorch学习笔记(深度之眼)(10)之正则化之weight_decay_第5张图片Pytorch学习笔记(深度之眼)(10)之正则化之weight_decay_第6张图片

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学习笔记(深度之眼)(10)之正则化之weight_decay_第7张图片

Dropout概念

Dropout:随机失活,随机是dropout probability,失活是指weight=0。

通过下面的示例图理解随机失活:
Pytorch学习笔记(深度之眼)(10)之正则化之weight_decay_第8张图片左边的图是正常的全连接网络,右边的图是使用dropout的神经网络,dropout是以一定的概率让一部分的神经元失活,这可以让神经元学习到更鲁棒的特征,减轻过度的依赖性,从而缓解过拟合,降低方差达到正则化效果,这种操作可以使模型更多样化,因为每一次前向传播神经元都会随机失活,每次训练得到的模型都是不一样的。

为什么dropout能够达到很好的正则化效果呢?

从特征依赖性角度
假设一个神经元会接收上一层的五个神经元的输出值,可以理解为上一层的特征,如果当前神经元特别依赖于某一个特征。如果加了dropout之后,当前神经元就不知道上一层所有神经元中哪些神经元会出现,这样当前神经元就不会过度依赖上一层神经元中的某些神经元。

数据尺度变化:
测试时,所有权重乘以1-drop_prob,例如drop_prob=0.3,1-drop_prob=0.7;

nn.Dropout

功能:Dropout层;
参数:
P:被舍弃概率,失活概率;
注意:dropout层通常放在需要dropout的网络层的前一层;

 torch.nn.Dropout(p=0.5,inplace=False)

下面通过代码分析Dropout层的作用:

import torch
import torch.nn as nn
import matplotlib.pyplot as plt
from toolss.common_tools import set_seed
from torch.utils.tensorboard import SummaryWriter

set_seed(1)  # 设置随机种子
n_hidden = 200
max_iter = 2000
disp_interval = 400
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, d_prob=0.5):
        super(MLP, self).__init__()
        self.linears = nn.Sequential(

            nn.Linear(1, neural_num),
            nn.ReLU(inplace=True),

            nn.Dropout(d_prob),
            nn.Linear(neural_num, neural_num),
            nn.ReLU(inplace=True),

            nn.Dropout(d_prob),
            nn.Linear(neural_num, neural_num),
            nn.ReLU(inplace=True),

            nn.Dropout(d_prob),
            nn.Linear(neural_num, 1),
        )

    def forward(self, x):
        return self.linears(x)


net_prob_0 = MLP(neural_num=n_hidden, d_prob=0.)
net_prob_05 = MLP(neural_num=n_hidden, d_prob=0.5)

# ============================ step 3/5 优化器 ============================
optim_normal = torch.optim.SGD(net_prob_0.parameters(), lr=lr_init, momentum=0.9)
optim_reglar = torch.optim.SGD(net_prob_05.parameters(), lr=lr_init, momentum=0.9)

# ============================ 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):

    pred_normal, pred_wdecay = net_prob_0(train_x), net_prob_05(train_x)
    loss_normal, loss_wdecay = loss_func(pred_normal, train_y), loss_func(pred_wdecay, train_y)

    optim_normal.zero_grad()
    optim_reglar.zero_grad()

    loss_normal.backward()
    loss_wdecay.backward()

    optim_normal.step()
    optim_reglar.step()

    if (epoch+1) % disp_interval == 0:

        net_prob_0.eval()
        net_prob_05.eval()

        # 可视化
        for name, layer in net_prob_0.named_parameters():
            writer.add_histogram(name + '_grad_normal', layer.grad, epoch)
            writer.add_histogram(name + '_data_normal', layer, epoch)

        for name, layer in net_prob_05.named_parameters():
            writer.add_histogram(name + '_grad_regularization', layer.grad, epoch)
            writer.add_histogram(name + '_data_regularization', layer, epoch)

        test_pred_prob_0, test_pred_prob_05 = net_prob_0(test_x), net_prob_05(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_prob_0.data.numpy(), 'r-', lw=3, label='d_prob_0')
        plt.plot(test_x.data.numpy(), test_pred_prob_05.data.numpy(), 'b--', lw=3, label='d_prob_05')
        plt.text(-0.25, -1.5, 'd_prob_0 loss={:.8f}'.format(loss_normal.item()), fontdict={'size': 15, 'color': 'red'})
        plt.text(-0.25, -2, 'd_prob_05 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()

        net_prob_0.train()
        net_prob_05.train()

Pytorch学习笔记(深度之眼)(10)之正则化之weight_decay_第9张图片

你可能感兴趣的:(python,深度学习,笔记,深度学习,机器学习,神经网络)