ucm数据集场景分类的代码
时间: 2023-08-15 15:05:30 浏览: 204
遥感图像数据集UCMerced_LandUse
以下是使用 Python 和 PyTorch 框架实现 UCMerced 场景分类的示例代码:
首先,需要下载 UCMerced 数据集并解压缩。可以从以下链接下载数据集:http://weegee.vision.ucmerced.edu/datasets/landuse.html
接下来,需要安装 PyTorch 和 torchvision 库。可以使用以下命令安装:
```
pip install torch torchvision
```
然后,可以使用以下代码加载数据集并进行预处理:
```python
import torch
from torchvision import transforms, datasets
# 定义数据预处理
data_transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
# 加载数据集
train_dataset = datasets.ImageFolder('UCMerced_LandUse/Images/', transform=data_transform)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=32, shuffle=True)
```
接下来,可以定义模型和训练过程。这里使用预训练的 ResNet18 模型:
```python
import torch.nn as nn
import torch.optim as optim
from torchvision.models import resnet18
# 定义模型
model = resnet18(pretrained=True)
model.fc = nn.Linear(512, 21)
# 定义损失函数和优化器
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
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 10 == 9:
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 10))
running_loss = 0.0
```
在训练完成后,可以使用以下代码对测试集进行预测:
```python
import os
import numpy as np
from PIL import Image
# 定义测试集路径和类别名称
test_path = 'UCMerced_LandUse/Images/'
class_names = os.listdir(test_path)
# 定义测试数据预处理
test_transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
# 加载测试数据集
test_images = []
for class_name in class_names:
class_path = os.path.join(test_path, class_name)
for file_name in os.listdir(class_path):
file_path = os.path.join(class_path, file_name)
image = Image.open(file_path)
image = test_transform(image)
test_images.append((image, class_name))
# 对测试数据进行预测
correct = 0
total = 0
with torch.no_grad():
for image, class_name in test_images:
output = model(image.unsqueeze(0))
predicted = class_names[np.argmax(output)]
if predicted == class_name:
correct += 1
total += 1
print('Accuracy: %.2f%%' % (100 * correct / total))
```
这样就完成了 UCMerced 场景分类的实现。
阅读全文