• 카테고리

    질문 & 답변
  • 세부 분야

    컴퓨터 비전

  • 해결 여부

    해결됨

Raccoon 데이터 세트에서 GPU대신 CPU를 사용하려면 어떻게 해야하나요?

21.05.09 11:05 작성 조회수 276

1

Raccoon 데이터 세트에서 GPU대신 CPU를 사용하려면 어떻게 해야하나요?

데스크탑에서 gpu로 학습을 완료하고 노트북cpu로 돌려보려고 합니다.

GPU, CPU 사용 설정을 어떻게 하는지 궁금합니다.

답변 2

·

답변을 작성해보세요.

1

노트북 CPU로 돌려 본다는게 학습이 아니라 Inference(predict)만 하신다는 건지요?

CPU는 학습이 오래 걸리니, 그렇게 하는걸로 이해하고 말씀 드리면,

1. Yolo 인지, RetinaNet 패키지를 사용하시는지 잘 모르겠지만,  Yolo, RetinaNet 모두 Inference 모델을 h5 확장자를 가진 file로 만듭니다. Inference 모델을 만드는 것은 Yolo, Retinanet 강의 동영상을 참조하면 됩니다.

2. 노트북에 Tensorflow 1.13 ~15와 keras 설정을 합니다. 이때 tensorflow_gpu 가 아닌 tensorflow를 셋업합니다.

h5 확장자를 가진 file을 노트북으로 옮기고, inference 모델을 load하고 Raccoon Dataset을 inference 합니다.

네, kerasYOLO를 데스크탑 GPU로 학습하고 노트북 CPU로 Inference한다는 의미였습니다. 부족하게 적었는데 이해해주셔서 감사합니다.

강의 내용을 참고하여 다른 데이터셋으로 실습해보고 있습니다.

13개의 multi-classes를 가진 옷 데이터셋으로 실습중 아래와 같은 에러가 발생하였습니다.

(실습 중인 데이터셋 링크)

https://github.com/switchablenorms/DeepFashion2

num_classes를 어디에서 수정해야할지 질문드립니다.

-----------------------------------------

tiny_yolo_anchors는 yolo사이트에서 수정없이  가져와서 사용중이고,

yolov3_tiny.cfg에서 filter를 yolo의 윗부분 convolutional에서 (classes개수[13] +5)*3 으로 변경하였습니다.

그후 변경하지 않은 yolov3_tiny.weights와 수정한 yolov3_tiny.cfg를 함께 yolov3_tiny.h5로 변환하였습니다.

pretrained_path: C:/JupyterNotebook/ClothClassified/YOLO_DARKflow/model_data/yolov3-tiny.h5
Create Tiny YOLOv3 model with 6 anchors and 13 classes.
Load weights C:/JupyterNotebook/ClothClassified/YOLO_DARKflow/model_data/yolov3-tiny.h5.
Freeze the first 42 layers of total 44 layers.
Train on 28938 samples, val on 3215 samples, with batch size 4.
Epoch 1/50
   1/7234 [..............................] - ETA: 2:10:25 - loss: 1478.9208
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-66-4070cbde17ab> in <module>
     14 epochs_cnt = 100
     15 
---> 16 train_yolo(pretrained_path, annotation_path,classes_path, anchors_path, log_dir,trained_model_name, b_size, epochs_cnt)

<ipython-input-65-229740a9ec0a> in train_yolo(pretrained_path, annotation_path, classes_path, anchors_path, log_dir, trained_model_name, b_size, epochs_cnt)
     57                     epochs=int(epochs_cnt/2),
     58                     initial_epoch=0,
---> 59                     callbacks=[logging, checkpoint])
     60             model.save_weights(log_dir + trained_model_name+'_stage_1.h5')
     61 

~\anaconda3\envs\115t\lib\site-packages\keras\legacy\interfaces.py in wrapper(*args, **kwargs)
     89                 warnings.warn('Update your `' + object_name + '` call to the ' +
     90                               'Keras 2 API: ' + signature, stacklevel=2)
