import torch
# ----------加法运算----------
a = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = torch.tensor([[10, 10, 10], [10, 10, 10], [10, 10, 10]])
print(a)
print(b)
# tensor([[1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]])
# tensor([[10, 10, 10],
# [10, 10, 10],
# [10, 10, 10]])
print(a + 100)
# tensor([[101, 102, 103],
# [104, 105, 106],
# [107, 108, 109]])
print(a + b)
# tensor([[11, 12, 13],
# [14, 15, 16],
# [17, 18, 19]])
print(a.add(b)) # a的值不会发生改变
# tensor([[11, 12, 13],
# [14, 15, 16],
# [17, 18, 19]])
print(a.add_(b)) # 带下划线的方式会改变a的值,即a.add_(b)等价于a=a+b
# tensor([[11, 12, 13],
# [14, 15, 16],
# [17, 18, 19]])
print("a发生改变:\n", a)
# a发生改变:
# tensor([[11, 12, 13],
# [14, 15, 16],
# [17, 18, 19]])
# ----------减法运算----------
a = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = torch.tensor([[10, 10, 10], [10, 10, 10], [10, 10, 10]])
print(b - a)
print(torch.sub(b, a))
print(b.sub(a))
print(b.sub_(a)) # 会将结果赋值给b
# tensor([[9, 8, 7],
# [6, 5, 4],
# [3, 2, 1]])
# ----------乘法运算----------
# 相乘的Tensor必须维度完全相同,并且对应的结果为对应元素相乘
a = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = torch.tensor([[10, 10, 10], [10, 10, 10], [10, 10, 10]])
print(a * b)
print(torch.mul(a, b))
print(a.mul(b))
print(a.mul_(b)) # a的值会发生改变
print(a)
# tensor([[110, 120, 130],
# [140, 150, 160],
# [170, 180, 190]])
# ----------除法运算----------
a = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float)
b = torch.tensor([[2, 4, 6], [8, 10, 12], [14, 16, 18]], dtype=torch.float)
print(b / a)
print(torch.div(b, a))
print(b.div(a))
print(b.div_(a)) # 会将结果赋值给b
# tensor([[2., 2., 2.],
# [2., 2., 2.],
# [2., 2., 2.]])
# # ----------矩阵运算----------
a = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = torch.tensor([[10, 10, 10], [10, 10, 10], [10, 10, 10]])
print(a @ b) # 矩阵相乘
print(a.mm(b))
print(a.matmul(b)) # 矩阵相乘
print(torch.mm(a, b)) # 矩阵相乘
print(torch.matmul(a, b)) # 矩阵相乘
# tensor([[ 60, 60, 60],
# [150, 150, 150],
# [240, 240, 240]])
# 对于高维度的Tensor(dim>2),定义其矩阵乘法仅在最后的两个维度上,要求前面的维度必须保持一致, 运算操作只有torch.matmul()
c = torch.ones(1, 2, 3, 4)
d = torch.ones(1, 2, 4, 3)
print(c)
print(d)
# tensor([[[[1., 1., 1., 1.],
# [1., 1., 1., 1.],
# [1., 1., 1., 1.]],
#
# [[1., 1., 1., 1.],
# [1., 1., 1., 1.],
# [1., 1., 1., 1.]]]])
# tensor([[[[1., 1., 1.],
# [1., 1., 1.],
# [1., 1., 1.],
# [1., 1., 1.]],
#
# [[1., 1., 1.],
# [1., 1., 1.],
# [1., 1., 1.],
# [1., 1., 1.]]]])
print(c.matmul(d))
# tensor([[[[4., 4., 4.],
# [4., 4., 4.],
# [4., 4., 4.]],
#
# [[4., 4., 4.],
# [4., 4., 4.],
# [4., 4., 4.]]]])
PyTorch--Tensor算术运算
最新推荐文章于 2024-11-17 16:43:54 发布