解釋張量及TF的一些API


張量的定義

  張量(Tensor)理論是數學的一個分支學科,在力學中有重要應用。張量這一術語起源於力學,它最初是用來表示彈性介質中各點應力狀態的,后來張量理論發展成為力學和物理學的一個有力的數學工具。張量之所以重要,在於它可以滿足一切物理定律必須與坐標系的選擇無關的特性。張量概念是矢量概念的推廣,矢量是一階張量。張量是一個可用來表示在一些矢量、標量和其他張量之間的線性關系的多線性函數(可以理解成是向量、矩陣以及更高維結構的統稱)。

  But we don’t have to restrict ourselves to linear algebra. As it turns out, we can move up the mathematical food chain a bit. It has long been known that there are bigger fish in the mathematical abstraction sea than just matrices. One such candidate is called a tensor. Tensors figure prominently in the mathematical underpinnings of general relativity and are fundamental to other branches of physics as well. But just as the mathematical concepts of matrices and vectors can be simplified down to the arrays we use in computers, tensors can also be simplified and represented as multidimensional arrays and some related operations. Unfortunately, things aren’t quite as simple as they were with matrices and vectors, largely because there isn’t an obvious and simple set of operations to be performed on tensors like there were with matrices and vectors.

  There is some really good news, though. Even though we can’t write just a few operations on tensors, we can write down a set of patterns of operations on tensors. That isn’t quite enough, however, because programs written in terms of these patterns can’t be executed at all efficiently as they were written. The rest of the good news is that our inefficient but easy to write programs can be transformed (almost) automatically into programs that do execute pretty efficiently.

  以下內容基於Tensorflow框架。(下面代碼是在notebook寫的,所以import tensorflow as tf只寫了一次,需要的自行添加)

Tensor基本操作

tensor的數據類型及屬性

  tensorflow中的數據類型有int、float、double、bool、string。

  創建這些數據的相應code例子如下:

tf.constant(1)
tf.constant(1.)
tf.constant(2.2,dtype=tf.int32)
tf.constant(2.,dtype=tf.double)
tf.constant([True,False])
tf.constant('Hello World')

  屬性

  1、device查看tensor的創建環境

a=tf.range(5)
a.device
輸出:
  '/job:localhost/replica:0/task:0/device:CPU:0'

   2、numpy將tensor數據類型轉numpy數據類型

a.numpy()
輸出:
  array([0, 1, 2, 3, 4], dtype=int32)

  3、ndimtensor的維度

a.ndim
輸出:
  1

  4、shapetensor的形狀

a.shape
輸出:
  TensorShape([5])

  5、ranktensor的維度,不過返回的是一個tensor

tf.rank(a)
tf.rank(tf.ones([1,2,3])) 輸出:   
<tf.Tensor: id=8, shape=(), dtype=int32, numpy=1> ##numpy是內容
  <tf.Tensor: id=12, shape=(), dtype=int32, numpy=3>

  6、isinstance/is_tensor判斷是不是tensor

way1:isinstance(a,tf.Tensor)
way2:tf.is_tensor(a)
輸出:
  True
  True

  7、dtype數據類型

a.dtype
輸出:
  tf.int32

  8、convert_to_tensornumpy轉tensor

import numpy as np
a=np.arange(5)
aa=tf.convert_to_tensor(a,dtype=tf.int32)
aa
輸出:
  <tf.Tensor: id=16, shape=(5,), dtype=int32, numpy=array([0, 1, 2, 3, 4], dtype=int32)>

  9、cast數據類型轉換

tf.cast(aa,dtype=tf.float32)
輸出:
  <tf.Tensor: id=17, shape=(5,), dtype=float32, numpy=array([0., 1., 2., 3., 4.], dtype=float32)>

  10、Variable:賦予參數一些額外的屬性

a=tf.range(5)
b=tf.Variable(a,name='asuka')
b.name
b.trainable #可求導
輸出:
  'asuka:0'
  True

  注意,

isinstance(b,tf.Tensor)   #所以 不推薦使用isinstance這種類型,還是用is_tensor比較好
isinstance(b,tf.Variable)
tf.is_tensor(b)
輸出:
  False
  True
  True

創建Tensor

  1、tf.convert_to_tensor

tf.convert_to_tensor(np.ones([2,2]))
tf.convert_to_tensor([[1],[2.]])
輸出:
  <tf.Tensor: id=79, shape=(2, 2), dtype=float64, numpy=
  array([[1., 1.],
         [1., 1.]])>
  <tf.Tensor: id=82, shape=(2, 1), dtype=float32, numpy=
  array([[1.],
         [2.]], dtype=float32)>

  2、tf.zeros/tf.ones

tf.zeros([])   #標量0
tf.zeros([1]) 
tf.zeros([2,2])
# tf.ones的代碼一樣,只是0變成了1
輸出:
  <tf.Tensor: id=89, shape=(), dtype=float32, numpy=0.0>
  <tf.Tensor: id=93, shape=(1,), dtype=float32, numpy=array([0.], dtype=float32)>
  <tf.Tensor: id=94, shape=(2, 2), dtype=float32, numpy=
  array([[0., 0.],
         [0., 0.]], dtype=float32)>

  此外,需要補充一下tf.zeros_like(a)/tf.ones_like(a)這種便捷功能。其生成tensor的shape與a一致,相當於tf.zeros(a.shape)/tf.ones(a.shape)

tf.zeros_like(a)
tf.ones_like(a)
輸出:
  <tf.Tensor: id=95, shape=(5,), dtype=int32, numpy=array([0, 0, 0, 0, 0], dtype=int32)>
  <tf.Tensor: id=98, shape=(5,), dtype=int32, numpy=array([1, 1, 1, 1, 1], dtype=int32)>

  3、tf.fill

tf.fill([2,2],66)
tf.fill([2,2],0.1)
輸出:
  <tf.Tensor: id=104, shape=(2, 2), dtype=int32, numpy=
  array([[66, 66],
         [66, 66]], dtype=int32)>
  <tf.Tensor: id=107, shape=(2, 2), dtype=float32, numpy=
  array([[0.1, 0.1],
         [0.1, 0.1]], dtype=float32)>

  4、隨機初始化

  ①正態分布:tf.random.normal([2,2], mean=0,stddev=1)

  ②截斷的正態分布:tf.random.truncated_normal([2,2], mean=0,stddev=1)

  ③均勻分布:tf.random.uniform([2,2],minval=0,maxval=1)

tf.random.normal([2,2], mean=0,stddev=1)
tf.random.truncated_normal([2,2], mean=0,stddev=1)
tf.random.uniform([2,2],minval=0,maxval=1)
輸出:
  <tf.Tensor: id=113, shape=(2, 2), dtype=float32, numpy=
  array([[-0.21209939, -0.64754343],
         [-1.0172042 ,  0.41624036]], dtype=float32)>
  <tf.Tensor: id=119, shape=(2, 2), dtype=float32, numpy=
  array([[-0.86256725, -0.72628754],
         [-0.3911226 ,  0.64116365]], dtype=float32)>
  <tf.Tensor: id=126, shape=(2, 2), dtype=float32, numpy=
  array([[0.92780185, 0.4641881 ],
         [0.30780447, 0.47879505]], dtype=float32)>

  補充:

