【笔记】tf.cast()函数:执行 tensorflow 中张量数据类型转换,比如读入的图片如果是int8类型的,一般在要在训练前把图像的数据格式转换为float32

      

cast定义:

cast(x, dtype, name=None)

    第一个参数 x:   待转换的数据(张量)
    第二个参数 dtype: 目标数据类型
    第三个参数 name: 可选参数,定义操作的名称


int32转换为float32:

  

  import tensorflow as tf
     
    t1 = tf.Variable([1,2,3,4,5])
    t2 = tf.cast(t1,dtype=tf.float32)
     
    print 't1: {}'.format(t1)
    print 't2: {}'.format(t2)
     
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        sess.run(t2)
        print t2.eval()
        # print(sess.run(t2))

输出:

    t1: <tf.Variable 'Variable:0' shape=(5,) dtype=int32_ref>
    t2: Tensor("Cast:0", shape=(5,), dtype=float32)
    [ 1.  2.  3.  4.  5.]


tensorflow中的数据类型列表: