Tensorflow笔记(一)Tensor的数据类型转换

目前处于学习Tensorflow的第一阶段,记录一下我的笔记。

一、tf.tensor的基础知识

scaler(标量):5 6
vector(向量):[1.2]; [1.1,2.2,3.3]
matrix(矩阵):[1.1,2.2];[3.3,4.4]
tensor(张量):rank>2 代表任意维度的数据

二、创建tensor

创建方式tf.constant(value,shape=维度, dtype=数据类型, verify_shape=False)
其中,value:可以为数值、列表、字符串或者布尔型

value数值、列表、字符串或者布尔型
shape形状,指维数以及每一维的大小
dtype指定数据类型,如dtype=tf.float32
verify_shape如果修改为True的话,表示检查value的形状与shape是否相符,如果不符会报错

注意:shape:当第一个参数value是数字时,张量的所有元素都会用该数字填充,shape=[2, 3]。
当第一个参数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')

注:其他创建方式本文不涉及。

三、数据类型

1. Create(初始化)


#int类型    
    tf.constant(1)
   	<tf.Tensor: id=2, shape=(), dtype= int32, numpy=1>
#float类型    
    tf.constant(1.)
   	<tf . Tensor: id=4, shape=(), dtype= float32,numpy=1 . 0>

	tf. constant(2.2, dtype=tf. int32 )
	#TypeError: Cannot convert provided value to Eager Tensor.
    #Provided value: 2.2 Requested dtype: int32
#double类型
	tf. constant(2., dtype=tf . double )
	<tf.Tensor: id=7, shape=( ),dtype= float64, numpy=2 . 0>
#bool类型
	tf. constant( [True, False] )
	<tf .Tensor: id=9, shape=(2, ),dtype-bool, numpy : array([ True, False])>
#string类型	
	tf . constant( 'hello, world.')
	<tf.Tensor: id=14, shape=( ),dtype= string, numpy=b ' hello, world.'>
	

2.Tensor Property(属性)

a.divice
aa = a.gpu()
bb = b.cpu()
b.numpy()
b.shape()
b.ndim()
tf.rank()

例如:(此处以网课截图作为参考案例)
Tensorflow笔记(一)Tensor的数据类型转换

3.Check Tensor Type(判断是否是Tensor)

isinstance(a,tf.Tensor)
tf.is_tensor(b)
a.dtype == tf.float32

例如(仅供参考):

In [1]: a=tf .constant( [1.] )
Out[1]: b=tf .constant( [ True,False] )

In [2]: isinstance(a, tf . Tensor ) 
Out[2]: True

In [3]: tf .is_ tensor( b)
Out[3]: True

4.Convert(类型转换)

a = np.arange(5) #array([0,1,2,3,4])
aa = tf.convert_to_tensor(a) #dtype=int64
aa = tf.convert_to_tensor(a,dtype=tf.int32)

tf.cast(aa,dtype=tf.float32或tf.double或tf.int32)
In [1]: b=tf. constant( [0,1] )
In [2]: tf.cast(b, dtype=tf . bool ) 
Out[2]: <tf . Tensor: id=31, shape=(2,), dtype=bool, numpy=array( [False, True])>

In [3]: bb=tf . cast(b, dtype=tf . bool )
In [4]: tf.cast(bb, tf. int32 )
Out[4]: <tf .Tensor: id=34, shape=(2,), dtype= int32,numpy=array([0, 1], dtype= int32)>

5. tf.Variable

x和y都是Tensor类型,但是w和b都是需要被梯度优化的参数,所以它除了是Tensor类型以外,它还有一个额外的属性,叫做Variable。

w=tf.Variable(w)

w本身是Tensor类型,我们把Tensor再包了一个tf.Variable。
包装后,它就自动具备了一些可求导的特性。程度会自动对Variable类型进行梯度信息的跟踪(记录)。

它是专门神经网络的参数所设计的类型

ininstance(b,tf.Tensor) #False

tf.is_tensor(b) #True

建议用is_tensor和dtype判断类型

Tensorflow笔记(一)Tensor的数据类型转换

6.To numpy

int(Tensor):转化为int

float(Tensor):转化为float

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2023年3月10日
下一篇 2023年3月10日

相关推荐