TF2.0笔记1

Tensor的数据类型

张量的创建

数据类型:
1.int32
2. float32
3. float64 对应 tf.double
4. bool
5. string

使用tf.constant()可以创建一个Tensor

tf.constant(1)
tf.constant(1.)
tf.constant(2.2,dtyoe=tf.double)
tf.constant([True,False])
tf.constant('helllo world')

相关属性

我们假设有一个tensor a
1.a.device
显示该张量所处于的设备,实在gpu:x或者cpu上
张量的相关操作必须在同一个设备上

2.a.gpu()
把张量a转移到gpu上

3.a.cpu()
把张量转换到cpu上

4.a.shape
返回一个list,展示一个tensor的shape

5.a.ndim或a.rank
返回一个tensor,表示这个tensor的纬度
[1,1,1,1] ---->返回tensor[1]

6.检查tensor的数据类型

常规的python方法 isinstance
检查a是否为tf.Tensor的子类

isinstance(a,tf.Tensor)

用tf2.0自有的api检查
api:tf.is_tensor()

tf.is_tensor(a)

7.获取Tensor的数据类型
a.dtype ==tf.float32
a.dtype ==tf.string
上面的代码展示了如何获取数据类型,并作出判断

类型转换

1.numpy转为tensor

api:tf.conver_to_tensor

a=np.arange(5)
tensor_a=tf.conver_to_tensor(a)
tensor_a=tf.conver_to_tensor(a,dtype=tf.int32)

2.tensor的类型互相转换
api:tf.cast()

tf.cast(aa,dtype=tf.double)
#把aa转化为float64类型

把aa转化为dtype类型
对于int和bool类型互相转化,可以让1 0和True False互相转化

3.把tensor转化为numpy
同时在gpu上的数据会自动返回到cpu上

a.numpy()

tf.Variable

把tensor进行一个修饰,让其具有梯度属性
内部属性:
1.name
tensor的名字
2.trainable
布尔值,tensor是否可训练

注意:要判断一个变量是否为variable时,需要使用tf.is_tensor,使用python内部的isinstance会产生错误的结果。

Tensor的创建

从numpy和list创建一个tensor

从numpy
1.tf.convert_to_tensor(np.ones([2,3]))

从list
2.tf.conver_to_tensor([1,2])

从api创建

1.tf.zeros()
括号内部的参数为shape
创建标量0 ------->tf.zeros([ ])

2.tf.zeros_like()
内部的参数为一个tensor,表示创建一个和括号内部变量相同shape的tensor
相当于复制了,参数tensor的纬度的一个全0张量

3.tf.fill()
两个参数,参数1为shape,参数2为要填充的值

4.Normal用正态分布初始化
tf.random.normal([2,2],mean=1,std=1)
默认为0 1分布

tf.random.trucated_normal()
截断型正态分布

tf.random.uniform([2,2],minval=0,maxval=1)
均分分布,从0到1之间

5.随机化shuffle( Random permutation )

idx=tf.range(10)
idx=tf.random.shuffle(idx)

a=tf.random.normal([10,784])
lable=tf.random.uniform([10],minval=0.maxval=10,dtype=tf.int32)

a=tf.gather(a,idx)
lables=tf.gather(label.idx)

6.tf.constant类似于tf.conver_to_tensor
接受scalar和list

猜你喜欢

转载自blog.csdn.net/weixin_43869493/article/details/106229256