108、TensorFlow 类型转换

# 除了维度之外Tensorflow也有数据类型
# 请参考 tf.DataType
# 一个张量只能有一个类型
# 可以使用tf.cast,将一个张量从一个数据类型转换到另一个数据类型
# 下面代码显示的就是将一个张量的类型从integer类型转换为float类型
import tensorflow as tf
float_tensor = tf.cast(tf.constant([1, 2, 3]), dtype=tf.float32)
# 当从一个python对象来创建张量的时候可以手动指定数据类型
# 如果你不手动指定数据类型
# TensorFlow 自动地将 Python integer 类型转换为tf.int32 并且将 python的 float类型转换为 tf.float32
# 另外TensorFlow使用相同的规则将numpy对象转换为Array
init = tf.global_variables_initializer()
sess = tf.Session()
print(sess.run(float_tensor))

下面是类型转换的结果:

2018-02-16 21:44:46.674417: I C:\tf_jenkins\workspace\rel-win\M\windows\PY\35\tensorflow\core\platform\cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
[ 1.  2.  3.]