学术
模块更新于 2026-11-20· 浏览 1· 下载 0

SpeKAN KAN光谱注意力模块

双池化样条精炼:同时做全局平均池化和全局最大池化,两路各过两层 KAN(可学习 B 样条激活)精炼,再由一层对齐 KAN 融合出通道重要性分数,逐通道加权输出

计算机视觉高光谱图像图像超分辨率SpeKANKANICASSP2025

结构图

SpeKAN KAN光谱注意力模块结构图
SpeKAN KAN光谱注意力模块结构图

双池化样条精炼:同时做全局平均池化和全局最大池化,两路各过两层 KAN(可学习 B 样条激活)精炼,再由一层对齐 KAN 融合出通道重要性分数,逐通道加权输出

论文信息

  • 论文:KSSANet: KAN-Driven Spatial-Spectral Attention Networks for Hyperspectral Image Super-Resolution
  • 出处:ICASSP 2025

核心痛点

高光谱图像超分中,CNN 感受野有限,难以重建长程光谱信息;Transformer 自注意力复杂度达 O(n²),高维 HSI 开销大、依赖大量训练数据,而高光谱样本稀缺;SE 类通道注意力靠池化加固定激活线性层打分,缺少局部塑性。

模块亮点

  • 双池化样条精炼:同时做全局平均池化和全局最大池化,两路各过两层 KAN(可学习 B 样条激活)精炼,再由一层对齐 KAN 融合出通道重要性分数,逐通道加权输出
  • 消融实打实:Chikusei ×4 上把 SpeKAN 换成 SSPSR 的光谱注意力残差模块,PSNR 从 41.02 dB 跌到 34.26 dB;KAN 层全换线性层也跌到 38.14 dB
  • 整体又轻又准:KSSANet 以 4.92M 参数、20.15G MACs 在 Chikusei ×4 拿到 41.02 dB,优于 11.1M 参数、48.65G MACs 的 ESSAFormer

适用场景

领域为高光谱图像超分辨率;原文在 Chikusei、Pavia Center、CAVE 验证了 ×2、×4、×8 超分;可迁移到高光谱去噪、光谱重建、分类等任务和需要通道注意力的视觉网络。

插入位置建议

  • 直接替换 SE、ECA 等通道注意力,放在卷积层或残差块之后
  • 与空间注意力串联组成双注意力块,原文 SSAB 就是 KAN-SpaAB 后接 SpeKAN
  • 放进级联复原网络基本块,原文 KSSANet 连堆 8 个 SSAB

适用任务

  • 高光谱图像超分辨率

完整代码

spekan.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from einops import rearrange


"""《KSSANet: KAN-Driven Spatial-Spectral Attention Networks for Hyperspectral Image Super-Resolution》 ICASSP 2025
由于物理成像的局限性,获取高分辨率高光谱图像(HR-HSI)一直是一项重大挑战。单幅高光谱图像超分辨率(SHSR)技术旨在通过处理低分辨率高光谱图像(LR-HSI)生成相应的HR-HSI。
与多源数据融合方法相比,SHSR仅依赖于单幅低分辨率图像,无需额外的辅助信息或多模态数据,使其在数据获取方面更加灵活高效。
近年来,源自Kolmogorov-Arnold表示定理的Kolmogorov-Arnold网络(KAN)在长程依赖关系建模方面展现出巨大潜力。本文进一步研究了KAN在高光谱图像复原中的潜力。
具体而言,我们提出了一个空间-光谱注意模块(SSAB),该模块包含一个基于KAN的空间注意模块(KAN-SpaAB)和一个基于KAN的光谱注意模块(KAN-SpeAB),分别用于恢复空间和光谱信息。
实验结果表明,KSSANet在定量评估和图像生成质量方面均优于现有方法,达到了当前最佳(SOTA)的性能。
"""