---> 91             return func(*args, **kwargs)
     92         wrapper._original_function = func
     93         return wrapper

~\anaconda3\envs\115t\lib\site-packages\keras\engine\training.py in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
   1416             use_multiprocessing=use_multiprocessing,
   1417             shuffle=shuffle,
-> 1418             initial_epoch=initial_epoch)
   1419 
   1420     @interfaces.legacy_generator_methods_support

~\anaconda3\envs\115t\lib\site-packages\keras\engine\training_generator.py in fit_generator(model, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
    179             batch_index = 0
    180             while steps_done < steps_per_epoch:
--> 181                 generator_output = next(output_generator)
    182 
    183                 if not hasattr(generator_output, '__len__'):

~\anaconda3\envs\115t\lib\site-packages\keras\utils\data_utils.py in get(self)
    707                     "`use_multiprocessing=False, workers > 1`."
    708                     "For more information see issue #1638.")
--> 709             six.reraise(*sys.exc_info())

~\anaconda3\envs\115t\lib\site-packages\six.py in reraise(tp, value, tb)
    701             if value.__traceback__ is not tb:
    702                 raise value.with_traceback(tb)
--> 703             raise value
    704         finally:
    705             value = None

~\anaconda3\envs\115t\lib\site-packages\keras\utils\data_utils.py in get(self)
    683         try:
    684             while self.is_running():
--> 685                 inputs = self.queue.get(block=True).get()
    686                 self.queue.task_done()
    687                 if inputs is not None:

~\anaconda3\envs\115t\lib\multiprocessing\pool.py in get(self, timeout)
    642             return self._value
    643         else:
--> 644             raise self._value
    645 
    646     def _set(self, i, obj):

~\anaconda3\envs\115t\lib\multiprocessing\pool.py in worker(inqueue, outqueue, initializer, initargs, maxtasks, wrap_exception)
    117         job, i, func, args, kwds = task
    118         try:
--> 119             result = (True, func(*args, **kwds))
    120         except Exception as e:
    121             if wrap_exception and func is not _helper_reraises_exception:

~\anaconda3\envs\115t\lib\site-packages\keras\utils\data_utils.py in next_sample(uid)
    624         The next value of generator `uid`.
    625     """
--> 626     return six.next(_SHARED_SEQUENCES[uid])
    627 
    628 

C:\JupyterNotebook\DLCV\Detection\yolo\keras-yolo3\train.py in data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes)
    179         image_data = np.array(image_data)
    180         box_data = np.array(box_data)
--> 181         y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes)
    182         yield [image_data, *y_true], np.zeros(batch_size)
    183 

C:\JupyterNotebook\DLCV\Detection\yolo\keras-yolo3\yolo3\model.py in preprocess_true_boxes(true_boxes, input_shape, anchors, num_classes)
    246 
    247     '''
--> 248     assert (true_boxes[..., 4]<num_classes).all(), 'class id must be less than num_classes'
    249     num_layers = len(anchors)//3 # default setting
    250     anchor_mask = [[6,7,8], [3,4,5], [0,1,2]] if num_layers==3 else [[3,4,5], [1,2,3]]

AssertionError: class id must be less than num_classes

attributeerror: module 'keras.backend' has no attribute 'control_flow_ops' 에러가 발생하여서 tf1.15.1에서 tf-gpu1.13.1, keras 2.2.4 버전으로 다운그레이드 하였습니다.

gpu 관련 설정(CUDA,cuDNN) 및 확인(device_lib.list_local_devices() 등등)은 모두 완료하였습니다.

annotation을 확인한 결과 라벨이 1~13으로 분포되어 있었습니다. coco dataset과 Google Open Image의 차이(0번부터 시작, 1번부터 시작)과 유사한 문제인것 같습니다. 어떻게 수정해야할지 질문드립니다.

0

해결했습니다.

KerasYolo_Raccoon_학습및_Detection.ipynb 의 train_yolo의 함수에서

num_classes = int(len(class_names)+1) 로 변경하니 작동하였습니다.

혹시 어떤 이유 때문인지 질문드려도 될까요?