pytorch张量运算

创建张量,torch.tensor()

import torch

# 创建一个标量(0维张量)
scalar = torch.tensor(5)

# 创建一个向量(1维张量)
vector = torch.tensor([1, 2, 3])

# 创建一个矩阵(2维张量)
matrix = torch.tensor([[1, 2], [3, 4]])

# 创建一个3维张量
tensor3d = torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

张量的加减乘除

###加法###
# 1.尺寸相同的张量相加,就是逐元素相加:
tensor1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
tensor2 = torch.tensor([[7, 8, 9], [10, 11, 12]])
print(tensor1 + tensor2)
# 输出:
tensor([[ 8, 10, 12],
        [14, 16, 18]])

# 2.张量加数字就是每个元素上加这个数字:
tensor1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(tensor1 + 1)
# 输出:
tensor([[2, 3, 4],
        [5, 6, 7]])
   
        
###减法###        
# 1.尺寸相同的张量相减,就是逐元素相减
tensor1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
tensor2 = torch.tensor([[7, 8, 9], [10, 11, 12]])
print(tensor1 - tensor2)
# 输出
tensor([[-6, -6, -6],
        [-6, -6, -6]])

# 2.张量减数字就是每个元素上减这个数字
tensor1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(tensor1 - 1)
# 输出
tensor([[0, 1, 2],
        [3, 4, 5]])


###乘法###  
# 1.元素乘法(Hadamard乘法/哈达玛积):尺寸相同的张量相乘,逐元素相乘
# 方法一(*)
tensor1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
tensor2 = torch.tensor([[7, 8, 9], [10, 11, 12]])
print(tensor1 * tensor2)
# 方法二(torch.mul())
tensor1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
tensor2 = torch.tensor([[7, 8, 9], [10, 11, 12]])
print(torch.mul(tensor1, tensor2))

# 输出
tensor([[ 7, 16, 27],
        [40, 55, 72]])

# 2.张量乘数字:逐元素相乘
tensor1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(tensor1 * 2)
# 输出
tensor([[ 2,  4,  6],
        [ 8, 10, 12]])

# 3.矩阵乘法:二元张量
# 方法一(@)
tensor1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
tensor2 = torch.tensor([[7, 8, 9, 10], [11, 12, 13, 14], [15, 16, 17, 18]])
print(tensor1 @ tensor2)

# 方法二(torch.mm())
tensor1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
tensor2 = torch.tensor([[7, 8, 9, 10], [11, 12, 13, 14], [15, 16, 17, 18]])
print(torch.mm(tensor1, tensor2))

# 方法三(torch.matmul())
tensor1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
tensor2 = torch.tensor([[7, 8, 9, 10], [11, 12, 13, 14], [15, 16, 17, 18]])
print(torch.matmul(tensor1, tensor2))

# 输出
tensor([[ 74,  80,  86,  92],
        [173, 188, 203, 218]])


###除法###  
# 1.张量相除:尺寸相同的张量相除,逐元素相除
tensor1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
tensor2 = torch.tensor([[7, 8, 9], [10, 11, 12]])
print(tensor1 / tensor2)
# 输出
tensor([[0.1429, 0.2500, 0.3333],
        [0.4000, 0.4545, 0.5000]])

# 2.张量除以数字:逐元素相除
tensor1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(tensor1 / 2)
# 输出
tensor([[0.5000, 1.0000, 1.5000],
        [2.0000, 2.5000, 3.0000]])

向量点积 torch.dot()

  • torch.dot()只支持一维向量点积
vector1 = torch.tensor([1, 2, 3])
vector2 = torch.tensor([4, 5, 6])
print(torch.dot(vector1, vector2))
# 输出
tensor(32)

tips:转载,仅作为学习记录便于查找

原作者:PyTorch张量运算

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值