Search code examples
pythonnumpypytorchsparse-matrix

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.

So for example the matrix below would be a window=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.

Has anyone got any ideas, this is to be used as a mask.


Solution

  • Pytorch provides the tensor.diagonal method, which gives you access to any diagonal of a tensor. To assign a value to the resulting view of your tensor, you can use 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