idx = tf.range(10)
idx = tf.random.shuffle(idx)     #對idx進行隨機打散
a = tf.random.normal([10,784])
a = tf.gather(a,idx)      #利用idx索引對a進行隨機打散
idx
a
輸出:
  <tf.Tensor: id=170, shape=(10,), dtype=int32, numpy=array([6, 3, 1, 4, 8, 9, 5, 7, 2, 0], dtype=int32)>
  <tf.Tensor: id=178, shape=(10, 784), dtype=float32, numpy=
  array([[-0.6336075 ,  1.4922131 , -2.320528  , ...,  0.2953391 ,
          -0.40848997,  0.9237991 ],
         [-1.1071885 ,  1.8510056 , -0.4211796 , ..., -0.11134891,
           0.00801583,  0.42422166],
         [-0.3443342 ,  1.5786427 , -3.8558512 , ...,  0.80399513,
           0.36636525, -0.29242495],
         ...,
         [-0.45643282, -0.99563426,  2.7573252 , ..., -1.9459194 ,
          -1.8840737 ,  0.5211977 ],
         [ 0.7347293 ,  0.59493566, -0.00406144, ..., -1.0898517 ,
          -0.3647101 ,  1.9180689 ],
         [-0.10276955, -0.71196973,  0.779926  , ..., -0.07749026,
          -0.25664854,  0.7480723 ]], dtype=float32)>

索引

  寫法一:用框框分隔

a = tf.ones([1,5,5,3])
a[0][0]
a[0][0][0]
輸出:
  array([[1., 1., 1.],
         [1., 1., 1.],
         [1., 1., 1.],
         [1., 1., 1.],
         [1., 1., 1.]], dtype=float32)>
  <tf.Tensor: id=106, shape=(3,), dtype=float32, numpy=array([1., 1., 1.], dtype=float32)>

  寫法二:用逗號分隔

a = tf.random.normal([1,5,5,3])
a[0,0]
a[0,2].shape
輸出:
  <tf.Tensor: id=130, shape=(5, 3), dtype=float32, numpy=
  array([[-0.35566926, -0.96789527, -0.930224  ],
         [-1.1206602 ,  0.88065714, -0.07800838],
         [-0.09039619,  0.03437081, -1.5635891 ],
         [ 0.20114912, -1.0815347 ,  0.30600008],
         [ 1.9283246 , -0.6195314 , -0.28424558]], dtype=float32)>
  TensorShape([5, 3])

切片

  start : end

a = tf.range(10)
a[-2:]
a[:2]
輸出:
  <tf.Tensor: id=164, shape=(2,), dtype=int32, numpy=array([8, 9], dtype=int32)>
  <tf.Tensor: id=176, shape=(2,), dtype=int32, numpy=array([0, 1], dtype=int32)>

  start : end : step

a = tf.range(5)
a[::-1]
a[::-2]
a[3:1:-2]
輸出:
  <tf.Tensor: id=200, shape=(5,), dtype=int32, numpy=array([4, 3, 2, 1, 0], dtype=int32)>
  <tf.Tensor: id=212, shape=(3,), dtype=int32, numpy=array([4, 2, 0], dtype=int32)>
  <tf.Tensor: id=228, shape=(1,), dtype=int32, numpy=array([3], dtype=int32)>

  相關函數

  1、tf.gather

  進行切片

  格式:tf.gather(params, indices, validate_indices=None, name=None, axis=0)

  其中,params表示待切的張量,indices表示取出數據的位置,axis指定切片所在的維度。

a = tf.random.normal([6,5,4],mean=1,stddev=1)
tf.gather(a,axis=0,indices=[2,3])
輸出:
  <tf.Tensor: id=237, shape=(2, 5, 4), dtype=float32, numpy=
  array([[[ 1.5593833 ,  1.0110648 ,  1.9511329 ,  1.2995625 ],
          [ 1.2551384 ,  2.2249537 ,  1.9536419 ,  2.041832  ],
          [ 0.9333749 ,  1.4165081 , -0.43102372,  2.3897305 ],
          [ 1.4070803 ,  1.4304484 ,  0.5074375 ,  0.1073221 ],
          [ 2.384912  , -1.0563302 ,  0.6985694 ,  1.1213328 ]],
  
         [[ 1.8210306 , -0.6484443 ,  0.4258331 ,  0.88605404],
          [ 0.6124698 , -0.654827  ,  2.163889  ,  1.2491949 ],
          [ 1.1132616 , -0.8744116 ,  1.5687683 ,  2.0351982 ],
          [ 0.93111885,  0.4436323 ,  1.5315795 ,  0.6178591 ],
          [-0.42866087,  1.9578406 ,  1.157727  ,  1.241925  ]]],
        dtype=float32)>

  2、tf.gather_nd

  也是切片,允許在多維上進行索引。

  格式:tf.gather_nd(params, indices, name=None)

a = tf.random.normal([6,5,4],mean=1,stddev=1)
tf.gather_nd(a, [[0,1],[1,1]])
tf.gather_nd(a, [[0,1],[1,1],[2,2]])
輸出:
  <tf.Tensor: id=265, shape=(2, 4), dtype=float32, numpy=
  array([[0.99216527, 1.2477858 , 0.14764303, 0.2085458 ],
        [0.65654033, 2.0438895 , 0.3014146 , 0.66133136]], dtype=float32)>
  <tf.Tensor: id=285, shape=(3, 4), dtype=float32, numpy=
  array([[-1.5789361 , 1.6277008 , 1.1488252 , 1.8736987 ],
   [-0.49054933, 1.8427005 , 0.77670544, 0.14120448],
   [ 0.41770607, 0.6793497 , -0.94432163, 0.8347257 ]], dtype=float32)>

  3、tf.boolean_mask

  按mask指定的列進行過濾,默認維度是0。

  格式:tf.boolean_mask(params,mask,name='boolean_mask',axis=None)

a = tf.ones([2,3,4])
tf.boolean_mask(a, mask=[True,True,True,False], axis=2)
輸出:
  <tf.Tensor: id=316, shape=(2, 3, 3), dtype=float32, numpy=
  array([[[1., 1., 1.],
          [1., 1., 1.],
          [1., 1., 1.]],
  
         [[1., 1., 1.],
          [1., 1., 1.],
          [1., 1., 1.]]], dtype=float32)>

維度變換

  1、tf.reshape

  作用:重新排列

a = tf.random.normal([6,4,8,4], mean=1, stddev=1)
a.shape
a.dim
輸出:
    Tensorshape([6, 4, 8, 4])
    4
