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)