日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Tensorflow2.0 tf.function和AutoGraph模式

發布時間:2024/7/5 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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模式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。