numpy的repeat和pytorch的repeat

numpy的repeat

在这里插入图片描述
重复数组中的元素

样例1

从某一个维度复制,如下面从第一维度复制,(2,3)的张量复制后就是(4,3)

x = np.array([1,2,3,4,5,6]).reshape(2,3)
print(x)
print("===repeat====")
# 也可以写作为
# x = np.repeat(x, 2, axis=0)
x = x.repeat(2, axis=0)
print(x, x.shape)

样例1结果

如果复制第二个维度呢,那么(2,3)的张量复制后就是(2,6),但是复制内容是一个一个复制,比如,1,2,3的复制是1,1,2,2,3,3而不是1,2,3,1,2,3

x = np.array([1,2,3,4,5,6]).reshape(2,3)
print(x)
print("===repeat====")
# 也可以写作为
# x = np.repeat(x, 2, axis=1)
x = x.repeat(2, axis=1)
print(x, x.shape)

样例1的结果

样例2

如果不指定axis会怎么样呢? 是把整个Tensor压成一维,然后repeat

x = np.array([1,2,3,4,5,6]).reshape(2,3)
print(x)
print("===repeat====")
# 也可以写作为
# x = np.repeat(x, 2)
x = x.repeat(2)
print(x, x.shape)

样例2结果

样例3

使用repeat初始化数组
第一个参数是重复的数,后一个参数是重复的个数

print("===repeat====")
x=np.repeat(2,3)
print(x)

样例3结果

样例4

在一个维度上重复的次数不一致

x = np.array([1,2,3,4,5,6]).reshape(2,3)
print(x)
print("===repeat====")
# 也可以写作为
# x = np.repeat(x, [1,2], axis=0)
x = x.repeat([1,2], axis=0)
print(x, x.shape)

样例4结果


numpy的tile

tile跟repeat功能基本一样,主要的区别是tile的复制是单个维度数据的整体复制;
但是它没有axis参数可以指定维度

样例1

x = np.array([1,2,3,4,5,6]).reshape(2,3)
print(x)
print("===repeat====")
# 注意不可以写作x.tile
x = np.tile(x, 2)
print(x, x.shape)

样例1结果
主要区别就是复制方式不同,而且只能作用于最后一维

=======================================================

torch的repeat

在这里插入图片描述

样例1

这个样例的操作类似numpy.tile(x, 2)

x = np.array([1,2,3,4,5,6]).reshape(2,3)
x1 = torch.from_numpy(x)

print(x1)
print("===repeat====")
x1 = x1.repeat(1,2)
print(x1, x1.shape)

样例1结果

样例2

这个样例有点类似numpy.repeat(x, 2, axis=0),但是复制的细节略有不同,请注意。

x = np.array([1,2,3,4,5,6]).reshape(2,3)
x1 = torch.from_numpy(x)

print(x1)
print("===repeat====")
x1 = x1.repeat(2,1)
print(x1, x1.shape)

样例2结果

样例3

如果repeat的维度多于原始张量的维度,那么会自动做阔维

x = np.array([1,2,3,4,5,6]).reshape(2,3)
x1 = torch.from_numpy(x)

print(x1)
print("===repeat====")
x1 = x1.repeat(2,2,2)
print(x1, x1.shape)

样例3结果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值