tensorflow基础操作

目录

数据类型:

数据载体:

如何创建一个tensor

        创建随机数

tensor的性质

        检查维度

      检查tensorflow是用cpu还是gpu

      将tensor格式转换成numpy格式

        检查tensor的数据类型

转换tensor

        将格式转换成tensor格式

        tensor间的数据类型转换

         将tensor声明成可训练变量

          将tensor转换成numpy格式

 索引与切片

        两种索引方式

        切片

        选择索引

维度变换

tensor的运算规则

                前置知识

                 tensor的运算

                        加法

                        函数实现        

数学计算


数据类型:

        与C语言类似   - int (整型), float(单精度浮点型) ,double(双精度浮点型)

                                -bool(布尔型,也就是True,Flase)

                                -string(字符型)

数据载体:

        这块就是tensorflow和其他库大相径庭的地方。为了能更好的适应深度学习,具备自动求导,gpu加速等,tensorflow中设计的数据载体为:Tensor

                        零维,也就是scalar,如1.1,2,3之类的标量

                        一维,vector,被称为向量,矢量,因为需要具备方向和大小两种数据,,如[ 1.1],[2.2,1.1],需要注意的是,其与scalar在表现形式上的差别在于数据外面有没有加方括号。

                        二维,matrix,矩阵,方框之外还套着层方框。如[[1.1,2.2,3.3],[4,2,6],[8,5.5,3]].        

                         当维度大于二时(rank>2)时,就称为tensor

        而tensorflow这词也是因此而起,tensor在程序里不断地流动。

如何创建一个tensor

        

        1.tf.constant,如:

#整型
const = tf.constant(1)

#单精度浮点型
flo   = tf.constant(1.1)

#双精度浮点型
dou   = tf.constant( 2. , dtype = tf.double)

#字符型
str   = tf.constant("Hello , Tensorflow")

