- numpy.repeat()官方文档链接
numpy.repeat(a, repeats, axis=None)
Repeat elements of an array.
Parameters: a: array_like
Input array.
repeats: int or array of ints
The number of repetitions for each element. repeats is broadcasted to fit the
shape of the given axis.
axis: int, optional
The axis along which to repeat values. By default, use the flattened input
array, and return a flat output array.
Returns: repeated_array: ndarray
Output array which has the same shape as a, except along the given axis.
example
>>>import numpy as np
# axis 默认值为 None, 相当与先将x进行flatten(展平)然后每个元素单独进行重复
>>>x = np.array([3])
>>>np.repeat(x, 4)
array([3, 3, 3, 3])
>>>x = np.array([[1, 2], [3, 4]])
>>>np.repeat(x, 2)
array([1, 1, 2, 2, 3, 3, 4, 4])
# axis 指定数值时,表示以第几个维的元素为单位进行repeat
>>>x = np.array([[1, 2], [3, 4]])
>>>np.repeat(x, 2, 0) # 第 0 维的元素是[1, 2], [3, 4]
array([[1, 2],
[1, 2],
[3, 4],
[3, 4]])
>>>np.repeat(x, 2, 1) # 第 1 维的元素是 1, 2, 3, 4
array([[1, 1, 2, 2],
[3, 3, 4, 4]])
# 参数repeats也可以是数组,对应下标的数值对应按照第axis维的元素的重复次数
>>>np.repeat(x, [3, 2], 0) # [1, 2] 重复 3 次, [2, 4] 重复 2 次
array([[1, 2],
[1, 2],
[1, 2],
[3, 4],
[3, 4]])
>>>np.repeat(x, [3, 2], 1) # 1, 3 重复 3 次, 2, 4 重复 2 次
array([[1, 1, 1, 2, 2],
[3, 3, 3, 4, 4]])
- tensor.repeat()官方文档[链接](https://pytorch.org/docs/stable/generated/torch.Tensor.repeat.html?highlight=repeat#torch.Tensor.repeat
Tensor.repeat(*sizes) → Tensor
Repeats this tensor along the specified dimensions.
Unlike expand(), this function copies the tensor’s data.
example
>>>import torch
# *size 从后往前执行,最后一个元素对应在第-1维度重复的次数,倒数第二个维度对应tensor的第-2维度重复的次数,以此类推
>>>x = torch.tensor([1, 2, 3])
>>>x.repeat(4, 2)
'''
先重复第-1维度2次变为[1, 2, 3, 1, 2, 3]
没有第-2维就在最前面插入新的维度变为[[1, 2, 3, 1, 2 ,3]]
再重复第-2维度4次变为
'''
tensor([[1, 2, 3, 1, 2, 3],
[1, 2, 3, 1, 2, 3],
[1, 2, 3, 1, 2, 3],
[1, 2, 3, 1, 2, 3]])
>>>x.repeat(4, 2, 1)
'''
先重复第-1维度1次变为[1, 2, 3]
没有第1维就在最前面插入新的维度变为[[1, 2, 3]]
再重复第-2维度2次变为
[[1, 2, 3],
[1, 2, 3]]
没有第-3维就在最前面插入新的维度变为
[[[1, 2, 3],
[1, 2, 3]]]
再重复第-3维度4次
'''
tensor([[[1, 2, 3],
[1, 2, 3]],
[[1, 2, 3],
[1, 2, 3]],
[[1, 2, 3],
[1, 2, 3]],
[[1, 2, 3],
[1, 2, 3]]])
>>>x = torch.tensor([[0], [1]])
>>>x.repeat(3, 2, 4)
'''
先重复第-1维度4次,变为
[[0, 0, 0, 0],
[1, 1, 1, 1]]
在重复第-2维度2次,变为
[[0, 0, 0, 0],
[1, 1, 1, 1],
[0, 0, 0, 0],
[1, 1, 1, 1]]
没有第-3维度,新增-3维度并重复3次,变为
[[[0, 0, 0, 0],
[1, 1, 1, 1],
[0, 0, 0, 0],
[1, 1, 1, 1]],
[[0, 0, 0, 0],
[1, 1, 1, 1],
[0, 0, 0, 0],
[1, 1, 1, 1]],
[[0, 0, 0, 0],
[1, 1, 1, 1],
[0, 0, 0, 0],
[1, 1, 1, 1]]]
'''