Transformers做cifar-10图像分类任务pytorch版本的代码
时间: 2024-01-17 18:04:37 浏览: 101
下面是一个基于PyTorch实现的Transformers对cifar-10图像分类的代码,使用了BERT作为Transformers的模型。
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from transformers import BertModel
# 超参数设置
input_size = 32
hidden_size = 768
num_classes = 10
batch_size = 100
num_epochs = 10
learning_rate = 0.001
# CIFAR-10数据集下载和预处理
transform = transforms.Compose(
[transforms.Resize((input_size, input_size)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
train_dataset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size,
shuffle=True, num_workers=2)
test_dataset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size,
shuffle=False, num_workers=2)
# BERT模型定义
class BERT(nn.Module):
def __init__(self, hidden_size, num_classes):
super(BERT, self).__init__()
self.bert = BertModel.from_pretrained('bert-base-uncased')
self.fc = nn.Linear(hidden_size, num_classes)
def forward(self, x):
# 前向传播 BERT
out = self.bert(x)[0][:, 0, :]
out = self.fc(out)
return out
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = BERT(hidden_size, num_classes).to(device)
# 损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 模型训练
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# 将图像转换成BERT需要的形状
images = images.reshape(-1, input_size * input_size * 3).to(device)
labels = labels.to(device)
# 前向传播
outputs = model(images)
loss = criterion(outputs, labels)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
.format(epoch+1, num_epochs, i+1, len(train_loader), loss.item()))
# 模型测试
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
# 将图像转换成BERT需要的形状
images = images.reshape(-1, input_size * input_size * 3).to(device)
labels = labels.to(device)
# 前向传播
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Test Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))
```
需要注意的是,这个代码中使用了一个将图像转换成BERT需要的形状的过程,即将每个图像的像素展平成一维向量。在这个例子中,我们使用了预训练的BERT模型来提取图像的特征,并将特征向量输入到一个全连接层中进行分类。
阅读全文