tensorflow2.0基础(三)

#读取精度 
import tensorflow as tf 
import numpy as np 
a = tf.constant(np.pi, dtype = tf.float32) 
print('before:',a.dtype) 
if a.dtype != tf.float64: 
    a = tf.cast(a,tf.float64) #tf.cast函数可以完成精度转换 
print('after:',a.dtype) 
before: <dtype: 'float32'>
after: <dtype: 'float64'>
#类型转换 转换为高精度 
import tensorflow as tf 
import numpy as np 
a = tf.constant(np.pi, dtype = tf.float16) 
a = tf.cast(a, tf.double) 
print(a) 
tf.Tensor(3.140625, shape=(), dtype=float64)
#转换为低精度类型,可能发生数据溢出隐患。 
import tensorflow as tf 
a = tf.constant(123456789, dtype = tf.int32) 
a = tf.cast(a, tf.int16) 
print(a) 
tf.Tensor(-13035, shape=(), dtype=int16)
#布尔类型与整形之间相互转换也是合法的,是比较常见的操作 
import tensorflow as tf 
a = tf.constant([True, False]) 
a = tf.cast(a, tf.int32) 
print(a) #一般默认0表示False, 1表示True,在TensorFlow中,将非0数字都是为Ture 
tf.Tensor([1 0], shape=(2,), dtype=int32)
import tensorflow as tf 
a = tf.constant([-1, 0, 1, 2]) 
a = tf.cast(a, tf.bool) 
print(a) 
tf.Tensor([ True False  True  True], shape=(4,), dtype=bool)
发布了11 篇原创文章 · 获赞 1 · 访问量 188

猜你喜欢

转载自blog.csdn.net/q5c521/article/details/105233893