PyTorch学习:动态图和静态图的例子

yipeiwu_com5年前Python基础

动态图和静态图

目前神经网络框架分为静态图框架和动态图框架,PyTorch 和 TensorFlow、Caffe 等框架最大的区别就是他们拥有不同的计算图表现形式。 TensorFlow 使用静态图,这意味着我们先定义计算图,然后不断使用它,而在 PyTorch 中,每次都会重新构建一个新的计算图。通过这次课程,我们会了解静态图和动态图之间的优缺点。

对于使用者来说,两种形式的计算图有着非常大的区别,同时静态图和动态图都有他们各自的优点,比如动态图比较方便debug,使用者能够用任何他们喜欢的方式进行debug,同时非常直观,而静态图是通过先定义后运行的方式,之后再次运行的时候就不再需要重新构建计算图,所以速度会比动态图更快。

# 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 需要将整个图构建成静态的,换句话说,每次运行的时候图都是一样的,是不能够改变的,所以不能直接使用 Python 的 while 循环语句,需要使用辅助函数 tf.while_loop 写成 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)

可以看到 PyTorch 的写法跟 Python 的写法是完全一致的,没有任何额外的学习成本

以上这篇PyTorch学习:动态图和静态图的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

在django view中给form传入参数的例子

在django的form表单会出现,在form的验证或者保存时需要非form中的field的信息参数。例如在对操作进行记录,我们需要根据将记录的操作人设置为当前的用户,所以在view中我...

Python语言的12个基础知识点小结

python编程中常用的12种基础知识总结:正则表达式替换,遍历目录方法,列表按列排序、去重,字典排序,字典、列表、字符串互转,时间对象操作,命令行参数解析(getopt),print...

Django REST Framework之频率限制的使用

Django REST Framework之频率限制的使用

开放平台的API接口调用需要限制其频率,以节约服务器资源和避免恶意的频繁调用 使用 自定义频率限制组件:utils/thottle.py class MyThrottle(BaseT...

python使用pip安装SciPy、SymPy、matplotlib教程

背景: 使用pip install SciPy的格式安装python函数库SciPy的时候,发现老是报错,从网上找信息也没找到合适的解决办法,最后使用whl格式文件安装成功。 过程: 本...

Python实现线程池代码分享

原理:建立一个任务队列,然多个线程都从这个任务队列中取出任务然后执行,当然任务队列要加锁,详细请看代码 import threading import time import sig...