1. 인공 신경망

 

위키: https://ko.wikipedia.org/wiki/%EC%9D%B8%EA%B3%B5%EC%8B%A0%EA%B2%BD%EB%A7%9D

인공신경망(人工神經網, 영어: artificial neural network, ANN)은 기계학습인지과학에서 생물학의 신경망(동물의 중추신경계중 특히 )에서 영감을 얻은 통계학적 학습 알고리즘이다. 인공신경망은 시냅스의 결합으로 네트워크를 형성한 인공 뉴런(노드)이 학습을 통해 시냅스의 결합 세기를 변화시켜, 문제 해결 능력을 가지는 모델 전반을 가리킨다.

 

인공 신경망은 사람의 두뇌가 여러 개의 뉴론으로 연결돼서 복잡한 연산을 수행한다는 데서 영감을 받아서, 머신러닝의 연산을 여러 개의 간단한 노드를 뉴론 처럼 상호 연결해서 복잡한 연산을 하겠다는 아이디어이다.

 

입력층, 은닉층, 출력층

 

 

              

x1, x2, 1이라는 3개의 신호가 뉴런에 입력되어, 각 신호에 가중치를 곱한 후, 다음 뉴런에 전달한다. 다음 뉴런에서는 이들 신호의 값을 더하여, 그 합이 0을 넘으면 1을 출력하고 그렇지 않으면 0을 출력한다. 이를 확장하여 가중치가 달린 입력 신호와 편향의 총합을 계산하고, 이를 a라 한다. 그리고 a를 함수 h()에 넣어 y를 출력하게된다.

 

y = h(b + w1x1 + w2x2)
h(x) = 0 (x<= 0)
     = 1 (x > 0)

 

입력 신호의 총합을 출력 신호로 변환하는 함수를 일반적으로 활성화 함수(activation function)이라 한다.

 

1.1 Activation Functions

 

인공 신경망 모델에서 뉴런의 주요 기능은 입력과 연결 강도의 가중합을 구한 다음 활성화 함수에 의해 출력을 내보내는 것이다. 따라서, 어떤 활성화 함수를 선택하느냐에 따라 뉴런의 출력이 달라질 수도 있다.


참조: https://www.quora.com/What-is-the-role-of-the-activation-function-in-a-neural-network-How-does-this-function-in-a-human-neural-network-system

 

※ "h(x) = 0 (x<= 0) = 1 (x > 0)"와 같은 활성화 함수는 임계값을 경계로 출력이 바뀌는데, 이런 함수를 계단 함수(step function)라 한다. 퍼셉트론에서는 활성화 함수로 계단 함수를 이용한다.

 

활성화 함수의 종류는 다양하며 어떤 활성화 함수를 쓰느냐에 따라서 학습 속도나 정확도가 달라지게 된다.

'머신러닝&딥러닝 > 알고리즘' 카테고리의 다른 글

계단 함수(Step Function)  (0) 2017.12.18
퍼셉트론  (0) 2017.12.16
Posted by 이성윤

프로젝트에서 폭발에 대해서 탐지기능을 갖추어야 한다.


이것을 진행하기위해서,

먼저, 폭발에 대한 이미지를 먼지/화염으로 각각 100장 수집하고 레이블링을 해보자


1. 이미지 수집 

   구글에서 이미지를 쉽게 긁어올 수 있는 도구가 없을까를 생각했다. 여기서 쉽게라는 것은 내가 화재라는 키워드를 주면 화재로 검색되어져 나오는 이미지를 다운로드 해주는 도구를 생각 했었다. 하지만, 키워드에 대한 이미지가 적절한 것인지에 정확성이 부족할 것 같다는 생각이 문득 들었다. 결국에는 사람이 이미지를 보고 원하는 이미지라는 것을 판단해야 하는 과정이 필요할 수 밖에 없는 것일까? 여기에는 많은 궁금점이 생긴다. (※ TODO 나보다 뛰어난 사람들이 저문제를 어떻게 해결 했는지 또는 해결해 나가는지 주기적으로 모니터링 할 필요가 있다는 생각이든다.)

여하튼, 현재의 나의 정보로는 적당한 생각이 들지 않아서 필요한 이미지에 대한 URL을 수집하여 URL을 통해 이미지를 다운로드하는 유틸리티(TODO) 정도를 만들어보려고 한다.

정정  필요한 도구를 만들기전에 잘만들어져 있는 도구를 찾는 것을 먼저 해보자. 있다면 그 도구를 잘 사용해보고 불편하거나 버그가 있으면 PR 해보기


1.1 이미지 수집 도구

  가. google-image-crawler

    github: https://github.com/walkoncross/google-image-crawler-zyf

  나. google-images-download

    github: https://github.com/hardikvasa/google-images-download

  다. icrawler

    github: https://github.com/hellock/icrawler

    docu: http://icrawler.readthedocs.io/en/latest/index.html

  라. image donwloader in chrome plug-in

    url: https://chrome.google.com/webstore/search/image%20downloader

 

  위의 도구들을 이용하면 원하는 키워드에 다양한 옵션들을 설정하여 구글이미지를 다운로드 받을 수 있다. 하지만 여기서 또 여전히 의문점이 있다. 특정 키워드로 다운 받은 이미지가 내가 원하는 이미지가 맞는지 확인이 필요하다는 것이다.

실제로 저러한 도구를 이용하여 다운로드 받아보니, 어떤 이미지는 "워터망킹 되어서 삭제", "키워드랑 전혀 연관이 없어서 삭제", "이미지가 너무 흐릿해서 삭제", "실물 사진이 필요한데 사람이 만들어낸 그림(?) 이라서 삭제" 등등 이슈가 있었다.


여기서 다음 스텝으로 어떻게 해야할지 결정해야 겠다.

a. 현재 상태에서 내가 직접눈으로 불필요한 것들을 지운다.

  - 이렇게 하면 지금 당장은 빠르지만 앞으로 같은일이 반복되었을때 같은 현상을 겪게 된다.

b. 구글 서칭 기법중 또는 옵션중에서 정확도를 높일수 있는 방법이 있는지 찾아본다.

  - 이거는 조금 검색해보면 검색 방법들이 나올 수 있을것 같다. 하지만 검색 방법을 찾는다면, 내가 다운로드 받은 도구중에 하나를 선택해서 저 검색 기법들을 적용할 수 있는지 확인하고 개발해야 한다.

c. 나보다 경험을 더 많이 갖고 있는 AI를 하고 있는 사람들이 이미지 수집을 어떻게 하고 있는지 알아보고 그러한 조사중에 위의 문제를 해결할 수 있는 스마트한 방법 및 도구가 있는지 찾아본다.

  - 이렇게 하면 "시간이 얼마나 걸릴지", "정말로 존재하는 것인지" 등의 의문을 갖으며 진행하게 될것 같다. 지인찬스를 한번 쓰는게 나을지도 모르겠다. 혹여나 찾으면 있다면 앞으로의 진행이 몇배는 빨라질거 같다. 

d. 아! 갑자기 google vision api가 생각 났다. 내가 원하는 explosion이 라벨링이 되어 있다. 그렇다는 것은 어딘가에 이미지셋으로 존재 한다는 말이다. imagenet, coco 등등의 이미지를 갖고있는 진영에 대한 조사를 해보는게 좋을것 같다.

  - 앞으로도 특정 오브젝트에 대한 이미지셋이(특이하지 않은) 필요할 예정이기 때문에 이방법을 선행하는게 좋겠다.


가. google-image-crawler


Image Donw load config.json 설정



{
    "save_dir": "./downloads/",
    "num_downloads_for_each_class": 200,
    "search_file_type": "jpg",
    "search_keywords_dict": {
        "millitary": [
            "millitary explosion"
        ]
    },
    "search_cdr_days": 60,
    "output_prefix": "download_urls",
    "output_suffix": "google"
}

cs


Download Image


현재 디렉토리 구조



Object-Detection
-images/
--test/
--train/
--...yourimages.jpg
cs


2. 이미지 라벨링

2.1 라벨링 도구

a. labelImg

  github: https://github.com/tzutalin/labelImg

