Tensorflow2.0 tf.function和AutoGraph模式
生活随笔
收集整理的這篇文章主要介紹了
Tensorflow2.0 tf.function和AutoGraph模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一個簡單記錄,后續慢慢補充。。。。。
一、函數
# 類似一個tensorflow操作 @tf.function def add(a, b):return a+b # 即使傳入數字,函數運算也是python基本運算,發返回值的類型也會變成tensor。print(add(1,2)) # tf.Tensor(3, shape=(), dtype=int32)print(add(tf.ones([2,2]), tf.ones([2,2]))) # 快速矩陣計算 # tf.Tensor( # [[2. 2.] # [2. 2.]], shape=(2, 2), dtype=float32)二、梯度
# 可以計算梯度 v = tf.Variable(2.0) with tf.GradientTape() as tape:res = add(v, 1.0) tape.gradient(res, v)三、for循環
@tf.function # 可以使用if, for, while break, continue, return def f(x): # 傳入python標量或列表時會建立一個新的圖(傳入參數大小不同,建的圖也不同)。要避免這種情況就將數字作為參數傳入ta = tf.TensorArray(dtype=tf.int32, size=0, dynamic_size=True)for i in range(len(x)): # for循環必須這樣寫,不然只能執行一次ta = ta.write(i, x[i] + 1)return ta.stack()f(tf.constant([1, 2, 3]))四、追蹤
def train_one_step():pass@tf.function def train(num_steps):print("追蹤: num_steps = {}".format(num_steps))for _ in tf.range(num_steps):train_one_step()# Python參數發生變化,那么必須回溯圖。 train(num_steps=10) train(num_steps=20) # 追蹤: num_steps = 10 # 追蹤: num_steps = 20# 使用tensor,同類型不會重復追蹤 train(num_steps=tf.constant(10)) train(num_steps=tf.constant(20)) # 追蹤: num_steps = Tensor("num_steps:0", shape=(), dtype=int32)# 使用tensor,類型不同才會有新的追蹤,(前一個單元格已追蹤int型,所以該處不追蹤) train(num_steps=tf.constant(10, dtype=tf.int32)) train(num_steps=tf.constant(20.6)) # 追蹤: num_steps = Tensor("num_steps:0", shape=(), dtype=float32)五、調試
@tf.function def f(x):print("追蹤:", x) # 使用Python副作用來調試跟蹤。tf.print('執行:', x) # tf.Variable.assign,tf.print和tf.summary是確保TensorFlow運行時,在每次調用時跟蹤和執行代碼的最佳方法。f(1) f(1) f(2)# 追蹤: 1 # 執行: 1 # 執行: 1 # 執行: 2 # 追蹤: 2總結
以上是生活随笔為你收集整理的Tensorflow2.0 tf.function和AutoGraph模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android官方开发文档Trainin
- 下一篇: 【LeetCode】3月28日打卡-Da