tf.reshape(a,[6,4*8,4]).shape
tf.reshape(a,[6,-1,4]).shape    #位置維度時,可以用-1填充
輸出:
    Tensorshape([6, 32, 4])
    Tensorshape([6, 32, 4])
tf.reshape(tf.reshape(a, [6, -1]), [6, 4, -1, 4]).shape
輸出:
    Tensorshape([6, 4, 8, 4])

  2、tf.transpose

  作用:轉置

  格式:tf.transpose(a, perm=None, name='transpose', conjugate=False)

  其中,a指需要變換的張量,perm指a的新的維度序列,默認將所有的軸進行轉置。

a = tf.random.normal([4,3,2,1]) 
a.shape 
tf.transpose(a).shape  #默認將所有軸進行轉置
tf.transpose(a,perm=[0,1,3,2]).shape
輸出:
    TensorShape([4, 3, 2, 1])
    TensorShape([1, 2, 3, 4])
    TensorShape([4, 3, 1, 2])

  3、tf.expand_dims

  作用:擴充維度(對於張量a,在axis軸處為其增加一個為1的維度)

  格式tf.expand_dims(a, axis=None)

a = tf.random.normal([3,4,5])
a.shape
tf.expand_dims(a,axis=0).shape
輸出:
    TensorShape([3, 4, 5])
    TensorShape([1, 3, 4, 5])
tf.expand_dims(a,axis=-1).shape
輸出:
    TensorShape([3, 4, 5, 1])

  4、tf.squeeze

  作用:去掉為1的維度,默認檢索所有軸。

  格式:tf.expand_dims(a, axis=None)

a = tf.zeros([1,2,1,1,3])
a.shape
tf.squeeze(a,axis=0).shape
tf.squeeze(a,axis=-2).shape
tf.squeeze(a).shape
輸出:
    TensorShape([1, 2, 1, 1, 3])
    TensorShape([2, 1, 1, 3])
    TensorShape([1, 2, 1, 3])
    TensorShape([2, 3])

基本運算

  1、加(+)、減(-)、乘(*)、除(/)、整除(//)、取余(%)、n次方(**)

a = tf.ones([2,2])
b = tf.fill([2,2],2.)
a+b
a-b
a*b
a/b
a//b
a%b
b**3

  2、tf.math.log()tf.math.exp()

a = tf.fill([2,2], 10.)
tf.math.log(a)  #取對數
tf.math.exp(a)  #取指數
tf.math.log(a)/tf.math.log(2.)  #計算矩陣對應元素以2為底的對數
輸出:
    <tf.Tensor: id=54, shape=(2, 2), dtype=float32, numpy=
    array([[2.3025851, 2.3025851],
           [2.3025851, 2.3025851]], dtype=float32)>
    <tf.Tensor: id=59, shape=(2, 2), dtype=float32, numpy=
    array([[22026.465, 22026.465],
           [22026.465, 22026.465]], dtype=float32)>
  <tf.Tensor: id=68, shape=(2, 2), dtype=float32, numpy=
  array([[3.321928, 3.321928],
         [3.321928, 3.321928]], dtype=float32)>

  3、tf.pow()tf.sqrt()

a = tf.fill([2,2], 2.)
tf.pow(a,3)   #立方,等效於a**3
tf.sqrt(a)      #開方
輸出:
    <tf.Tensor: id=101, shape=(2, 2), dtype=float32, numpy=
    array([[8., 8.],
              [8., 8.]], dtype=float32)>
    <tf.Tensor: id=107, shape=(2, 2), dtype=float32, numpy=
    array([[1.4142135, 1.4142135],
           [1.4142135, 1.4142135]], dtype=float32)>

  4、矩陣相乘:@/matmul

a = tf.fill([2,2],2.)
b = tf.fill([2,2],3.)
a @ b  #矩陣相乘
tf.matmul(a,b)#矩陣相乘的第二種寫法
輸出:
  <tf.Tensor: id=115, shape=(2, 2), dtype=float32, numpy=
  array([[12., 12.],
         [12., 12.]], dtype=float32)>

廣播

  Tensorflow中的廣播機制類似於numpy中的廣播機制,給出以下例子。

import tensorflow as tf
a = tf.reshape(range(12),[4,3])
輸出:
<tf.Tensor: id=42, shape=(4, 3), dtype=int32, numpy=
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]], dtype=int32)>
b = tf.cast(tf.ones([1,3]),dtype=tf.int32)
輸出:
<tf.Tensor: id=53, shape=(1, 3), dtype=int32, numpy=array([[1, 1, 1]], dtype=int32)>
c = a - b   #這種操作是隱式的
輸出:
<tf.Tensor: id=55, shape=(4, 3), dtype=int32, numpy=
array([[-1,  0,  1],
       [ 2,  3,  4],
       [ 5,  6,  7],
       [ 8,  9, 10]], dtype=int32)>
這里舉一個廣播和的矩陣相乘的例子
a = tf.fill([4,2,3],1.)
b = tf.fill([3,5],2.)
c = tf.broadcast_to(b,[4,3,5])
a @ c
輸出:
    <tf.Tensor: id=124, shape=(4, 2, 5), dtype=float32, numpy=
    array([[[6., 6., 6., 6., 6.],
            [6., 6., 6., 6., 6.]],
    
           [[6., 6., 6., 6., 6.],
            [6., 6., 6., 6., 6.]],
    
           [[6., 6., 6., 6., 6.],
            [6., 6., 6., 6., 6.]],
    
           [[6., 6., 6., 6., 6.],
            [6., 6., 6., 6., 6.]]], dtype=float32)>

高階操作

合並&分割

  1、tf.concat

  作用:合並

a = tf.ones([5,10,8])
b = tf.ones([5,10,8])
c = tf.concat([a,b],axis=2)
c.shape
輸出:
    TensorShape([5, 10, 16])

  2、tf.stack

  作用:堆疊(開辟新的維度)

a = tf.ones([5,10,8])
b = tf.ones([5,10,8])
c = tf.stack([a,b],axis=2)
c.shape
輸出:
  TensorShape([5, 10, 2, 8])

  3、tf.unstack

  作用:解堆疊

a = tf.ones([5,10,8])
b = tf.ones([5,10,8])
c = tf.stack([a,b],axis=2)
aa,bb = tf.unstack(c,axis=2)
aa.shape,bb.shape
輸出:
    (TensorShape([5, 10, 8]), TensorShape([5, 10, 8]))

  4、tf.split

  作用:分割

a = tf.ones([5,10,8])
b = tf.ones([5,10,8])
c = tf.stack([a,b],axis=2)
res=tf.split(c, axis=2, num_or_size_splits=2)
res[0].shape,res[1].shape
輸出:
    (TensorShape([5, 10, 1, 8]), TensorShape([5, 10, 1, 8]))

