2017-12-09 9 views
0

in the tutorial from the TensorFlow guide site 단계를 따라 AlexNet CNN 모델을 교육하려고합니다. 그러나 튜토리얼에서 아래 코드를 사용하여 교육 데이터로드TensorFlow - TF 레코드가 너무 커서 np 배열에 한 번에로드 할 수 없습니다.

mnist = tf.contrib.learn.datasets.load_dataset("mnist") 
train_data = mnist.train.images # Returns np.array 
train_labels = np.asarray(mnist.train.labels, dtype=np.int32) 
eval_data = mnist.test.images # Returns np.array 
eval_labels = np.asarray(mnist.test.labels, dtype=np.int32) 

제게는 데이터 세트 예제를 TFRecord 파일에 쓰는 스크립트를 작성한 다음 훈련 중에이 레코드를 읽고 alexnet 네트워크로 보내보십시오. 코드 아래를 참조

#FUNCTION TO GET ALL DATASET DATA 
def _read_multiple_images(filenames, perform_shuffle=False, repeat_count=1, 
batch_size=1, available_record=39209, num_of_epochs=1): 
    def _read_one_image(serialized): 
     #Specify the fatures you want to extract 
     features = {'image/shape': tf.FixedLenFeature([], tf.string), 
      'image/class/label': tf.FixedLenFeature([], tf.int64), 
      'image/class/text': tf.FixedLenFeature([], tf.string), 
      'image/filename': tf.FixedLenFeature([], tf.string), 
      'image/encoded': tf.FixedLenFeature([], tf.string)} 
     parsed_example = tf.parse_single_example(serialized, 
     features=features) 

     #Finese extracted data 
     image_raw = tf.decode_raw(parsed_example['image/encoded'], tf.uint8) 
     shape = tf.decode_raw(parsed_example['image/shape'], tf.int32) 
     label = tf.cast(parsed_example['image/class/label'], dtype=tf.int32) 
     reshaped_img = tf.reshape(image_raw, shape) 
     casted_img = tf.cast(reshaped_img, tf.float32) 
     label_tensor= [label] 
     image_tensor = [casted_img] 
     return label_tensor, image_tensor 

complete_labels = np.array([]) 
complete_images = np.array([]) 

dataset = tf.data.TFRecordDataset(filenames=filenames) 
dataset = dataset.map(_read_one_image) 
dataset = dataset.repeat(repeat_count)  #Repeats dataset this # times 
dataset = dataset.batch(batch_size)   #Batch size to use 
iterator = dataset.make_initializable_iterator() 
labels_tensor, images_tensor = iterator.get_next() #Get batch data 
no_of_rounds = int(math.ceil(available_record/batch_size)); 

#Create tf session, get nest set of batches, and evelauate them in batches 
sess = tf.Session() 
count=1 
for _ in range(num_of_epochs): 
    sess.run(iterator.initializer) 

    while True: 
    try: 
     evaluated_label, evaluated_image = sess.run([labels_tensor, 
     images_tensor]) 

     #convert evaluated tensors to np array 
     label_np_array = np.asarray(evaluated_label, dtype=np.uint8) 
     image_np_array = np.asarray(evaluated_image, dtype=np.uint8) 

     #squeeze np array to make dimesnsions appropriate 
     squeezed_label_np_array = label_np_array.squeeze() 
     squeezed_image_np_array = image_np_array.squeeze() 

     #add current batch to total 
     complete_labels = np.append(complete_labels, squeezed_label_np_array) 
     complete_images = np.append(complete_images, squeezed_image_np_array) 
     except tf.errors.OutOfRangeError: 
     print("End of Dataset Reached") 
     break 
    count=count+1 

sess.close() 
return complete_labels, complete_images 

내 주요 문제는, 그 내 TF 추정에 공급할 수 있도록 순이익 배열로 내 데이터 세트 (227x227x3)에있는 모든 39,209 이미지를 복원 기하기 위해 트링있다. 컴퓨터의 메모리가 부족합니다.

train_input_fn = tf.estimator.inputs.numpy_input_fn(x={"x": 
complete_images},y=complete_labels,batch_size=100,num_epochs=1, 
shuffle=True) 
dataset_classifier.train(input_fn=train_input_fn,num_epochs=1,hooks= 
[logging_hook]) 

내가 일괄 내 TF 기록에서 내 이미지 및 레이블을 얻을 일괄 내 TF.Estimator에 공급할 수 오히려 순이익 배열로에 모두로드해야하는 것보다있는 방법이 있나요 당신이 tf.data.Dataset로 데이터에 액세스 할 수있는 경우 in this tutorial

답변

3

지정 Estimator로 전달하기 전에 NumPy와 배열로 변환 할 필요가 없습니다. 그것은 한 번에 메모리에 모든 데이터 집합을 실현하는 것을 피한다 때문에,이 훨씬 더 효율적 NumPy와 배열을 구축하는 것보다해야

def train_input_fn(): 
    dataset = tf.data.TFRecordDataset(filenames=filenames) 
    dataset = dataset.map(_read_one_image) 
    dataset = dataset.repeat(1) # Because `num_epochs=1`. 
    dataset = dataset.batch(100) # Because `batch_size=1`. 

    dataset = dataset.prefetch(1) # To improve performance by overlapping execution. 

    iterator = dataset.make_one_shot_iterator() # NOTE: Use a "one-shot" iterator. 
    labels_tensor, images_tensor = iterator.get_next() 

    return {"x": images_tensor}, labels_tensor 

dataset_classifier.train(
    input_fn=train_input_fn, num_epochs=1, hooks=[logging_hook]) 

: 당신은 단순히 다음과 같이 함께, 귀하의 입력 기능에 직접 Dataset을 구축 할 수 있습니다 . 또한 훈련 속도를 향상시키기 위해 Dataset.prefetch()과 같은 성능 향상과 Dataset.map()의 병렬 버전을 사용할 수도 있습니다.