这里主要讲不同常见优化器代码的实现,以及在一个小数据集上做一个简单的比较。
备注:pytorch需要升级到最新版本
其中,SGD和SGDM,还有Adam是pytorch自带的优化器,而RAdam是最近提出的一个说是Adam更强的优化器,但是一般情况下真正的大佬还在用SGDM来做优化器。
导入必要库:
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import matplotlib.pyplot as plt
import torch.utils.data as Data
from torch.optim.optimizer import Optimizer
import math
主程序部分:
LR = 0.01
BATCH_SIZE = 32
EPOCH = 12
# fake dataset
x = torch.unsqueeze(torch.linspace(-1, 1, 300), dim=1)
y = x.pow(2) + 0.1 * torch.normal(torch.zeros(*x.size()))
torch_dataset = Data.TensorDataset(x, y)
loader = Data.DataLoader(
dataset=torch_dataset,
batch_size=BATCH_SIZE,
shuffle=True,
num_workers=2
)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.hidden = nn.Linear(1, 20)
self.prediction = nn.Linear(20, 1)
def forward(self, x):
x = F.relu(self.hidden(x))
x = self.prediction(x)
return x
def main():
net_SGD = Net()
net_Momentum = Net()
net_Adam = Net()
net_RAdam = Net()
nets = [net_SGD, net_Momentum, net_Adam, net_RAdam]
opt_SGD = optim.SGD(net_SGD.parameters(), lr=LR)
opt_Momentum = optim.SGD(net_Momentum.parameters(), lr=LR, momentum=0.9)
opt_Adam = optim.Adam(net_Adam.parameters(), lr=LR, betas=(0.9, 0.99))
opt_RAdam = RAdam(net_RAdam.parameters(),lr=LR,weight_decay=0)
optimizers = [opt_SGD, opt_Momentum, opt_Adam, opt_RAdam]
loss_func = nn.MSELoss()
losses_his = [[], [], [], []]
# training
for epoch in range(EPOCH):
print('EPOCH:', epoch)
for step, (batch_x, batch_y) in enumerate(loader):
b_x = batch_x
b_y = batch_y
for net, opt, l_his in zip(nets, optimizers, losses_his):
out = net(b_x)
loss = loss_func(out, b_y)
opt.zero_grad()
loss.backward()
opt.step()
l_his.append(loss.item())
labels = ['SGD', 'Momentum', 'Adam','RAdam']
for i, l_his in enumerate(losses_his):
plt.plot(l_his, label=labels[i])
plt.legend(loc='best')
plt.xlabel('Steps')
plt.ylabel('Loss')
plt.ylim((0, 0.2))
plt.show()
if __name__ == '__main__':
main()
下图是优化器的对比:
可以看出来,Adam的效果可以说是非常好的。然后SGDM其次,SGDM是大佬们经常会使用的,所以在这里虽然看起来SGDM效果不如Adam,但是依然推荐在项目中,尝试一下SGDM的效果。
往期精彩回顾
适合初学者入门人工智能的路线及资料下载机器学习及深度学习笔记等资料打印机器学习在线手册深度学习笔记专辑《统计学习方法》的代码复现专辑
AI基础下载机器学习的数学基础专辑获取一折本站知识星球优惠券,复制链接直接打开:https://t.zsxq.com/yFQV7am本站qq群1003271085。加入微信群请扫码进群: