machine-learning - 使用经过训练的字符级 LSTM 模型生成文本

标签 machine-learning tensorflow lstm generative

我训练了一个模型,目的是生成如下句子: 我提供 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)

最佳答案

我建议您使用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

关于machine-learning - 使用经过训练的字符级 LSTM 模型生成文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43391452/

相关文章:

python - 用于文本生成目的的 Keras LSTM 模型

python - 在 Python 中查找单词的所有变体(或时态)

python - 如何使用 fmin_ncg 计算成本和 theta

machine-learning - Keras categorical_accuracy 指标的输出是什么?

python - 在 Tensor Flow 中使用带有 midi 文件的 RBM,收到一些错误

tensorflow - Conda、Tensorflow 和 Keras 版本不匹配问题

tensorflow - 是否建议保存 RNN 训练的最终状态以在测试期间对其进行初始化?

python - 如何在SVC模型中设置特定阈值并生成混淆矩阵?

python - Tensorflow 对象检测不起作用,mAP 低如何增加

arm - 从 TensorFlow 图中清除 dropout 操作