填充

  格式:tf.pad(tensor, paddings, mode="CONSTANT", name=None, constant_values=0)

a = range(9)
a = tf.reshape(a,[3,3])
# 不填充
tf.pad(a,[[0,0],[0,0]])
輸出:
    <tf.Tensor: id=564, shape=(3, 3), dtype=int32, numpy=
    array([[0, 1, 2],
           [3, 4, 5],
           [6, 7, 8]], dtype=int32)>
# 填充
tf.pad(a,[[1,0],[0,0]])
輸出:
    <tf.Tensor: id=566, shape=(4, 3), dtype=int32, numpy=
    array([[0, 0, 0],
           [0, 1, 2],
           [3, 4, 5],
           [6, 7, 8]], dtype=int32)>
tf.pad(a,[[1,1],[1,1]])
輸出:
    <tf.Tensor: id=568, shape=(5, 5), dtype=int32, numpy=
    array([[0, 0, 0, 0, 0],
           [0, 0, 1, 2, 0],
           [0, 3, 4, 5, 0],
           [0, 6, 7, 8, 0],
           [0, 0, 0, 0, 0]], dtype=int32)>

  假設輸入的tensor有三個維度,paddings參數設置為 paddings = [[a,b], [c,d], [e,f]]

  其中,a,b表示為axis=0維度上最前面填充a行,最后面填充b行;c,d表示為axis=1維度上最前面填充c列,最后面填充d列;e,f表示為axis=2維度上最前面填充e,最后面填充f。更高維的以此類推。

復制

  格式:tf.tile(amultiples, name=None)

  其中,multiples為在某一維度上復制的次數。

a = tf.range(9)
a = tf.reshape(a,[3,3])
# 不復制
tf.tile(a,[1,1])
輸出:
  <tf.Tensor: id=576, shape=(3, 3), dtype=int32, numpy=
  array([[0, 1, 2],
         [3, 4, 5],
         [6, 7, 8]], dtype=int32)>
# 復制
tf.tile(a,[2,1])  #在axis=0維度上復制2次
輸出:
  <tf.Tensor: id=578, shape=(6, 3), dtype=int32, numpy=
  array([[0, 1, 2],
         [3, 4, 5],
         [6, 7, 8],
         [0, 1, 2],
         [3, 4, 5],
         [6, 7, 8]], dtype=int32)>
tf.tile(a,[1,2])  #在axis=1維度上復制2次
輸出:
  <tf.Tensor: id=580, shape=(3, 6), dtype=int32, numpy=
  array([[0, 1, 2, 0, 1, 2],
         [3, 4, 5, 3, 4, 5],
         [6, 7, 8, 6, 7, 8]], dtype=int32)>
tf.tile(a,[2,2])  #在axis=0和axis=1維度上分別復制2次,先復制小維度,再復制大維度
輸出:
  <tf.Tensor: id=582, shape=(6, 6), dtype=int32, numpy=
  array([[0, 1, 2, 0, 1, 2],
         [3, 4, 5, 3, 4, 5],
         [6, 7, 8, 6, 7, 8],
         [0, 1, 2, 0, 1, 2],
         [3, 4, 5, 3, 4, 5],
         [6, 7, 8, 6, 7, 8]], dtype=int32)>

  與廣播機制相比,broadcast_to相當於先expand_dims,再tile。

a = tf.reshape(tf.range(9),[3,3])
# broadcast_to相當於先expand_dims,再tile
# way1
aa = tf.expand_dims(a,axis=0)#先擴充維度 
bb = tf.tile(aa,[2,1,1])
# way2
cc = tf.broadcast_to(a,[2,3,3])
輸出:
    <tf.Tensor: id=594, shape=(2, 3, 3), dtype=int32, numpy=
    array([[[0, 1, 2],
            [3, 4, 5],
            [6, 7, 8]],

           [[0, 1, 2],
            [3, 4, 5],
            [6, 7, 8]]], dtype=int32)>

數據統計

  1、norm

  作用:求范數。

a = tf.ones([2,2])
#求a的二范數
tf.norm(a)#第一種寫法
    #<tf.Tensor: id=387, shape=(), dtype=float32, numpy=2.0> tf.sqrt(tf.reduce_sum(tf.square(a))) #第二種寫法 #<tf.Tensor: id=399, shape=(), dtype=float32, numpy=2.0> tf.norm(a,ord=2,axis=1) #求a在軸1方向上的二范數 #<tf.Tensor: id=416, shape=(2,), dtype=float32, numpy=array([1.4142135, 1.4142135], dtype=float32)> tf.norm(a,ord=1) #求a的一范數 #<tf.Tensor: id=437, shape=(), dtype=float32, numpy=4.0> tf.norm(a,ord=1,axis=0) #求a在軸0方向上的一范數 #<tf.Tensor: id=462, shape=(2,), dtype=float32, numpy=array([2., 2.], dtype=float32)> tf.norm(a,ord=1,axis=1) #求a在軸1方向上的一范數 #<tf.Tensor: id=462, shape=(2,), dtype=float32, numpy=array([2., 2.], dtype=float32)>

  2、max/min/mean

  作用:求最小值、最大值和均值

b = tf.random.normal([4,10])
tf.reduce_min(b)
    #<tf.Tensor: id=470, shape=(), dtype=float32, numpy=-2.5767317>
tf.reduce_max(b)
    #<tf.Tensor: id=472, shape=(), dtype=float32, numpy=1.5258235>
tf.reduce_mean(b)
    #<tf.Tensor: id=474, shape=(), dtype=float32, numpy=-0.22544508>
tf.reduce_min(b,axis=1)  #對軸1方向取最小值
    #<tf.Tensor: id=476, shape=(4,), dtype=float32, numpy=array([-2.3222475, -2.0107253, -1.5776284, -2.5767317], dtype=float32)>
tf.reduce_max(b,axis=1)  #對軸1方向取最大值  
    #<tf.Tensor: id=478, shape=(4,), dtype=float32, numpy=array([1.416933 , 1.5258235, 1.0989064, 1.1648433], dtype=float32)>
tf.reduce_mean(b,axis=1) #對軸1方向取均值
    #<tf.Tensor: id=480, shape=(4,), dtype=float32, numpy=array([-0.05750545, -0.18739279, -0.3392655 , -0.31761646], dtype=float32)>

  3、tf.argmax、tf.argmin

  作用:求最大值、最小值位置

c = tf.random.normal([4,10])     
tf.argmax(c).shape
    #TensorShape([10])
tf.argmax(c)
    #<tf.Tensor: id=490, shape=(10,), dtype=int64, numpy=array([2, 0, 1, 2, 3, 0, 2, 3, 0, 0])>
tf.argmin(c).shape 
    #TensorShape([10])
tf.argmin(c)      
    #<tf.Tensor: id=494, shape=(10,), dtype=int64, numpy=array([0, 2, 3, 1, 0, 1, 3, 2, 2, 3])>
tf.argmax(c,axis=1) 
    #<tf.Tensor: id=496, shape=(4,), dtype=int64, numpy=array([1, 7, 0, 7])>
tf.argmin(c,axis=1)
    #<tf.Tensor: id=498, shape=(4,), dtype=int64, numpy=array([6, 3, 8, 9])>

  4、tf.equal

  作用:判斷矩陣中數據相等。

d1 = tf.constant([0,2,3,2,4])
d2 = tf.range(5)
res = tf.equal(d1,d2)
d1,d2,res
輸出:
  (<tf.Tensor: id=499, shape=(5,), dtype=int32, numpy=array([0, 2, 3, 2, 4], dtype=int32)>,
   <tf.Tensor: id=503, shape=(5,), dtype=int32, numpy=array([0, 1, 2, 3, 4], dtype=int32)>,
   <tf.Tensor: id=504, shape=(5,), dtype=bool, numpy=array([ True, False, False, False,  True])>)

   通過比較數據,我們可以計算數據預測的准確度。

e = tf.constant([[0.1,0.2,0.7],[0.9,0.05,0.05],[0.1,0.8,0.1],[0.01,0.99,0]])
pred = tf.cast(tf.argmax(e,axis=1),dtype=tf.int32)
e,pred
輸出:
  (<tf.Tensor: id=518, shape=(4, 3), dtype=float32, numpy=
   array([[0.1 , 0.2 , 0.7 ],
          [0.9 , 0.05, 0.05],
          [0.1 , 0.8 , 0.1 ],
          [0.01, 0.99, 0.  ]], dtype=float32)>,
   <tf.Tensor: id=521, shape=(4,), dtype=int32, numpy=array([2, 0, 1, 1], dtype=int32)>)
y = tf.constant([2,0,1,2])
correct_num = tf.reduce_sum(tf.cast(tf.equal(pred,y),dtype=tf.int32))
accuracy = correct_num /e.shape[0]
correct_num,accuracy
輸出: 
  (<tf.Tensor: id=526, shape=(), dtype=int32, numpy=3>,
   <tf.Tensor: id=530, shape=(), dtype=float64, numpy=0.75>)   

  5、tf.unique

  作用:找不重復的地方

f1 = tf.range(5) 
Unique,idx = tf.unique(f1) 
Unique,idx
    #(<tf.Tensor: id=535, shape=(5,), dtype=int32, numpy=array([0, 1, 2, 3, 4], dtype=int32)>,
    #<tf.Tensor: id=536, shape=(5,), dtype=int32, numpy=array([0, 1, 2, 3, 4], dtype=int32)>)
f2 = tf.constant([4,2,2,4,3])  
Unique,idx = tf.unique(f2)
Unique,idx
    #(<tf.Tensor: id=538, shape=(3,), dtype=int32, numpy=array([4, 2, 3], dtype=int32)>,
    #<tf.Tensor: id=539, shape=(5,), dtype=int32, numpy=array([0, 1, 1, 0, 2], dtype=int32)>)
ff = tf.gather(Unique,idx)
ff
    #<tf.Tensor: id=541, shape=(5,), dtype=int32, numpy=array([4, 2, 2, 4, 3], dtype=int32)>

排序

  1、sort/argsort

   sort是按照升序或降序對張量進行排序,而argsort是按照升序或者降序對張量進行排序,返回的是索引。

  一維排序時,

# 一維
a = tf.range(5)
a = tf.random.shuffle(a)
輸出:
  <tf.Tensor: id=599, shape=(5,), dtype=int32, numpy=array([2, 1, 0, 3, 4], dtype=int32)>
tf.sort(a,direction='ASCENDING') #按照升序進行排列
輸出:
  <tf.Tensor: id=610, shape=(5,), dtype=int32, numpy=array([0, 1, 2, 3, 4], dtype=int32)>
tf.sort(a,direction='DESCENDING') #按照降序進行排列
輸出:
  <tf.Tensor: id=618, shape=(5,), dtype=int32, numpy=array([4, 3, 2, 1, 0], dtype=int32)>
idx_a = tf.argsort(a,direction='ASCENDING') #按照升序排列,並返回索引
輸出:
  <tf.Tensor: id=639, shape=(5,), dtype=int32, numpy=array([2, 1, 0, 3, 4], dtype=int32)>
idx_d = tf.argsort(a,direction='DESCENDING') #按照降序排列,並返回索引
輸出:
  <tf.Tensor: id=648, shape=(5,), dtype=int32, numpy=array([4, 3, 0, 1, 2], dtype=int32)>
tf.gather(a,idx_a)
輸出:
  <tf.Tensor: id=650, shape=(5,), dtype=int32, numpy=array([0, 1, 2, 3, 4], dtype=int32)>
tf.gather(a,idx_d)
輸出:
  <tf.Tensor: id=652, shape=(5,), dtype=int32, numpy=array([4, 3, 2, 1, 0], dtype=int32)>

  二維排序時,

# 二維
a = tf.random.uniform([3,3],minval=1,maxval=10,dtype=tf.int32) 
輸出:
<tf.Tensor: id=660, shape=(3, 3), dtype=int32, numpy=
array([[5, 9, 5],
       [1, 5, 4],
       [2, 2, 9]], dtype=int32)>
tf.sort(a,direction='ASCENDING')
輸出:
    <tf.Tensor: id=671, shape=(3, 3), dtype=int32, numpy=
    array([[5, 5, 9],
           [1, 4, 5],
           [2, 2, 9]], dtype=int32)>
tf.sort(a,direction='DESCENDING')
輸出:
    <tf.Tensor: id=679, shape=(3, 3), dtype=int32, numpy=
    array([[9, 5, 5],
           [5, 4, 1],
           [9, 2, 2]], dtype=int32)>
idx_a = tf.argsort(a,direction='ASCENDING')
輸出:
    <tf.Tensor: id=709, shape=(3, 3), dtype=int32, numpy=
    array([[0, 2, 1],
           [0, 2, 1],
           [0, 1, 2]], dtype=int32)>
idx_d = tf.argsort(a,direction='DESCENDING')
輸出:
    <tf.Tensor: id=718, shape=(3, 3), dtype=int32, numpy=
    array([[1, 0, 2],
           [1, 2, 0],
           [2, 0, 1]], dtype=int32)>

  2、top_k

  作用:返回前k個最大值。

  格式:tf.math.top_k(input, k=None, sorted=True, name=None)

a = tf.random.uniform([3,3],minval=0,maxval=10,dtype=tf.int32)
res = tf.math.top_k(a,2)#前2個最大值
a,res.indices,res.values   #indices是索引,values是值
輸出:
    (<tf.Tensor: id=726, shape=(3, 3), dtype=int32, numpy=
     array([[3, 5, 6],
            [7, 8, 2],
            [6, 4, 5]], dtype=int32)>,
     <tf.Tensor: id=729, shape=(3, 2), dtype=int32, numpy=
     array([[2, 1],
            [1, 0],
            [0, 2]], dtype=int32)>,
     <tf.Tensor: id=728, shape=(3, 2), dtype=int32, numpy=
     array([[6, 5],
            [8, 7],
            [6, 5]], dtype=int32)>)

張量限幅

  1、tf.clip_by_value

  作用:限制張量a的最小值為clip_value_min,最大值為clip_value_max。

  格式:tf.clip_by_value(a, clip_value_min, clip_value_max, name=None)

a = tf.range(9)
tf.clip_by_value(a,2,8) #限制tensor a中張量最小值為2,最大值為8
輸出:
    <tf.Tensor: id=756, shape=(9,), dtype=int32, numpy=array([2, 2, 2, 3, 4, 5, 6, 7, 8], dtype=int32)>

  2、tf.nn.relu()

  作用:計算激活函數 relu,大於0的數保持不變,小於0的數置為0

  格式:tf.nn.relu(features, name = None)

import numpy as np
a = np.arange(9)
a = a-5
a
tf.nn.relu(a)
輸出:
    <tf.Tensor: id=763, shape=(9,), dtype=int64, numpy=array([0, 0, 0, 0, 0, 0, 1, 2, 3])>

  3、tf.clip_by_norm

  作用:根據范數進行裁剪。

a = tf.random.normal([2,2], mean=10)
輸出:
    <tf.Tensor: id=892, shape=(2, 2), dtype=float32, numpy=
    array([[10.600117,  8.955517],
           [ 9.011888,  8.998526]], dtype=float32)>
tf.norm(a) #算一下a的二范數
輸出:
    <tf.Tensor: id=897, shape=(), dtype=float32, numpy=18.834845>
aa = tf.clip_by_norm(a, 15) #以15作為其新的二范數進行放縮
#進行放縮是為了保持張量a的方向不變,而只改變數值大小。
輸出:
    <tf.Tensor: id=929, shape=(2, 2), dtype=float32, numpy=
    array([[8.441894 , 7.13214  ],
           [7.177034 , 7.1663923]], dtype=float32)>
tf.norm(aa) #算一下aa的二范數
輸出:
    <tf.Tensor: id=934, shape=(), dtype=float32, numpy=14.999999>

  clip_by_norm的原型是clip_by_global_norm。(梯度裁剪的最直接目的就是防止梯度爆制梯度的最大范式)

  格式:tf.clip_by_global_norm(t_list, clip_norm, use_norm=None, name=None)

  其中,t_list指常輸入梯度,clip_norm指裁剪率,use_norm指使用已經計算規約。$$t\_list[i] = \frac{{t\_list[i]*clip\_norm}}{{max(global\_norm,clip\_norm)}}$$

高階操作

  1、tf.where

  作用:選出值為Ture的坐標。

a = tf.random.normal([3,3])  
a
輸出:
    <tf.Tensor: id=33, shape=(3, 3), dtype=float32, numpy=
    array([[ 0.6617151 ,  1.1925162 ,  1.2737513 ],
           [-0.6788862 , -1.013595  , -0.3029761 ],
           [ 0.3794667 ,  0.48392296,  1.4922591 ]], dtype=float32)>
mask = a>0
mask
輸出:
  <tf.Tensor: id=35, shape=(3, 3), dtype=bool, numpy=
  array([[ True,  True,  True],
         [False, False, False],
         [ True,  True,  True]])>
idx = tf.where(mask)
idx
輸出:
  <tf.Tensor: id=36, shape=(6, 2), dtype=int64, numpy=
  array([[0, 0],
         [0, 1],
         [0, 2],
         [2, 0],
         [2, 1],
         [2, 2]])>

  當tf.where(mask, a, b)輸入為三個參數時,當mask中取True時,取a中坐標的對應值,else取b中坐標的對應值。

a = tf.ones([3,3])
b = tf.zeros([3,3])
c = tf.where(mask, a, b)
a,b,c
輸出:
  (<tf.Tensor: id=39, shape=(3, 3), dtype=float32, numpy=
   array([[1., 1., 1.],
          [1., 1., 1.],
          [1., 1., 1.]], dtype=float32)>,
   <tf.Tensor: id=42, shape=(3, 3), dtype=float32, numpy=
   array([[0., 0., 0.],
          [0., 0., 0.],
          [0., 0., 0.]], dtype=float32)>,
   <tf.Tensor: id=43, shape=(3, 3), dtype=float32, numpy=
   array([[1., 1., 1.],
          [0., 0., 0.],
          [1., 1., 1.]], dtype=float32)>)

  2、tf.scatter_nd

  格式:tf.scatter_nd(indices, updates, shape, name=None)

  作用:根據indices將updates散布到新的(初始為零)張量中。

  

shape = tf.constant([8])
shape
輸出:
    <tf.Tensor: id=0, shape=(1,), dtype=int32, numpy=array([8], dtype=int32)>
indices = tf.constant([[4],[3],[1],[7]])
indices
輸出:
    <tf.Tensor: id=1, shape=(4, 1), dtype=int32, numpy=
array([[4],
           [3],
           [1],
           [7]], dtype=int32)>
updates = tf.constant([9,10,11,12])
updates
輸出:
    <tf.Tensor: id=2, shape=(4,), dtype=int32, numpy=array([ 9, 10, 11, 12], dtype=int32)>
tf.scatter_nd(indices,updates,shape)
輸出:
    <tf.Tensor: id=3, shape=(8,), dtype=int32, numpy=array([ 0, 11,  0, 10,  9,  0,  0, 12], dtype=int32)>

  3、tf.meshgrid

  格式:[A, B] = tf.meshgrid(a, b)

  作用:從數組a和數組b產生size(a)*size(b)大小的矩陣網格(可以是更高維的)。相當於a從一行重復增加到size(b)行,把b轉置成一列再重復增加到size(a)列

x = [1, 2, 3]
y = [4, 5, 6]
X,Y = tf.meshgrid(x,y)
X,Y
輸出:
  x = [1, 2, 3]
  y = [4, 5, 6]
  X,Y = tf.meshgrid(x,y)
  X,Y

 

相關函數與API補充

  摘自:https://cloud.tencent.com/developer/article/1489078