b. FastAnnotationTool

  github: https://github.com/christopher5106/FastAnnotationTool

c. ImageMagick

  url: http://imagemagick.org/script/download.php


a. 사용


Annotation.xml



<annotation>
    <folder>EXPLOSION</folder>
    <filename>f619a2dd1405af1e0118bd7700f84af4.jpg</filename>
    <path>/home/tensorflow/data/IMAGES/EXPLOSION/f619a2dd1405af1e0118bd7700f84af4.jpg</path>
    <source>
        <database>Unknown</database>
    </source>
    <size>
        <width>1920</width>
        <height>1200</height>
        <depth>3</depth>
    </size>
    <segmented>0</segmented>
    <object>
        <name>explosion</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>149</xmin>
            <ymin>112</ymin>
            <xmax>1286</xmax>
            <ymax>1031</ymax>
        </bndbox>
    </object>
</annotation>


cs

 


현재 디렉토리 구조



Object-Detection
-images/
--test/
--train/
--...yourimages.jpg
--...yourimages.xml
cs

3. 보유하고 있는 데이터를 train/test sample로 나누기

아래의 디렉토리 구조를 생성하고, 보유하고 있는 데이터를 train/test를 나눈다.



Object-Detection
-images/
--test/
---testingimages.jpg
---testingimages.xml
--train/
---trainingimages.jpg
---trainingimages.xml
--...yourimages.jpg
--...yourimages.xml

4. 학습을 위한 TF Records 변환

① xml 파일을 csv 파일로 변환



def main():
    for directory in ['train','test']:
        image_path = os.path.join(os.getcwd(), 'images/{}'.format(directory))
        xml_df = xml_to_csv(image_path)
        xml_df.to_csv('data/{}_labels.csv'.format(directory), index=None)
        print('Successfully converted xml to csv.')
cs


생성된 CSV 파일을 Object-Detection 디렉토리에 data 디렉토리를 생성하고, data 디렉토리로 csv 파일을 옮긴다. 그리고 Object-Detection 디렉토리에 training 디렉토리를 생성한다. 지금까지의 디렉토리 구조는 아래와 같다.

Object-Detection
-data/
--test_labels.csv
--train_labels.csv
-images/
--test/
---testingimages.jpg
---testingimages.xml
--train/
---trainingimages.jpg
---trainingimages.xml
--...yourimages.jpg
--...yourimages.xml
-training
-xml_to_csv.py
cs


② 이제 CSV 파일을 TFRecord파일로 변환

generate_tfrecord.py



# TO-DO replace this with label map
def class_text_to_int(row_label):
    if row_label == 'explosion':
        return 1
    else:
        None
cs


이제 generate_tfrecord.py 스크립트를 수행한다. train TFRecord와 test TFRecord를 위해 두번 수행하게 된다.

train TFRecord:



python generate_tfrecord.py --csv_input=data/train_labels.csv  --output_path=data/train.record
cs

test TFRecord:



python generate_tfrecord.py --csv_input=data/test_labels.csv  --output_path=data/test.record


현재 디렉토리:

Object-Detection
-data/
--test.record
--test_labels.csv
--train.record
--train_labels.csv
-images/
--test/
---testingimages.jpg
---testingimages.xml
--train/
---trainingimages.jpg
---trainingimages.xml
--...yourimages.jpg
--...yourimages.xml
-training
-xml_to_csv.py


5. 학습에 사용할 모델 고르기

먼저 checkpoint 와 configuration 파일을 다운 받는다.


I am going to go with mobilenet, using the following checkpoint and configuration file
wget https://raw.githubusercontent.com/tensorflow/models/master/object_detection/samples/configs/ssd_mobilenet_v1_pets.config
wget http://download.tensorflow.org/models/object_detection/ssd_mobilenet_v1_coco_11_06_2017.tar.gz
You can check out some of the other checkpoint options to start with here.

models/object_detection 디렉토리에서 ssd_mobilenet_v1을 가져와서 training 디렉토리에 놓는다.
ssd_mobilenet_v1_pets.config을 우리 환경에 맞게 그리고 여러 하이퍼 파라미터들을 조정 할 수 있다.
여기에서는
우리 환경에 맞게 설정해야할 몇몇 값들을 수정한다.
Put the config in the training directory, and extract the ssd_mobilenet_v1 in the models/object_detection directory
In the configuration file, you need to search for all of the PATH_TO_BE_CONFIGURED points and change them. You may also want to modify batch size.
Currently, it is set to 24 in my configuration file. Other models may have different batch sizes.
If you get a memory error, you can try to decrease the batch size to get the model to fit in your VRAM.
Finally, you also need to change the checkpoint name/path, num_classes to 1, num_examples to 12,
and label_map_path: "training/object-detect.pbtxt"

- 클래스가1개 이기때문에 num_classes를 1로 설정
- batch size는 메모리 여건에 따라서 조정
- fine_tune_checkpoint 경로 변경
- 학습 횟수가 디폴트로 20만번으로 되어있다. 상황에 따라서 num_steps을 조정
- train_input_reader의 input_path, label_map_path 경로 변경
- eval_input_readerinput_path, label_map_path 경로 변경
- TODO 기타 설정 값들에 대한 정리 자료 작성 필요

It's a few edits, so here is my full configuration file:
# Users should configure the fine_tune_checkpoint field in the train config as
# well as the label_map_path and input_path fields in the train_input_reader and
# eval_input_reader. Search for "${YOUR_GCS_BUCKET}" to find the fields that
# should be configured.
model {
  ssd {
    num_classes: 1
    box_coder {
      faster_rcnn_box_coder {
        y_scale: 10.0
        x_scale: 10.0
        height_scale: 5.0
        width_scale: 5.0
      }
    }
    matcher {
      argmax_matcher {
        matched_threshold: 0.5
        unmatched_threshold: 0.5
        ignore_thresholds: false
        negatives_lower_than_unmatched: true
        force_match_for_each_row: true
      }
    }
    similarity_calculator {
      iou_similarity {
      }
    }
    anchor_generator {
      ssd_anchor_generator {
        num_layers: 6
        min_scale: 0.2
        max_scale: 0.95
        aspect_ratios: 1.0
        aspect_ratios: 2.0
        aspect_ratios: 0.5
        aspect_ratios: 3.0
        aspect_ratios: 0.3333
      }
    }
    image_resizer {
      fixed_shape_resizer {
        height: 300
        width: 300
      }
    }
    box_predictor {
      convolutional_box_predictor {
        min_depth: 0
        max_depth: 0
        num_layers_before_predictor: 0
        use_dropout: false
        dropout_keep_probability: 0.8
        kernel_size: 1
        box_code_size: 4
        apply_sigmoid_to_scores: false
        conv_hyperparams {
          activation: RELU_6,
          regularizer {
            l2_regularizer {
              weight: 0.00004
            }
          }
          initializer {
            truncated_normal_initializer {
              stddev: 0.03
              mean: 0.0
            }
          }
          batch_norm {
            train: true,
            scale: true,
            center: true,
            decay: 0.9997,
            epsilon: 0.001,
          }
        }
      }
    }
    feature_extractor {
      type: 'ssd_mobilenet_v1'
      min_depth: 16
      depth_multiplier: 1.0
      conv_hyperparams {
        activation: RELU_6,
        regularizer {
          l2_regularizer {
            weight: 0.00004
          }
        }
        initializer {
          truncated_normal_initializer {
            stddev: 0.03
            mean: 0.0
          }
        }
        batch_norm {
          train: true,
          scale: true,
          center: true,
          decay: 0.9997,
          epsilon: 0.001,
        }
      }
    }
    loss {
      classification_loss {
        weighted_sigmoid {
          anchorwise_output: true
        }
      }
      localization_loss {
        weighted_smooth_l1 {
          anchorwise_output: true
        }
      }
      hard_example_miner {
        num_hard_examples: 3000
        iou_threshold: 0.99
        loss_type: CLASSIFICATION
        max_negatives_per_positive: 3
        min_negatives_per_image: 0
      }
      classification_weight: 1.0
      localization_weight: 1.0
    }
    normalize_loss_by_num_matches: true
    post_processing {
      batch_non_max_suppression {
        score_threshold: 1e-8
        iou_threshold: 0.6
        max_detections_per_class: 100
        max_total_detections: 100
      }
      score_converter: SIGMOID
    }
  }
}
train_config: {
  batch_size: 10
  optimizer {
    rms_prop_optimizer: {
      learning_rate: {
        exponential_decay_learning_rate {
          initial_learning_rate: 0.004
          decay_steps: 800720
          decay_factor: 0.95
        }
      }
      momentum_optimizer_value: 0.9
      decay: 0.9
      epsilon: 1.0
    }
  }
  fine_tune_checkpoint: "ssd_mobilenet_v1_coco_11_06_2017/model.ckpt"
  from_detection_checkpoint: true
  data_augmentation_options {
    random_horizontal_flip {
    }
  }
  data_augmentation_options {
    ssd_random_crop {
    }
  }
}
train_input_reader: {
  tf_record_input_reader {
    input_path: "data/train.record"
  }
  label_map_path: "data/object-detection.pbtxt"
}
eval_config: {
  num_examples: 40
}
eval_input_reader: {
  tf_record_input_reader {
    input_path: "data/test.record"
  }
  label_map_path: "training/object-detection.pbtxt"
  shuffle: false
  num_readers: 1
}

