Transfer tensor value in certain range

Hi, I would like to change some values in a tensor to a certain value.
For example, I have a tensor like this:

tensor([[[[0.3217, 0.3228, 0.3219,  ..., 0.3383, 0.3396, 0.3388],
          [0.3246, 0.3243, 0.3244,  ..., 0.3389, 0.3391, 0.3413],
          [0.3225, 0.3233, 0.3220,  ..., 0.3352, 0.3365, 0.3376],
          ...,
          [0.3404, 0.3409, 0.3416,  ..., 0.3438, 0.3424, 0.3422],
          [0.3383, 0.3393, 0.3394,  ..., 0.3436, 0.3422, 0.3414],
          [0.3402, 0.3407, 0.3412,  ..., 0.3488, 0.3446, 0.3446]],

         [[0.3191, 0.3189, 0.3193,  ..., 0.3310, 0.3372, 0.3301],
          [0.3192, 0.3193, 0.3192,  ..., 0.3320, 0.3320, 0.3350],
          [0.3198, 0.3193, 0.3193,  ..., 0.3288, 0.3319, 0.3309],
          ...,
          [0.3321, 0.3322, 0.3330,  ..., 0.3371, 0.3359, 0.3342],
          [0.3326, 0.3322, 0.3336,  ..., 0.3370, 0.3395, 0.3342],
          [0.3317, 0.3321, 0.3327,  ..., 0.3435, 0.3392, 0.3369]],

         [[0.3333, 0.3302, 0.3334,  ..., 0.3372, 0.3416, 0.3376],
          [0.3324, 0.3328, 0.3325,  ..., 0.3389, 0.3374, 0.3404],
          [0.3336, 0.3304, 0.3335,  ..., 0.3350, 0.3400, 0.3365],
          ...,
          [0.3386, 0.3397, 0.3393,  ..., 0.3430, 0.3405, 0.3413],
          [0.3399, 0.3372, 0.3406,  ..., 0.3413, 0.3436, 0.3393],
          [0.3383, 0.3396, 0.3390,  ..., 0.3460, 0.3426, 0.3428]]]],

Apparently, the values shown above are around 0.3, and the tensor has other values too.
The question is:
I want to convert all the values near 0.3 to some certain value, for example un integer 1.
and all the values near 0.6 to 2. etc.

Does anyone know how to do this?

Thank you in advance!

>>> a = torch.rand(10)/100 + 0.3 * torch.randint(1,4,(10,)).float()
>>> a
tensor([0.3033, 0.3015, 0.6091, 0.3027, 0.9099, 0.6055, 0.3092, 0.3045, 0.6024, 0.9005])
>>> torch.round(a / 0.3).long()
tensor([1, 1, 2, 1, 3, 2, 1, 1, 2, 3])

The integer tensor can serve as index to get a value.

1 Like