高光谱图像分类python代码
时间: 2025-01-06 09:46:39 浏览: 22
### Python 实现高光谱图像分类的代码示例
对于高光谱图像分类的任务,可以采用深度学习框架来构建卷积神经网络(CNN)。下面是一个基于 PyTorch 的简单 CNN 模型用于高光谱图像分类的例子:
```python
import torch
from torch import nn, optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from DeepHyperX.models.cnn import HSIClassifier # 假设这是来自DeepHyperX库的一个预定义模型[^3]
# 数据加载与预处理
transform = transforms.Compose([
transforms.ToTensor(),
])
train_dataset = datasets.ImageFolder(root='path_to_train_data', transform=transform)
test_dataset = datasets.ImageFolder(root='path_to_test_data', transform=transform)
train_loader = DataLoader(dataset=train_dataset, batch_size=64, shuffle=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=64, shuffle=False)
# 初始化模型、损失函数和优化器
device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = HSIClassifier(num_classes=10).to(device) # 这里的num_classes取决于具体的数据集类别数
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# 训练过程
def train_model(model, criterion, optimizer, num_epochs=25):
model.train()
for epoch in range(num_epochs):
running_loss = 0.0
for inputs, labels in train_loader:
inputs, labels = inputs.to(device), labels.to(device)
outputs = model(inputs)
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f"Epoch {epoch+1}/{num_epochs}, Loss: {running_loss/len(train_loader)}")
# 测试过程
def test_model(model):
correct = 0
total = 0
with torch.no_grad():
model.eval()
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(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: %d %%' % (
100 * correct / total))
train_model(model, criterion, optimizer)
test_model(model)
```
此代码片段展示了如何利用 `PyTorch` 和第三方库 `DeepHyperX` 来创建并训练一个简单的 CNN 模型来进行高光谱图像分类。注意,在实际应用中可能还需要调整超参数以及数据增强策略以获得更好的性能。
阅读全文