TODO pbtxt 역할에 대해서 정리하기.
vi object-detection.pbtxt
Inside training dir, add object-detection.pbtxt: 
item {  
 id: 1  
 name: 'macncheese'
}

현재 디렉토리:







Object-Detection
-data/
--test.record
--test_labels.csv
--train.record
--train_labels.csv
-images/
--test/
---testingimages.jpg
---testingimages.xml
--train/
---trainingimages.jpg
---trainingimages.xml
--...yourimages.jpg
--...yourimages.xml
-ssd_mobilenet_v1_coco_11_06_2017
-training
-xml_to_csv.py

6. 학습 시키기(Train)
학습이 진행되는 것을보여준다. 
And now, the moment of truth! From within models/object_detection:
python train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/ssd_mobilenet_v1_pets.config

Barring errors, you should see output like:
INFO:tensorflow:global step 11788: loss = 0.6717 (0.398 sec/step)
INFO:tensorflow:global step 11789: loss = 0.5310 (0.436 sec/step)
INFO:tensorflow:global step 11790: loss = 0.6614 (0.405 sec/step)
INFO:tensorflow:global step 11791: loss = 0.7758 (0.460 sec/step)
INFO:tensorflow:global step 11792: loss = 0.7164 (0.378 sec/step)
INFO:tensorflow:global step 11793: loss = 0.8096 (0.393 sec/step)


현재 디렉토리:

Object-Detection
-data/
--...test.record
--...test_labels.csv
--...train.record
--...train_labels.csv
-images/
--test/
---...testingimages.jpg
---...testingimages.xml
--train/
---...trainingimages.jpg
---...trainingimages.xml
--...yourimages.jpg
--...yourimages.xml
-ssd_mobilenet_v1_coco_11_06_2017
-training
--...checkpoint
--...events.out.tfevents.1513316190.6f49228ef2c1
--...graph.pbtxt
--...model.ckpt-2276.data-00000-of-00001
--...model.ckpt-2276.index
--...model.ckpt-2276.meta
--...object-detection.pbtxt
--...pipeline.config
--...ssd_mobilenet_v1_pets.config
-...xml_to_csv.py


7. Object Detection API(결과)


Train Image Count : 67 장

Train Step : 약 5000

loss: 약 0.9


프로젝트 폭발 오브젝트 탐지 시험을 간단하게 완료 하였다.

생각보다 적은량의 이미지로 학습을 적게 하여도 생각보다 꽤 탐지율이 괜찮게 나왔다고 생각한다.


다음 스텝은 Object Detection API 사용되는 모델들은 90 Object에 대한 학습된 모델들이다. COCO 트레이닝

셋에서 사람만 학습하여 모델을 만드는 과정을 진행해야 한다. 이를 진행함과 동시에 부족한 부분을 채워 나가도록하자.

Posted by 이성윤

▶ Machine Learning

   Machine Learning은 컴퓨터에게 사람이 직접 명시적으로 Logic을 지시하지 않아도 데이터를 통해 컴퓨터가 ‘학습’을 하고 그것을 사용해 컴퓨터가 자동으로 문제를 해결하도록하는 것을 의미한다.

   머신러닝은 ‘기계’가 일일이 코드로 명시하지 않은 동작을 데이터로부터 ‘학습’하여 실행할 수 있도록 하는 ‘알고리즘’을 개발하는 연구 분야이다


▶ TensorFlow Object Detection API

   사진속의 다양한 물체의 위치를 특정하고 종류를 분류해주는 기능을 오픈소스 형태로 제공한다. 연구자들에게는 이 모델을 기초로 더 빠른 연구를 진행하게 하고 애플리케이션 개발자들에게는 딥러닝 모델을 직접 만들고 학습시키지 않아도 관련기술을 사용할 수 있게 하는데에 목적이 있다. TensorFlow API는 NestCam, 스타일 기반 이미지 검색, 구글 스트리트 뷰에서의 글자인식과 같은 구글 서비스에서 사용되고 있는 API와 같은 API라고 한다.

   참조:

    https://github.com/tensorflow/models/tree/master/research/object_detection

    https://research.googleblog.com/2017/06/supercharge-your-computer-vision-models.html


▶ Model

    어떤 상황을 해결하기 위한 문제를 세우고 그 문제를 풀기 위한 모델을 만들기 위해 데이터에 대한 가설을 세우고, 그 가설에 부합하는 알고리즘을 개발하는 과정이다.


  ㅇ 어떤 대상을 모두에게 공통적으로 이해되도록 약속된 방식(수식,그림 등)으로 표현하는 것
     - 복잡한 현실세계를 단순화(추상화) 즉, `추상적 체계적으로 표현하는 작업 또는 방법`
        . 통상, 관련자들끼리 상호이해를 쉽게 하도록 다이어그램화 함

  ㅇ 공학적으로는, 시스템(체계)적인 특성을 `수학적으로 표현하는 과정(수식화)`
     - 정량적으로 표현되도록 수학적 언어로 전환시키는 과정
        . 좋은 모델링 이란?   컴퓨터를 이용하여 해석,시뮬레이션,설계하기 쉬운 모델


▶ SSD: Single Shot Multibox Detector Model  

    1번의 네트워크 forwarding 만으로 여러 물체를 검출하는 모델입니다. R-CNN류에서 상대적으로 좋은 성능이 나오다가, 이 논문을 통해 Single shot detector로도 충분히 좋은 성능이 나올 수 있다는 것을 보여준 것 같습니다. 특히, 속도가 빠르다보니 실시간 물체 검출에 사용됩니다.

  • YOLO 보다 빠르면서 R-CNN류만큼 정확한 성능
    • SSD : 72.1% mAP @ 58FPS
    • Faster R-CNN : 73.2% mAP @ 7FPS
    • YOLO : 63.4% mAP @ 45FPS
  • 여러 Feature Scale을 잘 사용할 수 있도록 모델링
  • 학습이 쉽도록 각 filter별 역할을 잘 분리시켜, location 정보와 class 정보 등을 출력하도록 함
  • 학습이 쉽도록 각 feature map은 서로 다른 scale을 담당하도록 하고, anchor 설계를 함.

▶ Google Inception Model

    Tensorflow 공개 후 우리가 가장 많이 사용하는 Conv-Net 모델


▶ Inception. v1. (a.k.a GoogLeNet) Model

    #google 에서 ‘Inception’ 이라는 이름으로 부르는 네트워크 구조를 처음으로 밝힌 논문입니다. 22개의 네트워크를 쌓아서 2014년 ILSVRC에서 우수한 성적을 보고했습니다.

  • 알렉스넷에 비해 12배나 적은 파라미터 수, 훨씬 정확한 성능
  • 더욱 효율적임
  • 단일 Convolutional Operation을 쌓아서 네트워크를 구성하던 기존의 방식과는 다르게 Layer하나가 더욱 많은 계산을 하도록 설계. Network in Network1과 유사.
  • Network in Network1에서는 MLP로 Convolutional Filter를 대체했다면, 이 논문에서는 Inception Module로 해당 기능을 대체.

     참조:

      http://openresearch.ai/t/inception-v1-going-deeper-with-convolutions/40


