pytorch中 tensor.repeat()函数用法

官方解释链接

torch.tensor.repeat(*size)

函数作用

用于进行张量数据复制和维度扩展的函数。参数是沿着维度重复的次数。

注意⚠️:

  • repeat()函数跟expand()函数不同,repeat()函数重复的时候是根据tensor内的数据。
  • 同时,对于函数中的参数个数一定不能小于tensor的维度个数。【1】
  • size中不允许使用负数保持不变时使用1。【2】

举例

参数数量不正确:

res_1.shape  #  torch.Size([4, 1])
res_2 = res_1.repeat(3)
res_2.shape

# 输出
RuntimeError                              Traceback (most recent call last)
Cell In[7], line 1
----> 1 res_2 = res_1.repeat(3)
      2 res_2.shape

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

参数错误 使用负数:

res_2 = res_1.repeat(-23)
res_2.shape

#输出
RuntimeError                              Traceback (most recent call last)
Cell In[10], line 1
----> 1 res_2 = res_1.repeat(-2,3)
      2 res_2.shape

RuntimeError: Trying to create tensor with negative dimension -8: [-8, 3]

正确使用例子:参数数量大于等于维度个数,且为正整数

res_1.shape  #  torch.Size([4, 1])
res_2 = res_1.repeat(23)
res_2.shape

#输出
torch.Size([8, 3])

references:
[1] PyTorch中tensor.repeat()的使用
[2] Pytorch 中 expand和repeat

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值