- API
torch.optim.Optimizer(params, defaults)
- 代码示例
import torch
from torch import nn,optim
from torch.nn import Sequential, Conv2d, MaxPool2d, Flatten, Linear
import torchvision
from torch.utils.data import DataLoader
dataset = torchvision.datasets.CIFAR10("./dataset",train=False,transform=torchvision.transforms.ToTensor(),download=True)
dataloader = DataLoader(dataset=dataset,batch_size=4096)
class seq(nn.Module):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.model1 = Sequential(
Conv2d(3,32,5,padding=2),
MaxPool2d(2),
Conv2d(32,32,5,stride=1,padding=2),
MaxPool2d(2),
Conv2d(32,64,5,stride=1,padding=2),
MaxPool2d(2),
Flatten(),
Linear(64*4*4,64),
Linear(64,10),
)
def forward(self,x):
x = self.model1(x)
return x
loss = nn.CrossEntropyLoss()
seq_test = seq()
optim = torch.optim.SGD(seq_test.parameters(),lr=0.01)
for epoch in range(2):
running_loss = 0.0
for data in dataloader:
imgs,targets = data
outputs = seq_test(imgs)
results = loss(outputs,targets)
optim.zero_grad()
results.backward()
optim.step()
running_loss = running_loss + results
print(running_loss)