创建张量,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张量运算