tf.cast()类型转换函数

作用:类型转换函数

tf.cast(x, dtype, name=None)

参数:

  • x:输入
  • dtype:转换目标类型
  • name:名称

返回:Tensor,跟输入同shape

这里补充下tf的数据类型,作为tf.cast()的参数时,需要写为tf.float32.

uint8, uint16, uint32, uint64, int8, int16, int32, int64, float16, float32, float64, complex64, complex128, bfloat16

例子:

import tensorflow as tf
sess = tf.Session()
a = tf.constant(8)
print a
print sess.run(a)
b = tf.cast(a, tf.float32)
print b
print sess.run(b)

输出:
Tensor("Const:0", shape=(), dtype=int32)
8
Tensor("Cast:0", shape=(), dtype=float32)
8.0

该函数常用于解决:TypeError: Expected int32, got 512.0 of type 'float' instead.

举个例子,会报上述错误,也就是说进行相除的两个tensor,得是同类型的,此时tf.cast()来救场:

import tensorflow as tf
a = tf.constant(50)
f = tf.div(a, 512.0)
sess = tf.Session()
print sess.run(f)

转换类型后:

import tensorflow as tf
a = tf.constant(50)
f = tf.div(tf.cast(a, tf.float32), 512.0)
sess = tf.Session()
print sess.run(f)

输出:
0.09765625

文档:https://www.tensorflow.org/api_docs/python/tf/cast

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值