RNN做cifar-10图像分类任务pytorch版本的代码
时间: 2023-12-25 09:05:44 浏览: 144
以下是使用PyTorch实现RNN进行CIFAR-10图像分类任务的代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
# 超参数设置
input_size = 3072
hidden_size = 100
num_classes = 10
batch_size = 100
num_epochs = 10
learning_rate = 0.001
# CIFAR-10数据集的预处理
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
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=batch_size,
shuffle=False, num_workers=2)
# 定义RNN模型
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.rnn = nn.RNN(input_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size, num_classes)
def forward(self, x):
# 初始的隐状态
h0 = torch.zeros(1, x.size(0), self.hidden_size)
# 前向传播
out, _ = self.rnn(x, h0)
out = out[:, -1, :]
out = self.fc(out)
return out
rnn = RNN(input_size, hidden_size, num_classes)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(rnn.parameters(), lr=learning_rate)
# 训练模型
total_step = len(trainloader)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(trainloader):
# 把数据展开成一维向量
images = images.reshape(-1, input_size)
# 前向传播
outputs = rnn(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, total_step, loss.item()))
# 测试模型
with torch.no_grad():
correct = 0
total = 0
for images, labels in testloader:
images = images.reshape(-1, input_size)
outputs = rnn(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: {} %'.format(100 * correct / total))
# 保存模型
torch.save(rnn.state_dict(), 'rnn.ckpt')
```
在训练过程中,我们先把图像数据展开成一维向量,然后再输入到RNN模型中进行处理。在每个时刻,RNN的输入是当前时刻的图像向量和上一个时刻的隐状态,输出是当前时刻的隐状态和输出向量。我们只取最后一个时刻的输出向量,并将其输入到全连接层中进行分类。
在测试过程中,我们同样要把图像数据展开成一维向量,然后输入到训练好的RNN模型中进行预测。最后计算预测准确率。
阅读全文