【问题标题】:Implementing an LSTM cell with Tensorflow without using tf.contrib在不使用 tf.contrib 的情况下使用 Tensorflow 实现 LSTM 单元
【发布时间】:2018-11-13 23:07:27
【问题描述】:

我的任务是在不使用 tf.contrib 的任何模块的情况下,实现一个基本的 LSTM 网络,用于从 android 手机的运动传感器数据中识别字母。输入数据的形状为 (?, 150, 3) --> ?: # of letters, 150: # of values, 3: x,y,z 坐标。

计划是构建一个 LSTM Cell 并使用 Adam Optimizer 来调整权重。问题是,事实。 LSTM 在我将数据输入 sess.run() 之前执行。如何防止图表执行?我必须将所有代码放在一个类中还是有其他方法?

代码

x = tf.placeholder(tf.float32, shape=[None, n_features * fixed_length_of_feed_array])
y_ = tf.placeholder(tf.float32, shape=[None, 5])

x_r = tf.reshape(x, [-1, fixed_length_of_feed_array, 3])

states = [tf.random_normal([hidden, hidden]), tf.random_normal([hidden, hidden])]


def LSTM_Cell(hidden, inputs, states):

    x_i = tf.add(tf.matmul(x_r, wx[:, :hidden]), bx[:, :hidden])
    x_f = tf.add(tf.matmul(x_r, wx[:, hidden:hidden * 2]), bx[:, hidden:hidden * 2])
    x_c = tf.add(tf.matmul(x_r, wx[:, hidden * 2:hidden * 3]), bx[:, hidden * 2:hidden * 3])
    x_o = tf.add(tf.matmul(x_r, wx[:, hidden * 3:]), bx[:, hidden * 3:])

    hi = tf.sigmoid(tf.concat([tf.matmul(states[0], wh[:, :hidden]), x_i], 1))
    hf = tf.sigmoid(tf.concat([tf.matmul(states[0], wh[:, hidden:hidden * 2]), x_f], 1))
    ho = tf.sigmoid(tf.concat([tf.matmul(states[0], wh[:, hidden * 2:hidden * 3]), x_o], 1))
    hc = tf.tanh(tf.concat([tf.matmul(states[0], wh[:, hidden * 3:]), x_c], 1))

    c = tf.multiply(hf, states[1]) + tf.multiply(hi, hc)
    h = tf.multiply(ho, tf.tanh(c))

    return h, c


def LSTM(hidden, inputs, states):

    arr_inputs = inputs.split()

    return LSTM_Cell(hidden, arr_inputs, states)


# pred
h, c = LSTM(hidden, x_r, states)
states[0], states[1] = h, c
y = tf.softmax(tf.add(tf.matmul(h, wy), by))

【问题讨论】:

    标签: python tensorflow neural-network lstm


    【解决方案1】:

    在您使用 session.run 提供数据之前,不会执行 LSTM。相反,您的 python 代码会执行并构建一个图,该图仅在以后进行评估。

    【讨论】:

      猜你喜欢
      • 2021-05-29
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-09
      • 2018-04-26
      • 1970-01-01
      • 2013-08-08
      相关资源
      最近更新 更多