torch小记-常用张量操作

当然,以下是一些常用的张量计算操作的代码示例:

  1. 张量创建:
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.]])
  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])
  1. 张量变换:
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中的张量运算。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值