repeat()函数 数组numpy里与张量tensor里的差别对比

一.  numpy.repeat(a, repeats, axis=None) 

查看内置函数的定义

解读:

numpy.repeat(a, repeats, axis=None) 

axis=0表示按行

功能: 将矩阵A按照给定的axis将每个元素重复repeats次数 
参数: a:输入矩阵, repeats:每个元素重复的次数, axis:需要重复的维度 
返回值: 输出矩阵

>>> np.repeat(3, 4)
array([3, 3, 3, 3])  #每个元素重复4次
>>> x = np.array([[1,2],[3,4]])
>>> np.repeat(x, 2)
array([1, 1, 2, 2, 3, 3, 4, 4]) #每个元素重复两次
>>> np.repeat(x, 3, axis=1)
array([[1, 1, 1, 2, 2, 2],
       [3, 3, 3, 4, 4, 4]])   #每个元素按照列重复3次
>>> np.repeat(x, [1, 2], axis=0)  
array([[1, 2],
       [3, 4],
       [3, 4]])  #第1行元素重复1次,第2行元素重复2次

举例:

import numpy as np
a = np.linspace(-1, 1, 5)
c = a.reshape(1, -1)
print('a',a.shape)
print('a',a)
print('c',c.shape)
print('c',c)
d = np.repeat(c, 5, 0)
e = np.repeat(c, 5, 1)
f = d.reshape(-1, 1)
print('d',d.shape)
print('d',d)
print('e',e.shape)
print('e',e)
print('f',f.shape)
print('f',f)

 

 

二.   torch.Tensor.repeat(*sizes) 

在张量的某个维度上复制

1. 张量维度 等于 repeat参数个数

#创建一个二维张量
x = torch.randn((2,3)) #torch.Size([2, 3])
#在x的两个维度上分别重复4次,2次,即得目标维度:4x2=8, 2x3=6,即(8,6)
x= x.repeat(4, 2) #torch.Size([8, 6])

2. 张量维度 不等于 repeat参数个数

repeat类似于平铺操作 tile,repeat参数指定了在每个维度(dimention)平铺(tile)的次数,如果张量维度 < repeat参数数量,则添加新的维度。如下所示:

#创建一个二维张量
t1 = torch.randn((1,2)) #torch.Size([1, 2])

#维度为2,小于repeat参数数量3,则结果大小:(3,1x5, 2x6)
t2 = t1.repeat(3,5,6) #torch.Size([3, 5, 12])
#创建一个三维张量
t1 = torch.randn((2,2,3)) #torch.Size([2, 2, 3])
#目标大小(3, 2x4, 2x5, 3x6)
t2 = t1.repeat(3,4,5,6)#torch.Size([3, 8, 10, 18])

举例:

 

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值