关于如何有效地创建此矩阵/掩码,有什么想法吗?

2024-05-16 19:22:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想制作一个torch张量或numpy数组,它是一个1的移动窗口

例如,下面的矩阵是一个窗口=3。 对角线元素的右边有31秒,左边有31秒,但它不像循环矩阵那样环绕,所以第1行只有41秒

有人有什么想法吗,这是用来做面具的


Tags: numpy元素矩阵torch数组对角线面具
1条回答
网友
1楼 · 发布于 2024-05-16 19:22:01

Pytorch提供了tensor.diagonal方法,可以访问张量的任何对角线。要为张量的结果视图赋值,可以使用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

相关问题 更多 >