Jonathan Guymont
Jonathan Guymont

Reputation: 497

RuntimeError when changing the values of specific parts of a `torch.Tensor`

Say I have a 3 dimentional tensor x initialized with zeros:

x = torch.zeros((2, 2, 2))

and an other 3 dimentional tensor y

y = torch.ones((2, 1, 2))

I am trying to change the values of the first line of x[0] and x[1] like this

x[:, 0, :] = y

but I get this error:

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

It is as if the tensor y was getting squeezed somehow. Is there a way around this?

Upvotes: 0

Views: 552

Answers (2)

Jonathan Guymont
Jonathan Guymont

Reputation: 497

I found a straight forward way to do it:

x[:, 0, :] = y[:, 0, :]

Upvotes: 0

lincr
lincr

Reputation: 1653

Is this what you want?

x = torch.arange(0, 8).reshape((2,2,2))
y = torch.ones((2,2))
x2 = x.permute(1,0,2)
x2[0] = y
x_target = x2.permute(1,0,2)

The value of first rows of x are changed by y .

Upvotes: 1

Related Questions