论文下载地址1:https://ieeexplore.ieee.org/document/8736016
论文下载地址2:https://pan.baidu.com/s/1dK811oJrGdhUwDSlel9PZA 提取码:55ty
首先,介绍一下本论文的主角——高光谱图像(HyperSpectral Image,简称HSI):
之后,对于卷积网络,处理高光谱图像时,会有一些技术问题:
所以,作者:
实验使用了三个公开的HSI数据集:Indian Pines (IP)、University of Pavia (UP)和Salinas Scene (SA)。
数据集 | 图像维数 | 波长范围 | 光谱波段个数 | 地面图像被划分为多少类 |
---|---|---|---|---|
Indian Pines (IP) | 145 ∗ 145 145 *145 145∗145 | 400 ~ 2500 nm | 224 | 16 |
University of Pavia (UP) | 610 ∗ 340 610 *340 610∗340 | 430~ 860 nm | 103 | 9 |
Salinas Scene (SA) | 512 ∗ 217 512 * 217 512∗217 | 360 ~2500 nm | 224 | 16 |
注意:
首先取得数据——Indian pines(这是论文中引用的三个数据集中的一个)
#数据准备
! wget http://www.ehu.eus/ccwintco/uploads/6/67/Indian_pines_corrected.mat
! wget http://www.ehu.eus/ccwintco/uploads/c/c4/Indian_pines_gt.mat
! pip install spectral
##引入基本函数库
import numpy as np
import matplotlib.pyplot as plt
import scipy.io as sio
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, accuracy_score, classification_report, cohen_kappa_score
import spectral
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
包括:
代码实现:
##定义 HybridSN 类
class_num = 16
class HybridSN(nn.Module):
def __init__(self, num_classes=16):
super(HybridSN, self).__init__()
# conv1:(1, 30, 25, 25), 8个 7x3x3 的卷积核 ==>(8, 24, 23, 23)
self.conv1 = nn.Conv3d(1, 8, (7, 3, 3))
# conv2:(8, 24, 23, 23), 16个 5x3x3 的卷积核 ==>(16, 20, 21, 21)
self.conv2 = nn.Conv3d(8, 16, (5, 3, 3))
# conv3:(16, 20, 21, 21),32个 3x3x3 的卷积核 ==>(32, 18, 19, 19)
self.conv3 = nn.Conv3d(16, 32, (3, 3, 3))
# conv3_2d (576, 19, 19),64个 3x3 的卷积核 ==>((64, 17, 17)
self.conv3_2d = nn.Conv2d(576, 64, (3,3))
# 全连接层(256个节点)
self.dense1 = nn.Linear(18496,256)
# 全连接层(128个节点)
self.dense2 = nn.Linear(256,128)
# 最终输出层(16个节点)
self.out = nn.Linear(128, num_classes)
# Dropout(0.4)
self.drop = nn.Dropout(p=0.4)
######################
#这里是优化的方向(一会还会添加注意力机制)
######################
#软最大化
#self.soft = nn.LogSoftmax(dim=1)
self.soft = nn.Softmax(dim=1)
#加入BN归一化数据
self.bn1=nn.BatchNorm3d(8)
self.bn2=nn.BatchNorm3d(16)
self.bn3=nn.BatchNorm3d(32)
self.bn4=nn.BatchNorm2d(64)
# 激活函数ReLU
self.relu = nn.ReLU()
#####################
#####################
#定义完了各个模块,记得在这里调用执行:
def forward(self, x):
out = self.relu(self.conv1(x))
#out = self.bn1(out)#BN层
out = self.relu(self.conv2(out))
#out = self.bn2(out)#BN层
out = self.relu(self.conv3(out))
#out = self.bn3(out)#BN层
out = out.view(-1, out.shape[1] * out.shape[2], out.shape[3], out.shape[4])# 进行二维卷积,因此把前面的 32*18 reshape 一下,得到 (576, 19, 19)
#out = self.attention(out)#调用注意力机制
out = self.relu(self.conv3_2d(out))
#out = self.bn4(out)#BN层
# flatten 操作,变为 18496 维的向量,
out = out.view(out.size(0), -1)
out = self.dense1(out)
out = self.drop(out)
out = self.dense2(out)
out = self.drop(out)
out = self.out(out)
out = self.soft(out)
return out
在这一步,我们主要完成:
首先,我们定义一些基本函数来完成上述功能的基础部分:
# 对高光谱数据 X 应用 PCA 变换
def applyPCA(X, numComponents):
newX = np.reshape(X, (-1, X.shape[2]))
pca = PCA(n_components=numComponents, whiten=True)
newX = pca.fit_transform(newX)
newX = np.reshape(newX, (X.shape[0], X.shape[1], numComponents))
return newX
# 对单个像素周围提取 patch 时,边缘像素就无法取了,因此,给这部分像素进行 padding 操作
def padWithZeros(X, margin=2):
newX = np.zeros((X.shape[0] + 2 * margin, X.shape[1] + 2* margin, X.shape[2]))
x_offset = margin
y_offset = margin
newX[x_offset:X.shape[0] + x_offset, y_offset:X.shape[1] + y_offset, :] = X
return newX
# 在每个像素周围提取 patch ,然后创建成符合 keras 处理的格式
def createImageCubes(X, y, windowSize=5, removeZeroLabels = True):
# 给 X 做 padding
margin = int((windowSize - 1) / 2)
zeroPaddedX = padWithZeros(X, margin=margin)
# split patches
patchesData = np.zeros((X.shape[0] * X.shape[1], windowSize, windowSize, X.shape[2]))
patchesLabels = np.zeros((X.shape[0] * X.shape[1]))
patchIndex = 0
for r in range(margin, zeroPaddedX.shape[0] - margin):
for c in range(margin, zeroPaddedX.shape[1] - margin):
patch = zeroPaddedX[r - margin:r + margin + 1, c - margin:c + margin + 1]
patchesData[patchIndex, :, :, :] = patch
patchesLabels[patchIndex] = y[r-margin, c-margin]
patchIndex = patchIndex + 1
if removeZeroLabels:
patchesData = patchesData[patchesLabels>0,:,:,:]
patchesLabels = patchesLabels[patchesLabels>0]
patchesLabels -= 1
return patchesData, patchesLabels
def splitTrainTestSet(X, y, testRatio, randomState=345):
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=testRatio, random_state=randomState, stratify=y)
return X_train, X_test, y_train, y_test
读取并创建数据集:
# 地物类别
class_num = 16
X = sio.loadmat('Indian_pines_corrected.mat')['indian_pines_corrected']
y = sio.loadmat('Indian_pines_gt.mat')['indian_pines_gt']
# 用于测试样本的比例
test_ratio = 0.90
# 每个像素周围提取 patch 的尺寸
patch_size = 25
# 使用 PCA 降维,得到主成分的数量
pca_components = 30
print('Hyperspectral data shape: ', X.shape)
print('Label shape: ', y.shape)
print('\n... ... PCA tranformation ... ...')
X_pca = applyPCA(X, numComponents=pca_components)
print('Data shape after PCA: ', X_pca.shape)
print('\n... ... create data cubes ... ...')
X_pca, y = createImageCubes(X_pca, y, windowSize=patch_size)
print('Data cube X shape: ', X_pca.shape)
print('Data cube y shape: ', y.shape)
print('\n... ... create train & test data ... ...')
Xtrain, Xtest, ytrain, ytest = splitTrainTestSet(X_pca, y, test_ratio)
print('Xtrain shape: ', Xtrain.shape)
print('Xtest shape: ', Xtest.shape)
# 改变 Xtrain, Ytrain 的形状,以符合 keras 的要求
Xtrain = Xtrain.reshape(-1, patch_size, patch_size, pca_components, 1)
Xtest = Xtest.reshape(-1, patch_size, patch_size, pca_components, 1)
print('before transpose: Xtrain shape: ', Xtrain.shape)
print('before transpose: Xtest shape: ', Xtest.shape)
# 为了适应 pytorch 结构,数据要做 transpose
Xtrain = Xtrain.transpose(0, 4, 3, 1, 2)
Xtest = Xtest.transpose(0, 4, 3, 1, 2)
print('after transpose: Xtrain shape: ', Xtrain.shape)
print('after transpose: Xtest shape: ', Xtest.shape)
""" Training dataset"""
class TrainDS(torch.utils.data.Dataset):
def __init__(self):
self.len = Xtrain.shape[0]
self.x_data = torch.FloatTensor(Xtrain)
self.y_data = torch.LongTensor(ytrain)
def __getitem__(self, index):
# 根据索引返回数据和对应的标签
return self.x_data[index], self.y_data[index]
def __len__(self):
# 返回文件数据的数目
return self.len
""" Testing dataset"""
class TestDS(torch.utils.data.Dataset):
def __init__(self):
self.len = Xtest.shape[0]
self.x_data = torch.FloatTensor(Xtest)
self.y_data = torch.LongTensor(ytest)
def __getitem__(self, index):
# 根据索引返回数据和对应的标签
return self.x_data[index], self.y_data[index]
def __len__(self):
# 返回文件数据的数目
return self.len
# 创建 trainloader 和 testloader
trainset = TrainDS()
testset = TestDS()
train_loader = torch.utils.data.DataLoader(dataset=trainset, batch_size=128, shuffle=True, num_workers=2)
test_loader = torch.utils.data.DataLoader(dataset=testset, batch_size=128, shuffle=False, num_workers=2)
# 使用GPU训练,可以在菜单 "代码执行工具" -> "更改运行时类型" 里进行设置
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# 网络放到GPU上
net = HybridSN().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=0.001)#设置学习率
# 计时
import time
time_start=time.time()
# 开始训练
total_loss = 0
for epoch in range(100):
for i, (inputs, labels) in enumerate(train_loader):
inputs = inputs.to(device)
labels = labels.to(device)
# 优化器梯度归零
optimizer.zero_grad()
# 正向传播 + 反向传播 + 优化
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
total_loss += loss.item()
print('[Epoch: %d] [loss avg: %.4f] [current loss: %.4f]' %(epoch + 1, total_loss/(epoch+1), loss.item()))
time_end=time.time()
print('totally cost',time_end-time_start)
print('Finished Training')
#训练完了,开始模型测试
count = 0
# 模型测试
for inputs, _ in test_loader:
inputs = inputs.to(device)
outputs = net(inputs)
outputs = np.argmax(outputs.detach().cpu().numpy(), axis=1)
if count == 0:
y_pred_test = outputs
count = 1
else:
y_pred_test = np.concatenate( (y_pred_test, outputs) )
# 生成分类报告
classification = class
个人感觉,在本代码中只有
可以优化,故做了以下实验:
#这里是优化的方向
#软最大化
#self.soft = nn.LogSoftmax(dim=1)
self.soft = nn.Softmax(dim=1)
#加入BN归一化数据
#self.bn1=nn.BatchNorm3d(8)
#self.bn2=nn.BatchNorm3d(16)
#self.bn3=nn.BatchNorm3d(32)
#self.bn4=nn.BatchNorm2d(64)
#这里是优化的方向
#软最大化
self.soft = nn.LogSoftmax(dim=1)
#self.soft = nn.Softmax(dim=1)
#加入BN归一化数据
#self.bn1=nn.BatchNorm3d(8)
#self.bn2=nn.BatchNorm3d(16)
#self.bn3=nn.BatchNorm3d(32)
#self.bn4=nn.BatchNorm2d(64)
#这里是优化的方向
#软最大化
self.soft = nn.LogSoftmax(dim=1)
#self.soft = nn.Softmax(dim=1)
#加入BN归一化数据
self.bn1=nn.BatchNorm3d(8)
self.bn2=nn.BatchNorm3d(16)
self.bn3=nn.BatchNorm3d(32)
self.bn4=nn.BatchNorm2d(64)
def forward(self, x):
out = self.relu(self.conv1(x))
out = self.bn1(out)#BN层
out = self.relu(self.conv2(out))
out = self.bn2(out)#BN层
out = self.relu(self.conv3(out))
out = self.bn3(out)#BN层
# 进行二维卷积,因此把前面的 32*18 reshape 一下,得到 (576, 19, 19)
out = out.view(-1, out.shape[1] * out.shape[2], out.shape[3], out.shape[4])
out = self.relu(self.conv3_2d(out))
out = self.bn4(out)#BN层
# flatten 操作,变为 18496 维的向量,
out = out.view(out.size(0), -1)
out = self.dense1(out)
out = self.drop(out)
out = self.dense2(out)
out = self.drop(out)
out = self.out(out)
out = self.soft(out)
return out
所以我得出结论:
2D卷积:
二维卷积大家都很熟悉,就是通常所用到的“普通”卷积,其卷积过程见下图:
个人理解:
3D卷积:
三维卷积类似于下图(坐标轴的注释与本文无关):
(1)神经网络算法初始化随机权重,因此用同样的数据训练同一个网络会得到不同的结果。
(2)个人感觉,在网络中,还能牵扯到随机性的部分,就是那个Dropout了。在训练模式中,采用了Dropout使得网络在训练的时候,抗噪声能力更强,防止过拟合。但是在测试模型的时候,随机的drop,就会导致最终结果的不一致。为了解决这个问题,在训练模型的时候要加上model.train()开启drop;在测试模型的时候加上model.eval()关掉drop,以此来保持结果一致。
注意力机制的加入,相当于让网络对某些特征有了更高的权重,使网络更加有侧重的学习,以此提高网络的学习能力。
我在第一个2D卷积之前添加了一层注意力机制来试试效果
##重新定义增加了注意力机制的HybridSN 类
class_num = 16
# 通道注意力机制
class ChannelAttention(nn.Module):
def __init__(self, in_planes, ratio=16):
super(ChannelAttention, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.max_pool = nn.AdaptiveMaxPool2d(1)
self.fc1 = nn.Conv2d(in_planes, in_planes // 16, 1, bias=False)
self.relu1 = nn.ReLU()
self.fc2 = nn.Conv2d(in_planes // 16, in_planes, 1, bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
avg_out = self.fc2(self.relu1(self.fc1(self.avg_pool(x))))
max_out = self.fc2(self.relu1(self.fc1(self.max_pool(x))))
out = avg_out + max_out
return self.sigmoid(out)
# 空间注意力机制
class SpatialAttention(nn.Module):
def __init__(self, kernel_size=7):
super(SpatialAttention, self).__init__()
assert kernel_size in (3, 7), 'kernel size must be 3 or 7'
padding = 3 if kernel_size == 7 else 1
self.conv1 = nn.Conv2d(2, 1, kernel_size, padding=padding, bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
avg_out = torch.mean(x, dim=1, keepdim=True)
max_out, _ = torch.max(x, dim=1, keepdim=True)
x = torch.cat([avg_out, max_out], dim=1)
x = self.conv1(x)
return self.sigmoid(x)
class HybridSN(nn.Module):
def __init__(self, num_classes=16):
super(HybridSN, self).__init__()
self.conv1 = nn.Sequential(nn.Conv3d(1, 8, (7, 3, 3)), nn.BatchNorm3d(8), nn.ReLU())
self.conv2 = nn.Sequential(nn.Conv3d(8, 16, (5, 3, 3)), nn.BatchNorm3d(16), nn.ReLU())
self.conv3 = nn.Sequential(nn.Conv3d(16, 32, (3, 3, 3)), nn.BatchNorm3d(32), nn.ReLU())
self.conv3_2d = nn.Sequential(nn.Conv2d(576, 64, (3,3)), nn.BatchNorm2d(64), nn.ReLU())
self.dense1 = nn.Linear(18496,256)
self.dense2 = nn.Linear(256,128)
self.out = nn.Linear(128, num_classes)
self.drop = nn.Dropout(p=0.4)
self.soft = nn.LogSoftmax(dim=1)
self.relu = nn.ReLU()
self.channel_attention_1 = ChannelAttention(576)
self.spatial_attention_1 = SpatialAttention(kernel_size=7)
self.channel_attention_2 = ChannelAttention(64)
self.spatial_attention_2 = SpatialAttention(kernel_size=7)
def forward(self, x):
out = self.relu(self.conv1(x))
out = self.relu(self.conv2(out))
out = self.relu(self.conv3(out))
# 进行二维卷积,因此把前面的 32*18 reshape 一下,得到 (576, 19, 19)
out = out.view(-1, out.shape[1] * out.shape[2], out.shape[3], out.shape[4])
out = self.channel_attention_1(out) * out
out = self.spatial_attention_1(out) * out
out = self.relu(self.conv3_2d(out))
# flatten 操作,变为 18496 维的向量,
out = out.view(out.size(0), -1)
out = self.dense1(out)
out = self.drop(out)
out = self.dense2(out)
out = self.drop(out)
out = self.out(out)
out = self.soft(out)
return out
个人感觉,: