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)'
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
Yee Liu
  • 1,417
  • 3
  • 15
  • 17

5 Answers5

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)
Mark McDonald
  • 7,571
  • 6
  • 46
  • 53
  • 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 '17 at 13:46
12

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

 tf.to_float(x, name='ToFloat')
Yee Liu
  • 1,417
  • 3
  • 15
  • 17
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)
stackoverflowuser2010
  • 38,621
  • 48
  • 169
  • 217
  • 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 07 '17 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

Roby
  • 145
  • 1
  • 12
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)
Pe Dro
  • 2,651
  • 3
  • 24
  • 44