#布尔型
boo   = tf.constant([ True , Flase ])


        2. tf.convert_to_tensor()

        3. tf.zeros()   #此处函数传递的是shape而不是data

        4.tf.zeros_like() #此处函数传递的是data 其可等价为 

        5.tf.ones() #与3用法一样

        6.tf.oner_like()

        7.tf.fill ( [ 2,3 ] , 0)  #将创建一个矩阵将一个常数填满其中 

        创建随机数

         1. tf.random.normal( shape ,

                                             mean = 0.0 ,

                                              tddev = 1.0  ,

                                              dtype = tf.float32 ,

                                             seed = None , name  = None )                #具有正态分布概率的随机数

        ` shape: 张量类型,必填

        · mean :正态分布的均值 , 默认为0.0

         ·stddev : 正态分布的标准差, 默认为1.0

          ·dtype : 输出的类型 , 默认为tf.float32 

           `seed : 随机种子数,是一个整数,设置后,每次生成的随机数都一样

            `name : 操作的名字 

          2. tf.random.truncated_normal (shape ,mean = 0.0 , tddev = 1.0  ,dtype = tf.float32 , seed = None , name  = None)         #参数与上面如出一辙,不过随机值是从截断的正态分布中输出,生成的值服从具有指定平均值和标准偏差的正态分布,如果生成的值大于平均值2个标准偏差的值则丢弃重新选择

                3. tf.random_uniform(   shape,

                                                        minval=0,

                                                        maxval=None,

                                                        dtype=tf.float32,

                                                        seed=None,

                                                        name=None)         #具有上下限的随数机

        ·minval : 最小值

        ·maxval : 最大值

       4. tf.random.shuffle(value,         

                                        seed = None,

                                        name = None )   #沿着零维打乱

        

a = tf.zeros( [2,5 ] )

tf.zeros_like( a )

#上下这二者等价
tf.zeros( a.shape ) 

tensor的性质

        检查维度

                   1.      .ndim()

                    2.    tf.rank()

                        

 a = tf.constant( 1.1)

 a.ndim()
 print(a.ndim())

 tf.rank(a)
 print(tf.rank(a))

      检查tensorflow是用cpu还是gpu

        .gpu()   .cpu()

      将tensor格式转换成numpy格式

           .numpy()

        检查tensor的数据类型

              1. tf.is_tensor()

              2. .dtype

              3. isinstance(a , tf.Tensor)

转换tensor

        将格式转换成tensor格式

        tf.convert_to_tensor( )

                 

a = tf.constant(1) 


flo_a =  tf.convert_to_tensor(a, dtype =tf.float32) 
print( type( flo_a ) )

dou_a = tf.convert_to_tensor(a , dtype =tf.double)
print( type( dou_a ) )

        

        tensor间的数据类型转换

               tf.cast( a, dtype = tf.  )

         将tensor声明成可训练变量

                 tf.Variable( a )

                注意:此处若是想用isconstance()检查是否为tensor格式,将无法检测出来

                

 a = tf.constant(1)

 a = tf.Variable(a)

 isinstance( a , tf.Tensor)#False

 isinstance( a , tf,Variable)#True

          将tensor转换成numpy格式

              1.  .numpy()

               2. int( a )  #直接用强制类型转换

 索引与切片

        两种索引方式

               1. Basic indexing  # [idx][idx]

               2. Same with Numpy         #[idx,idx] 

        切片

                需配合着第二种索引方式 ,形式为[ start:over  :  step]   #start 为起始下标,默认为0,over为结束下标,默认为最后一个数字+1,step为步长 。 step默认为1。注意,此处设定的切片是包含左左端,不包含右端,故给定数值时需注意

        

  a =tf.range( 5 )
  #[0 ,1, 2, 3, 4]
  
  a[ 1 : 5 : 2]
  #[1, 3]
 
  a[ -1 : -4 : 1 ]
  # [4, 3, 2]   

                 也可用...代替重复冗杂的数值

        

a =tf.random.normal([4,28,28,3])

a.shape
#[4,28,28,3]

a[1,2].shape
#[28,3]

a[0 , ...,0].shape
#[28,28]

a[0 , : : ,: : , 0].shape
#[28,28]

a[...,0].shape
#[4,28,28]

        选择索引

      1. tf.gather(params,

                        axis 

                        indices, 

                        validate_indices=None, 

                        batch_dims=0,

                        name=None )                #就是抽取出params的第axis维度上在indices里面所有的index

 a= tf.random.normal([4,28,28,3])

 tf.gather(a, axis =1 , indices = [4,2]).shape
 # [4,2,28,3]

        2.  tf.gather_nd(params,

                                indices,

                                name=None)

         #在params中的indices中的所有index

 a =tf.random.normal([4,28,28,3])

 tf.gather_nd(a , [0,1]).shape
 # [28,3]
 
 tf.gather_nd(a, [0,1,0]).shape
 #[3]
 

 tf.gather_nd(a, [ [0,0,0],[1,1,1] ]).shape
 #[2,6]

 tf.gather_nd(a , [[[0,0,0],[1,1,1],[2,2,2]]]).shape
 #[1,3,3]

             3.    tf.boolean_mask(
                                                            tensor,
                                                             mask,
                                                            name='boolean_mask',
                                                            axis=None
                                                        )

            

a = tf.random.normal([4,28,28,3]) 

 tf.boolean_mask(a,mask = [True,True,False,False],axis = 0).shape
 #[2,28,28,3]
 
b =tf.ones([2,3,4]) 
 
tf.boolean_mask(b , mask = [ [True,True,False],[True,False,True] ]).shape
 #[4,4]

维度变换

       1.  tf.reshape(

                                tensor,

                                 shape,

                                  name=None

                              )    #注意:只是转换了view而没转换content

        

a = tf.random.normal([4,28,28,3])

tf.reshape(a, [4,-1,3]).shape
#[4,28,28,3]

tf.reshape(a, [4,784,3]).shape
#[4,784,3]

       

     2.   transpose(
                  tensor,
                  perm=None,
                  name='transpose' 
                 )                 
                  
        #转置函数 此函数会将content转换。,若是不设定perm 参数,函数将默认将tensor倒置  
a  = tf.random.normal( [4,10,2])

tf.transpose(a ,[2,1,0]).shape
#[2,10,4]

tensor的运算规则

                此处涉及到线性代数方面的知识

                前置知识

                        两矩阵相加的条件是 两矩阵必须同阶,相加也就是对应位置的数值相加

                          \begin{bmatrix} 2 &2 \\ 3 &2 \end{bmatrix}\ +\begin{bmatrix} 2& 6 \\ 7 & 8 \end{bmatrix}=\begin{bmatrix} 4 &8 \\ 11& 10 \end{bmatrix}

        

                 tensor的运算

                         于是,但两个tensor运算时也需遵守这些规则。但值得注意的是,tensorflow中的乘法和加法会对tensor进行一定变化后才运算。

                        加法

                                两shape不同的tensor,符合最小维度相同也能够相加,如

                                                 \begin{bmatrix} 4 &5 \\ 2 & 2\\ 3&1 \end{bmatrix} + \begin{bmatrix} 1 &1 \end{bmatrix} 

      一个是[3,2] ,另一个是[1,2],它们最小的维度都为2 ,且不相同的维度其为1, tensorflow会将[1,2]转换成[3,2]若是  [3,2] +[2,2]就无法完成转换。

                                                \begin{bmatrix} 1 & 1 \end{bmatrix}  --->\begin{bmatrix} 1 &1 \\ 1&1 \\ 1 &1 \end{bmatrix} 。

                而对于更高维度的tensor加法,同样适用

                        函数实现        

用tf.broadcast_to的好处是:broadcast不会真将矩阵扩大,而是在运行时一个优化手段,既高效又省内存

                

 a =tf.random.normal([2,3,2,4])

 b =tf.random.normal([3,2,4])

 (a+b).shape
#[2,3,2,4]


'''
只要符合规则,tensor会自动变换,
但是这变换其实是有几个步骤,

比如说
a.shape = [3,2,4]  b.shape = [2,3,2,4]
a + b 

需要先将[3,2,4]expand,变成[1,3,2,4]
再tile , 变成[2,3,2,4]

'''
b =tf.random.normal([3,2,4])

b1  = tf.expand_dims(b , axis = 0)
#[1,3,2,4]
b1  = tf.till( b1, [2,1,1,1])
#[2,3,2,4]

#而brocast_to可以一步到位
b2 = tf.brocast_to(b , [2,3,2,4])

数学计算

               element-wise:

                      +(加), -(减), *(点乘,两个相同阶的矩阵,相对位置直接相乘),/(除),

                       **(次方) ,tf.pow(次方)  ,tf.square(平方) ,tf.sqrt(平方根)

                        //(整除),%(取余)

                       tf. exp(以e为底的幂函数),tf.math.log(以e为底的对数)        

                matrix-wise:

                        @(矩阵乘运算,叉乘),tf.matmul(矩阵乘运算) 比如[n,3,4]+[n,4,5] = [ n,3 ,5 ],需保证前个矩阵的列数和后个矩阵的行数相同,且最大的维度相同

                 dim-wise:

                        tf.reduce_mean/max/min/sum

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值