python - PyTorch reshape 张量维度

标签 python pytorch reshape tensor

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

相关文章:

python - 我怎样才能根据值(value)而不是内存使 x=y ?

python - 两个列表的条件压缩

python - 在 Pytorch 中连接两个张量

pytorch - ImportError : TensorBoard logging requires TensorBoard version 1. 15 或以上

performance - 在 matlab 中使用列零填充将向量 reshape 为矩阵

python - 比较 2 个文件,当它们与 file1 中找到的值匹配时,删除 file2 中的任何行

python - 使用 zappa 部署到 AWS Lambda 时,spaCy 抛出 OSError

pytorch - 如何使用两个或多个输入训练 Pytorch CNN

将杂乱且不平衡的数据集从宽到长 reshape

将 data.frame 从宽 reshape 为长,从一组变量创建多个列