動(dòng)態(tài)圖和靜態(tài)圖
目前神經(jīng)網(wǎng)絡(luò)框架分為靜態(tài)圖框架和動(dòng)態(tài)圖框架,PyTorch 和 TensorFlow、Caffe 等框架最大的區(qū)別就是他們擁有不同的計(jì)算圖表現(xiàn)形式。 TensorFlow 使用靜態(tài)圖,這意味著我們先定義計(jì)算圖,然后不斷使用它,而在 PyTorch 中,每次都會(huì)重新構(gòu)建一個(gè)新的計(jì)算圖。通過(guò)這次課程,我們會(huì)了解靜態(tài)圖和動(dòng)態(tài)圖之間的優(yōu)缺點(diǎn)。
對(duì)于使用者來(lái)說(shuō),兩種形式的計(jì)算圖有著非常大的區(qū)別,同時(shí)靜態(tài)圖和動(dòng)態(tài)圖都有他們各自的優(yōu)點(diǎn),比如動(dòng)態(tài)圖比較方便debug,使用者能夠用任何他們喜歡的方式進(jìn)行debug,同時(shí)非常直觀,而靜態(tài)圖是通過(guò)先定義后運(yùn)行的方式,之后再次運(yùn)行的時(shí)候就不再需要重新構(gòu)建計(jì)算圖,所以速度會(huì)比動(dòng)態(tài)圖更快。
# tensorflowimport tensorflow as tffirst_counter = tf.constant(0)second_counter = tf.constant(10)# tensorflowimport tensorflow as tffirst_counter = tf.constant(0)second_counter = tf.constant(10)def cond(first_counter, second_counter, *args): return first_counter < second_counterdef body(first_counter, second_counter): first_counter = tf.add(first_counter, 2) second_counter = tf.add(second_counter, 1) return first_counter, second_counterc1, 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 需要將整個(gè)圖構(gòu)建成靜態(tài)的,換句話(huà)說(shuō),每次運(yùn)行的時(shí)候圖都是一樣的,是不能夠改變的,所以不能直接使用 Python 的 while 循環(huán)語(yǔ)句,需要使用輔助函數(shù) tf.while_loop 寫(xiě)成 TensorFlow 內(nèi)部的形式
# pytorchimport torchfirst_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 的寫(xiě)法跟 Python 的寫(xiě)法是完全一致的,沒(méi)有任何額外的學(xué)習(xí)成本
以上這篇PyTorch學(xué)習(xí):動(dòng)態(tài)圖和靜態(tài)圖的例子就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持武林網(wǎng)之家。
新聞熱點(diǎn)
疑難解答
圖片精選