How to convert tf.int64 to tf.float32?

2020-05-30 02:55发布

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条回答
smile是对你的礼貌
2楼-- · 2020-05-30 03:38

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)
查看更多
Ridiculous、
3楼-- · 2020-05-30 03:40

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

 tf.to_float(x, name='ToFloat')
查看更多
霸刀☆藐视天下
4楼-- · 2020-05-30 03:45

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

查看更多
干净又极端
5楼-- · 2020-05-30 03:47

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)
查看更多
三岁会撩人
6楼-- · 2020-05-30 03:50

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)
查看更多
登录 后发表回答