神经网络——动态图和静态图

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

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

 

import torch
from torch.autograd import Variable

x=Variable(torch.randn(1,10))
prev_h=Variable(torch.randn(1,20))
W_h=Variable(torch.randn(20,20))
W_x=Variable(torch.randn(20,10))

i2h=torch.mm(W_x,x.t())
h2h=torch.mm(W_h,prev_h.t())

比较while循环语句在TensorFlow和PyTorch中的定义

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):
    first_counter+=2
    second_counter+=1

print(first_counter)
print(second_counter)



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

动态图的方式更加简单且直观。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乐亦亦乐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值