TensorFlow2.0常用函式
內容來源視訊,視訊地址:here
2019年3月 tensorflow 2.0 測試版釋出
2019年10月 tensorflow 2.0 正式釋出
2020年1月 tensorflow2.1 釋出
-
建立一個張量,
tf.constant(張量內容, dtype=資料型別[可選])
-
將
numpy
資料裝換成tensor
資料型別,tf.convert_to_tensor(資料名, dtype=資料型別[可選])
-
建立全為
0
的張量,tf.zeros(維度)
; -
建立全為
1
的張量,tf.ones(維度)
; -
建立全為指定值的張量,
tf.fill(維度, 指定值)
-
生成正態分佈的隨機數, 預設均值為
0
,標準差為1
,tf.random.normal(維度, mean=均值, stddev=標準差)
; -
生成截斷式正態分佈的隨機數,
tf.random.truncated_normal(維度, mean=均值, stddev=標準差)
;
隨機數的取值在 ( μ − 2 θ , μ + 2 θ ) (\mu - 2\theta, \mu + 2\theta) (μ−2θ,μ+2θ)之間,之外會重新生成; -
生成均勻分佈隨機數,
tf.random.uniform(維度, minval=最小值, maxval=最大值)
; -
tensor
資料型別轉換:tf.cast(張量名, dtype=資料型別)
-
計算張量維度上的元素最小值:
tf.reduce_min(張量名, axis=軸)
,axix=0
表示列上,1
表示行上;
類似的還有:tf.reduce_max
、tf.reduce_sum
、tf.reduce_mean
等; -
tf.Variable(初始值)
將變數標記為“可訓練”,被標記的變數會在反向傳播中記錄梯度資訊。
eg.w = tf.Variable(tf.random.normal([2, 2], mean=0, stddev=1))
,也就是正太分佈隨機初始化我們定義維度的可訓練引數w
:
-
四則運算:
tf.add(張量1, 張量2)
、tf.subtract(張量1, 張量2)
、tf.multiply(張量1, 張量2)
tf.divide(張量1, 張量2)
,分別對應加減乘除;維度相同的張量才可進行四則運算
。 -
tf.square(張量)
、tf.pow(張量, n次方)
、tf.sqrt(張量)
,分別對應平方、次方和開方; -
使用
tf.matmul(矩陣1, 矩陣2)
來進行矩陣乘法; -
輸入特徵與對應標籤的配對,使用
tf.data.Dataset.from_tensor_slices((輸入特徵, 標籤))
,Numpy
和Tensor
格式的都可以使用該語句讀入資料。 -
函式對引數的求導運算,使用
with
結構記錄計算過程,gradient
求出張量的梯度。
with tf.GradientTape() as tape:
若干個計算過程
grad = tape.gradient(函式, 對誰求導)
案例:
with tf.GradientTape() as tape:
w = tf.Variable(tf.constant(3.0))
loss = tf.pow(w, 2)
grad = tape.gradient(loss, w)
print(grad) # 6.0
因為目標函式是
y
=
w
2
y=w^2
y=w2, 而標記的求導變數是w
,且初始化為常數3
,那麼結果就是6
。
- 獨熱編碼表示,使用
tf.one_hot(帶轉換資料, depth=幾分類)
,
eg.
datas = tf.constant([2, 0, 1])
classes = 3 # 待分類類別
output = tf.one_hot(datas, depth=classes)
print(output)
softmax
即:tf.nn.softmax(x)
- 引數自更新函式,
tensor.assign_sub(tensor要自減的內容)
w = tf.Variable(4)
w.assign_sub(2)
print(w) # 2
類似的,還有assign_add
- 返回張量在指定軸上的最大值下標,
tf.argmax(tensor, axis=軸)
a = tf.constant([[1, 2, 3],[4, 5, 6]])
print(tf.argmax(a, axis=0))
print(tf.argmax(a, axis=1))
- 條件語句,
tf.where(條件語句, 真返回A, 假返回B)
- 將兩個資料按照垂直方向疊加,
np.vstack(陣列1, 陣列2)
import numpy as np
a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
c = np.vstack((a, b))
print(c)
- 網格座標點生成,
np.mgrid[],.ravel(), np.c_[]
x, y = np.mgrid[1:3:1, 2:4:0.5] # 起始值:結束值:步長
print(x)
print(y)
x, y = np.mgrid[1:3:1, 2:4:0.5] # 起始值:結束值:步長
grid = np.c_[x.ravel(), y.ravel()]
print(grid)