我想将形状为 (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/