Tensor加法:
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])
c = a + b
print(c) # tensor([5, 7, 9])
c = torch.add(a, b)
print(c) # tensor([5, 7, 9])
c = a.add(b)
print(c) # tensor([5, 7, 9])
Tensor减法:
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])
c = a - b
print(c) # tensor([-3, -3, -3])
c = torch.sub(a, b)
print(c) # tensor([-3, -3, -3])
c = a.sub(b)
print(c) # tensor([-3, -3, -3])
Tensor乘法:
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])
c = a * b
print(c) # tensor([ 4, 10, 18])
c = torch.mul(a, b)
print(c) # tensor([ 4, 10, 18])
c = a.mul(b)
print(c) # tensor([ 4, 10, 18])
Tensor除法:
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])
c = a / b
print(c) # tensor([0.2500, 0.4000, 0.5000])
c = torch.div(a, b)
print(c) # tensor([0.2500, 0.4000, 0.5000])
c = a.div(b)
print(c) # tensor([0.2500, 0.4000, 0.5000])
Tensor矩阵乘法:
a = torch.tensor([[1, 2, 3], [4, 5, 6]]) # size: 2, 3
b = torch.full([3, 4], 2) # size: 3, 4
c = torch.matmul(a, b)
print(c) # tensor([[12, 12, 12, 12], [30, 30, 30, 30]]) size:2, 4
c = a.matmul(b)
print(c) # tensor([[12, 12, 12, 12], [30, 30, 30, 30]]) size:2, 4
若张量维数大于2,则对最后两维进行matmul。进行此运算的要求是张量a与b除最后两维外的其他维必须一致:文章来源地址https://www.toymoban.com/news/detail-522726.html
a = torch.full([3, 2, 4, 3], 5)
b = torch.full([3, 2, 3, 6], 2)
c = torch.matmul(a, b)
print(c.size()) # size: 3, 2, 4, 6
c = a.matmul(b)
print(c.size()) # size: 3, 2, 4, 6
文章来源:https://www.toymoban.com/news/detail-522726.html
到了这里,关于Pytorch入门:Tensor加减乘除矩阵运算的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!