【问题标题】:Is there a way to compute a circulant matrix in Pytorch?有没有办法在 Pytorch 中计算循环矩阵?
【发布时间】:2021-11-03 06:52:29
【问题描述】:

我想要一个类似于https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.circulant.html 的函数来使用 PyTorch 创建一个循环矩阵。我需要它作为我的深度学习模型的一部分(为了减少我的一些全连接层中的过度参数化,如https://arxiv.org/abs/1907.08448(图 3)中所建议的那样)

函数的输入为一维torch张量,输出为二维循环矩阵。

【问题讨论】:

标签: pytorch


【解决方案1】:

您可以使用unfold 来提取滑动窗口。但要获得正确的顺序,您需要翻转(稍后取消翻转)张量,并首先将翻转的张量连接到自身。

circ=lambda v:torch.cat([f:=v.flip(0),f[:-1]]).unfold(0,len(v),1).flip(0)

【讨论】:

    【解决方案2】:

    这是 pytorch 张量的通用函数,用于获取一维的循环矩阵。它基于unfold,适用于二维循环矩阵或高维张量。

    def circulant(tensor, dim):
        """get a circulant version of the tensor along the {dim} dimension.
        
        The additional axis is appended as the last dimension.
        E.g. tensor=[0,1,2], dim=0 --> [[0,1,2],[2,0,1],[1,2,0]]"""
        S = tensor.shape[dim]
        tmp = torch.cat([tensor.flip((dim,)), torch.narrow(tensor.flip((dim,)), dim=dim, start=0, length=S-1)], dim=dim)
        return tmp.unfold(dim, S, 1).flip((-1,))
    

    本质上,这是 scipy.linalg.circulant 的 PyTorch 版本,适用于多维张量。

    还有一个类似的问题:Create array/tensor of cycle shifted arrays

    【讨论】:

      猜你喜欢
      • 2023-02-18
      • 1970-01-01
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      • 2013-01-11
      • 2012-06-19
      • 1970-01-01
      相关资源
      最近更新 更多