数据基本介绍: 高光谱图像分类 数据样本数量: 总共有340×610个像素点组成的高光谱图像 数据样本X特点:每个像素点为103个特征,因此X维度为(103,340,610) 数据样本Y特点:每个像素点对应了一个类别,总共为9个类别,因此labe为[0,1,2,3,4,5,6,7,8,9]。 其中Y的维度为(340,610) 数据样本要求:对label进行分类pytorch代码
时间: 2023-10-23 15:12:42 浏览: 93
对高光谱图像数据进行分析
以下是一个简单的基于PyTorch的高光谱图像分类代码示例:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
import numpy as np
# 定义超参数
batch_size = 64
learning_rate = 0.01
epochs = 10
# 定义数据集类
class HSI_Dataset(Dataset):
def __init__(self, x, y):
self.x = x
self.y = y
def __len__(self):
return len(self.y)
def __getitem__(self, idx):
return torch.from_numpy(self.x[:, idx % 340, idx // 340]).float(), self.y[idx]
# 定义卷积神经网络模型
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=5, stride=1, padding=2)
self.conv2 = nn.Conv2d(32, 64, kernel_size=5, stride=1, padding=2)
self.fc1 = nn.Linear(64 * 85 * 153, 1024)
self.fc2 = nn.Linear(1024, 9)
def forward(self, x):
x = x.view(-1, 1, 103, 340)
x = nn.functional.relu(self.conv1(x))
x = nn.functional.max_pool2d(x, 2)
x = nn.functional.relu(self.conv2(x))
x = nn.functional.max_pool2d(x, 2)
x = x.view(-1, 64 * 85 * 153)
x = nn.functional.relu(self.fc1(x))
x = self.fc2(x)
return x
# 加载数据集
x = np.load('x.npy')
y = np.load('y.npy')
dataset = HSI_Dataset(x, y)
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
# 定义模型、损失函数和优化器
model = CNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
# 训练模型
for epoch in range(epochs):
running_loss = 0.0
for i, data in enumerate(dataloader, 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
print('Finished Training')
# 保存模型
torch.save(model.state_dict(), 'model.pt')
```
请注意,这只是一个简单的示例,可能需要根据实际情况进行修改和调整。另外,还需要将数据集x和y保存为.npy格式的文件,并将其放置在正确的路径下。
阅读全文