▶ Inception. v2 Model

     2015.12  개선된 Inception Module과 Label Smoothing 제안. 약간의 성능 향상.


▶ Inception. v3 Model

     약간 큰 사이즈로 더 높은 정확도를 제공한다. 기술은 MobileNet과 유사하다

     Inception.v2 구조도를 그대로 Inception.v3 라 생각해도 된다.

       ◦Inception.v3 모델을 Inception.v2++ 정도로 봐도 무방

▶ MobileNet Model

     1000개의 object 클래스들은 디텍션하는 모델을 모바일과 임베디드에 맞춰서 다시 진행


▶ ResNet Model

    #microsoft::Tag 에서 Resnet 이라는 이름으로 제안한 네트워크 아키텍쳐입니다.

  • 100개, 1000개가 넘는 Layer를 쌓아 Imagenet 3.5% 에러 수준을 달성
  • Residual Learning이라는 개념의 소개로, Skip connection을 도입해 네트워크를 deep하게 쌓음

▶ RCNN 

Multiple-Object Detection에 대한 관심을 가지게 된다면 가장 먼저 접하게 될 테크닉이 바로 R-CNN이다. Region의 R을 CNN에 붙인 이 방법은 사실 간단한 프로세스를 거친다. 

  1. CNN을 fine-tuning한다.
  2. Input Image에 Selective search를 적용하여 object detecting을 수행한다.
  3. Detected Object(proposals)를 CNN에 넣고 feature extract를 수행한다.
  4. 분석된 Feature들을 softmax classifier나 SVM에 붙여서 각 proposal의 score를 매긴다.
  5. Non-Maximum Suppression(NMS)을 이용하여 bounding box를 구한다.

  6. <span style="font-size: 8pt;">*여기서 사용된 Selective search와 NMS는 다음 포스트에서 설명하기로 한다. </span>

간단히 말하자면, R-CNN은 Input image에서 수많은 Object 후보들을 찾아내고 이들을 모두 CNN에 넣어서 Feature를 뽑아낸다. 그리고 뽑아낸 Feature들을 SVM등의 Classifier에 넣어서 분류작업을 수행하고 NMS와 같은 기법으로 Bounding Box를 이미지 위에 그려내는 방법이다. 다음 그림은 전체적인 과정에 대한 이해를 도와준다.


▶ COCO(Common Objects in COntext) Detection Challenge

    마이크로소프트에서 만든 이미지 인식(recognition), 분리(segmentation), 캡션 붙이기(captioning), 사람의 키포인트(keypoint) 찾기 등을 위한 데이터입니다. 대단히 많은 데이터로 구성되어 있고 MS에서 작정하고 만든 데이터입니다. 매년 챌린지가 열리고 있습니다!

    마이크로소프트의 COCO(Common Object in COntex) 프로젝트는 이미지 객체 인식을 확장한 장면 이해를
목표로 91종의 객체 유형에 대해 라벨링된 33만장 규모의 새로운 DB를 공개

   참조:

    http://cocodataset.org/#home


▶ ImageNet

    ImageNet은 ILSVRC 챌린지에서 사용하는 데이터입니다. ImageNet 전 세계에서 모은 이미지들로 챌린지를 열어 누가 컴퓨터 비젼 분야에서 제일 뛰어난 기술을 갖고 있는지를 겨룹니다. 매년 새로운 승자가 등장하고, 그렇게 등장한 기술들은 거의 대부분 반드시 사용해야만 하는 기술이 되곤 합니다. 아쉽게도 2017년을 마지막으로 한다는 뉴스가 있었습니다.

1,000 종류의 1,281,167 개 데이터가 주어지고 데이터가 어떤 물체인지를 맞추는 챌린지입니다. 각 종류별 데이터의 갯수도 다릅니다. 분류 외에도 탐지(detection) 등 다른 부문도 있지만, 제일 유명한 것은 1,000 종류 분류입니다. 엄청나게 많은 데이터인데다, 전체를 합치면 200GB에 가깝습니다. 이 크기는 절대 GPU에 들어갈 수 없기 때문에 보통 특별한 방법을 써서 GPU 훈련을 시킵니다.


   ILSVRC: ImageNet Large Scale Visual Recognition Competetion


    논문에서 사용하는 ImageNet 데이터는 ILSVRC 2012 의 분류 문제에 사용된 데이터입니다. 실제로 ImageNet 데이터는 저게 전부가 아니고, 훨씬 많은 전 세계에서 모은 데이터들을 모아 놓은 사이트입니다. 다만 이 중 일부를 떼서 챌린지 용으로 사용하는 것 뿐입니다. ImageNet 회원이 되면 비상업적 목적으로 원본 이미지를 다운받을 수도 있고, 이미지의 URL만 받아 불러올 수도 있습니다. 하지만 훈련을 위해서는 역시 원본 이미지가 있어야 합니다. 이미지들의 크기도 전부 다르기 때문에 전처리도 필요합니다. 
    참조:

     http://www.image-net.org/



+ MAP

+ Pre-trained

+ TFRecord

+ CloudML

+ Oxford-IIIT Pets lives

+ Annotate

+ Label

...

Posted by 이성윤


1. 용어정리

+ COCO(Common Objects in COntext) Detection Challenge

   http://cocodataset.org/#home

+ TensorFlow Object Detection API

   https://github.com/tensorflow/models/tree/master/research/object_detection

+ Model

  https://github.com/tensorflow/models

+ COCO-trained models

+ Kitti-trained models

