3

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.

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You are right, I think using squeeze would be the best way to reshape my b tensor to fix the issue (as I don't define tensor b myself in the actual code) and reduce dimensions.
1

Thanks to @Khoyo's tip on the source of the problem, I used reshape to fix this as following

import torch

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

i = 2
j = 2
U[:, :, i, j] = b.reshape((-1))

Comments

0

there is a shape mismatch in your assignment. U[..., [i], [j]] will do the same meanwhile keep the last two dimensions for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.