Skip to content
Advertisement

Assigning values to torch tensors

I’m trying to assign some values to a torch tensor. In the sample code below, I initialized a tensor U and try to assign a tensor b to its last 2 dimensions. In reality, this is a loop over i and j that solves some relation for a number of training data (here 10) and assigns it to its corresponding location.

import torch

U = torch.zeros([10, 1, 4, 4])
b = torch.rand([10, 1, 1, 1])

i = 2
j = 2
U[:, :, i, j] = b

I was expecting vector b to be assigned for dimensions i and j of corresponding training data (shape of training data being (10,1)) but it gives me an error. The error that I get is the following

RuntimeError: expand(torch.FloatTensor{[10, 1, 1, 1]}, size=[10, 1]): the number of sizes provided (2) must be greater or equal to the number of dimensions in the tensor (4)

Any suggestions on how to fix it would be appreciated.


As an example, you can think of this as if ‘[10, 1]’ is the shape of my data. Imagine it is 10 images, each of which has one channel. Then imagine each image is of shape ‘[4, 4]’. In each iteration of the loop, pixel ‘[i, j]’ for all images and channels is being calculated.

Advertisement

Answer

Your b tensor has too much dimensions.

U[:, :, i, j] has a [10, 1] shape (try U[:, :, i, j].shape)

Use b = torch.rand([10, 1]) instead.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement