栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

numpy的repeat和pytorch的repeat

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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)

如果复制第二个维度呢,那么(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)

样例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)

样例3

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

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

样例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)

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)


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

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

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)

样例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)

样例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)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/726184.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号