gpt4 book ai didi

python - PyTorch reshape 张量维度

转载 作者:IT老高 更新时间:2023-10-28 22:17:40 25 4
gpt4 key购买 nike

我想将形状为 (5,) 的向量 reshape 为形状为 (1, 5) 的矩阵。

有了 numpy,我可以做到:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5])
>>> a.shape
(5,)
>>> a = np.reshape(a, (1, 5))
>>> a.shape
(1, 5)
>>> a
array([[1, 2, 3, 4, 5]])

但是如何使用 PyTorch 做到这一点?

最佳答案

使用 torch.unsqueeze(input, dim, out=None) :

>>> import torch
>>> a = torch.Tensor([1, 2, 3, 4, 5])
>>> a

1
2
3
4
5
[torch.FloatTensor of size 5]

>>> a = a.unsqueeze(0)
>>> a

1 2 3 4 5
[torch.FloatTensor of size 1x5]

关于python - PyTorch reshape 张量维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43328632/

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