PyTorch张量转换:列向量转列矩阵、张量转置实现方法
Hey there! Let's break down your two questions with practical examples, using your sample code as a starting point.
Question 1: Convert a mathematical column vector tensor to a column matrix tensor
First, it's important to note that a 1D tensor like torch.Size([4]) in PyTorch isn't strictly a column or row vector in the linear algebra sense—it's just a 1-dimensional array. To turn it into a column matrix (2D tensor with shape [4, 1]), you need to add an extra dimension. Here are the most common, reliable ways to do this:
Using
torch.unsqueeze(): This method explicitly adds a dimension at your chosen index. For a column matrix, add a dimension at position 1:import torch import numpy as np coef = torch.from_numpy(np.arange(1.0, 5.0)).float() column_matrix = coef.unsqueeze(1) print(column_matrix) print(column_matrix.size()) # Output: torch.Size([4, 1])Using
torch.view(): If you know the exact target shape,viewreshapes the tensor (as long as the total number of elements matches). Use-1to let PyTorch automatically calculate the first dimension:column_matrix = coef.view(-1, 1)Using
torch.reshape(): Similar toview, but works even if the tensor isn't contiguous (it will create a copy if necessary):column_matrix = coef.reshape(-1, 1)
Question 2: Convert a tensor corresponding to a column vector to its transpose
A quick clarification first: A 1D tensor's transpose is still a 1D tensor (since there's only one axis to swap). To get the transpose of a column matrix (which would be a row matrix of shape [1, 4]), you first need to convert the 1D tensor to a 2D column matrix, then take its transpose.
Using your sample coef tensor:
- Convert to a 2D column matrix first:
column_matrix = coef.unsqueeze(1) - Take the transpose to get a row matrix:
row_matrix = column_matrix.T # Alternatively use torch.transpose(column_matrix, 0, 1) print(row_matrix) print(row_matrix.size()) # Output: torch.Size([1, 4])
If your only goal was to get the [4, 1] shape from the original [4] tensor, the methods from Question 1 will do exactly that—no transpose needed in that case.
内容的提问来源于stack exchange,提问作者user25004

