簡體   English   中英

Pytorch/Numpy:從單個矩陣中減去 N 個元素中的每一個,得到 N 個矩陣?

[英]Pytorch/Numpy: Subtract each of N elements from a single matrix, resulting in N matrices?

標題中的問題。 有沒有一種操作或方法可以在不循環的情況下進行廣播? 這是一個帶有列表理解的簡單示例:

image = torch.tensor([[6, 9], [8.7, 5.5]])
c = torch.tensor([5.7675, 8.8325])

# with list comprehension
desired_result = torch.stack([image - c_i for c_i in c])

# output:
tensor([[[ 0.2325,  3.2325],
         [ 2.9325, -0.2675]],

        [[-2.8325,  0.1675],
         [-0.1325, -3.3325]]])

我嘗試過重塑“標量數組”,以各種方式獲得所需的結果,但沒有運氣。

不確定torch是否有outer

- np.subtract.outer(c.numpy(), image.numpy() )

輸出:

array([[[ 0.23250008,  3.2325    ],
        [ 2.9325    , -0.26749992]],

       [[-2.8325005 ,  0.16749954],
        [-0.13250065, -3.3325005 ]]], dtype=float32)

在 Torch 中,您可以展平兩個張量並重塑:

-(c[:,None] - image.ravel()).reshape(*c.shape, *image.shape)

輸出:

tensor([[[ 0.2325,  3.2325],
         [ 2.9325, -0.2675]],

        [[-2.8325,  0.1675],
         [-0.1325, -3.3325]]])

暫無
暫無

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

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