我正在使用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()
方法。