Tensorflow2.1基礎知識---常用的函數API

  1. 強制tensor轉換爲該數據類型
    tf.cast(張量名,dtype=數據類型)

  2. 計算張量維度上元素的最小值
    tf.reduce_min(張量名)

  3. 計算張量維度上元素的最大值
    tf.reduce_max(張量名)

    例子:

     import tensorflow as tf
    
     x1 = tf.constant([1,2,3],dtype=tf.float64)
     print(x1)
     x2 = tf.cast(x1,tf.int32)
     print(x2)
     print(tf.reduce_min(x2),tf.reduce_max(x2))
     
     輸出結果:
     	tf.Tensor([1. 2. 3.], shape=(3,), dtype=float64)
     	tf.Tensor([1 2 3], shape=(3,), dtype=int32)
     	tf.Tensor(1, shape=(), dtype=int32) tf.Tensor(3, shape=(), dtype=int32)
    
  4. 計算張量沿着指定維度的平均值
    tf.reduce_mean(張量名,axis=操作軸)

  5. 計算張量沿着指定維度的和
    tf.reduce_sum(張量名,axis=操作軸)

    例子:

     import tensorflow as tf
    
     x = tf.constant([[1,2,3],[2,2,3]])
     print(x)
     print(tf.reduce_mean(x))
     print(tf.reduce_sum(x,axis = 1))
     
     輸出結果:
     	tf.Tensor([[1 2 3][2 2 3]], shape=(2, 3), dtype=int32)
     	tf.Tensor(2, shape=(), dtype=int32)
     	tf.Tensor([6 7], shape=(2,), dtype=int32)
    
  6. tf.Variable()將變量標記爲“可訓練”,被標記的變量會在反向傳播中記錄梯度信息。神經網絡訓練中,常用該函數標記待訓練參數

     tf.Variable(初始值)
     w = tf.Variable(tf.random.normal([2,2],mean=0,stddev=1))
    
  7. Tensorflow中的數學運算
    a. 對應元素的四則運算:tf.add,tf.substract,tf.multiply,tf.divide 只有維度相同的張量纔可以做四則運算

    例子:

     import tensorflow as tf
     
     a = tf.ones([1,3])
     b = tf.fill([1,3],3.)
     print(a)
     print(b)
     print(tf.add(a,b))
     print(tf.subtract(a,b))
     print(tf.multiply(a,b))
     print(tf.divide(b,a))
     
     輸出結果:
     	tf.Tensor([[1. 1. 1.]], shape=(1, 3), dtype=float32)
     	tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
     	tf.Tensor([[4. 4. 4.]], shape=(1, 3), dtype=float32)
     	tf.Tensor([[-2. -2. -2.]], shape=(1, 3), dtype=float32)
     	tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
     	tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
    

    b. 平方、次方與開方:tf.square,tf.pow,tf.sqrt

    例子:

     import tensorflow as tf
     
     a = tf.fill([1,2],3.)
     print(a)
     print(tf.pow(a,3))
     print(tf.square(a))
     print(tf.sqrt(a))
     
     輸出結果:
     	tf.Tensor([[3. 3.]], shape=(1, 2), dtype=float32)
     	tf.Tensor([[27. 27.]], shape=(1, 2), dtype=float32)
     	tf.Tensor([[9. 9.]], shape=(1, 2), dtype=float32)
     	tf.Tensor([[1.7320508 1.7320508]], shape=(1, 2), dtype=float32)
    

    c. 矩陣乘:tf.matmul

    例子:

     import tensorflow as tf
     
     a = tf.ones([3,2])
     b = tf.fill([2,3],3.)
     print(tf.matmul(a,b))
     輸出結果:
     	tf.Tensor(
     	[[6. 6. 6.]
     	[6. 6. 6.]
     	[6. 6. 6.]], shape=(3, 3), dtype=float32)
    
  8. tf.data.Dataset.from_tensor_slices()切分出入張量的第一維度,生成輸入特徵/標籤對,構建數據集 data=tf.data.Dataset.from_tensor_slices((輸入特徵,標籤)) (Numpy和Tensor格式都可用該語句讀入數據)

    例子:

     import tensorflow as tf
     
     features = tf.constant([12,23,10,17])
     labels = tf.constant([0,1,1,0])
     dataset = tf.data.Dataset.from_tensor_slices((features,labels))
     print(dataset)
     for element in dataset:
         print(element)
         
     輸出結果:
     	<TensorSliceDataset shapes: ((), ()), types: (tf.int32, tf.int32)>
     	(<tf.Tensor: shape=(), dtype=int32, numpy=12>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)
     	(<tf.Tensor: shape=(), dtype=int32, numpy=23>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
     	(<tf.Tensor: shape=(), dtype=int32, numpy=10>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
     	(<tf.Tensor: shape=(), dtype=int32, numpy=17>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)
    
  9. tf.GradientTape() with結構記錄計算過程,gradient求出張量的梯度
    用法:

     with tf.GradientTape() as tape:
     	若干個計算過程
     grad = tape.gradient(函數,對誰求導)
    

    例子:

     import tensorflow as tf
     
     with tf.GradientTape() as tape:
         w = tf.Variable(tf.constant(3.0))
         loss = tf.pow(w,2)
     grad = tape.gradient(loss,w)
     print(grad)
     
     輸出結果:
     	tf.Tensor(6.0, shape=(), dtype=float32)
    
  10. enumerate是python的內建函數,它可遍歷每個元素(如列表、元組或字符串),組合爲:索引、元素,常在for循環中使用。
    用法:

    enumerate(列表名)
    

    例子:

    seq = ['one','two','three']
    for i,element in enumerate(seq):
        print(i,element)
    輸出結果:
    	0 one
    	1 two
    	2 three
    
  11. tf.one_hot 獨熱編碼(one-hot encoding):在分類問題中,常用獨熱碼做標籤,標記類別:1表示是,0表示非
    Tf.one_hot()函數將待轉換的數據,轉換爲one-hot形式的輸出 tf.one_hot(待轉換數據,depth=幾分類)
    例子:

    import tensorflow as tf
    
    classes = 3
    labels = tf.constant([1,0,2]) #輸入最小元素值爲0,最大爲2
    output = tf.one_hot(labels,depth = classes)
    print(output)
    
    輸出結果:
    	tf.Tensor([[0. 1. 0.][1. 0. 0.][0. 0. 1.]], shape=(3, 3), dtype=float32)
    
  12. Tf.nn.softmax() 是輸出符合概率分佈
    在這裏插入圖片描述
    當n個分類的n個輸出(y0,y1,……,yn-1)通過softmax()函數,便符合概率分佈。
    在這裏插入圖片描述
    例子:

    import tensorflow as tf
    
    y = tf.constant([1.01,2.01,-0.66])
    y_pro = tf.nn.softmax(y)
    print("After softmax,y_pro is:",y_pro)
    輸出結果:
    	After softmax,y_pro is: tf.Tensor([0.25598174 0.69583046 0.0481878 ], shape=(3,), dtype=float32)
    
  13. assign_sub()函數 作用:賦值操作,更新參數的值並返回 調用assign_sub前,先用tf.Variable定義變量w爲可訓練(可自更新)
    用法:

    w.assign_sub(w要減的內容)
    

    例子:
    import tensorflow as tf

    w = tf.Variable(4)
    w.assign_sub(1)
    print(w)
    
    輸出結果:
    	<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>
    
  14. Tf.argmax() 返回張量沿指定維度最大值的索引 tf.argmax(張量名,axis=操作軸)
    例子:

    import tensorflow as tf
    
    test = np.array([[1,2,3],[2,3,4],[5,4,3],[8,7,2]])
    print(test)
    print(tf.argmax(test,axis=0)) #返回每一列最大值的索引
    print(tf.argmax(test,axis=1)) #返回每一行最大值的索引
    
    輸出結果:
    	[[1 2 3]
    	 [2 3 4]
    	 [5 4 3]
    	 [8 7 2]]
    	tf.Tensor([3 3 1], shape=(3,), dtype=int64)
    	tf.Tensor([2 2 0 0], shape=(4,), dtype=int64)
    
  15. Tf.where() 條件語句真返回A,條件語句假返回B tf.where(條件語句,真返回A,假返回B)
    例子:

    a = tf.constant([1,2,3,1,1])
    b = tf.constant([0,1,3,4,5])
    c = tf.where(tf.greater(a,b),a,b)  #若a>b,返回a對應位置的元素,否則返回b對應位置的元素
    print("c:",c)
    
    輸出結果:
    	c: tf.Tensor([1 2 3 4 5], shape=(5,), dtype=int32)
    
  16. np.random.RandomState.rand()返回一個[0,1)之間的一個隨機數 np.random.RandomState.rand(維度) #維度爲空,返回標量
    例子:

    import numpy as np
    
    rdm = np.random.RandomState(seed=1) #seed=常數 表示每次生成隨機數相同
    a = rdm.rand() #返回一個隨機標量
    b = rdm.rand(2,3) #返回維度爲2行3列隨機數矩陣
    print("a:",a)
    print("b:",b)
    
    輸出結果:
    	a: 0.417022004702574
    	b: [[7.20324493e-01 1.14374817e-04 3.02332573e-01]
    	[1.46755891e-01 9.23385948e-02 1.86260211e-01]]
    
  17. np.vstack()將兩個數組按垂直方向相加 np.vstack(數組1,數組2)
    例子:

    import numpy as np
    
    a = np.array([1,2,3])
    b = np.array([4,5,6])
    c = np.vstack((a,b))
    print("c:\n",c)
    
    輸出結果:
    	c:
    	[[1 2 3]
    	[4 5 6]]
    
  18. np.mgrid[]、.ravel()、np.c_[]
    np.mgrid[起始值:結束值:步長,起始值:結束值:步長,……] [起始值,結束值)前閉後開的一個等差數列
    x.ravel()將x變爲一維數組,“把 . 前變量拉直”
    np.c_[]使返回的間隔數值點配對 np.c_[數組1,數組2,……]
    例子:

    import numpy as np
    
    x,y = np.mgrid[1:3:1,2:4:0.5]
    grid = np.c_[x.ravel(),y.ravel()]
    print("x:",x)
    print("y:",y)
    print("grid:\n",grid)
    
    輸出結果:
    	x: [[1. 1. 1. 1.]
    	[2. 2. 2. 2.]]
    	y: [[2.  2.5 3.  3.5]
    	[2.  2.5 3.  3.5]]
    	grid:
    	[[1.  2. ]
    	[1.  2.5]
    	[1.  3. ]
    	[1.  3.5]
    	[2.  2. ]
    	[2.  2.5]
    	[2.  3. ]
    	[2.  3.5]]
    
下面的是筆者的微信公衆號,歡迎關注,會持續更新c++、python、tensorflow、機器學習、深度學習等系列文章

                      在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章