簡體   English   中英

關於如何有效地創建這個矩陣/掩碼的任何想法?

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

我想有效地制作一個火炬張量或 numpy 數組,該矩陣是一個 1s 的移位 window 矩陣。

因此,例如下面的矩陣將是一個窗口 = 3。 對角線元素右側有 3 個 1,左側有 3 個 1,但它不像循環矩陣那樣環繞,所以第 1 行只有 4 個 1。

有沒有人有任何想法,這是用作面具。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM