比较与torch.Tensor.repeat的功能差异
torch.Tensor.repeat
torch.Tensor.repeat(*sizes)
更多内容详见torch.Tensor.repeat。
mindspore.numpy.tile
mindspore.numpy.tile(a, reps)
更多内容详见mindspore.numpy.tile。
使用方式
- MindSpore:把输入的张量 - a复制- reps指定的次数来构造一个数组。假设- reps长度为- d,- a的维度为- a.dim,复制的规则是:- 如果 - a.ndim=- d:把- a沿着各轴复制对应的- reps次。- 如果 - a.ndim<- d:通过添加新轴将- a.dim提升为- d维,再进行复制;- 如果 - a.ndim>- d:将通过在前面补1把- reps提升为- a.ndim,再进行复制。
- PyTorch:输入为复制的次数 - size,且限制- size的长度需大于等于原始张量的维度,即不支持上述第三种情况。
代码示例
MindSpore:
import mindspore.numpy as np
a = np.array([[0, 2, 1], [3, 4, 5]])
b = np.tile(a, 2)
print(b)
# out:
# [[0 2 1 0 2 1]
#  [3 4 5 3 4 5]]
c = np.tile(a, (2, 1))
print(c)
# out:
# [[0 2 1]
#  [3 4 5]
# [0 2 1]
#  [3 4 5]]
d = np.tile(a, (2, 1, 2))
print(d)
# out
# [[[0 2 1 0 2 1]
#   [3 4 5 3 4 5]]
#  [[0 2 1 0 2 1]
#   [3 4 5 3 4 5]]]
PyTorch:
import torch
a = torch.tensor([[0, 2, 1], [3, 4, 5]])
b = a.repeat(2)
# error:
# RuntimeError: Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor
c = a.repeat(2, 1)
print(c)
# out:
#tensor([[0, 2, 1],
#         [3, 4, 5],
#         [0, 2, 1],
#         [3, 4, 5]])
d = a.repeat(2, 1, 2)
print(d)
# out:
#tensor([[[0, 2, 1, 0, 2, 1],
#          [3, 4, 5, 3, 4, 5]],
#
#         [[0, 2, 1, 0, 2, 1],
#          [3, 4, 5, 3, 4, 5]]])
