张量之间可以进行运算,例如加减乘除。
下面将举例说明常用的运算:
- 调整张量形状
- 张量的加减乘除
- 求张量的平均值,标准差等等
# 创建 tensor
tensor = torch.ones(3,3)
print("\n",tensor)
# 调整形状
print("{}{}\n".format(tensor.view(9).shape,tensor.view(9)))
# 加法
print("Addition: {}\n".format(torch.add(tensor,tensor)))
# 减法
print("Subtraction: {}\n".format(tensor.sub(tensor)))
# 元素相乘
print("Element wise multiplication: {}\n".format(torch.mul(tensor,tensor)))
# 元素相除
print("Element wise division: {}\n".format(torch.div(tensor,tensor)))
# 平均值
tensor = torch.Tensor([1,2,3,4,5])
print("Mean: {}".format(tensor.mean()))
# 标准差
print("std: {}".format(tensor.std()))
输出
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
torch.Size([9])tensor([1., 1., 1., 1., 1., 1., 1., 1., 1.])
Addition: tensor([[2., 2., 2.],
[2., 2., 2.],
[2., 2., 2.]])
Subtraction: tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
Element wise multiplication: tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
Element wise division: tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
Mean: 3.0
std: 1.5811388492584229