tf.keras create random integers of type float

Viewed 220

I try to create some integers in tensors to inspect visually some operations. But it seems that you can just make "real" integers where doing operations like mean is also casted to an integer.

I would like to get the mean of a tensor of integers but the mean should be a float. How would I do that? example:

a=tf.random.uniform(
    (2,3,4), minval=0, maxval=3, dtype=tf.int32, seed=None, name=None
)

print(a)
amean=tf.keras.backend.mean(
    a, axis=-1, keepdims=False
)

print(amean)

gives:

[[[0 1 2 0]
  [1 2 2 0]
  [2 2 1 2]]

 [[2 2 2 1]
  [1 1 2 1]
  [1 1 0 2]]], shape=(2, 3, 4), dtype=int32)

tf.Tensor(
[[0 1 1]
 [1 1 1]], shape=(2, 3), dtype=int32)

But instead I want that I can see values of th emean as 2.5, etc and not casted down to an integer of just 0 and 1.

1 Answers

you simply have to cast it to dtype=tf.float32 when you compute the mean

a=tf.random.uniform(
    (2,3,4), minval=0, maxval=3, dtype=tf.int32, seed=None, name=None
)

print(a)

amean=tf.keras.backend.mean(
    tf.cast(a, tf.float32), axis=-1, keepdims=False
)

print(amean)

gives:

tf.Tensor(
[[[1 2 2 0]
  [0 2 2 0]
  [0 2 2 0]]

 [[2 0 0 0]
  [2 1 0 1]
  [0 0 0 0]]], shape=(2, 3, 4), dtype=int32)
tf.Tensor(
[[1.25 1.   1.  ]
 [0.5  1.   0.  ]], shape=(2, 3), dtype=float32)
Related