您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關PyTorch中動態(tài)圖和靜態(tài)圖的示例分析的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
動態(tài)圖和靜態(tài)圖
目前神經(jīng)網(wǎng)絡框架分為靜態(tài)圖框架和動態(tài)圖框架,PyTorch 和 TensorFlow、Caffe 等框架最大的區(qū)別就是他們擁有不同的計算圖表現(xiàn)形式。 TensorFlow 使用靜態(tài)圖,這意味著我們先定義計算圖,然后不斷使用它,而在 PyTorch 中,每次都會重新構建一個新的計算圖。通過這次課程,我們會了解靜態(tài)圖和動態(tài)圖之間的優(yōu)缺點。
對于使用者來說,兩種形式的計算圖有著非常大的區(qū)別,同時靜態(tài)圖和動態(tài)圖都有他們各自的優(yōu)點,比如動態(tài)圖比較方便debug,使用者能夠用任何他們喜歡的方式進行debug,同時非常直觀,而靜態(tài)圖是通過先定義后運行的方式,之后再次運行的時候就不再需要重新構建計算圖,所以速度會比動態(tài)圖更快。
# tensorflow import tensorflow as tf first_counter = tf.constant(0) second_counter = tf.constant(10) # tensorflow import tensorflow as tf first_counter = tf.constant(0) second_counter = tf.constant(10) def cond(first_counter, second_counter, *args): return first_counter < second_counter def body(first_counter, second_counter): first_counter = tf.add(first_counter, 2) second_counter = tf.add(second_counter, 1) return first_counter, second_counter c1, c2 = tf.while_loop(cond, body, [first_counter, second_counter]) with tf.Session() as sess: counter_1_res, counter_2_res = sess.run([c1, c2]) print(counter_1_res) print(counter_2_res)
可以看到 TensorFlow 需要將整個圖構建成靜態(tài)的,換句話說,每次運行的時候圖都是一樣的,是不能夠改變的,所以不能直接使用 Python 的 while 循環(huán)語句,需要使用輔助函數(shù) tf.while_loop 寫成 TensorFlow 內(nèi)部的形式
# pytorch import torch first_counter = torch.Tensor([0]) second_counter = torch.Tensor([10]) while (first_counter < second_counter)[0]: first_counter += 2 second_counter += 1 print(first_counter) print(second_counter)
可以看到 PyTorch 的寫法跟 Python 的寫法是完全一致的,沒有任何額外的學習成本
感謝各位的閱讀!關于“PyTorch中動態(tài)圖和靜態(tài)圖的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。