+ Open Images-trained models {#open-images-models}

+ MAP

+ Pre-trained

+ TFRecord

+ CloudML

+ Oxford-IIIT Pets lives

+ Annotate

+ Label
...


2. AI 관련 기법 정리

+ 각종 모델 정리

+ 학습을 위한 두 가지 방법 정리(We can use a pre-trained model, and then use transfer learning to learn a new object, or we could learn new objects entirely from scratch)

...


3. Object Detection API 내 파일 정보 정리

+ Check point (model.ckpt.data-00000-of-00001, model.ckpt.index, model.ckpt.meta)

   텐서플로우 학습 체크 포인트로, 나중에, 다른 데이타를 학습 시킬때 Transfer Learning을 이용할

   때, 텐서플로우 그래프에 이 체크포인트를 로딩하여, 그 체크포인트 당시의 상태로 학습 시켜놓

   을 수 있다. 이 예제에서는 사용하지 않지만, 다른 데이타를 이용하여 학습할때 사용한다.

학습된 모델 그래프 (frozen_inference_graph.pb)

    학습이 완료된 그래프에 대한 내용을 Export 해놓은 파일이다. 이 예제에서는 이 모델 파일을 다시 로딩하여

     Prediction을 수행한다.

Graph proto (pgrah.pbtxt)

라벨맵

    라벨맵은 {Object Detection API 설치 디렉토리}/models/object_detection/data  디렉토리 안에 몇몇 샘플 모

    델에 대한 라벨맵이 저장되어 있다. 라벨맵은 모델에서 사용한 분류 클래스에 대한 정보로

    name,id,display_name 식으로 정의되며, name은 텍스트 라벨, id는 라벨을 숫자로 표현한 값 (반드시 1부

    터 시작해야 한다.), display_name은 Prediction 결과를 원본 이미지에서 인식한 물체들을 박스처리해서 출

    력하는데 이때 박스에 어떤 물체인지 출력해주는 문자열에 들어가는 텍스트 이다.
    여기서 사용한 라벨맵은 mscoco_label_map.pbtxt 파일이 사용되었다.

학습 CONFIG 파일

   모델 학습과 예측에 사용되는 각종 설정 정보를 저장한 파일로 위에서 미리 정의된 모델별로 각각 다른 설정 

   파일을 가지고 있으며 설정 파일의 위치는  {Object Detection API 설치 디렉토

   리}/models/object_detection/samples/configs 에 {모델명}.config 에 저장되어 있다.

Annotation XML 설정값들 정리

pbtxt 역할에 대해서 정리하기.

Configuring jobs(https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/configuring_jobs.md)

...


4. 학습 관련 도구 정리

- 이미지 라벨링 학습도구 목록 업데이트

...


5. 소스코드 분석


Posted by 이성윤

이제 마지막 단계이다.

학습된 데이터를 기반으로 Object Detection API를 활용하여 test디렉토리에 있는 학습하지 않은 새로운 이미지를 인풋으로 주어 학습 데이터의 정확도를 검증할 차례이다. 그 과정은 아래와 같다.


8. Detect custom objects in real time


Welcome to part 6 of the TensorFlow Object Detection API tutorial series. In this part of the tutorial, we are going to test our model and see if it does what we had hoped. In order to do this, we need to export the inference graph.

Luckily for us, in the models/object_detection directory, there is a script that does this for us: export_inference_graph.py

To run this, you just need to pass in your checkpoint and your pipeline config, then wherever you want the inference graph to be placed. For example:




python3 export_inference_graph.py \
    --input_type image_tensor \
    --pipeline_config_path training/ssd_mobilenet_v1_pets.config \
    --trained_checkpoint_prefix training/model.ckpt-10856 \
    --output_directory mac_n_cheese_inference_graph
cs


Your checkpoint files should be in the training directory. Just look for the one with the largest step (the largest number after the dash), and that's the one you want to use. Next, make sure the pipeline_config_path is set to whatever config file you chose, and then finally choose the name for the output directory, I went with mac_n_cheese_inference_graph

Run the above command from models/object_detection


나의 경우에는 아래와 같이 설정을 했다.

TODO 각각의 파라미터들에 대해서 정리하자.



python3 export_inference_graph.py \
    --input_type image_tensor \
    --pipeline_config_path TELCO_OBJ_DETECTION/training/ssd_mobilenet_v1_pets.config \
    --trained_checkpoint_prefix TELCO_OBJ_DETECTION/training/model.ckpt-33354 \
    --output_directory mac_n_cheese_inference_graph
cs


Otherwise, you should have a new directory, in my case, mine is mac_n_cheese_inference_graph, inside it, I have new checkpoint data, a saved_model directory, and, most importantly, the forzen_inference_graph.pb file.


TODO mac_ncheese_inference_graph에 생성된 각각의 파일들에 대해서 정리하자.


Now, we're just going to use the sample notebook, edit it, and see how our model does on some testing images. I copied some of my models/object_detection/images/test images into the models/object_detection/test_images directory, and renamed them to be image3.jpg, image4.jpg...etc.


Object Detection API에서 제공하는 object_detection_tutorial.ipynb를 활용하여 images/test에 있는 시험용 이미지들을 object_detection/test_images 디렉토리에 옮겨 학습이 제대로 이루어졌는지 정확도를 측정해 볼 차례이다.

Object Detection API를 사용하는 방법은 [API] Object Detection API를 이용한 오브젝트 인식하기 Part 1. - 설정 [펌] 포스팅을 참조하면 된다.


추가적으로, 우리가 만든 모델을 적용하기위해서 몇 가지 정보를 수정해주어야 한다.

Booting up jupyter notebook and opening the object_detection_tutorial.ipynb, let's make a few changes. First, head to the Variables section, and let's change the model name, and the paths to the checkpoint and the labels:


# What model to download.
MODEL_NAME
= 'mac_n_cheese_inference_graph'

# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT
= MODEL_NAME + '/frozen_inference_graph.pb'

# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS
= os.path.join('training', 'object-detection.pbtxt')

NUM_CLASSES
= 1
cs


Next, we can just delete the entire Download Model section, since we don't need to download anymore.




opener = urllib.request.URLopener()
opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)
tar_file = tarfile.open(MODEL_FILE)
for file in tar_file.getmembers():
    file_name = os.path.basename(file.name)
    if 'frozen_inference_graph.pb' in file_name:
        tar_file.extract(file, os.getcwd())

cs


Finally, in the Detection section, change the TEST_IMAGE_PATHS var to:




PATH_TO_TEST_IMAGES_DIR = 'test_images'
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 8) ]
# Size, in inches, of the output images.
IMAGE_SIZE = (12, 8)

cs


Here are a few of my results:


Tensorflow Object Detection API tutorial


Tensorflow Object Detection API tutorial


Tensorflow Object Detection API tutorial


나는 GPU를 이용하여 약 35,000번의 학습단계를 거쳐서 로스가 약 0.8정도까지 내려가도록 학습하였다. 학습을 하면서 느낀거지만 35,000번을 수행하는동안 체감상 약 3시간 정도 걸린것 같다. 로스가 0에 가까워지는 수치가 되었다는것은 아주 훌륭하게 학습이 되었다는것을 의미하기도 하다.

100개의 이미지를 가지고 학습을 진행하였는데 생각보다 더 훌륭한 결과를 보여주고 있는게 아닌가 싶다.


Tensorflow에서 제공하는 Object Detection API덕분에 내가 AI를 통해서 해볼 수 있는 것들을 아주 쉽고 편하게 사용을 해본것 같다.(이것은 생각 이상으로 결과를 빨리 얻었다고 생각한다) 지금까지 해본 것들을 정리해 보면 아래와 같다.

- 나만의 이미지를 학습시키는 방법,

- 학습된 이미지를 사용해보는 방법

- 다양한 모델을 적용해보는 방법

- 이미지에서 특정 오브젝트들을 탐지하는 방법

- 실시간/비실시간 영상에서 특정 오브젝트들을 탐지하는 방법


여기까지 진행해온 동안, 여러 가지 결과를 빨리 보고 싶어서 중간중간 알아야할 것들을 그냥 지나쳐왔다. 이제부터는 지나쳤던 정보들을 하나하나 정리해가는 시간을 가져야겠다.

Posted by 이성윤

이번 단계는 custom object를 탐지하기 위해, 우리의 object detection 모델을 학습하고, 모델 환경을 설정할 것이다.


5. 학습에 사용할 모델 고르기


새로운 오브젝트를 학습하기 위해서 두가지 방법이 있다고 한다.

Here, we have two options. We can use a pre-trained model, and then use transfer learning to learn a new object, or we could learn new objects entirely from scratch. The benefit of transfer learning is that training can be much quicker, and the required data that you might need is much less. For this reason, we're going to be doing transfer learning here.

TODO 위의 두 가지 방법에 대한 언급은 아직 잘 모르겠다. 꼭 알아야 하는부분 같으니 차후 다시 학습하기로 하자.


TensorFlow has quite a few pre-trained models with checkpoint files available, along with configuration files. You can do all of this yourself if you like by checking out their configuring jobs documentation. The object API also provides some sample configurations to choose from.

TODO 위의 언급은 아직 잘 모르겠다. 꼭 알아야 하는부분 같으니 차후 다시 학습하기로 하자.


일단 블로거가 가이드한대로 따라가기로 한다.


먼저 checkpoint 와 configuration 파일을 다운 받는다.


I am going to go with mobilenet, using the following checkpoint and configuration file
wget https://raw.githubusercontent.com/tensorflow/models/master/object_detection/samples/configs/ssd_mobilenet_v1_pets.config
wget http://download.tensorflow.org/models/object_detection/ssd_mobilenet_v1_coco_11_06_2017.tar.gz
You can check out some of the other checkpoint options to start with here.

models/object_detection 디렉토리에서 ssd_mobilenet_v1을 가져와서 training 디렉토리에 놓는다.
ssd_mobilenet_v1_pets.config을 우리 환경에 맞게 그리고 여러 하이퍼 파라미터들을 조정 할 수 있다.
여기에서는
우리 환경에 맞게 설정해야할 몇몇 값들을 수정한다.
Put the config in the training directory, and extract the ssd_mobilenet_v1 in the models/object_detection directory
In the configuration file, you need to search for all of the PATH_TO_BE_CONFIGURED points and change them. You may also want to modify batch size.
Currently, it is set to 24 in my configuration file. Other models may have different batch sizes.
If you get a memory error, you can try to decrease the batch size to get the model to fit in your VRAM.
Finally, you also need to change the checkpoint name/path, num_classes to 1, num_examples to 12,
and label_map_path: "training/object-detect.pbtxt"

