swin transformer实现猫狗图像分类的代码
时间: 2023-04-02 14:00:58 浏览: 216
Swin Transformer 实现图像分类
5星 · 资源好评率100%
以下是使用 Swin Transformer 实现猫狗图像分类的代码示例:
```
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from swin_transformer import SwinTransformer
# 定义数据预处理
transform = transforms.Compose(
[transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize((.5, .5, .5), (.5, .5, .5))])
# 加载数据集
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=32,
shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=32,
shuffle=False, num_workers=2)
# 定义模型
model = SwinTransformer(img_size=224, patch_size=4, in_chans=3, num_classes=2)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=.001, momentum=.9)
# 训练模型
for epoch in range(10): # 训练 10 轮
running_loss = .
for i, data in enumerate(trainloader, ):
inputs, labels = data
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 200 == 199: # 每 200 个 batch 输出一次损失值
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 200))
running_loss = .
print('Finished Training')
# 测试模型
correct =
total =
with torch.no_grad():
for data in testloader:
images, labels = data
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size()
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: %d %%' % (
100 * correct / total))
```
注意:这只是一个示例代码,实际使用时需要根据具体情况进行修改。
阅读全文