简单粗暴PyTorch之张量操作

1、张量的操作:拼接、切分、索引和变换

1.1 张量的拼接与切分

拼接
torch.cat() # 不会扩张维度
功能:将张量按维度dim进行拼接
• tensors: 张量序列 • dim : 要拼接的维度

    t = torch.ones((2, 3))
    t_0 = torch.cat([t, t], dim=0)  # 行拼接在一起
    t_1 = torch.cat([t, t, t], dim=1) # 列拼接在一起
    print("t_0:{} shape:{}\nt_1:{} shape:{}".format(t_0, t_0.shape, t_1, t_1.shape))

在这里插入图片描述
torch.stack() # 创建新的维度
功能:在新创建的维度dim上进行拼接
• tensors:张量序列
• dim :要拼接的维度

    t = torch.ones((2, 3))
    t_stack = torch.stack([t, t, t], dim=0) # 在0维新创建维度
    print("\nt_stack:{} shape:{}".format(t_stack, t_stack.shape))

在这里插入图片描述

    t = torch.ones((2, 3))
    t_stack = torch.stack([t, t], dim=2) # 在新创建的维度2拼接

在这里插入图片描述
切分

torch.chunk()
功能:将张量按维度dim进行平均切分
返回值:张量列表
注意事项:若不能整除,最后一份张量小于 其他张量
• input: 要切分的张量
• chunks : 要切分的份数,向上取整
• dim : 要切分的维度

    a = torch.ones((2, 7)) 
    list_of_tensors = torch.chunk(a, dim=1, chunks=3) #在维度1切分3份
    for idx, t in enumerate(list_of_tensors):
        print("第{}个张量:{}, shape is {}".format(idx+1, t, t.shape))

在这里插入图片描述

torch.split()
功能:将张量按维度dim进行切分
返回值:张量列表
• tensor: 要切分的张量
• split_size_or_sections : 为int时,表示 每一份的长度;为list时,按list元素切分
• dim : 要切分的维度

    t = torch.ones((2, 
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值