【TensorFlow2.0】(1) tensor数据类型,类型转换

您所在的位置:网站首页 byte转为int要强制转换吗 【TensorFlow2.0】(1) tensor数据类型,类型转换

【TensorFlow2.0】(1) tensor数据类型,类型转换

2023-07-15 19:58| 来源: 网络整理| 查看: 265

各位同学好,今天和大家分享一下TensorFlow2.0中的tensor数据类型,以及各种类型之间的相互转换方法。

1. tf.tensor 基础操作

scaler标量:1.2

vector向量:[1.2]、[1.1,2.2,3.3]      注意:此处的[1.2]是一维的,而1.2是0维的

matrix矩阵:[[1.1,2.2],[3.3,4.4]]

tensor张量:代表任意维度的数据

1.1 创建一个tensor 创建方法: tf.constant(value, shape=维度, dtype=数据类型, verify_shape=False)

value:可以为数值、列表、字符串、布尔型

shape:形状,指维数以及每一维的大小。当第一个参数value是数字时,张量的所有元素都会用该数字填充,shape=[2, 3]。当第一个参数value是一个列表时,注意列表的长度必须小于等于参数shape的大小(即各维大小的乘积)

shape:指定数据类型,如dtype=tf.float64

verify_shape:如果修改为True的话,表示检查value的形状与shape是否相符,如果不符会报错。

a1 = tf.constant(1,shape=[2,2]) # 整型tensor,2行2列都是1 a2 = tf.constant([1,2],dtype=tf.float32) # 浮点型tensor,指定数据类型 a3 = tf.constant(True) #布尔类型 a4 = tf.constant('keep coding') 2.2 tensor和numpy之间的转换 方法: tensor变量.numpy()

将tensor类型变成数组类型显示

# ==2== 和numpy之间的转换 a1.numpy() a5 = tf.range(4) #定义0-3的tensor列表 a5.numpy()

当tensor型数据是一个标量,即只有一个值时,可以直接使用类型转换函数:int()、float()

b = tf.ones([]) # 1 b.numpy() # 输出 1.0 int(b) # int类型的 1 float(b) # float类型的 1 2.3 查看tensor维度及大小 查看维度,返回int类型: tensor名.ndim 查看维度,返回tensor类型: tf.rank(tensor名) 查看tensor的形状: tensor名.shape # 定义一个一维tensor a5 = tf.range(4) a5.ndim # 返回 1 tf.rank(a5) # 返回 1 a6.shape # 返回(4,)

2.4 判断是不是tensor类型

判断变量是否属于该数据类型,返回布尔类型: isinstance(变量, 数据类型)   

判断变量是否是tensor类型,返回布尔类型: tf.is_tensor(变量)

查看变量数据类型,返回数据类型: 变量.dtype

s1 = tf.constant([1.]) s2 = tf.constant([True,False]) s3 = tf.constant('hello') s4 = np.arange(4) # ==1== isinstance(变量,数据类型) # 返回布尔类型 t1 = isinstance(s1,tf.Tensor) # ==2== tf.is_tensor(变量) t2 = tf.is_tensor(s2) t4 = tf.is_tensor(s4) #属于int型数据 # ==3== 变量.dtype # 查看数据类型 t3 = s3.dtype

2. 数据间类型转换 2.1 其他类型转到tensor类型 转到tensor类型方法: tf.convert_to_tensor(变量, dtype=tf.数据类型) a = np.arange(5) #创建numpy类型数据 a.dtype #int32类型的数据 # ==1== 转换到 tensor 数据 b = tf.convert_to_tensor(a) b.dtype #tf.int32类型 2.2 各种类型间的转换 方法: tf.cast(变量, dtype = tf.指定数据类型) a = np.arange(5) #int32类型 b = tf.cast(a,dtype=tf.float32) # 原来b是tf.int32类型,现在变为tf.float32类型

布尔型和整形之间的转换

整型转布尔:0转为False,大于0转为True

布尔转整型:true转为1,false转为0

定义的a1为[0,2,5],最终a3为[0,1,1]

# 定义整形tensor a1 = tf.constant([0,2,5]) # int32 [0,2,5] # 转为布尔型tensor a2 = tf.cast(a1,dtype=tf.bool) # bool [False,True,True] # 再将布尔型转回整形 a3 = tf.cast(a2,dtype=tf.int32) # int32 [0,1,1] 2.3  tf.Variable类型

tf.Variable 类型属于神经网络参数类型,属于tensor类型,记录梯度相关信息,先做了解,后续会详谈。

将tensor类型转为Variable类型: tf.Variable(tensor变量) a = tf.range(5) # 定义一个tensor数据 b = tf.Variable(a) # 变成Variable类型数据 b.trainable # 返回True # 查看数据类型 tf.is_tensor(b) #True,属于tensor



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3