- 클래스가1개 이기때문에 num_classes를 1로 설정
- batch size는 메모리 여건에 따라서 조정
- fine_tune_checkpoint 경로 변경
- 학습 횟수가 디폴트로 20만번으로 되어있다. 상황에 따라서 num_steps을 조정
- train_input_reader의 input_path, label_map_path 경로 변경
- eval_input_readerinput_path, label_map_path 경로 변경
- TODO 기타 설정 값들에 대한 정리 자료 작성 필요

It's a few edits, so here is my full configuration file:
# SSD with Mobilenet v1, configured for the mac-n-cheese dataset.
# Users should configure the fine_tune_checkpoint field in the train config as
# well as the label_map_path and input_path fields in the train_input_reader and
# eval_input_reader. Search for "${YOUR_GCS_BUCKET}" to find the fields that
# should be configured.
model {
  ssd {
    num_classes: 1
    box_coder {
      faster_rcnn_box_coder {
        y_scale: 10.0
        x_scale: 10.0
        height_scale: 5.0
        width_scale: 5.0
      }
    }
    matcher {
      argmax_matcher {
        matched_threshold: 0.5
        unmatched_threshold: 0.5
        ignore_thresholds: false
        negatives_lower_than_unmatched: true
        force_match_for_each_row: true
      }
    }
    similarity_calculator {
      iou_similarity {
      }
    }
    anchor_generator {
      ssd_anchor_generator {
        num_layers: 6
        min_scale: 0.2
        max_scale: 0.95
        aspect_ratios: 1.0
        aspect_ratios: 2.0
        aspect_ratios: 0.5
        aspect_ratios: 3.0
        aspect_ratios: 0.3333
      }
    }
    image_resizer {
      fixed_shape_resizer {
        height: 300
        width: 300
      }
    }
    box_predictor {
      convolutional_box_predictor {
        min_depth: 0
        max_depth: 0
        num_layers_before_predictor: 0
        use_dropout: false
        dropout_keep_probability: 0.8
        kernel_size: 1
        box_code_size: 4
        apply_sigmoid_to_scores: false
        conv_hyperparams {
          activation: RELU_6,
          regularizer {
            l2_regularizer {
              weight: 0.00004
            }
          }
          initializer {
            truncated_normal_initializer {
              stddev: 0.03
              mean: 0.0
            }
          }
          batch_norm {
            train: true,
            scale: true,
            center: true,
            decay: 0.9997,
            epsilon: 0.001,
          }
        }
      }
    }
    feature_extractor {
      type: 'ssd_mobilenet_v1'
      min_depth: 16
      depth_multiplier: 1.0
      conv_hyperparams {
        activation: RELU_6,
        regularizer {
          l2_regularizer {
            weight: 0.00004
          }
        }
        initializer {
          truncated_normal_initializer {
            stddev: 0.03
            mean: 0.0
          }
        }
        batch_norm {
          train: true,
          scale: true,
          center: true,
          decay: 0.9997,
          epsilon: 0.001,
        }
      }
    }
    loss {
      classification_loss {
        weighted_sigmoid {
          anchorwise_output: true
        }
      }
      localization_loss {
        weighted_smooth_l1 {
          anchorwise_output: true
        }
      }
      hard_example_miner {
        num_hard_examples: 3000
        iou_threshold: 0.99
        loss_type: CLASSIFICATION
        max_negatives_per_positive: 3
        min_negatives_per_image: 0
      }
      classification_weight: 1.0
      localization_weight: 1.0
    }
    normalize_loss_by_num_matches: true
    post_processing {
      batch_non_max_suppression {
        score_threshold: 1e-8
        iou_threshold: 0.6
        max_detections_per_class: 100
        max_total_detections: 100
      }
      score_converter: SIGMOID
    }
  }
}
train_config: {
  batch_size: 10
  optimizer {
    rms_prop_optimizer: {
      learning_rate: {
        exponential_decay_learning_rate {
          initial_learning_rate: 0.004
          decay_steps: 800720
          decay_factor: 0.95
        }
      }
      momentum_optimizer_value: 0.9
      decay: 0.9
      epsilon: 1.0
    }
  }
  fine_tune_checkpoint: "ssd_mobilenet_v1_coco_11_06_2017/model.ckpt"
  from_detection_checkpoint: true
  data_augmentation_options {
    random_horizontal_flip {
    }
  }
  data_augmentation_options {
    ssd_random_crop {
    }
  }
}
train_input_reader: {
  tf_record_input_reader {
    input_path: "data/train.record"
  }
  label_map_path: "data/object-detection.pbtxt"
}
eval_config: {
  num_examples: 40
}
eval_input_reader: {
  tf_record_input_reader {
    input_path: "data/test.record"
  }
  label_map_path: "training/object-detection.pbtxt"
  shuffle: false
  num_readers: 1
}
TODO pbtxt 역할에 대해서 정리하기.
vi object-detection.pbtxt
Inside training dir, add object-detection.pbtxt: 
item {  
 id: 1  
 name: 'macncheese'
}
6. 학습 시키기(Train)
학습이 진행되는 것을보여준다. 
And now, the moment of truth! From within models/object_detection:
python train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/ssd_mobilenet_v1_pets.config

Barring errors, you should see output like:
INFO:tensorflow:global step 11788: loss = 0.6717 (0.398 sec/step)
INFO:tensorflow:global step 11789: loss = 0.5310 (0.436 sec/step)
INFO:tensorflow:global step 11790: loss = 0.6614 (0.405 sec/step)
INFO:tensorflow:global step 11791: loss = 0.7758 (0.460 sec/step)
INFO:tensorflow:global step 11792: loss = 0.7164 (0.378 sec/step)
INFO:tensorflow:global step 11793: loss = 0.8096 (0.393 sec/step)

7. Export graph from new trained model
Your steps start at 1 and the loss will be much higher. Depending on your GPU and how much training data you have, 
this process will take varying amounts of time. On something like a 1080ti, it should take only about an hour or so.
If you have a lot of training data, it might take much longer.
You want to shoot for a loss of about ~1 on average (or lower).
I wouldn't stop training until you are for sure under 2. You can check how the model is doing via TensorBoard.
Your models/object_detection/training directory will have new event files that can be viewed via TensorBoard.
From models/object_detection, via terminal, you start TensorBoard with:
tensorboard --logdir='training'
This runs on 127.0.0.1:6006 (visit in your browser)
My total loss graph:


Looks good enough, but does it detect macaroni and cheese?!
In order to use the model to detect things, we need to export the graph, so, in the next tutorial, 
we're going to export the graph and then test the model.
Posted by 이성윤

LabelImg


LabelImg is a graphical image annotation tool.

It is written in Python and uses Qt for its graphical interface.

Annotations are saved as XML files in PASCAL VOC format, the format used byImageNet.

Demo Image

Demo Image

Watch a demo video

Installation

Download prebuiltbinaries

Build from source

Linux/Ubuntu/Mac requires at least Python 2.6and has been tested with PyQt 4.8.

Ubuntu Linux

Python 2 + Qt4

sudo apt-getinstall pyqt4-dev-tools

sudo pip installlxml

make qt4py2

python labelImg.py

python labelImg.py[IMAGE_PATH] [PRE-DEFINED CLASS FILE]


Python 3 + Qt5

sudo apt-getinstall pyqt5-dev-tools

sudo pip3 installlxml

make qt5py3

python3labelImg.py

python3labelImg.py [IMAGE_PATH] [PRE-DEFINED CLASS FILE]

macOS

Python 2 + Qt4

brew install qtqt4

brew installlibxml2

make qt4py2

python labelImg.py

python  labelImg.py [IMAGE_PATH] [PRE-DEFINED CLASSFILE]

