Mapping values in a tensor

Hello,

I’m trying to map the values of a 1D Long CUDA tensor to the values given by a dictionary. For instance:

x = torch.tensor([3, 4, 2, 1, 3, 4]).to('cuda')
d = {'0':25, '1':4, '2':65, '3':33, '4':17}
y = dictionary_mapping_fn(x, d)

Then y should be:

>>> y
tensor([33, 17, 65, 4, 33, 17])

If it helps, the dictionary contains keys for all elements in between 0 and the maximum value in x. Also, the mapping does not need to be necessarily expressed as a dictionary but it can be given as a pair of 1D tensors (or even a single tensors with the values of the dictionary as we know they keys are just a range).

A similar question was asked in here with no solution available.

It seems that you cannot do that on a cuda tensor; should move it to cpu before apply_:

val_if_not_shown = 0  # 0 can be any other number within dtype range
y.cpu().apply_(lambda val: d.get(val, val_if_not_shown)).to(y.device)
# in case that some of the values in `y` don't exist in `d.keys()`

Beware that it is an inplace operation.

I think this is what you’re looking for Cv2 remap in pytorch? - #10 by Felix_Lessange