ViT pytorch的代码
时间: 2024-02-28 20:51:10 浏览: 181
ViT pytorch代码
ViT(Vision Transformer)是一种基于Transformer的图像分类模型,它将图像分割成一系列的图像块,并使用Transformer编码器来处理这些图像块。以下是一个使用PyTorch实现ViT的简单代码示例:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import transforms, datasets
from torch.utils.data import DataLoader
from torchsummary import summary
# 定义ViT模型
class ViT(nn.Module):
def __init__(self, image_size, patch_size, num_classes, dim):
super(ViT, self).__init__()
num_patches = (image_size // patch_size) ** 2
self.patch_embedding = nn.Conv2d(3, dim, kernel_size=patch_size, stride=patch_size)
self.positional_embedding = nn.Parameter(torch.randn(1, num_patches + 1, dim))
self.transformer = nn.TransformerEncoder(nn.TransformerEncoderLayer(d_model=dim, nhead=8), num_layers=12)
self.fc = nn.Linear(dim, num_classes)
def forward(self, x):
x = self.patch_embedding(x)
x = x.flatten(2).transpose(1, 2)
x = torch.cat([self.positional_embedding, x], dim=1)
x = self.transformer(x)
x = x[:, 0]
x = self.fc(x)
return x
# 数据预处理
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
# 加载数据集
train_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)
# 创建模型实例
model = ViT(image_size=224, patch_size=16, num_classes=10, dim=256)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# 训练模型
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
for epoch in range(10):
running_loss = 0.0
for i, (inputs, labels) in enumerate(train_loader):
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f"Epoch {epoch+1} loss: {running_loss/len(train_loader)}")
# 测试模型
model.eval()
correct = 0
total = 0
with torch.no_grad():
for inputs, labels in test_loader:
inputs, labels = inputs.to(device), labels.to(device)
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = 100 * correct / total
print(f"Test accuracy: {accuracy}%")
# 打印模型结构
summary(model, (3, 224, 224))
```
这段代码实现了一个简单的ViT模型,使用CIFAR-10数据集进行训练和测试。代码中包括了模型的定义、数据预处理、数据加载、训练过程、测试过程以及模型结构的打印。
阅读全文