使用经过训练的字符级 LSTM 模型生成文本
Posted
技术标签:
【中文标题】使用经过训练的字符级 LSTM 模型生成文本【英文标题】:Generate text with a trained character level LSTM model 【发布时间】:2017-09-09 12:40:13 【问题描述】:我训练了一个模型,目的是生成如下句子: 我提供了 2 个序列作为训练示例:x 是字符序列,y 是相同的移位。该模型基于 LSTM,使用 tensorflow 创建。 我的问题是:由于模型接受一定大小的输入序列(在我的例子中是 50 个),我如何才能做出预测只给他 单个字符作为种子?我在一些示例中看到,在训练后,它们通过简单地输入单个字符来生成句子。 这是我的代码:
with tf.name_scope('input'):
x = tf.placeholder(tf.float32, [batch_size, truncated_backprop], name='x')
y = tf.placeholder(tf.int32, [batch_size, truncated_backprop], name='y')
with tf.name_scope('weights'):
W = tf.Variable(np.random.rand(n_hidden, num_classes), dtype=tf.float32)
b = tf.Variable(np.random.rand(1, num_classes), dtype=tf.float32)
inputs_series = tf.split(x, truncated_backprop, 1)
labels_series = tf.unstack(y, axis=1)
with tf.name_scope('LSTM'):
cell = tf.contrib.rnn.BasicLSTMCell(n_hidden, state_is_tuple=True)
cell = tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=dropout)
cell = tf.contrib.rnn.MultiRNNCell([cell] * n_layers)
states_series, current_state = tf.contrib.rnn.static_rnn(cell, inputs_series, \
dtype=tf.float32)
logits_series = [tf.matmul(state, W) + b for state in states_series]
prediction_series = [tf.nn.softmax(logits) for logits in logits_series]
losses = [tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels) \
for logits, labels, in zip(logits_series, labels_series)]
total_loss = tf.reduce_mean(losses)
train_step = tf.train.AdamOptimizer(learning_rate).minimize(total_loss)
【问题讨论】:
【参考方案1】:我建议您使用dynamic_rnn
而不是static_rnn
,它会在执行期间创建图表并允许您输入任意长度。您的输入占位符将是
x = tf.placeholder(tf.float32, [batch_size, None, features], name='x')
接下来,您需要一种将自己的初始状态输入网络的方法。您可以通过将initial_state
参数传递给dynamic_rnn
来做到这一点,例如:
initialstate = cell.zero_state(batch_sie, tf.float32)
outputs, current_state = tf.nn.dynamic_rnn(cell,
inputs,
initial_state=initialstate)
这样,为了从单个字符生成文本,您可以一次输入图形 1 个字符,每次都传入前一个字符和状态,例如:
prompt = 's' # beginning character, whatever
inp = one_hot(prompt) # preprocessing, as you probably want to feed one-hot vectors
state = None
while True:
if state is None:
feed = x: [[inp]]
else:
feed = x: [[inp]], initialstate: state
out, state = sess.run([outputs, current_state], feed_dict=feed)
inp = process(out) # extract the predicted character from out and one-hot it
【讨论】:
非常感谢。动态 RNN 的技巧非常巧妙。现在清楚多了。以上是关于使用经过训练的字符级 LSTM 模型生成文本的主要内容,如果未能解决你的问题,请参考以下文章