class KANLinear(torch.nn.Module):
    def __init__(
            self,
            in_features,
            out_features,
            grid_size=5,
            spline_order=3,
            scale_noise=0.1,
            scale_base=1.0,
            scale_spline=1.0,
            enable_standalone_scale_spline=True,
            base_activation=torch.nn.SiLU,
            grid_eps=0.02,
            grid_range=[-1, 1],
    ):
        super(KANLinear, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.grid_size = grid_size
        self.spline_order = spline_order

        h = (grid_range[1] - grid_range[0]) / grid_size
        grid = (
            (
                    torch.arange(-spline_order, grid_size + spline_order + 1) * h
                    + grid_range[0]
            )
                .expand(in_features, -1)
                .contiguous()
        )
        self.register_buffer("grid", grid)

        self.base_weight = torch.nn.Parameter(torch.Tensor(out_features, in_features))
        self.spline_weight = torch.nn.Parameter(
            torch.Tensor(out_features, in_features, grid_size + spline_order)
        )
        if enable_standalone_scale_spline:
            self.spline_scaler = torch.nn.Parameter(
                torch.Tensor(out_features, in_features)
            )

        self.scale_noise = scale_noise
        self.scale_base = scale_base
        self.scale_spline = scale_spline
        self.enable_standalone_scale_spline = enable_standalone_scale_spline
        self.base_activation = base_activation()
        self.grid_eps = grid_eps

        self.reset_parameters()

    def reset_parameters(self):
        torch.nn.init.kaiming_uniform_(self.base_weight, a=math.sqrt(5) * self.scale_base)
        with torch.no_grad():
            noise = (
                    (
                            torch.rand(self.grid_size + 1, self.in_features, self.out_features)
                            - 1 / 2
                    )
                    * self.scale_noise
                    / self.grid_size
            )
            self.spline_weight.data.copy_(
                (self.scale_spline if not self.enable_standalone_scale_spline else 1.0)
                * self.curve2coeff(
                    self.grid.T[self.spline_order: -self.spline_order],
                    noise,
                )
            )
            if self.enable_standalone_scale_spline:
                # torch.nn.init.constant_(self.spline_scaler, self.scale_spline)
                torch.nn.init.kaiming_uniform_(self.spline_scaler, a=math.sqrt(5) * self.scale_spline)

    def b_splines(self, x: torch.Tensor):
        assert x.dim() == 2 and x.size(1) == self.in_features

        grid: torch.Tensor = (
            self.grid
        )  # (in_features, grid_size + 2 * spline_order + 1)
        x = x.unsqueeze(-1)
        bases = ((x >= grid[:, :-1]) & (x < grid[:, 1:])).to(x.dtype)
        for k in range(1, self.spline_order + 1):
            bases = (
                            (x - grid[:, : -(k + 1)])
                            / (grid[:, k:-1] - grid[:, : -(k + 1)])
                            * bases[:, :, :-1]
                    ) + (
                            (grid[:, k + 1:] - x)
                            / (grid[:, k + 1:] - grid[:, 1:(-k)])
                            * bases[:, :, 1:]
                    )

        assert bases.size() == (
            x.size(0),
            self.in_features,
            self.grid_size + self.spline_order,
        )
        return bases.contiguous()

    def curve2coeff(self, x: torch.Tensor, y: torch.Tensor):
        """
        Compute the coefficients of the curve that interpolates the given points.

        Args:
            x (torch.Tensor): Input tensor of shape (batch_size, in_features).
            y (torch.Tensor): Output tensor of shape (batch_size, in_features, out_features).

        Returns:
            torch.Tensor: Coefficients tensor of shape (out_features, in_features, grid_size + spline_order).
        """
        assert x.dim() == 2 and x.size(1) == self.in_features
        assert y.size() == (x.size(0), self.in_features, self.out_features)

        A = self.b_splines(x).transpose(
            0, 1
        )  # (in_features, batch_size, grid_size + spline_order)
        B = y.transpose(0, 1)  # (in_features, batch_size, out_features)
        solution = torch.linalg.lstsq(
            A, B
        ).solution  # (in_features, grid_size + spline_order, out_features)
        result = solution.permute(
            2, 0, 1
        )  # (out_features, in_features, grid_size + spline_order)

        assert result.size() == (
            self.out_features,
            self.in_features,
            self.grid_size + self.spline_order,
        )
        return result.contiguous()

    @property
    def scaled_spline_weight(self):
        return self.spline_weight * (
            self.spline_scaler.unsqueeze(-1)
            if self.enable_standalone_scale_spline
            else 1.0
        )

    def forward(self, x: torch.Tensor):
        assert x.size(-1) == self.in_features
        original_shape = x.shape
        x = x.reshape(-1, self.in_features)

        base_output = F.linear(self.base_activation(x), self.base_weight)
        spline_output = F.linear(
            self.b_splines(x).view(x.size(0), -1),
            self.scaled_spline_weight.view(self.out_features, -1),
        )
        output = base_output + spline_output

        output = output.reshape(*original_shape[:-1], self.out_features)
        return output

    @torch.no_grad()
    def update_grid(self, x: torch.Tensor, margin=0.01):
        assert x.dim() == 2 and x.size(1) == self.in_features
        batch = x.size(0)

        splines = self.b_splines(x)  # (batch, in, coeff)
        splines = splines.permute(1, 0, 2)  # (in, batch, coeff)
        orig_coeff = self.scaled_spline_weight  # (out, in, coeff)
        orig_coeff = orig_coeff.permute(1, 2, 0)  # (in, coeff, out)
        unreduced_spline_output = torch.bmm(splines, orig_coeff)  # (in, batch, out)
        unreduced_spline_output = unreduced_spline_output.permute(
            1, 0, 2
        )  # (batch, in, out)

        # sort each channel individually to collect data distribution
        x_sorted = torch.sort(x, dim=0)[0]
        grid_adaptive = x_sorted[
            torch.linspace(
                0, batch - 1, self.grid_size + 1, dtype=torch.int64, device=x.device
            )
        ]

        uniform_step = (x_sorted[-1] - x_sorted[0] + 2 * margin) / self.grid_size
        grid_uniform = (
                torch.arange(
                    self.grid_size + 1, dtype=torch.float32, device=x.device
                ).unsqueeze(1)
                * uniform_step
                + x_sorted[0]
                - margin
        )

        grid = self.grid_eps * grid_uniform + (1 - self.grid_eps) * grid_adaptive
        grid = torch.concatenate(
            [
                grid[:1]
                - uniform_step
                * torch.arange(self.spline_order, 0, -1, device=x.device).unsqueeze(1),
                grid,
                grid[-1:]
                + uniform_step
                * torch.arange(1, self.spline_order + 1, device=x.device).unsqueeze(1),
            ],
            dim=0,
        )

        self.grid.copy_(grid.T)
        self.spline_weight.data.copy_(self.curve2coeff(x, unreduced_spline_output))

    def regularization_loss(self, regularize_activation=1.0, regularize_entropy=1.0):
        """
        Compute the regularization loss.

        This is a dumb simulation of the original L1 regularization as stated in the
        paper, since the original one requires computing absolutes and entropy from the
        expanded (batch, in_features, out_features) intermediate tensor, which is hidden
        behind the F.linear function if we want an memory efficient implementation.

        The L1 regularization is now computed as mean absolute value of the spline
        weights. The authors implementation also includes this term in addition to the
        sample-based regularization.
        """
        l1_fake = self.spline_weight.abs().mean(-1)
        regularization_loss_activation = l1_fake.sum()
        p = l1_fake / regularization_loss_activation
        regularization_loss_entropy = -torch.sum(p * p.log())
        return (
                regularize_activation * regularization_loss_activation
                + regularize_entropy * regularization_loss_entropy
        )


class SpeKAN(nn.Module):
    def __init__(self, dim, scale):
        super(SpeKAN, self).__init__()
        self.dim = dim
        self.scale = scale
        self.avg_kan01 = KANLinear(dim, dim)
        self.avg_kan02 = KANLinear(dim, dim)
        self.max_kan01 = KANLinear(dim, dim)
        self.max_kan02 = KANLinear(dim, dim)
        self.sum_kan = KANLinear(dim * 2, dim)

    def forward(self, x):
        avg_score = F.adaptive_avg_pool2d(x, (1, 1))
        avg_score = rearrange(avg_score, 'b c 1 1 -> b c')
        avg_score = self.avg_kan01(avg_score)
        avg_score = self.avg_kan02(avg_score)
        max_score = F.adaptive_max_pool2d(x, (1, 1))
        max_score = rearrange(max_score, 'b c 1 1 -> b c')
        max_score = self.max_kan01(max_score)
        max_score = self.max_kan02(max_score)
        score = self.sum_kan(torch.cat([avg_score, max_score], dim=1))
        score = rearrange(score, 'b c -> b c 1 1')
        x = x * score + x
        return x


if __name__ == '__main__':
    block = SpeKAN(dim=64, scale=1.0).to('cuda')
    input = torch.rand(1, 64, 64, 64).to('cuda')
    output = block(input)
    print(input.size())
    print(output.size())




环境与依赖

Python 3.9+

继续浏览

下一篇SSPCAB 自监督预测卷积注意力模块重建写进卷积核:感受野中心被遮挡、只保留四角子核,逼网络用上下文"脑补"中心信息;膨胀率 d 控制上下文从局部到全局

相关资源