当然,以下是一些常用的张量计算操作的代码示例:
- 张量创建:
import torch
# 从Python列表创建张量
data = [1, 2, 3]
tensor1 = torch.tensor(data)
print(tensor1) # tensor([1, 2, 3])
# 创建全零张量
shape = (2, 3)
tensor2 = torch.zeros(shape)
print(tensor2) # tensor([[0., 0., 0.],
# [0., 0., 0.]])
# 创建全一张量
tensor3 = torch.ones(shape)
print(tensor3) # tensor([[1., 1., 1.],
# [1., 1., 1.]])
# 创建单位矩阵张量
n = 3
tensor4 = torch.eye(n)
print(tensor4) # tensor([[1., 0., 0.],
# [0., 1., 0.],
# [0., 0., 1.]])
- 张量运算:
import torch
tensor1 = torch.tensor([1, 2, 3])
tensor2 = torch.tensor([4, 5, 6])
# 逐元素相加
result1 = torch.add(tensor1, tensor2)
print(result1) # tensor([5, 7, 9])
# 逐元素相减
result2 = torch.sub(tensor1, tensor2)
print(result2) # tensor([-3, -3, -3])
# 逐元素相乘
result3 = torch.mul(tensor1, tensor2)
print(result3) # tensor([4, 10, 18])
# 逐元素除以
result4 = torch.div(tensor1, tensor2)
print(result4) # tensor([0.2500, 0.4000, 0.5000])
- 张量变换:
import torch
tensor = torch.tensor([[1, 2], [3, 4]])
# 改变形状
result1 = torch.reshape(tensor, (4,))
print(result1) # tensor([1, 2, 3, 4])
# 交换维度
result2 = torch.transpose(tensor, 0, 1)
print(result2) # tensor([[1, 3],
# [2, 4]])
# 拼接张量
tensor1 = torch.tensor([[1, 2], [3, 4]])
tensor2 = torch.tensor([[5, 6]])
result3 = torch.cat((tensor1, tensor2), dim=0)
print(result3) # tensor([[1, 2],
# [3, 4],
# [5, 6]])
# 分割张量
tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
result4 = torch.split(tensor, split_size_or_sections=2, dim=1)
print(result4) # (tensor([[1, 2],
# [4, 5]]),
# tensor([[3],
# [6]]))
这些代码示例演示了一些常用的张量计算操作,希望能帮助你更好地理解和应用PyTorch中的张量运算。