PyTorch repeat() 函数

1.官方讲解

Tensor.repeat(*sizes) → [Tensor]

tensor 沿着指定维度复制。不同于 expand(),该函数复制了 tensor 的数据,而不是只返回 tensor 的一个视图。关于 expand() ,详情可见 PyTorch expand() 函数_长命百岁️的博客-CSDN博客

参数:

sizes (torch.Size or int...) – 沿着每一维复制的次数

注意:

repeat dims 的维度不能小于 tensor 的维度(可以大于)。

2.例子

2.1.repeat dims的维度与 tensor 维度相同

a = torch.rand(2, 3)
b = a.repeat(2, 2)
print(a)
print(b)
print(b.shape)
>>tensor([[0.0757, 0.3003, 0.9648],
        [0.1594, 0.8253, 0.1031]])
>>tensor([[0.0757, 0.3003, 0.9648, 0.0757, 0.3003, 0.9648],
        [0.1594, 0.8253, 0.1031, 0.1594, 0.8253, 0.1031],
        [0.0757, 0.3003, 0.9648, 0.0757, 0.3003, 0.9648],
        [0.1594, 0.8253, 0.1031, 0.1594, 0.8253, 0.1031]])
>>torch.Size([4, 6])

可见。b 的维度变成了 Size([4, 6]),两个维度的大小都变成原来的两倍

print(a.storage().data_ptr())
print(b.storage().data_ptr())
>>94149111617984
>>94149109116160

可见 ab 并不共用一个存储区,也就说明了 repeat 函数是进行数据的复制,而不是返回一个 view

2.2.repeat dims的维度大于 tensor 维度

a = torch.rand(2, 3)
b = a.repeat(2, 2, 2)
print(a)
print(b)
print(b.shape)
>>tensor([[0.8346, 0.2550, 0.8920],
        [0.1972, 0.1876, 0.6154]])
>>tensor([[[0.8346, 0.2550, 0.8920, 0.8346, 0.2550, 0.8920],
         [0.1972, 0.1876, 0.6154, 0.1972, 0.1876, 0.6154],
         [0.8346, 0.2550, 0.8920, 0.8346, 0.2550, 0.8920],
         [0.1972, 0.1876, 0.6154, 0.1972, 0.1876, 0.6154]],

        [[0.8346, 0.2550, 0.8920, 0.8346, 0.2550, 0.8920],
         [0.1972, 0.1876, 0.6154, 0.1972, 0.1876, 0.6154],
         [0.8346, 0.2550, 0.8920, 0.8346, 0.2550, 0.8920],
         [0.1972, 0.1876, 0.6154, 0.1972, 0.1876, 0.6154]]])
>>torch.Size([2, 4, 6])

可见,repeat 默认后面的维度是用来复制原 tensor 的 ,如果参数更多的话,会在前面增加维度。(因为不能在后面增加维度,后面都没有数据,复制谁呢?)在前面增加维度,就可以复制该维度后面的数据。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长命百岁️

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值