输入如下代码:
import torch
a=torch.zeros(2,1)
b=torch.ones(1,3)
c=a+b
print("a=",a)
print("b=",b)
print("c=",c)
输出为:
a= tensor([[0.],
[0.]])
b= tensor([[1., 1., 1.]])
c= tensor([[1., 1., 1.],
[1., 1., 1.]])
加法的具体计算过程如下:
1、将a的形状扩展为(2,3)
a= tensor([[0., 0., 0.],
[0., 0., 0.]])
2、将b的形状扩展为(2,3)
b= tensor([[1., 1., 1.],
[1., 1., 1.]])
3、然后两个tensor对应位置的值相加得到最终结果
c= tensor([[1., 1., 1.],
[1., 1., 1.]])
注意事项
如下代码运行会出错,因为两个tensor的形状不匹配
import torch
a=torch.zeros(2,1)
b=torch.ones(3,1)
c=a+b
参考文章:https://blog.csdn.net/weixin_40952784/article/details/92575851