user8020627
user8020627

Reputation: 21

Tensorflow Get a Number of a Tensor

I have a random Search Problem. I need the hyperparameter.

z_mean = Dense(units=hp.Int('unitsBottle',min_value=8,max_value=48,step=8))(h)
latentVariable = hp.get('unitsBottle')
z_log_var = Dense(units=latentVariable)(h)

latentVariable is a tensor. I can print it:

tf.Tensor(16, shape=(), dtype=int32)

But I need the number 16. Not as a tensor. As an integer number (scalar), so that I can put it into

z = Lambda(sampling, 
            output_shape=(latenteVariable,))([z_mean, 
            z_log_var, latenteVariable])

How can I only get the number?

Upvotes: 2

Views: 2443

Answers (2)

Innat
Innat

Reputation: 17219

Using .numpy() is more intuitive as mentioned by @Ynjxsjmh. However, we can also use eval on the tensor to get the values.

from tensorflow.keras.backend import eval 

one = tf.constant(8)
two = tf.constant(8)
product = tf.add(one, two)

eval(one), eval(two), eval(product)
(8, 8, 16)

Upvotes: 0

Ynjxsjmh
Ynjxsjmh

Reputation: 29992

It is as simple as calling int() on the tensor:

>>> tensor = tf.constant(16)
>>> print(tensor)
tf.Tensor(16, shape=(), dtype=int32)

>>> int(tensor)
16

>>> tensor.numpy()
16
>>> print(type(tensor.numpy()))
<class 'numpy.int32'>

Upvotes: 4

Related Questions