tensorflow下lstm的实践

lstm作为一个优秀的rnn变体,在时间序列的预测中有着优秀的运用。在了解其原理1之后,继续来了解实践中的lstm如何运用。
说道LSTM,首先得了解RNN在tensorflow中的基本函数tf.nn.rnn_cell.LSTMCell,相比基本的BasicLSTMCell模块,LSTMCell中有加入一些变种的特性clipping,projection layer,peep-hole等,如果不了解可以保持默认设置。LSTM的基本设置为:

tf.nn.rnn_cell.LSTMCell(num_units=64, state_is_tuple=True)

其中num_units是LSTM的状态H和C的长度,这两者长度在tensorflow中一样(虽然论文中的长度可以任意指定,个人觉得这里是和原理中有点不一样的地方)
我们的输入X的长度可以任意长,这个长度在LSTMCell的初始化中不需要指定。
我们看下tf.nn.rnn_cell.LSTMCell的build函数:

  @tf_utils.shape_type_conversion
  def build(self, inputs_shape):
    if inputs_shape[-1] is None:
      raise ValueError("Expected inputs.shape[-1] to be known, saw shape: %s"
                       % inputs_shape)

    input_depth = inputs_shape[-1]
    h_depth = self._num_units if self._num_proj is None else self._num_proj
    maybe_partitioner = (
        partitioned_variables.fixed_size_partitioner(self._num_unit_shards)
        if self._num_unit_shards is not None
        else None)
    self._kernel = self.add_variable(
        _WEIGHTS_VARIABLE_NAME,
        shape=[input_depth + h_depth, 4 * self._num_units],
        initializer=self._initializer,
        partitioner=maybe_partitioner)
    if self.dtype is None:
      initializer = init_ops.zeros_initializer
    else:
      initializer = init_ops.zeros_initializer(dtype=self.dtype)
    self._bias = self.add_variable(
        _BIAS_VARIABLE_NAME,
        shape=[4 * self._num_units],
        initializer=initializer)
    if self._use_peepholes:
      self._w_f_diag = self.add_variable("w_f_diag", shape=[self._num_units],
                                         initializer=self._initializer)
      self._w_i_diag = self.add_variable("w_i_diag", shape=[self._num_units],
                                         initializer=self._initializer)
      self._w_o_diag = self.add_variable("w_o_diag", shape=[self._num_units],
                                         initializer=self._initializer)

    if self._num_proj is not None:
      maybe_proj_partitioner = (
          partitioned_variables.fixed_size_partitioner(self._num_proj_shards)
          if self._num_proj_shards is not None
          else None)
      self._proj_kernel = self.add_variable(
          "projection/%s" % _WEIGHTS_VARIABLE_NAME,
          shape=[self._num_units, self._num_proj],
          initializer=self._initializer,
          partitioner=maybe_proj_partitioner)

    self.built = True

build函数在tensorflow图的构建时会执行。其中input_depth也是由输入推断出来的,不需要自己指定,但是输入的维度确定后就不会再更改了,否则会报错


  1. 强烈推荐这篇博文:https://zybuluo.com/hanbingtao/note/581764深入浅出,讲的非常好 ↩︎

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值