【问题标题】:Is there any way to create a tensor with a specific pattern in Pytorch?有什么方法可以在 Pytorch 中创建具有特定模式的张量?
【发布时间】:2021-11-02 11:39:50
【问题描述】:

我正在使用 Y=Q(X+A) 形式的线性变换,其中 X 是输入张量,Y 是输出,Q 和 A 是要学习的两个张量。 Q 是一个任意张量,因此我可以使用nn.Linear。但是 A 是一个(可微的)张量,它有一些特定的模式,作为一个简短的例子,

A = [[a0,a1,a2,a2,a2], 
     [a1,a0,a1,a2,a2],
     [a2,a1,a0,a1,a2],
     [a2,a2,a1,a0,a1],
     [a2,a2,a2,a1,a0]]. 

所以我无法在nn.Linear 中定义这样的模式。有没有办法在 Pytorch 中定义这样的张量?

【问题讨论】:

    标签: pytorch tensor


    【解决方案1】:

    这看起来像Toeplitz matrix。 PyTorch 中一个可能的实现是:

    def toeplitz(c, r):
        vals = torch.cat((r, c[1:].flip(0)))
        shape = len(c), len(r)
        i, j = torch.ones(*shape).nonzero().T
        return vals[j-i].reshape(*shape)
    

    在您的情况下,a00a11a22

    >>> toeplitz(torch.tensor([0,1,2,2,2]), torch.tensor([0,1,2,2,2]))
    tensor([[0, 1, 2, 2, 2],
            [1, 0, 1, 2, 2],
            [2, 1, 0, 1, 2],
            [2, 2, 1, 0, 1],
            [2, 2, 2, 1, 0]])
    

    更详细的解释请参考我的另一个回答here

    【讨论】:

    • 我想在反向传播过程中同时更新所有同名元素。比如一步之后,所有a0还是一样的。
    • @Zouzou 好问题,这个答案确实会复制a0a1,......因为索引会复制。我不相信您可以进行选择并返回原始数据的视图。
    猜你喜欢
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 2019-06-03
    • 2019-04-19
    • 2020-11-01
    • 2011-09-06
    • 2021-07-31
    相关资源
    最近更新 更多