重塑 torch 张量

huangapple go评论71阅读模式
英文:

Reshaping torch tensor

问题

我有一个形状为(1,3,8)的张量。我想要增加第一个维度到n,从而得到最终形状为(n,3,8)的张量。我想要填充这个形状的零值。这是我尝试的方法:

n = 5
a = torch.randn(1,3,8) # 随机生成一个(1,3,8)的张量
b = torch.cat((a,torch.zeros_like(a)))
for i in range(n-2):
    b = torch.cat((b,torch.zeros_like(a)))
print(b.shape) # (5,3,8)

这个方法有效,但是否有更好和更优雅的解决方案?

英文:

I have a torch of shape (1,3,8). I want to increase the first dimension to n, resulting in the final tensor of shape (n,3,8). I want to pad zeroes of that shape. Here is what I worked on:

n = 5
a = torch.randn(1,3,8) # Random (1,3,8) tensor
b = torch.cat((a,torch.zeros_like(a)))
for i in range(n-2):
    b = torch.cat((b,torch.zeros_like(a)))
print(b.shape) # (5,3,8)

This works, but is there a better and more elegant solution?

答案1

得分: 2

你可以通过立即创建一个长度为 n-1 的零张量来避免循环:

torch.cat((a, torch.zeros(n - 1, a.shape[1], a.shape[2]))
英文:

You can avoid the loop by creating a tensor of zeros of length n-1 straight away:

torch.cat((a, torch.zeros(n - 1, a.shape[1], a.shape[2])))

答案2

得分: 1

你可以使用 pad 函数,例如,

n = 5
a = torch.randn(1,3,8)

b = torch.nn.functional.pad(a, (0, 0, 0, 0, n - 1, 0), value=0)

print(b.shape)
torch.Size([5, 3, 8])

请注意,元组中的值 (0, 0, 0, 0, n - 1, 0) 是按从最后到第一个维度的顺序工作,即初始的两个零表示在最后一个维度上填充 0 个点,而最后两个值 (n - 10) 表示在第一个维度的末尾填充 n - 1 个值,并在前面填充 0 个值。

英文:

You can use the pad function, e.g.,

n = 5
a = torch.randn(1,3,8)

b = torch.nn.functional.pad(a, (0, 0, 0, 0, n - 1, 0), value=0)

print(b.shape)
torch.Size([5, 3, 8])

Note that the values in the tuple (0, 0, 0, 0, n - 1, 0) work through the dimensions from last to first, i.e., the initial two zeros mean pad 0 points to the last dimension, while the last two values (n - 1 and 0) mean pad n - 1 values to the back of the first dimension and 0 values to the front.

huangapple
  • 本文由 发表于 2023年3月7日 20:27:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75661970.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定