2017-09-26 5 views
0

훈련 된 LSTM 모델을 저장 했으므로 테스트에 사용하기 위해 예측을 복원하고 싶습니다. 나는 this post을 따르려고했다. 그러나 나는 오류가 있습니다. 여기에 내가 뭘하려 : 그 후Saver를 사용하여 Tensorflow에서 lstm 학습 모델을 저장하고 복원하는 방법은 무엇입니까?

x = tf.placeholder('tf.float32', [None, input_vec_size, 1]) 
y = tf.placeholder('tf.float32') 


def recurrent_neural_network(x): 
    layer = {'weights': tf.Variable(tf.random_normal([n_hidden, n_classes])), 
      'biases': tf.Variable(tf.random_normal([n_classes]))}  
    x = tf.transpose(x, [1, 0, 2]) 
    x = tf.reshape(x, [-1, 1]) 
    x = tf.split(x, input_vec_size, 0) 

    lstm_cell = rnn.BasicLSTMCell(n_hidden, state_is_tuple=True) 
    outputs, states = rnn.static_rnn(lstm_cell, x, dtype=tf.float32) 
    output = tf.add(tf.matmul(outputs[-1], layer['weights']), layer['biases']) 

    return output 

def train_neural_network(x): 
    prediction = recurrent_neural_network(x) 
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y)) 
    optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost) 
    saver = tf.train.Saver() 

    with tf.Session() as sess: 
     sess.run(tf.global_variables_initializer()) 

     Training ... 
     saver.save(sess, os.path.join(os.getcwd(), 'my_test_model')) 

, 훈련 단계에서 내가

def test_neural_network(input_data): 
    with tf.Session() as sess: 
     #sess.run(tf.global_variables_initializer()) 
     new_saver = tf.train.import_meta_graph('my_test_model.meta') 
     new_saver.restore(sess, tf.train.latest_checkpoint('./')) 
     prediction = tf.get_default_graph().get_tensor_by_name("prediction:0") 

     Calculate features from input_data ... 
     result = sess.run(tf.argmax(prediction.eval(feed_dict={x: features}), 1)) 

을 시도하고있다 그러나 이것은 다음과 같은 오류가 발생합니다 : 다음

KeyError: "The name 'prediction:0' refers to a Tensor which does not exist. The operation, 'prediction', does not exist in the graph."

나는 추가 시도를 : 복원 후 prediction = tf.get_collection('prediction')[0]으로 저장하고 교체하기 전에 tf.add_to_collection('prediction', prediction)을 입력하십시오. 그러나이 나에게 다음과 같은 오류 제공 : 나는 첫 번째 오류 알고

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_2' with dtype float and shape [?,34,1] [[Node: Placeholder_2 = Placeholderdtype=DT_FLOAT, shape=[?,34,1], _device="/job:localhost/replica:0/task:0/cpu:0"]]

을, 나는 복원하지만 prediction는 tensorflow 변수 아니다하기 위해 이름을 지정하기로하고 있습니다. 몇 가지 이전 게시물과 기사를 살펴 보았지만 제대로 된 해결책을 찾지 못했습니다. 따라서 내 질문은 다음과 같습니다.

  1. 개념적으로 잘못된 것을하고 있습니까? 그렇다면, 무엇?
  2. 그렇지 않은 경우 구현 오류가 있습니까? 어떻게 해결할 수 있을까요?

감사합니다.

답변

0

마지막으로 훈련 된 모델을 저장할 수 있으므로 누구나이 질문에 답변 할 수 있도록 답변을 게시 할 수 있습니다. 나는 정확한 문제에 대한 해결책을 얻지 못했지만 tflearn을 사용하여 모델을 만들고 저장할 수있었습니다. 훈련하기 위해 저장에서 :

model.load(filepath+"lstm_model") 

모델로 작업하기 훨씬 쉬운 방법이 될 듯하고, 할 수있는 컴팩트하고 새로운 방법을 제공합니다

model = tflearn.DNN(lstm_model(n_classes, input_vec_size)) 
model.fit(train_x, train_y, validation_set=(test_x, test_y), n_epoch=20, 
      show_metric=True, snapshot_epoch=True, run_id='lstm_model') 
model.save("../Models/lstm_model") 

그리고 나중에 복원 내가 그 질문에 올린 동일한 과제.

관련 문제