Reshape Tensors to discard all empty slots

lets say i make a tensor

tensor = torch.empty(10,10)

And then lets say i have some logic that fills out 8x8 of that empty space with values.

tensor[0:8,0:8] = 2

is there an easy way to reshape such a tensor into a 8x8 tensor removing all the remaining empty slots.?

And you are not aware of the dimensions of the subspace that has been filled so 8x8 is unknown to you


is not a solution

You could try to do it via binary masking and indexing like this:

new_tensor = tensor[tensor!=0]

Edit: you would have to create a tensor of zeros, as you don’t have any control over the content of an empty tensor.

problem is 0 is also a valid value that will be put into the subspace.

it is nifti input. So every value from -1000 to 30000 is valid values.

You would have to pick a value, which is not in your input space. Something like this:


tensor = torch.ones(10,10) * ARBITRARY_VAL 
tensor[0:8, 0:8] = 2
new_tensor = tensor[tensor!=ARBITRARY_VAL]

Instead of != you could also use other logical operators like >= (depending on your arbitrary value).

tensor = torch.ones(10,10)
tensor[0:8,0:8] = 2

will return a 1x64 tensor

Strange, but true.
And you cannot access any of the dimensions?

I could but it will require some extra work which I am trying to avoid. Thanks though

Is the result always a square or always continuous between rows columns?

nonzeros = torch.nonzero(tensor != DUMMY)
c_min, c_max, r_min, r_max = nonzeros[:, 0].min(), nonzeros[:, 0].max(), nonzeros[:, 1].min(), nonzeros[:, 1].max()
tensor = tensor[c_min:c_max+1, r_min:r_max+1]
1 Like