基于PyTorch实现cosine learning rate

1.需要用到的库

设置学习率和模型

import math
import matplotlib.pyplot as plt
import torch.optim as optim
from torchvision.models import resnet18

lr_rate = 0.1
model = resnet18(num_classes=10)

2.LambdaLR实现cosine learning rate

设置lambda、optimizer和scheduler 

lambda1 = lambda epoch: (epoch / 4000) if epoch < 4000 else 0.5 * (math.cos((epoch - 4000)/(100 * 1000 - 4000) * math.pi) + 1)
optimizer = optim.SGD(model.parameters(), lr=lr_rate, momentum=0.9, nesterov=True)
scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda1)

3.learning rate设置

index = 0
x = []
y = []
for epoch in range(100):
    for batch in range(1000):
        x.append(index)
        y.append(optimizer.param_groups[0]['lr'])
        index += 1
        scheduler.step()

4.可视化learning rate

plt.figure(figsize=(10, 8), dpi=200)
plt.xlabel('batch stop')
plt.ylabel('learning rate')
plt.plot(x, y, color='r', linewidth=2.0, label='modify data')
plt.legend(loc='upper right')
plt.savefig('result.png')
plt.show()

5.learning rate变化结果

基于PyTorch实现cosine learning rate_第1张图片

TensorBoard learning rate可视化

基于PyTorch实现cosine learning rate_第2张图片

 

你可能感兴趣的:(深度学习,Pytorch,图像分类)