gpt4 book ai didi

pytorch - 如何在 PyTorch 中将张量大小从 [a, b] 转换为 [a, b, k]

转载 作者:行者123 更新时间:2023-12-02 16:16:52 24 4
gpt4 key购买 nike

我想给一个张量增加一个额外的维度,并将这个维度的值设置为一个特定的值。
例如,

print(a.size)
torch.Size([10, 5])
# after tranformation and set a to b
print(b.size)
torch.Size([10, 5, 1])
# after transformation and set a to c
print(c.size)
torch.Size([10, 2, 5])

提前致谢。

最佳答案

torch.stack 允许您沿新维度连接两个数组

value = 1.37
a = torch.normal(0, 1, size=(5, 10))
c = torch.stack([a, torch.ones(a.shape) * value], dim=1)
c.shape

Out: torch.Size([5, 2, 10])
c[:, 0, :]

Out: tensor([[-0.2944, -0.7366, 0.6882, -0.7106, 0.0182, -0.1156, -1.0394, -0.7524,
0.7587, -0.6066],
[-1.0445, -2.7990, 0.0232, 0.5246, -0.7383, 0.0306, -1.0277, -0.8969,
0.4026, 0.2006],
[-1.2622, -0.6563, -1.9218, -0.6932, -1.9633, 1.8271, 0.6753, -0.7564,
0.0107, -0.2312],
[-0.8111, -1.0776, -0.8583, 0.2782, -0.8116, 0.0984, 0.4799, 0.6854,
0.4408, -0.4280],
[-1.1083, 1.8509, 0.1209, 0.5571, -1.1472, 0.2342, 0.3912, 0.7858,
0.5879, 0.4139]])

c[:, 1, :]

Out: tensor([[1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700,
1.3700],
[1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700,
1.3700],
[1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700,
1.3700],
[1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700,
1.3700],
[1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700,
1.3700]])

关于pytorch - 如何在 PyTorch 中将张量大小从 [a, b] 转换为 [a, b, k],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66422022/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com