一、头文件
torch.optim.Optimizer(params, defaults)
optim文档
for input, target in dataset:optimizer.zero_grad()output = model(input)loss = loss_fn(output, target)loss.backward()optimizer.step()
二、代码
不带优化器的代码框架
import torch
import torchvision
from torch import nn
from torch.nn import MaxPool2d, Conv2d, Flatten, Linear
from torch.utils.data import DataLoaderdataset = torchvision.datasets.CIFAR10("datasets",train=False,transform=torchvision.transforms.ToTensor(),download=True)
dataloader = DataLoader(dataset,batch_size=1)class Mary(nn.Module):def __init__(self):super(Mary,self).__init__()self.model1 = nn.Sequential(Conv2d(3, 32, 5, padding=2),MaxPool2d(2),Conv2d(32, 32, 5, padding=2),MaxPool2d(2),Conv2d(32, 64, 5, padding=2),MaxPool2d(2),Flatten(),Linear(1024, 64),Linear(64, 10))def forward(self,x):x = self.model1(x)return xYorelee = Mary()
loss = nn.CrossEntropyLoss()
optim = torch.optim.SGD(Yorelee.parameters(),lr=0.01)for epoch in range(20):total_loss = 0for data in dataloader:img,target = dataoutput = Yorelee(img)# print(output)# print(target)result_loss = loss(output,target)# print(result_loss)# print("***********************")optim.zero_grad()result_loss.backward()optim.step()total_loss += result_lossprint(total_loss)
输出:
tensor(18861.5215, grad_fn=<AddBackward0>)
tensor(16226.8633, grad_fn=<AddBackward0>)
tensor(15367.2148, grad_fn=<AddBackward0>)