tensorflow dynamic_rnn与static_rnn使用注意

不同有好多,例如:输入输出

输入输出要格外注意,敲代码的时候,这个和我们关系最大
帖俩段代码,注意其中的输入输出

这个是static_rnn

def lstm_model(x,y):
  # x = tf.transpose(x, [1, 0, 2])
  # x = tf.reshape(x, [-1, 1])
  # x = tf.split(x, 10, axis=0)
#上面和下面这一句效果一样
   x=tf.unstack(x,axis=2)
   lstm_cell = rnn.BasicLSTMCell(20)
   outputs, states = rnn.static_rnn(lstm_cell, x, dtype=tf.float32)
   output=outputs[-1]
   prediction,loss=learn.models.linear_regression(output,y)
   train_op=tf.contrib.layers.optimize_loss(loss,tf.contrib.framework.get_global_step(),\
   optimizer='Adagrad',learning_rate=0.1)
   return prediction,loss,train_op

很明显,这个输入是一个list,len(list)=步长 list[0].shape=[batch,input]
这个输出和输入一样是个list,len(list)=步长,list[0].shape=[batch,hidden]
所以output=outputs[-1] 就取到了最后一步的ouput

这个是dynamic_rnn

#n_steps = 25 
#n_hidden = 32
def lstm_model(x,y):
    lstm_cell = rnn.BasicLSTMCell(20)
    outputs, states = tf.nn.dynamic_rnn(lstm_cell, x, dtype=tf.float32)
    output=tf.transpose(outputs, [1, 0, 2])[-1]
    prediction,loss=learn.models.linear_regression(output,y)
    train_op=tf.contrib.layers.optimize_loss(loss,tf.contrib.framework.get_global_step(),\
    optimizer='Adagrad',learning_rate=0.1)
    return prediction,loss,train_op

这个输入就不一样了,[batch,步长,input]
机智,输出看看什么样子
Tensor(“rnn/transpose:0”, shape=(?, 25, 32), dtype=float32)
这个应该就是[batch,n_steps,n_hidden]
所以我们需要tf.transpose(outputs, [1, 0, 2]),这样就可以取到最后一步的output

不同

这张图是引用 知乎的,有侵权请联系本人

参考:static_rnn与dynamic_rnn不同

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值