You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyTorch张量转换:列向量转列矩阵、张量转置实现方法

PyTorch Tensor Reshaping Questions: Column Vector to Column Matrix & Transpose

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, view reshapes the tensor (as long as the total number of elements matches). Use -1 to let PyTorch automatically calculate the first dimension:

    column_matrix = coef.view(-1, 1)
    
  • Using torch.reshape(): Similar to view, 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:

  1. Convert to a 2D column matrix first:
    column_matrix = coef.unsqueeze(1)
    
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:01:21