densenet121实现图片大小为48*48分类代码
时间: 2023-11-23 17:07:40 浏览: 128
以下是使用Pytorch实现densenet121对大小为48x48的图像进行分类的代码示例:
首先,导入必要的库:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.datasets as datasets
import torchvision.transforms as transforms
```
定义超参数:
```python
num_epochs = 10
batch_size = 128
learning_rate = 0.001
```
定义数据预处理:
```python
transform = transforms.Compose([
transforms.Resize(48),
transforms.CenterCrop(48),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
```
加载数据集:
```python
train_dataset = datasets.ImageFolder(root='path/to/train/data', transform=transform)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_dataset = datasets.ImageFolder(root='path/to/test/data', transform=transform)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
```
定义模型:
```python
class DenseNet(nn.Module):
def __init__(self):
super(DenseNet, self).__init__()
self.densenet121 = nn.Sequential(*list(torchvision.models.densenet121(pretrained=True).children())[:-1])
self.fc = nn.Linear(1024, 10)
def forward(self, x):
features = self.densenet121(x)
out = self.fc(features.view(features.size(0), -1))
return out
```
定义损失函数和优化器:
```python
model = DenseNet()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
```
训练模型:
```python
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = images.cuda()
labels = labels.cuda()
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if (i+1) % 10 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
.format(epoch+1, num_epochs, i+1, len(train_loader), loss.item()))
# Test the model
model.eval()
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
images = images.cuda()
labels = labels.cuda()
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Test Accuracy of the model on the test images: {} %'.format(100 * correct / total))
```
这样就完成了使用densenet121对大小为48x48的图像进行分类的代码实现。
阅读全文