Machine learning 使用经过训练的字符级LSTM模型生成文本
我训练了一个模型,目的是生成以下句子: 作为训练示例,我输入了2个序列:x是字符序列,y是相同的移位。该模型基于LSTM,并使用tensorflow创建Machine learning 使用经过训练的字符级LSTM模型生成文本,machine-learning,tensorflow,lstm,generative,Machine Learning,Tensorflow,Lstm,Generative,我训练了一个模型,目的是生成以下句子: 作为训练示例,我输入了2个序列:x是字符序列,y是相同的移位。该模型基于LSTM,并使用tensorflow创建 我的问题是:既然模型接受一定大小的输入序列(在我的例子中是50个),那么我如何才能预测,只给他一个字符作为种子?我在一些例子中看到,经过训练后,他们只需输入一个字符就可以造句 这是我的密码: with tf.name_scope('input'): x = tf.placeholder(tf.float32, [batc
我的问题是:既然模型接受一定大小的输入序列(在我的例子中是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)
我建议您使用而不是static\u rnn
,它在执行期间创建图形,并允许您拥有任意长度的输入。您的输入占位符将是
x = tf.placeholder(tf.float32, [batch_size, None, features], name='x')
接下来,您需要一种将自己的初始状态输入网络的方法。您可以通过将初始状态
参数传递到动态
来实现这一点,如:
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的技巧非常巧妙。现在清楚多了。