关于如何有效创建此 matrix/mask 的任何想法?

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

我想有效地制作一个矩阵的 torch 张量或 numpy 数组,该矩阵是 1s 的 window 移位。

因此,例如下面的矩阵将是 window=3。 对角线元素右边有 3 个 1,左边有 3 个 1,但它不像循环矩阵那样环绕,所以第 1 行只有 4 个 1。

有没有人有什么想法,这个是用来当面具的。

Pytorch 提供了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_。那会给你类似的东西:

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