AlexNet网络模型五分类,图片大小11*11的代码实现
时间: 2023-08-20 17:07:22 浏览: 79
利用Alexnet网络实现图像分类项目代码
将AlexNet网络模型应用于五分类任务,同时将输入图像大小裁剪为11x11,可以参考以下代码实现:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torchvision.datasets import ImageFolder
import numpy as np
import cv2
# 定义AlexNet网络模型
class AlexNet(nn.Module):
def __init__(self, num_classes=5):
super(AlexNet, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 96, kernel_size=11, stride=4, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(96, 256, kernel_size=5, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(256, 384, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(384, 384, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(384, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
)
self.classifier = nn.Sequential(
nn.Dropout(),
nn.Linear(256 * 2 * 2, 4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(4096, 4096),
nn.ReLU(inplace=True),
nn.Linear(4096, num_classes),
)
def forward(self, x):
x = self.features(x)
x = torch.flatten(x, start_dim=1)
x = self.classifier(x)
return x
# 定义数据预处理函数
transform = transforms.Compose([
transforms.Resize(11),
transforms.ToTensor(),
])
# 加载数据集
train_dataset = ImageFolder(root="train_path", transform=transform)
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
test_dataset = ImageFolder(root="test_path", transform=transform)
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)
# 定义网络模型、损失函数和优化器
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = AlexNet(num_classes=5).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
# 训练网络模型
for epoch in range(10):
running_loss = 0.0
for i, data in enumerate(train_loader, 0):
inputs, labels = data
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()
if i % 100 == 99:
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 100))
running_loss = 0.0
# 测试网络模型
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the test images: %d %%' % (
100 * correct / total))
```
在上述代码中,我们首先定义了一个AlexNet网络模型,并使用PyTorch内置的ImageFolder数据集加载了训练集和测试集。使用`transforms.Resize(11)`将输入图像裁剪为11x11大小,然后使用`transforms.ToTensor()`将其转换为张量格式,方便输入到神经网络中。接着,我们定义了损失函数和优化器,并使用GPU进行计算。在训练网络模型和测试网络模型时,我们按照常规的方式进行即可。
阅读全文