35

I tried:

test_image = tf.convert_to_tensor(img, dtype=tf.float32)

Then following error appears:

ValueError: Tensor conversion requested dtype float32 for Tensor with dtype int64: 'Tensor("test/ArgMax:0", shape=TensorShape([Dimension(None)]), dtype=int64)'

5 Answers 5

57

You can cast generally using:

tf.cast(my_tensor, tf.float32)

Replace tf.float32 with your desired type.


Edit: It seems at the moment at least, that tf.cast won't cast to an unsigned dtype (e.g. tf.uint8). To work around this, you can cast to the signed equivalent and used tf.bitcast to get all the way. e.g.

tf.bitcast(tf.cast(my_tensor, tf.int8), tf.uint8)
1
  • 1
    It should be noted that tf cannot compute gradients for these operations, so they cannot be used to simulate quantized weights.
    – oarfish
    Nov 23, 2017 at 13:46
12

Oops, I find the function in the API...

 tf.to_float(x, name='ToFloat')
1
  • 4
    tf.to_float() is now deprecated and tf.cast() should be used instead.
    – Richard
    Nov 21, 2019 at 19:39
5

You can use either tf.cast(x, tf.float32) or tf.to_float(x), both of which cast to float32.

Example:

sess = tf.Session()

# Create an integer tensor.
tensor = tf.convert_to_tensor(np.array([0, 1, 2, 3, 4]), dtype=tf.int64)
sess.run(tensor)
# array([0, 1, 2, 3, 4])

# Use tf.cast()
tensor_float = tf.cast(tensor, tf.float32)
sess.run(tensor_float)
# array([ 0.,  1.,  2.,  3.,  4.], dtype=float32)

# Use tf.to_float() to cast to float32
tensor_float = tf.to_float(tensor)
sess.run(tensor_float)
# array([ 0.,  1.,  2.,  3.,  4.], dtype=float32)
1
  • when I cast an mage with type of tf.uint8 to tf.float32, and used matplotlib to show them, tf.float32 change. How can show the main image?
    – Tavakoli
    Feb 7, 2017 at 18:29
1

imagetype cast you can use tf.image.convert_image_dtype() which convert image range [0 255] to [0 1]:

img_uint8 = tf.constant([1,2,3], dtype=tf.uint8)
img_float = tf.image.convert_image_dtype(img_uint8, dtype=tf.float32)
with tf.Session() as sess:
    _img= sess.run([img_float])
    print(_img, _img.dtype)

output:

[0.00392157 0.00784314 0.01176471] float32

if you only want to cast type and keep value range use tf.cast or tf.to_float as @stackoverflowuser2010 and @Mark McDonald answered

1

In case your data is actually a Pandas dataframe, we can first check for the datatype using:

print(dataset.dtypes)

To cast all the entries into float32 (for e.g.),

# Typecast
dataset = dataset.astype('float32')

#print them to verify
print(dataset.dtypes)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.