基于cifar-10数据集生成vgg16代码使得数据集各种类分辩率达85%使用pytorch
时间: 2023-12-14 20:37:06 浏览: 140
好的,首先我们需要导入必要的库:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
```
然后,我们需要定义一些超参数:
```python
# 超参数
batch_size = 128 # 批大小
num_epochs = 50 # 训练轮数
learning_rate = 0.001 # 学习率
```
接下来,我们需要下载并加载 CIFAR-10 数据集:
```python
# 下载并加载 CIFAR-10 数据集
train_dataset = torchvision.datasets.CIFAR10(root='./data', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = torchvision.datasets.CIFAR10(root='./data', train=False, transform=transforms.ToTensor(), download=True)
# 数据加载器
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
```
现在,我们可以定义 VGG16 模型了:
```python
# VGG16 模型
class VGG16(nn.Module):
def __init__(self):
super(VGG16, self).__init__()
self.conv1 = nn.Sequential(nn.Conv2d(3, 64, 3, padding=1), nn.ReLU(inplace=True))
self.conv2 = nn.Sequential(nn.Conv2d(64, 64, 3, padding=1), nn.ReLU(inplace=True))
self.maxpool1 = nn.MaxPool2d(2, 2)
self.conv3 = nn.Sequential(nn.Conv2d(64, 128, 3, padding=1), nn.ReLU(inplace=True))
self.conv4 = nn.Sequential(nn.Conv2d(128, 128, 3, padding=1), nn.ReLU(inplace=True))
self.maxpool2 = nn.MaxPool2d(2, 2)
self.conv5 = nn.Sequential(nn.Conv2d(128, 256, 3, padding=1), nn.ReLU(inplace=True))
self.conv6 = nn.Sequential(nn.Conv2d(256, 256, 3, padding=1), nn.ReLU(inplace=True))
self.conv7 = nn.Sequential(nn.Conv2d(256, 256, 3, padding=1), nn.ReLU(inplace=True))
self.maxpool3 = nn.MaxPool2d(2, 2)
self.conv8 = nn.Sequential(nn.Conv2d(256, 512, 3, padding=1), nn.ReLU(inplace=True))
self.conv9 = nn.Sequential(nn.Conv2d(512, 512, 3, padding=1), nn.ReLU(inplace=True))
self.conv10 = nn.Sequential(nn.Conv2d(512, 512, 3, padding=1), nn.ReLU(inplace=True))
self.maxpool4 = nn.MaxPool2d(2, 2)
self.conv11 = nn.Sequential(nn.Conv2d(512, 512, 3, padding=1), nn.ReLU(inplace=True))
self.conv12 = nn.Sequential(nn.Conv2d(512, 512, 3, padding=1), nn.ReLU(inplace=True))
self.conv13 = nn.Sequential(nn.Conv2d(512, 512, 3, padding=1), nn.ReLU(inplace=True))
self.maxpool5 = nn.MaxPool2d(2, 2)
self.fc1 = nn.Sequential(nn.Linear(512, 4096), nn.ReLU(inplace=True), nn.Dropout())
self.fc2 = nn.Sequential(nn.Linear(4096, 4096), nn.ReLU(inplace=True), nn.Dropout())
self.fc3 = nn.Linear(4096, 10)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.maxpool1(x)
x = self.conv3(x)
x = self.conv4(x)
x = self.maxpool2(x)
x = self.conv5(x)
x = self.conv6(x)
x = self.conv7(x)
x = self.maxpool3(x)
x = self.conv8(x)
x = self.conv9(x)
x = self.conv10(x)
x = self.maxpool4(x)
x = self.conv11(x)
x = self.conv12(x)
x = self.conv13(x)
x = self.maxpool5(x)
x = x.view(x.size(0), -1)
x = self.fc1(x)
x = self.fc2(x)
x = self.fc3(x)
return x
# 实例化模型
model = VGG16()
# 将模型移动到 GPU 上(如果有的话)
if torch.cuda.is_available():
model.cuda()
```
接下来,我们需要定义损失函数和优化器:
```python
# 损失函数
criterion = nn.CrossEntropyLoss()
# 优化器
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
```
最后,我们可以进行训练和测试:
```python
# 训练
for epoch in range(num_epochs):
# 训练模式
model.train()
train_loss = 0.0
train_correct = 0
train_total = 0
for images, labels in train_loader:
# 将数据移动到 GPU 上(如果有的话)
if torch.cuda.is_available():
images = images.cuda()
labels = labels.cuda()
# 前向传播和反向传播
outputs = model(images)
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 统计训练损失和正确率
train_loss += loss.item() * images.size(0)
_, predicted = torch.max(outputs.data, 1)
train_total += labels.size(0)
train_correct += (predicted == labels).sum().item()
# 计算训练损失和正确率
train_loss = train_loss / len(train_loader.dataset)
train_accuracy = 100.0 * train_correct / train_total
# 测试模式
model.eval()
test_loss = 0.0
test_correct = 0
test_total = 0
with torch.no_grad():
for images, labels in test_loader:
# 将数据移动到 GPU 上(如果有的话)
if torch.cuda.is_available():
images = images.cuda()
labels = labels.cuda()
# 前向传播
outputs = model(images)
loss = criterion(outputs, labels)
# 统计测试损失和正确率
test_loss += loss.item() * images.size(0)
_, predicted = torch.max(outputs.data, 1)
test_total += labels.size(0)
test_correct += (predicted == labels).sum().item()
# 计算测试损失和正确率
test_loss = test_loss / len(test_loader.dataset)
test_accuracy = 100.0 * test_correct / test_total
# 输出训练和测试结果
print('[Epoch %d] Train Loss: %.3f, Train Accuracy: %.2f%%, Test Loss: %.3f, Test Accuracy: %.2f%%' % (epoch+1, train_loss, train_accuracy, test_loss, test_accuracy))
```
这样,我们就可以使用 VGG16 模型对 CIFAR-10 数据集进行分类了。
阅读全文