简体   繁体   English

关于如何有效地创建这个矩阵/掩码的任何想法?

[英]Any ideas on how to efficiently create this matrix/mask?

I want to make a torch tensor or numpy array efficiently of a matrix that is a shifting window of 1s.我想有效地制作一个火炬张量或 numpy 数组,该矩阵是一个 1s 的移位 window 矩阵。

So for example the matrix below would be a window=3.因此,例如下面的矩阵将是一个窗口 = 3。 The diagonal element has 3 1s to it's right, and 3 1s to it's left but it doesn't wrap round like a circulant matrix, so row 1 just has 4 1s.对角线元素右侧有 3 个 1,左侧有 3 个 1,但它不像循环矩阵那样环绕,所以第 1 行只有 4 个 1。

Has anyone got any ideas, this is to be used as a mask.有没有人有任何想法,这是用作面具。

Pytorch provides the tensor.diagonal method, which gives you access to any diagonal of a tensor. Pytorch 提供了tensor.diagonal方法,它使您可以访问张量的任何对角线。 To assign a value to the resulting view of your tensor, you can usetensor.copy_ .要将值分配给张量的结果视图,您可以使用tensor.copy_ That would give you something like:这会给你类似的东西:

def circulant(n, window):
    circulant_t = torch.zeros(n,n)
    # [0, 1, 2, ..., window, -1, -2, ..., window]
    offsets = [0] + [i for i in range(window)] + [-i for i in range(window)]
    for offset in offsets:
        #size of the 1-tensor depends on the length of the diagonal
        circulant_t.diagonal(offset=offset).copy_(torch.ones(n-abs(offset)))
    return circulant_t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM