2017-10-24 4 views
0

필자는 Iterator를 사용하여 내 네트워크를 훈련시키는 모델을 가지고 있습니다. 현재 Google에서 권장하는 새로운 Dataset API 파이프 라인 모델을 따르고 있습니다.반복자를 사용하는 Tensorflow 모델 복원

tfrecord 파일을 읽고, 네트워크에 데이터를 보내고, 잘 훈련되고, 모두 잘 진행되고 있습니다. 나중에 추론을 실행할 수 있도록 훈련이 끝나면 모델을 저장합니다. 코드 단순화 된 버전은 다음과 같습니다 :

""" Training and saving """ 

training_dataset = tf.contrib.data.TFRecordDataset(training_record) 
training_dataset = training_dataset.map(ds._path_records_parser) 
training_dataset = training_dataset.batch(BATCH_SIZE) 
with tf.name_scope("iterators"): 
    training_iterator = Iterator.from_structure(training_dataset.output_types, training_dataset.output_shapes) 
    next_training_element = training_iterator.get_next() 
    training_init_op = training_iterator.make_initializer(training_dataset) 

def train(num_epochs): 
    # compute for the number of epochs 
    for e in range(1, num_epochs+1): 
    session.run(training_init_op) #initializing iterator here 
    while True: 
     try: 
     images, labels = session.run(next_training_element) 
     session.run(optimizer, feed_dict={x: images, y_true: labels}) 
     except tf.errors.OutOfRangeError: 
     saver_name = './saved_models/ucf-model' 
     print("Finished Training Epoch {}".format(e)) 
     break 



    """ Restoring """ 
# restoring the saved model and its variables 
session = tf.Session() 
saver = tf.train.import_meta_graph(r'saved_models\ucf-model.meta') 
saver.restore(session, tf.train.latest_checkpoint('.\saved_models')) 
graph = tf.get_default_graph() 

# restoring relevant tensors/ops 
accuracy = graph.get_tensor_by_name("accuracy/Mean:0") #the tensor that when evaluated returns the mean accuracy of the batch 
testing_iterator = graph.get_operation_by_name("iterators/Iterator") #my iterator used in testing. 
next_testing_element = graph.get_operation_by_name("iterators/IteratorGetNext") #the GetNext operator for my iterator 
# loading my testing set tfrecords 
testing_dataset = tf.contrib.data.TFRecordDataset(testing_record_path) 
testing_dataset = testing_dataset.map(ds._path_records_parser, num_threads=4, output_buffer_size=BATCH_SIZE*20) 
testing_dataset = testing_dataset.batch(BATCH_SIZE) 

testing_init_op = testing_iterator.make_initializer(testing_dataset) #to initialize the dataset 

with tf.Session() as session: 
    session.run(testing_init_op) 
    while True: 
    try: 
     images, labels = session.run(next_testing_element) 
     accuracy = session.run(accuracy, feed_dict={x: test_images, y_true: test_labels}) #error here, x, y_true not defined 
    except tf.errors.OutOfRangeError: 
     break 

내 문제는 주로 모델을 복원 할 때입니다. 테스트 데이터를 네트워크에 공급하는 방법은 무엇입니까? GetNext() failed because the iterator has not been initialized. Ensure that you have run the initializer operation for this iterator before getting the next element.

  • 그래서 내가 사용하여 내 데이터 집합을 초기화하려고 않았다 : testing_init_op = testing_iterator.make_initializer(testing_dataset))
    • 내가 testing_iterator = graph.get_operation_by_name("iterators/Iterator")next_testing_element = graph.get_operation_by_name("iterators/IteratorGetNext"), 나는 다음과 같은 오류가 사용하여 내 Iterator를 복원

      . 그래프에 직접 반복자 피드 데이터 같이 training_model에 자리를 사용할 필요가 없습니다, 반복자를 사용하고 있기 때문에 AttributeError: 'Operation' object has no attribute 'make_initializer'

    또 다른 문제가있다 :이 오류가 발생했습니다. 그러나이 방법은, "정확도"op에 데이터를 입력 할 때 마지막 줄에서 3 번째 줄에 내 feed_dict 키를 복원하는 방법입니까?

    EDIT : 반복자와 네트워크 입력간에 자리 표시자를 추가하는 방법을 제안 할 수 있다면 데이터를 플레이스 홀더에 입력하고 반복자를 모두 무시하면서 "정확도"텐서를 평가하여 그래프를 실행 해 볼 수 있습니다.

  • 답변

    0

    반복자를 초기화하는 것과 관련된 문제를 해결할 수 없지만 map 메서드를 사용하여 데이터 집합을 사전 처리하고 py_func으로 랩핑 된 파이썬 연산에 정의 된 변환을 적용합니다.이 변환은 \ restore를 저장하기 위해 직렬화 할 수 없습니다. 어쨌든 데이터 세트를 복원하려면 데이터 세트를 초기화해야합니다.

    그래서, 그래프를 복원 할 때 그래프에 데이터를 공급하는 방법이 문제입니다. 반복기 출력과 네트워크 입력 사이에 tf.identity 노드를 두었습니다. 복원시, ID 노드에 내 데이터를 제공합니다. A 더 나은 솔루션은 this answer에 설명 된대로 placeholder_with_default()을 사용하고 있습니다.