torch.repeat()和torch.repeat_interleave()的区别

本文详细介绍了在PyTorch中torch.repeat()和torch.repeat_interleave()函数的用法,包括它们在处理Tensor时的维度扩展规则,以及如何理解并列项和整体维度的概念。
摘要由CSDN通过智能技术生成

torch.repeat()用法和理解

import torch


x = torch.arange(1, 7).reshape(2, 3)
print(x)          

=>
tensor([[1, 2, 3],
        [4, 5, 6]])

x1 = x.repeat(1)
print(x1)

=>
RuntimeError: Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor

#  说明不可以低于初始维度进行 repeat, repeat是按照x 整体进行拓展


x1 = x.repeat(2,3)
print(x1)

=>
tensor([[1, 2, 3, 1, 2, 3, 1, 2, 3],
        [4, 5, 6, 4, 5, 6, 4, 5, 6],
        [1, 2, 3, 1, 2, 3, 1, 2, 3],
        [4, 5, 6, 4, 5, 6, 4, 5, 6]])

# 可以理解为整体 拓展2行, 拓展后的整体再拓展3列
# 强调是 整体 !!!
tensor([[1, 2, 3],   =>  tensor([[1, 2, 3],     =>   tensor([[1, 2, 3, 1, 2, 3, 1, 2, 3],
        [4, 5, 6],               [4, 5, 6],                  [4, 5, 6, 4, 5, 6, 4, 5, 6],                        
                                 [1, 2, 3],                  [1, 2, 3, 1, 2, 3, 1, 2, 3],
                                 [4, 5, 6]])                 [4, 5, 6, 4, 5, 6, 4, 5,6]])   
                       
x1 = x.repeat(1,2,1)
print(x1)

=>
tensor([[[1, 2, 3],
         [4, 5, 6],
         [1, 2, 3],
         [4, 5, 6]]])
# 说明可以超过原来的 x 维度(2, 3),进行维度拓展(1,2,3)
                                
                                    

torch.repeat_interleave()用法和理解

import torch

x = torch.arange(1, 7).reshape(1, 2, 3)
print(x)

=>
tensor([[[1, 2, 3],
         [4, 5, 6]]])

x = x.repeat_interleave(2,dim=0)
print(x)

=>
tensor([[[1, 2, 3],
         [4, 5, 6]],

        [[1, 2, 3],
         [4, 5, 6]]])

x = x.repeat_interleave(2,dim=1)
print(x)
=>
tensor([[[1, 2, 3],
         [1, 2, 3],
         [4, 5, 6],
         [4, 5, 6]]])

x = x.repeat_interleave(2,dim=2)
print(x)
=>
tensor([[[1, 1, 2, 2, 3, 3],
         [4, 4, 5, 5, 6, 6]]])

# 综合上述三个实例, 可以将维度理解为 【】 括起来的整体内容, 如dim=0就是第一个【】括起来的整体内容, dim=1 就是第一个【】括起来的内容
# 而 逗号分隔 的视为 并列项
# 拓展就是将该维度括号里的每一并列项变为指定次数的 并列项,强调是并列项,用逗号分隔,而不是加【】 
# 可以理解为不增加改维度下的【】数

# 综合上述三个实例, 可以将维度理解为 【】 括起来的整体内容, 如dim=0就是第一个【】括起来的整体内容, dim=1 就是第一个【】括起来的内容
# 而 逗号分隔 的视为 并列项
# 拓展就是将该维度括号里的每一并列项变为指定次数的 并列项,强调是并列项,用逗号分隔,而不是加【】 
# 可以理解为不增加该维度下的【】数

好学者可以自行取码,修改运行,逐一校对, 屡试不爽哦!!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值