欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

在 pytorch EN 中询问矩阵和向量之间的加法/减法问题

最编程 2024-05-22 11:50:05
...

要使用广播,您需要

推广

张量的维数

从张量到二维

是二维的。

代码语言:javascript
复制
In [43]: a
Out[43]: 
tensor([[ 0.9455,  0.2088,  0.1070],
        [ 0.0823,  0.6509,  0.1171]])

In [44]: b
Out[44]: tensor([ 0.4321,  0.8250])

# subtraction    
In [46]: a - b[:, None]
Out[46]: 
tensor([[ 0.5134, -0.2234, -0.3252],
        [-0.7427, -0.1741, -0.7079]])

# alternative way to do subtraction
In [47]: a.sub(b[:, None])
Out[47]: 
tensor([[ 0.5134, -0.2234, -0.3252],
        [-0.7427, -0.1741, -0.7079]])

# yet another approach
In [48]: torch.sub(a, b[:, None])
Out[48]: 
tensor([[ 0.5134, -0.2234, -0.3252],
        [-0.7427, -0.1741, -0.7079]])

其他操作(

)可以类似地完成。

在性能方面,使用一种方法似乎比使用其他方法没有优势。只需使用这三种方法中的任何一种。

代码语言:javascript
复制
In [49]: a = torch.rand(2000, 3000)
In [50]: b = torch.rand(2000)

In [51]: %timeit torch.sub(a, b[:, None])
2.4 ms ± 8.31 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [52]: %timeit a.sub(b[:, None])
2.4 ms ± 6.94 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [53]: %timeit a - b[:, None]
2.4 ms ± 12 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

推荐阅读