Windows

Download and setup Python 2.6 orlater, PyQt4and install lxml.

Open cmd and go to labelImgdirectory

pyrcc4 -oresources.py resources.qrc

python labelImg.py

python labelImg.py[IMAGE_PATH] [PRE-DEFINED CLASS FILE]

Get from PyPI

pip installlabelImg

labelImg

labelImg[IMAGE_PATH] [PRE-DEFINED CLASS FILE]

I tested pip on Ubuntu 14.04 and 16.04. However, I didn't test pip on macOSand Windows

Use Docker

docker run -it \

--user $(id -u) \

-eDISPLAY=unix$DISPLAY \

--workdir=$(pwd) \

--volume="/home/$USER:/home/$USER"\

--volume="/etc/group:/etc/group:ro"\

--volume="/etc/passwd:/etc/passwd:ro"\

--volume="/etc/shadow:/etc/shadow:ro"\

--volume="/etc/sudoers.d:/etc/sudoers.d:ro"\

-v /tmp/.X11-unix:/tmp/.X11-unix\

tzutalin/py2qt4

 

makeqt4py2;./labelImg.py

You can pull the image which has all of the installed and requireddependencies. Watch a demo video

Usage

Steps

  1. Build and launch using the instructions above.
  2. Click 'Change default saved annotation folder' in Menu/File
  3. Click 'Open Dir'
  4. Click 'Create RectBox'
  5. Click and release left mouse to select a region to annotate the rect box
  6. You can use right mouse to drag the rect box to copy or move it

The annotation will be saved to the folder you specify.

You can refer to the below hotkeys to speed up your workflow.

Create pre-definedclasses

You can edit the data/predefined_classes.txtto load pre-defined classes

Hotkeys

Ctrl + u

Load all of the images from a directory

Ctrl + r        

Change the default annotation target dir

Ctrl + s

Save

Ctrl + d

Copy the current label and rect box

Space

Flag the current image as verified

w

Create a rect box

d

Next image

a

Previous image

del

Delete the selected rect box

Ctrl++

Zoom in

Ctrl--

Zoom out

↑→↓←

Keyboard arrows to move selected rect box

How to contribute

Send a pull request

License

Free software:MIT license

Citation: Tzutalin. LabelImg. Git code (2015). https://github.com/tzutalin/labelImg

Related

  1. ImageNet Utils to download image, create a label text for machine learning, etc
  2. Use Docker to run labelImg
  3. Generating the PASCAL VOC TFRecord files
Posted by 이성윤

머신러닝을 시작하면서 "데이터가 가장 중요하다.", "데이터가 돈이 된다" 이런 말들을 들었었다.


저런 말들을 들었을때, 그럴 수 있겠구나 싶었지만 와닿지는 않았다.

이번 과정을 통해서 왜 알바를 써서 이미지를 레이블링하는지, 왜 데이터가 중요하는지 등을 느낄 수 있었다.


1. 학습시킬 이미지 준비

sentdex로 부터 제공받은 macaroni and cheese를 사용하겠다. 이미지는 Google, Bing, ImageNet에서 수집했으며 이미지의 크기는 대부분 800x600 이다.

어떤 이미지이든지 100개 이상의 이미지를 확보해야 하며, 이미지가 확보 되면 레이블링 처리하는 Annotation을 수행해야 한다.

TODO 구글에서 내가 원하는 이미지를 확보할 수 있는 도구 찾아보기

TODO 구글에서 내가 원하는 이미지를 쉽게 확보 할 수 있는 도구 만들어보기


2. Annotate/label

이미지 레이블링은 labelImg 도구를 사용한다.

labelImg: https://github.com/tzutalin/labelImg


labelImg 설치는 다음을 참조한다.

[설치] image annotation tool

http://cafe.naver.com/telcosn/661


labelImg를 설치하고나서 데스크탑 모드에서 실행을 한다.

$ python labelImg.py


실행을 하고나면, GUI Window가 실행된다.

python tutorials


- 이미지가 저장되어 있는 디렉토리를 오픈한다.

- Create RectBox 버튼을 클릭하여 사진에서 Object를 드래그하여 레이블링을 한다.

- ctrl+s 로 저장을 하면 이미지와 같은 이름으로 xml 파일이 생성된다. 일반적으로 ANNOTATION이라는 디렉토리에 저장하는것이 관례인듯하다.

 ※ TODO XML파일을 열어보니 각각의 의미하는 내용을 정리해야 할 것 같다.



<annotation>
    <folder>images</folder>
    <filename>velveetashellsandcheese.jpg</filename>
    <path>/home/paperspace/Desktop/images/velveetashellsandcheese.jpg</path>
    <source>
        <database>Unknown</database>
    </source>
    <size>
        <width>900</width>
        <height>602</height>
        <depth>3</depth>
    </size>
    <segmented>0</segmented>
    <object>
        <name>macncheese</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>167</xmin>
            <ymin>169</ymin>
            <xmax>795</xmax>
            <ymax>527</ymax>
        </bndbox>
    </object>
</annotation>
cs


- 보유하고 있는 모든 이미지를 위의 방법으로 반복해서 작업한다.


3. 보유하고 있는 데이터를 train/test sample로 나누기

아래의 디렉토리 구조를 생성하고, 보유하고 있는 데이터를 train/test를 나눈다.



Object-Detection
-images/
--test/
---testingimages.jpg
--train/
---testingimages.jpg
--...yourimages.jpg
--...yourimages.xml
cs


4. 학습을 위한 TF Records 변환

참고: [TFRecord] 텐서플로우 트레이닝 데이타 포맷인 *.tfrecord 파일 읽고 쓰기 [펌]

TFRecord 파일 포맷이란

TFRecord 파일은 텐서플로우의 학습 데이타 등을 저장하기 위한 바이너리 데이타 포맷으로, 구글의 Protocol Buffer 포맷으로 데이타를 파일에 Serialize 하여 저장한다.

CSV 파일에서와 같이 숫자나 텍스트 데이타를 읽을때는 크게 지장이 없지만, 이미지를 데이타를 읽을 경우 이미지는 JPEG나 PNG 형태의 파일로 저장되어 있고 이에 대한 메타 데이타와 라벨은 별도의 파일에 저장되어 있기 때문에, 학습 데이타를 읽을때 메타데이타나 라벨용 파일 하나만 읽는 것이 아니라 이미지 파일도 별도로 읽어야 하기 때문에, 코드가 복잡해진다.


또한 이미지를 JPG나 PNG 포맷으로 읽어서 매번 디코딩을 하게 되면, 그 성능이 저하되서 학습단계에서 데이타를 읽는 부분에서 많은 성능 저하가 발생한다.


이와 같이 성능과 개발의 편의성을 이유로 TFRecord 파일 포맷을 이용하는 것이 좋다.


위와 같은 이유로 TFRecord 파일로 변환하기 위해서 labelImg를 통해 생성한 xml 파일을 먼저 CSV 파일로 변환해야 한다.


① xml 파일을 csv 파일로 변환하기 위해 Dat Tran 블로거가 작성한 xml_to_csv.py 스크립트를 사용한다.

github: https://github.com/datitran/raccoon_dataset

raccoon_dataset 의 xml_to_csv.py 스크립트를 수정하여 사용한다.


Within the xml_to_csv script, I changed:



def main():
    image_path
= os.path.join(os.getcwd(), 'annotations')
    xml_df
= xml_to_csv(image_path)
    xml_df
.to_csv('raccoon_labels.csv', index=None)
   
print('Successfully converted xml to csv.')
cs

To:



def main():
   
for directory in ['train','test']:
        image_path
= os.path.join(os.getcwd(), 'images/{}'.format(directory))
        xml_df
= xml_to_csv(image_path)
        xml_df
.to_csv('data/{}_labels.csv'.format(directory), index=None)
       
print('Successfully converted xml to csv.')
cs


 

생성된 CSV 파일을 Object-Detection 디렉토리에 data 디렉토리를 생성하고, data 디렉토리로 csv 파일을 옮긴다. 그리고 Object-Detection 디렉토리에 training 디렉토리를 생성한다. 지금까지의 디렉토리 구조는 아래와 같다.

