基于pytorch水果图像识别实现批量标准化和Dropout
时间: 2023-09-25 19:11:26 浏览: 124
批量标准化(Batch Normalization)和 Dropout 是深度学习中常用的正则化方法,可以有效地防止神经网络过拟合。
下面是一个基于 PyTorch 的水果图像识别模型,我们将在这个模型中添加批量标准化和 Dropout。
首先,我们需要导入 PyTorch 和相关的包:
```python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
```
然后,我们定义一个水果图像识别模型 FruitNet,该模型包含两个卷积层、两个池化层和三个全连接层。
```python
class FruitNet(nn.Module):
def __init__(self):
super(FruitNet, self).__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(64 * 8 * 8, 128)
self.fc2 = nn.Linear(128, 64)
self.fc3 = nn.Linear(64, 5)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 64 * 8 * 8)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
```
接下来,我们定义一个函数 train_model,该函数用于训练模型,并添加批量标准化和 Dropout。
```python
def train_model(model, train_loader, optimizer, epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
data = data.to(device)
target = target.to(device)
# 添加批量标准化
data = nn.BatchNorm2d(3)(data)
output = model(data)
# 添加 Dropout
output = nn.Dropout(p=0.5)(output)
loss = F.cross_entropy(output, target)
loss.backward()
optimizer.step()
if batch_idx % 20 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
```
在训练模型的过程中,我们将输入数据进行批量标准化和 Dropout 处理,以防止过拟合。
最后,我们定义一个函数 test_model,该函数用于测试模型,并计算测试准确率。
```python
def test_model(model, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data = data.to(device)
target = target.to(device)
# 添加批量标准化
data = nn.BatchNorm2d(3)(data)
output = model(data)
# 添加 Dropout
output = nn.Dropout(p=0.5)(output)
test_loss += F.cross_entropy(output, target, reduction='sum').item()
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
```
现在,我们可以使用上述函数来训练和测试我们的水果图像识别模型了。
```python
# 设置设备
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 加载数据
train_dataset = datasets.ImageFolder('fruits-360/Training',
transform=transforms.Compose([
transforms.Resize((32, 32)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
]))
test_dataset = datasets.ImageFolder('fruits-360/Test',
transform=transforms.Compose([
transforms.Resize((32, 32)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
]))
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=True)
# 初始化模型和优化器
model = FruitNet().to(device)
optimizer = optim.Adam(model.parameters(), lr=0.001)
# 训练模型
for epoch in range(1, 11):
train_model(model, train_loader, optimizer, epoch)
test_model(model, test_loader)
```
在训练过程中,我们会看到输出的训练损失和测试准确率。您可以根据需要调整批量标准化和 Dropout 的参数来优化模型的性能。
阅读全文