动态图

      动态图意味着计算图的构建和计算同时发生(define by run)。这种机制由于能够实时得到中间结果的值,使得调试更加容易,同时我们将大脑中的想法转化为代码方案也变得更加容易,对于编程实现来说更友好。Pytorch使用的就是动态图机制,因此它更易上手,风格更加pythonic,大受科研人员的喜爱。

静态图

      静态图则意味着计算图的构建和实际计算是分开(define and run)的。在静态图中,会事先了解和定义好整个运算流,这样之后再次运行的时候就不再需要重新构建计算图了(可理解为编译),因此速度会比动态图更快,从性能上来说更加高效,但这也意味着你所期望的程序与编译器实际执行之间存在着更多的代沟,代码中的错误将难以发现,无法像动态图一样随时拿到中间计算结果。Tensorflow默认使用的是静态图机制,这也是其名称的由来,先定义好整个计算流(flow),然后再对数据(tensor)进行计算。

动态图与静态图差异对比

一段代码分别基于pytorch和tensorflow的实现

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)

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在静态图的模式下,每次运算使用的计算图都是同一个,因此不能直接使用Python的while 循环语句,而是要使用其内置的辅助函数tfwhile loop,而且还要tf.Session().run()之类的乱七八糟.

而Pytorch是动态图的模式,每次运算会构建新的计算图,在编程实现上不需要额外的学习成本

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