densenet121实现图片大小为48×48×3四分类代码
时间: 2023-11-23 19:07:40 浏览: 65
以下是使用PyTorch实现densenet121进行48x48x3图像四分类的示例代码:
```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
from torchvision.models import densenet121
# 定义超参数
batch_size = 32
learning_rate = 0.001
num_epochs = 10
# 数据预处理
transform = transforms.Compose([
transforms.Resize(48),
transforms.CenterCrop(48),
transforms.ToTensor(),
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
])
# 加载数据集
train_dataset = ImageFolder(root="./train", transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
val_dataset = ImageFolder(root="./val", transform=transform)
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
test_dataset = ImageFolder(root="./test", transform=transform)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
# 定义模型
model = densenet121(pretrained=True)
num_ftrs = model.classifier.in_features
model.classifier = nn.Linear(num_ftrs, 4) # 四分类问题,输出节点数为4
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 训练模型
for epoch in range(num_epochs):
model.train()
for images, labels in train_loader:
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# 在验证集上测试模型性能
model.eval()
with torch.no_grad():
correct = 0
total = 0
for images, labels in val_loader:
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
val_acc = correct / total
print("Epoch {}, Validation Accuracy: {:.2f}%".format(epoch+1, val_acc*100))
# 在测试集上测试模型性能
model.eval()
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
test_acc = correct / total
print("Test Accuracy: {:.2f}%".format(test_acc*100))
```
在上述代码中,我们使用ImageFolder类从文件夹中加载图像数据集,并使用DataLoader类进行批量读取。我们使用预训练的densenet121模型,将其全连接层的输出节点数修改为4。使用交叉熵损失函数进行训练,使用Adam优化器进行参数更新。在每个epoch结束时,我们在验证集上测试模型性能,并输出验证集准确率。最后,在测试集上测试模型性能并输出测试集准确率。
阅读全文