2017-04-13 5 views
1

다음과 같이 문장을 생성 할 목적으로 모델을 훈련 시켰습니다 : 훈련 예 2 시퀀스 : x는 문자의 시퀀스이고 y는 하나의 동일한 시프트입니다 . 모델은 LSTM을 기반으로하며 tensorflow로 생성됩니다.
내 질문은입니다 : 모델이 입력에 (내 경우에는 50) 특정 크기의 시퀀스을하기 때문에, 어떻게 씨앗으로 그에게 단 하나의 문자을주는 예측을 할 수 있습니까? 몇 가지 예에서 교육을 한 후 문자 하나를 입력하여 문장을 생성하는 것을 보았습니다. 난 당신이 대신 실행 시간 동안 그래프를 생성하고 어떤 길이의 입력을 할 수 있습니다 static_rnndynamic_rnn 사용하는 것이 좋습니다훈련 된 문자 수준의 LSTM 모델을 사용하여 텍스트 생성

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) 

답변

2

:
다음은 내 코드입니다. 귀하의 입력 자리

x = tf.placeholder(tf.float32, [batch_size, None, features], name='x') 

다음, 네트워크에 입력에 자신의 초기 상태를 수있는 방법이 필요합니다 것입니다. 당신은 같은 dynamic_rnninitial_state 매개 변수를 전달하여 해당 작업을 수행 할 수 있습니다, 당신은 한 번에 그래프 1 문자를 공급할 수있는 단일 문자의 텍스트를 생성하기 위해, 그와

initialstate = cell.zero_state(batch_sie, tf.float32) 
outputs, current_state = tf.nn.dynamic_rnn(cell, 
              inputs, 
              initial_state=initialstate) 

이전 문자를 전달하고 상태는 다음과 같습니다.

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 
+0

고맙습니다. 동적 RNN의 트릭은 정말 멋지다. 지금은 훨씬 더 명확 해. – JimZer

관련 문제