RNN做cifar-10图像分类任务pytorch版本的代码
时间: 2023-12-25 21:05:44 浏览: 94
以下是使用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 = 32 # 输入图像大小
hidden_size = 128 # 隐藏层大小
num_layers = 2 # RNN层数
num_classes = 10 # 输出类别数
batch_size = 100
num_epochs = 10
learning_rate = 0.001
# 加载数据集
transform = transforms.Compose(
[transforms.Resize((input_size, input_size)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[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)
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)
# 定义RNN模型
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.rnn = nn.RNN(input_size, hidden_size, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_size, num_classes)
def forward(self, x):
# 初始化隐藏状态
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
# 前向传播 RNN
out, _ = self.rnn(x, h0)
# 解码最后一个时间步的隐状态
out = self.fc(out[:, -1, :])
return out
# 实例化模型并将其移到GPU上(如果有GPU)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = RNN(input_size, hidden_size, num_layers, num_classes).to(device)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 训练模型
total_step = len(train_loader)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# 将数据移到GPU上(如果有GPU)
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()
# 每100个batch打印一次训练状态
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 test_loader:
# 将数据移到GPU上(如果有GPU)
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 {} test images: {} %'.format(total, 100 * correct / total))
```
以上代码使用了一个2层的RNN模型对CIFAR-10数据集进行图像分类。请注意,这个模型可能无法取得最好的性能,因为对于图像分类任务,通常使用卷积神经网络(CNN)而不是循环神经网络(RNN)。
阅读全文