比较与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]]])