Object-Detection
-data/
--test_labels.csv
--train_labels.csv
-images/
--test/
---testingimages.jpg
--train/
---testingimages.jpg
--...yourimages.jpg
-training
-xml_to_csv.py
cs


② 이제 CSV 파일을 TFRecord파일로 변환하기 위해 Dat Tran 블로거가 작성한 generate_tfrecord.py 스크립트를 사용한다.

Within the generate_tfrecord script, I changed:



# TO-DO replace this with label map
def class_text_to_int(row_label):
    if row_label == 'raccoon':
        return 1
    else:
        None

cs

To:



# TO-DO replace this with label map
def class_text_to_int(row_label):
    if row_label == 'macncheese':
        return 1
    else:
        None
cs


TODO 현재 Class가 macncheese 한 종류이기 때문에 하나만 작성한다. 만약 여러개의 클래스가 있다면 이부분을 수정해야 한다.


이제 generate_tfrecord.py 스크립트를 수행한다. train TFRecord와 test TFRecord를 위해 두번 수행하게 된다.

train TFRecord:



python generate_tfrecord.py --csv_input=data/train_labels.csv  --output_path=data/train.record
cs

test TFRecord:



python generate_tfrecord.py --csv_input=data/test_labels.csv  --output_path=data/test.record
cs


Next up, we need to setup a configuration file and then either train a new model or start from a checkpoint with a pre-trained model, which is what we'll be covering in the next tutorial.

Posted by 이성윤
http://cafe.naver.com/telcosn/554 주소복사 게시글분석

강의를 듣기 시작했다.

강의를 2강의 쯤 들었을때 수학이 필요하겠다라는 생각이 들었다.

텐서플로우는 파이썬 기반으로 개발이 된듯 하다. 파이썬으로 가벼운 프로그램 만들 수 있는 수준이라면

강의 듣는데는 문제가 생기진 않는다.

수학 공부를.. 제대로 하지 않은 나로서는 고민이 많이 되었다.  필요한 수학을 먼저 공부하고 들을지

아니면 어차피 제공되는 TensorFlow API를 쓰면 되는거라 대략 이해되면 넘어갈지.


고민하던차에, 먼저 강의를 쭈욱 들어보기로 했다. 현재 섹션 7까지 들었다.

섹션 4까지는 그리큰 시간을 투자하지 않아도 언급되는 수학 수식에 대한 이해가 그렇게 어렵지는 않았다.

Logistic (Regression) Classification에서 부터는 어려움을 느꼈고, 수식이 정확히 이해되지 않아도 큰 그림과 설명하는 의도가 이해가 되면, 그냥 넘어가면서 섹션 7까지 왔다.


섹션7까지 오면서, 점점 더 언급되는 수식이라도 정확히 이해하고 강의를 듣고 싶은 마음이 들었다. 수식을 이해하고 있다면 좀더 재미를 느낄 수 있지 않을까 라는 생각이 들기도 한다.

그래서 잠시.. 갈길을 멈추고, 수식을 먼저 공부하고자 한다.



섹션 0. 오리엔테이션
수업 소개와 개요 미리보기 00:10:00
섹션 1. 머신러닝의 개념과 용어
기본적인 Machine Learnnig 의 용어와 개념 설명 미리보기 00:12:00
TensorFlow의 설치및 기본적인 operations (new) 00:17:00
섹션 2. Linear Regression 의 개념
Linear Regression의 Hypothesis 와 cost 00:13:00
Tensorflow로 간단한 linear regression을 구현 (new) 00:15:00
섹션 3. Linear Regression cost 함수 최소화
Linear Regression의 cost 최소화 알고리즘의 원리 00:16:00
Linear Regression 의 cost 최소화의 TensorFlow 구현(new) 00:15:00
섹션 4. 여러개의 입력(feature)의 Linear Regression
multi-variable linear regression (new) 00:17:00
lab 04-1: multi-variable linear regression을 TensorFlow에서 구현하기 미리보기 00:08:00
lab 04-2: TensorFlow로 파일에서 데이타 읽어오기 (new) 00:06:00
섹션 5. Logistic (Regression) Classification
Logistic Classification의 가설 함수 정의 00:15:00
Logistic Regression의 cost 함수 설명 00:14:00
TensorFlow로 Logistic Classification의 구현하기(new) 00:15:00
섹션 6. Softmax Regression (Multinomial Logistic Regression)
Multinomial 개념 소개 00:10:00
Cost 함수 소개 00:15:00
lab 06-1: TensorFlow로 Softmax Classification의 구현하기 (new) 00:12:00
lab 06-2: TensorFlow로 Fancy Softmax Classification의 구현하기 (new) 00:16:00
섹션 7. ML의 실용과 몇가지 팁
학습 rate, Overfitting, 그리고 일반화 (Regularization) 00:14:00
Training/Testing 데이타 셋 00:09:00
lab 07-1: training/test dataset, learning rate, normalization (new) 00:11:00
lab 07-2: Meet MNIST Dataset (new) 00:13:00

 

Posted by 이성윤

TensorFlow를 본격적으로 시작하기전에, 관련된 블로그, 책, 까페, 강의 뭐 이런것들에 대한 정보를 수집하였다.


처음엔 팀장님이 말한 CNN위주로 검색을 했지만, 키워드를 TensorFlow와 머신러닝에 맞추었다.


다행이도, 가장 먼저 아주 훌륭한 TensorFlow강의를 발견하게 되었다.


강의제목

모두를 위한 머신러닝/딥러닝

강의URL

https://www.inflearn.com/course/%EA%B8%B0%EB%B3%B8%EC%A0%81%EC%9D%B8-%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D-%EB%94%A5%EB%9F%AC%EB%8B%9D-%EA%B0%95%EC%A2%8C/

1. 강좌 소개

알파고와 이세돌의 경기를 보면서 이제 머신 러닝이 인간이 잘 한다고 여겨진 직관과 의사 결정능력에서도 충분한 데이타가 있으면 어느정도 또는 우리보다 더 잘할수도 있다는 생각을 많이 하게 되었습니다. Andrew Ng 교수님이 말씀하신것 처럼 이런 시대에 머신 러닝을 잘 이해하고 잘 다룰수 있다면 그야말로 “Super Power”를 가지게 되는 것이 아닌가 생각합니다.

더 많은 분들이 머신 러닝과 딥러닝에 대해 더 이해하고 본인들의 문제를 이 멋진 도구를 이용해서 풀수 있게 하기위해 비디오 강의를 준비하였습니다. 더 나아가 이론에만 그치지 않고 최근 구글이 공개한 머신러닝을 위한 오픈소스인 TensorFlow를 이용해서 이론을 구현해 볼수 있도록 하였습니다.

이 머신러닝, 딥러닝 강좌는 수학이나 컴퓨터 공학적인 지식이 없이도 쉽게 볼수 있도록 만들려고 노력하였습니다.

2. 도움되는 분들

  • 인공지능에 대해 관심이 있는 누구나
  • 머닝러신, 딥러닝의 개념을 이해하고 싶으신분
  • 머닝러신의 직접 구현해보고 싶으신 분

3. 참고자료

이 비디오는 저도 인터넷등을 통해 공부하면서 만든것이며 아래 자료를 많이 사용하였습니다.

4. 지식공유자 소개

김성훈

Hong Kong University of Science and Technology 에서 컴퓨터 공학쪽으로 연구를 하고 있습니다.
비디오나 강의에 대한 의견이 있으시면 아래로 이메일을 보내 주시면 됩니다.
hunkim+ml@gmail.com


강의를 듣다가 이것저것 검색하다보니, 굳이 위의 사이트를 가입하지 않아도 볼 수 있었다..

http://hunkim.github.io/ml/


한마디 더 붙이자면, 김성훈 교수님같이 자신의 시간을 투자하여 아낌 없이 가지고 있는 지식을 공유하는분들이

점점 늘어나고 있다. 덕분에 많은 도움을 받고있다. 감사합니다.

Posted by 이성윤