简体   繁体   English

Pytorch/Numpy:从单个矩阵中减去 N 个元素中的每一个,得到 N 个矩阵?

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

Question in the title.标题中的问题。 Is there an operation or way to broadcast to do this without looping?有没有一种操作或方法可以在不循环的情况下进行广播? Here's a simple example with list comprehension:这是一个带有列表理解的简单示例:

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]]])

I've tried reshaping the "scalar array" every which way to get the desired results with no luck.我尝试过重塑“标量数组”,以各种方式获得所需的结果,但没有运气。

Not sure if torch has outer :不确定torch是否有outer

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

Output:输出:

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

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

In torch, you can flatten the two tensors and reshape:在 Torch 中,您可以展平两个张量并重塑:

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

Output:输出:

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