如何将 Pytorch 张量从数学上的列向量转换为列矩阵?
How to convert from a Pytroch Tensor from mathematically a column vector to a column matrix?
我正在使用 pytorch 中的张量。
如何将列向量对应的张量转换为其转置对应的张量?
import numpy as np
coef = torch.from_numpy(np.arange(1.0, 5.0)).float()
print(coef)
print(coef.size())
目前 coef
的大小是 [4]
但我希望它是 [4, 1]
且内容相同。
在PyTorch中很容易实现。您可以使用 view()
方法。
coef = coef.view(4, 1)
print(coef.size()) # now the shape will be [4, 1]
虽然通常使用 .view
当然是一个不错的选择,但为了完整起见,我想补充一点,还有 .unsqueeze()
方法可以在指定的索引处添加一个额外的维度(与删除统一维度的 .squeeze()
方法相反):
>>> coef = coef.unsqueeze(-1) # add extra dimension at the end
>>> coef.shape
torch.Size([4, 1])
对于一般的换位,您可以使用 .t()
方法。
我正在使用 pytorch 中的张量。 如何将列向量对应的张量转换为其转置对应的张量?
import numpy as np
coef = torch.from_numpy(np.arange(1.0, 5.0)).float()
print(coef)
print(coef.size())
目前 coef
的大小是 [4]
但我希望它是 [4, 1]
且内容相同。
在PyTorch中很容易实现。您可以使用 view()
方法。
coef = coef.view(4, 1)
print(coef.size()) # now the shape will be [4, 1]
虽然通常使用 .view
当然是一个不错的选择,但为了完整起见,我想补充一点,还有 .unsqueeze()
方法可以在指定的索引处添加一个额外的维度(与删除统一维度的 .squeeze()
方法相反):
>>> coef = coef.unsqueeze(-1) # add extra dimension at the end
>>> coef.shape
torch.Size([4, 1])
对于一般的换位,您可以使用 .t()
方法。