Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytorch, how to extend a tensor

Tags:

python

pytorch

I want to extend a tensor in PyTorch in the following way:

Let C be a 3x4 tensor which requires_grad = True. I want to have a new C which is 3x5 tensor and C = [C, ones(3,1)] (the last column is a one-vector, and others are the old C) Moreover, I need requires_grad = True for new C.

What is an efficient way to do this?

like image 721
FA mn Avatar asked Sep 12 '25 00:09

FA mn


1 Answers

You could do something like this -

c = torch.rand((3,4), requires_grad=True)  # a random matrix c of shape 3x4
ones = torch.ones(c.shape[0], 1)  # creating a vector of 1's using shape of c

# merging vector of ones with 'c' along dimension 1 (columns)
c = torch.cat((c, ones), 1)

# c.requires_grad will still return True...
like image 98
Khalid Saifullah Avatar answered Sep 13 '25 13:09

Khalid Saifullah