使用pytorch和自定义卷积神经网络模型实现花朵识别代码
时间: 2024-03-15 07:47:19 浏览: 93
好的,以下是一个使用 PyTorch 和自定义卷积神经网络模型实现花朵识别的代码示例。这个示例使用的是 Oxford Flowers 17 数据集,其中包含 17 种不同的花卉类别。
首先,我们需要导入必要的库和设置一些超参数:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, datasets
# 设置超参数
batch_size = 64
num_epochs = 20
learning_rate = 0.001
```
接下来,我们需要定义自定义卷积神经网络模型。这里我们使用了 4 个卷积层和 2 个全连接层:
```python
class FlowerNet(nn.Module):
def __init__(self):
super(FlowerNet, 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.conv3 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)
self.conv4 = nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1)
self.fc1 = nn.Linear(256 * 7 * 7, 512)
self.fc2 = nn.Linear(512, 17)
def forward(self, x):
x = nn.functional.relu(self.conv1(x))
x = nn.functional.relu(self.conv2(x))
x = nn.functional.max_pool2d(x, 2)
x = nn.functional.relu(self.conv3(x))
x = nn.functional.relu(self.conv4(x))
x = nn.functional.max_pool2d(x, 2)
x = x.view(-1, 256 * 7 * 7)
x = nn.functional.relu(self.fc1(x))
x = self.fc2(x)
return x
```
然后,我们需要加载数据集并进行数据增强:
```python
# 加载数据集并进行数据增强
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
train_dataset = datasets.ImageFolder('flower_photos/train', transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_dataset = datasets.ImageFolder('flower_photos/test', transform=transform)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=True)
```
最后,我们需要定义损失函数和优化器,并开始训练模型:
```python
# 定义损失函数和优化器
net = FlowerNet()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=learning_rate)
# 训练模型
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
optimizer.zero_grad()
outputs = net(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if (i + 1) % 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(
epoch + 1, num_epochs, i + 1, len(train_loader), loss.item()))
# 在测试集上测试模型
correct = 0
total = 0
with torch.no_grad():
for images, labels in test_loader:
outputs = net(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: {} %'.format(100 * correct / total))
# 保存模型
torch.save(net.state_dict(), 'flower_net.pth')
```
这个例子中,我们使用交叉熵损失函数和 Adam 优化器进行训练。在每个 epoch 结束时,在测试集上评估模型的准确度,并保存模型参数。
阅读全文