回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>假设我有一个经过训练的RNN(例如语言模型),我想看看它自己会产生什么,<strong>我应该如何将它的输出反馈给它的输入?</strong></p>
<p>我阅读了以下相关问题:</p>
<ul>
<li><p><a href="https://stackoverflow.com/questions/36609920/tensorflow-using-lstms-for-generating-text">TensorFlow using LSTMs for generating text</a></p></li>
<li><p><a href="https://stackoverflow.com/questions/34302042/tensorflow-lstm-generative-model?rq=1">TensorFlow LSTM Generative Model</a></p></li>
</ul>
<p>理论上我很清楚,在tensorflow中我们使用截断的反向传播,所以我们必须定义我们想要“跟踪”的最大步长。此外,我们为批处理预留了一个维度,因此如果我想训练正弦波,就必须输入<code>[None, num_step, 1]</code>。</p>
<p>以下代码有效:</p>
<pre><code>tf.reset_default_graph()
n_samples=100
state_size=5
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(state_size, forget_bias=1.)
def_x = np.sin(np.linspace(0, 10, n_samples))[None, :, None]
zero_x = np.zeros(n_samples)[None, :, None]
X = tf.placeholder_with_default(zero_x, [None, n_samples, 1])
output, last_states = tf.nn.dynamic_rnn(inputs=X, cell=lstm_cell, dtype=tf.float64)
pred = tf.contrib.layers.fully_connected(output, 1, activation_fn=tf.tanh)
Y = np.roll(def_x, 1)
loss = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)
opt = tf.train.AdamOptimizer().minimize(loss)
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
# Initial state run
plt.show(plt.plot(output.eval()[0]))
plt.plot(def_x.squeeze())
plt.show(plt.plot(pred.eval().squeeze()))
steps = 1001
for i in range(steps):
p, l, _= sess.run([pred, loss, opt])
</code></pre>
<p>LSTM的状态大小是可以改变的,我还尝试了向网络中输入正弦波和零点,在这两种情况下,LSTM在~500次迭代中收敛。到目前为止,我已经了解到,在这种情况下,图由共享其参数的LSTM单元的<code>n_samples</code>个数组成,只有我才能将输入作为<em>时间序列</em>提供给它们。但是,当生成样本时,网络显式地依赖于它以前的输出—这意味着我不能一次为展开的模型提供数据。我试图计算每一步的状态和输出:</p>
<pre><code>with tf.variable_scope('sine', reuse=True):
X_test = tf.placeholder(tf.float64)
X_reshaped = tf.reshape(X_test, [1, -1, 1])
output, last_states = tf.nn.dynamic_rnn(lstm_cell, X_reshaped, dtype=tf.float64)
pred = tf.contrib.layers.fully_connected(output, 1, activation_fn=tf.tanh)
test_vals = [0.]
for i in range(1000):
val = pred.eval({X_test:np.array(test_vals)[None, :, None]})
test_vals.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>(val)
</code></pre>
<p>然而,在这个模型中,LSTM单元之间似乎没有连续性。这是怎么回事?</p>
<p>我是否必须用100个时间步初始化一个零数组,并将每次运行的结果分配到数组中?就像给网络提供这个:</p>
<p>运行0:<code>input_feed = [0, 0, 0 ... 0]; res1 = result</code></p>
<p>运行1:<code>input_feed = [res1, 0, 0 ... 0]; res2 = result</code></p>
<p>运行1:<code>input_feed = [res1, res2, 0 ... 0]; res3 = result</code></p>
<p>等等。。。</p>
<p><strong>如果我想使用这个经过训练的网络在下一个时间步中使用自己的输出作为输入,该怎么办?</strong></p>