RMSProp算法

https://zh.d2l.ai/chapter_optimization/rmsprop.html

问题一,若设置gamma=1,则states无法更新,学习率为固定的值,由于之前states初始化为0,将使得学习率过大,从而导致无法收敛,loss=nan

为什么在11.6节中使用泄露平均值的时候第二项系数为1,而这里第二项系数是(1-\gamma)呢,只是因为是平方项所以用更小的系数去约束它吗?那么是不是其实不一定要用(1-\gamma)呢?如果是因为“平均值”的定义,那么11.6节的公式是否存在错误?

# 练习2
def rmsprop_2d(x1, x2, s1, s2):
    g1, g2, eps = 0.2 * x1 + 0.2 * x2 + 4 * x1 - 4 * x2, 0.2 * x1 + 0.2 * x2 - 4 * x1 + 4 * x2, 1e-6
    s1 = gamma * s1 + (1 - gamma) * g1 ** 2
    s2 = gamma * s2 + (1 - gamma) * g2 ** 2
    x1 -= eta / math.sqrt(s1 + eps) * g1
    x2 -= eta / math.sqrt(s2 + eps) * g2
    return x1, x2, s1, s2

def f_2d(x1, x2):
    return 0.1 * (x1+x2) ** 2 + 2 * (x1-x2) ** 2

eta, gamma = 0.6, 0.9
d2l.show_trace_2d(f_2d, d2l.train_2d(rmsprop_2d))
# 练习3
# AlexNet
from torch import nn
from d2l import torch as d2l

net = nn.Sequential(
    nn.Conv2d(1, 6, kernel_size=5, padding=2), nn.Sigmoid(),
    nn.AvgPool2d(kernel_size=2, stride=2),
    nn.Conv2d(6, 16, kernel_size=5), nn.Sigmoid(),
    nn.AvgPool2d(kernel_size=2, stride=2),
    nn.Flatten(),
    nn.Linear(16 * 5 * 5, 120), nn.Sigmoid(),
    nn.Linear(120, 84), nn.Sigmoid(),
    nn.Linear(84, 10))

def train_ch6_2(net, train_iter, test_iter, num_epochs, lr, alpha, device):
    """用GPU训练模型(在第六章定义)"""
    def init_weights(m):
        if type(m) == nn.Linear or type(m) == nn.Conv2d:
            nn.init.xavier_uniform_(m.weight)
    net.apply(init_weights)
    print('training on', device)
    net.to(device)
    optimizer = torch.optim.RMSprop(net.parameters(), lr=lr, alpha=alpha)
    # optimizer = torch.optim.SGD(net.parameters(), lr=lr)
    loss = nn.CrossEntropyLoss()
    animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs],
                            legend=['train loss', 'train acc', 'test acc'])
    timer, num_batches = d2l.Timer(), len(train_iter)
    for epoch in range(num_epochs):
        # 训练损失之和,训练准确率之和,样本数
        metric = d2l.Accumulator(3)
        net.train()
        for i, (X, y) in enumerate(train_iter):
            timer.start()
            optimizer.zero_grad()
            X, y = X.to(device), y.to(device)
            y_hat = net(X)
            l = loss(y_hat, y)
            l.backward()
            optimizer.step()
            with torch.no_grad():
                metric.add(l * X.shape[0], d2l.accuracy(y_hat, y), X.shape[0])
            timer.stop()
            train_l = metric[0] / metric[2]
            train_acc = metric[1] / metric[2]
            if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
                animator.add(epoch + (i + 1) / num_batches,
                             (train_l, train_acc, None))
        test_acc = d2l.evaluate_accuracy_gpu(net, test_iter)
        animator.add(epoch + 1, (None, None, test_acc))
    print(f'loss {train_l:.3f}, train acc {train_acc:.3f}, '
          f'test acc {test_acc:.3f}')
    print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec '
          f'on {str(device)}')
    

batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size=batch_size)

lr, alpha, num_epochs = 0.9, 0.6, 10
train_ch6_2(net, train_iter, test_iter, num_epochs, lr, alpha, d2l.try_gpu())

效果很差的样子,不知道是不是正常的

发现问题了,学习率应该用0.01,只有SGD能用零点几的学习率