How can I convert a tensor with the shape of [1, 3, 64, 64] to [1, 4, 64, 64] with the newly added layer being the same as the previous?

Question:

I have a PyTorch tensor with the shape of [1, 3, 64, 64], and I want to convert it to the shape [1, 4, 64, 64] while setting the value of the newly added layer to be the same as the previous layer in the same dimension (eg newtensor[0][3] = oldtensor[0][2])

Note that my tensor has requires_grad=True, so I cannot use resize_()

How can I do this?

Asked By: raspiduino

||

Answers:

Get a slice from the old tensor, and concatenate it to the new tensor along dimension 1.

tslice = old[:,-1:,:,:]
new = torch.cat((old,tslice), dim = 1)
Answered By: DerekG

This will work perfectly. @DerekG code had an error in -1, but his idea is correct.
tensor is your tensor data.

new = torch.cat((tensor, tensor[:, 0:1, :, :]), dim=1)
Answered By: Mohamed Fathallah
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.