Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transpose a column vector in torch

Tags:

torch

I have a colum vector which I want to tranpose into row vector, I get the following error while doing it. Is there a way to tranpose 1 dimensional vectors in torch

th> bb
 1
 2
[torch.DoubleTensor of size 2]

                                                                      [0.0005s]
th> bb:t()
[string "_RESULT={bb:t()}"]:1: calling 't' on bad self (Tensor must have 2 dimensions at /tmp/luarocks_torch-scm-1-5379/torch7/generic/Tensor.c:590)
stack traceback:
    [C]: in function 't'
    [string "_RESULT={bb:t()}"]:1: in main chunk
    [C]: in function 'xpcall'
like image 520
Rahul Avatar asked Feb 07 '16 23:02

Rahul


People also ask

How do you transpose in torch?

We can transpose a torch tensor by using torch. transpose(input, dim0, dim1) function which will consist of the input tensor and dimensions. The function will return the transposed version of the input given and the dimensions given i.e dim0 and dim1 are swapped.

What is the transpose of a column vector?

In general, the transpose of a matrix is a new matrix in which the rows and columns are interchanged. For vectors, transposing a row vector results in a column vector, and transposing a column vector results in a row vector. In MATLAB, the apostrophe (or single quote) is built-in as the transpose operator.

How does transpose work in PyTorch?

Returns a tensor that is a transposed version of input . The given dimensions dim0 and dim1 are swapped. If input is a strided tensor then the resulting out tensor shares its underlying storage with the input tensor, so changing the content of one would change the content of the other.


2 Answers

This is because your tensor has a dimension of 1. You can only take the transpose of a tensor with dimension 2.

In order to do this, first resize your tensor as

bb:resize(2,1)

After that, it should work:

th> bb:t()
 1  2

More generally, for a tensor with any other size, you can simply use:

bb:resize(bb:size(1),1)
like image 148
Karishma Malkan Avatar answered Oct 20 '22 00:10

Karishma Malkan


for Transpose of 1d tensor you can do something like this:

let's say you have 1D tensor b:

import torch

a = torch.rand(1,10)
b = a[0,:]

and .t() not working for 1D

print(b)
#print(b.t()) # not going to work 1D

you can use one of the following option:

print(b.reshape(1,-1).t())
print(b.reshape(-1,1))

first line create 1*N matrix and then transpose it, and the second create N*1 matrix that transposed

like image 30
ChaosPredictor Avatar answered Oct 20 '22 00:10

ChaosPredictor