函數列表

    1. abs(...): 計算張量的絕對值。
    2. accumulate_n(...): 返回張量列表的元素和。
    3. acos(...): 計算x元素的acos。
    4. acosh(...): 計算逆雙曲余弦x元素。
    5. add(...): 返回x + y元素。
    6. add_n(...): 按元素順序添加所有輸入張量。
    7. angle(...): 返回復張量(或實張量)的元素參數。
    8. argmax(...): 返回一個張量在軸上的最大值的指標。 (deprecated arguments)
    9. argmin(...): 返回一個張量橫軸方向上值最小的指標。(deprecated arguments)
    10. asin(...): 計算x元素的三角反正弦。
    11. asinh(...): 計算逆雙曲正弦x元素。
    12. atan(...): 計算x元素的三角反切。
    13. atan2(...): 根據參數的符號計算arctan (y/x)。
    14. atanh(...): 計算x元素的逆雙曲正切。
    15. bessel_i0(...): 計算x元素的貝塞爾i0函數。
    16. bessel_i0e(...): 計算x元素的貝塞爾i0e函數。
    17. bessel_i1(...): 計算x元素的貝塞爾i1函數。
    18. bessel_i1e(...): 計算x元素的貝塞爾i1e函數。
    19. betainc(...): 計算正則化不完全積分。
    20. bincount(...): 計算整數數組中每個值出現的次數。
    21. ceil(...): 返回元素方向上不小於x的最小整數。
    22. confusion_matrix(...): 根據預測和標簽計算混淆矩陣。
    23. conj(...): 返回復數的復共軛。
    24. cos(...): 計算cosx元素。
    25. cosh(...): 計算x元素的雙曲余弦。
    26. count_nonzero(...): 計算張量維上非零元素的個數。(deprecated arguments) (deprecated arguments)
    27. cumprod(...): 計算張量x沿軸的累積積。
    28. cumsum(...): 沿着軸計算張量x的累積和。
    29. digamma(...): 計算導數絕對值的對數
    30. divide(...): 計算Python風格的x除以y的除法。
    31. divide_no_nan(...): 計算一個不安全的除法,如果y為零,該除法返回0。
    32. equal(...): 返回(x == y)元素的真值。
    33. erf(...):計算x元素的高斯誤差函數。
    34. erfc(...): 計算x元素的互補誤差函數。
    35. exp(...): 計算x元素的指數。
    36. expm1(...): 計算x - 1元素的指數。
    37. floor(...): 返回不大於x的元素最大整數。
    38. floordiv(...): 除以x / y元素,四舍五入到最負的整數。
    39. floormod(...): 當x < 0 xor y < 0時,返回除法的元素剩余部分。
    40. greater(...): 返回元素(x > y)的真值。
    41. greater_equal(...): 返回元素的真值(x >= y)。
    42. igamma(...): 計算下正則化不完全函數P(a, x)。
    43. igammac(...): 計算上正則化不完全函數Q(a, x)。
    44. imag(...): 返回復張量(或實張量)的虛部。
    45. in_top_k(...): 表示目標是否在前K個預測中。
    46. invert_permutation(...): 計算張量的逆置換。
    47. is_finite(...): 返回x的哪些元素是有限的。
    48. is_inf(...): 返回x的哪些元素是Inf。
    49. is_nan(...): 返回x的哪些元素是NaN。
    50. is_non_decreasing(...): 如果x不遞減,則返回True。
    51. is_strictly_increasing(...): 如果x嚴格遞增,則返回True。
    52. l2_normalize(...): 使用L2范數沿着維度軸進行標准化。 (deprecated arguments)
    53. lbeta(...): 計算,沿最后一個維度減小。
    54. less(...): 返回(x < y)元素的真值。
    55. less_equal(...): 返回元素的真值(x <= y)。
    56. lgamma(...): 計算元素(x)絕對值的對數。
    57. log(...): 計算x元素的自然對數。
    58. log1p(...): 計算(1 + x)元素的自然對數。
    59. log_sigmoid(...): 計算x元素的log sigmoid。
    60. log_softmax(...): 計算對數softmax激活。(deprecated arguments)
    61. logical_and(...): 返回x和y元素的真值。
    62. logical_not(...): 返回NOT x element-wise的真值。
    63. logical_or(...): 返回x或y元素的真值。
    64. logical_xor(...): 邏輯異或函數。
    65. maximum(...): 返回x和y的最大值(即x > y ?x: y)元素方面。
    66. minimum(...): 返回x和y的最小值(即x < y ?x: y)元素方面。
    67. mod(...): 當x < 0 xor y < 0時,返回除法的元素剩余部分。
    68. multiply(...): 返回x * y元素。
    69. multiply_no_nan(...): 計算x和y的乘積,如果y是0,即使x是NaN或無窮大,返回0。
    70. negative(...): 計算數值負值元素。
    71. nextafter(...): 返回元素方向上x1的下一個可表示值。
    72. not_equal(...): 返回元素的真值(x != y)。
    73. polygamma(...): 計算多元函數。
    74. polyval(...): 計算多項式的元素值。
    75. pow(...): 計算一個值對另一個值的冪。
    76. real(...): 返回復張量(或實張量)的實部。
    77. reciprocal(...): 計算x元素的倒數。
    78. reduce_all(...): 計算元素跨張量維數的“邏輯和”。(deprecated arguments)
    79. reduce_any(...): 計算元素跨張量維數的“邏輯或”。(deprecated arguments)
    80. reduce_euclidean_norm(...): 計算元素跨張量維數的歐幾里德范數。
    81. reduce_logsumexp(...): 計算log(sum(exp(一個張量的維度上的元素))。 (deprecated arguments)
    82. reduce_max(...): 計算張量維數中元素的最大值。(deprecated arguments)
    83. reduce_mean(...): 計算元素跨張量維數的平均值。
    84. reduce_min(...): 計算張量維數中元素的最小值。(deprecated arguments)
    85. reduce_prod(...): 計算元素跨張量維數的乘積。 (deprecated arguments)
    86. reduce_std(...): 計算元素跨張量維數的標准偏差。
    87. reduce_sum(...): 計算張量維數中元素的和。(deprecated arguments)
    88. reduce_variance(...): 計算元素跨張量維數的方差。
    89. rint(...): 返回最接近x的元素整數。
    90. round(...): 元素方面,將張量的值舍入到最近的整數。
    91. rsqrt(...): 計算x元素平方根的倒數。
    92. scalar_mul(...): 將標量乘以張量或索引切片對象。
    93. segment_max(...): 計算張量沿段的最大值。
    94. segment_mean(...): 沿張量的段計算平均值。
    95. segment_min(...): 計算張量沿段的最小值。
    96. segment_prod(...): 沿着張量的段計算乘積。
    97. segment_sum(...): 沿着張量的段計算和。
    98. sigmoid(...): 計算x元素的sigmoid。
    99. sign(...): 返回數字符號的元素指示。
    100. sin(...): 計算sin (x)元素。
    101. sinh(...): 計算x元素的雙曲正弦。
    102. softmax(...): 計算softmax激活。(deprecated arguments)
    103. softplus(...): 計算softplus: log(exp(features) + 1).
    104. softsign(...): 計算softsign: features / (abs(features) + 1).
    105. sqrt(...): 計算x元素的平方根。
    106. square(...): 計算x元素的平方。
    107. squared_difference(...): 返回(x - y)(x - y)元素。
    108. subtract(...): 返回x - y元素。
    109. tan(...): 計算x元素的tan值。
    110. tanh(...): 計算x元素的雙曲正切。
    111. top_k(...): 查找最后一個維度的k個最大項的值和索引。
    112. truediv(...): 使用Python 3的除法運算符語義來分割x / y元素。
    113. unsorted_segment_max(...): 計算張量沿段的最大值。
    114. unsorted_segment_mean(...): 沿張量的段計算平均值。
    115. unsorted_segment_min(...): 計算張量沿段的最小值。
    116. unsorted_segment_prod(...): 沿着張量的段計算乘積。
    117. unsorted_segment_sqrt_n(...): 計算張量沿段的和除以根號N。
    118. unsorted_segment_sum(...): 沿着張量的段計算和。
    119. xdivy(...): 如果x == 0返回0,否則返回x / y, elementwise。
    120. xlogy(...): 如果x == 0返回0,否則返回x * log(y), elementwise。
    121. zero_fraction(...):返回值中0的分數。
    122. zeta(...): 計算Hurwitz zeta函數。

重要的API

1、tf.floor

  返回不大於x的元素最大整數。

tf.math.floor( x, name=None )

  參數:

  • x: 張量。必須是以下類型之一:bfloat16、half、float32、float64。
  • name: 操作的名稱(可選)。

  返回值:

  • 與x類型相同的張量。

2、tf.log

  計算x元素的自然對數。

tf.math.log( x, name=None )

  參數:

  • x: 張量。必須是以下類型之一:bfloat16、half、float32、float64、complex64、complex128。
  • name: 操作的名稱(可選)。

  返回值:

  • 一個與x類型相同的張量。

3、tf.reduce_mean

  計算元素跨張量維數的平均值。

tf.math.reduce_mean( input_tensor, axis=None, keepdims=False, name=None )

  沿着坐標軸給出的維數減少input_張量。除非keepdims為真,否則對於軸上的每一項,張量的秩都會減少1。如果keepdims為真,則使用長度1保留縮減后的維度。如果軸為空,則所有維數都被縮減,並返回一個只有一個元素的張量。

  例如:

x = tf.constant([[1., 1.], [2., 2.]]) tf.reduce_mean(x) # 1.5 tf.reduce_mean(x, 0) # [1.5, 1.5] tf.reduce_mean(x, 1) # [1., 2.]

  參數:

  • input_tensor: 要減少的張量。應該具有數值類型。
  • axis: 要縮小的尺寸。如果沒有(默認值),則減少所有維度。必須在[-rank(input_張量),rank(input_張量)]范圍內。
  • keepdims: 如果為真,則保留長度為1的縮減維度。
  • name: 操作的名稱(可選)。

  返回值:

  • 一個減少的張量。

  請注意np.mean有一個dtype參數,可用於指定輸出類型。默認情況下,這是dtype=float64。另一方面,tf.reduce_mean有一個來自input_張量的攻擊類型推斷,例如:

x = tf.constant([1, 0, 1, 0]) tf.reduce_mean(x) # 0 y = tf.constant([1., 0., 1., 0.]) tf.reduce_mean(y) # 0.5

4、tf.reduce_sum

  計算張量維數中元素的和。

tf.math.reduce_sum( input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None )

  警告:一些參數是不支持的:(keep_dims)。它們將在未來的版本中被刪除。

  更新說明:不推薦使用keep_dims,而是使用keepdims。

  沿着坐標軸給出的維數減少input_張量。除非keepdims為真,否則對於軸上的每一項,張量的秩都會減少1。如果keepdims為真,則使用長度1保留縮減后的維度。如果軸為空,則所有維數都被縮減,並返回一個只有一個元素的張量。

  例如:

x = tf.constant([[1, 1, 1], [1, 1, 1]]) tf.reduce_sum(x) # 6 tf.reduce_sum(x, 0) # [2, 2, 2] tf.reduce_sum(x, 1) # [3, 3] tf.reduce_sum(x, 1, keepdims=True) # [[3], [3]] tf.reduce_sum(x, [0, 1]) # 6 x = tf.constant([[1, 2, 4], [8, 16, 32]]) a = tf.reduce_sum(x, -1) # [ 9 18 36]

  參數:

  • input_tensor:要減少的張量。應該具有數值類型。
  • axis:要縮小的尺寸。如果沒有(默認值),則減少所有維度。必須在[-rank(input_張量),rank(input_張量)]范圍內。
  • keepdims:如果為真,則保留長度為1的縮減維度。
  • name:操作的名稱(可選)。
  • reduction_indices: axis的舊名稱(已棄用)。
  • keep_dims: keepdims的棄用別名。

  返回值:

  • 簡化張量,與input_tensor具有相同的d型。

5、tf.add_n

  按順序對輸入的張量進行求和。

tf.add_n( inputs, name=None )

  在添加之前將indexedslice對象轉換為密集張量。

  例如:

a = tf.constant([[3, 5], [4, 8]]) b = tf.constant([[1, 6], [2, 9]]) tf.math.add_n([a, b, a]) # [[7, 16], [10, 25]]

6、tf.math.top_k

tf.math.top_k( input, k=1, sorted=True, name=None )

  查找最后一個維度的k個最大項的值和索引。如果輸入是一個向量(rank=1),找到向量中k個最大的元素,並將它們的值和索引作為向量輸出。因此value [j]是輸入的第j個最大的條目,它的索引是index [j]。矩陣(分別地。,計算每一行的前k個條目(resp)。沿着最后一個維度的向量)。因此,

values.shape = indices.shape = input.shape[:-1] + [k]

  如果兩個元素相等,則首先出現下標元素。

  參數:

  • input:一維或更高張量,最后維數至少為k。
  • k: 0-D int32張量。要沿着最后一個維度查找的頂部元素的數量(對於矩陣,沿着每一行查找)。
  • sorted:如果為真,則得到的k個元素將按降序排列。
  • name:操作的可選名稱。

  返回值:

  • values: 沿最后一個維度切片的k個最大元素。
  • indices: 輸入的最后一個維度內的值的索引。

7、tf.math.argmax

  返回一個張量在軸上的最大值的指標。

tf.math.argmax( input, axis=None, name=None, dimension=None, output_type=tf.dtypes.int64 )

  參數:

  • input:一個張量。必須是以下類型之一:float32、float64、int32、uint8、int16、int8、complex64、int64、qint8、quint8、qint32、bfloat16、uint16、complex128、half、uint32、uint64。
  • axis:張量。必須是下列類型之一:int32、int64。int32或int64,必須在[-rank(輸入),rank(輸入)]范圍內。描述輸入張量的哪個軸要縮小。對於向量,使用axis = 0。
  • output_type:一個可選的tf.DType from: tf.int32, tf.int64。默認為tf.int64。
  • name:操作的名稱(可選)。

  返回值:

  • 一個輸出t_type類型的張量。
<tf.Tensor: id=599, shape=(5,), dtype=int32, numpy=array([2, 1, 0, 3, 4], dtype=int32)>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM