简体   繁体   中英

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.

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 usetensor.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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