Segmentation

Semantic Segmentation

- 모든 pixel에 label을 할당하는 것 (one label per pixel)

- instance를 구분하지 않음

- class의 수는 보통 정해져 있음

 

Instance Segmentation

- instance를 detect하고, 각각의 pixel에 label을 부여하여 instance를 구분함.

- "simultaneous detection and segmentation" (SDS)라고 불리기도 함.

 

Semantic Segmenation

이미지 input -> 특정 patch를 추출 -> cnn에 돌림 -> 가운데 픽셀이 분류됨

=> 이 과정들을 모든 pixel에 반복함

하지만, 이 방법은 비용이 너무 많이 드는 문제가 있음.

 

patch를 사용하는 것 대신 fully convolutional network를 사용하여 모든 픽셀을 한번에 얻는 방법을 사용함.

그런데 이 방법은 pooling layer 로 크기가 작아지는 문제가 있음.

Segmantic Segmentation : Multi-Scale

여러개의 스케일을 사용하는 아이디어.

 

이미지를 다양한 스케일로 resizing (마치 이미지 피라미드와 같음) -> 스케일링된 이미지를 각각의 CNN으로 돌려줌 -> 모두 원본과 같은 크기로 upsampling하고 concatenate 과정을 거침

 

이미지를 외부에서 "bottom-up" segmentation 과정을 거침(super pixels or segmentation tree)

 

=> 두 과정을 결합시켜 최종 output을 완성시킴

 

 

Segmantic Segmentation : Refinement

이미지를 RGB 3개의 채널로 분리된 상태로 cnn에 적용해 모든 label을 얻어낸다 -> 그 결과에 다시 한번 cnn 적용 -> 다시 적용

(이 3번의 과정에서 cnn은 parameter를 sharing 하고 있다.)

 

 

Segmantic Segmentation : Upsampling

작아진 feature map을 복원해주는 upsampling 방법에서 기존에는 별도의 작업을 사용했지만, 이 방법에서는 upsampling 과정까지도 network에 포함시킴. 즉, 학습이 가능한 upsampling layer가 등장한 것.

또한 skip connection 과정을 통해 앞단의 pooling layer를 가져와 통합시켜 성능을 향상시킴.

 

 

Learnable Upsampling : "Deconvolution"

위와 같이 학습할 수 있는 upsampling 방법을 Deconvolution 이라고 부르기도 한다.

 

일반적인 convolution의 결과는 dot product를 통해 다음과 같은 output이 도출될 것이다.

(4-3+2x1)/1 +1 = 4

 

Deconvolution은 weight을 부여하는 과정을 통해 upsampling을 한다.

겹치는 부분은 sum 연산으로 처리한다. convolution에서의 backward pass와 동일하다.

즉, deconv의 forward pass = conv의 backward pass

deconv의 backward pass = conv의 forward pass 와 동일한 과정이다.

그래서, 사실 "inverse of convolution"이 정확한 표현이다. 

 

 

 

 

 

Instance Segmenation

오래전부터 연구되어오던 Semantic segmentation과 달리 instance segmentation은 비교적 최근 연구 주제이다.

 

R-CNN과 비슷한 방식이다.

 

external segment proposal을 진행하고, 이를 통해 feature를 뽑아내어 box CNN에 돌려 bounding box를 얻어낸다.

동시에 mean image를 사용해 background를 제거한 이미지를 Region CNN에 돌린다.

두 결과물을 Region에 대해 분류를 진행한다. 마지막으로 Region refinement 과정을 거친다.

 

Instance Segmentation: Hypercolumns

원본이미지를 crop하여 alexnet에 돌리고, conv과정에서 upsampling 을 적용해 combine하여 결과를 도출한다.

 

 

Instance Segmentation: Cascades

Faster R-CNN과 매우 유사하다.

이미지 자체를 convolution 시켜 거대한 feature map을 만들어내고 RPN을 이용해 ROI를 뽑아낸다.

생성된 box를 warping과 pooling으로 동일한 사이즈로 맞춰주고 FC에 돌린다. 그 후 figure / ground logistic regression을 이용해 mask instances를 생성한다. 그 후 masking 과정을 통해 background를 제거하고 FC에 돌려 object의 class을 분류해낸다.

모든 과정은 end-to-end로 학습 시킬 수 있다.

Semantic segmentation

○ Classify all pixels

○ Fully convolutional models, downsample then upsample

○ Learnable upsampling: fractionally strided convolution

○ Skip connections can help

 

● Instance Segmentation

○ Detect instance, generate mask -> detection의 R-CNN, Faster R-CNN과 유사한 개념들이 등장

○ Similar pipelines to object detection

 

 

Attention Models

 

Recall : RNN for captioning

해당 방법은 RNN이 전체의 이미지를 한번만 보게되는 한계점이 존재, 따라서 RNN이 매 timestep 마다 이미지의 다른 부분을 보는 방법이 등장하게 됨.

 

 

그 방법이 바로 Soft Attention for Captioning

Soft Attention for Captioning

FC layer에서 나온 single feature가 아닌 그 전의 feature grid를 사용

이를 h0을 초기화 하는데 사용, a1(location에 대한 확률 분포)을 바로 추출, 이 확률 분포를 feature와 연산하여 weighted feature를 계산함. 이는 single summarization vector가 됨. 이를 생성하는 방법에는 2가지 방법이 존재

바로, soft attention, hard attention이다.

 

Soft vs Hard Attention

soft attention에서는 모든 location을 고려함. gradient descent를 사용하는데 적합 -> end-to-end 학습 가능

=> 연산량이 많음

hard attention에서는 가장 높은 확률을 가지는 grid를 선택, gradient descent를 사용할 수 없음. -> 별도의 강화학습 필요

=> 연산량이 적고, 정확도가 높음

 

결과

 

정해져 있는 grid에 대한 attention만 가능하다는 문제점 존재

-> 임의의 지점에 attention을 주는 방법 등장

 

 

Attending to Arbitrary Regions : DRAW

 

Attending to Arbitrary Regions : Spatial Transformer Network

localize 후 좌표를 생성, 그 후 crop하여 rescale 과정을 거침.

이를 함수라고 한다면 이를 미분가능한 함수를 만들 수 있을까?

input의 픽셀 좌표를 output의 픽셀 좌표로 mapping 해주는 함수를 생성

이를 통해 sampling grid를 생성, 그 후 bilinear interpolation으로 최종 결과물을 얻을 수 있음

 

 

Soft attention:

○ Easy to implement: produce distribution over input locations, reweight features and feed as input

○ Attend to arbitrary input locations using spatial transformer networks

 

Hard attention:

○ Attend to a single input location

○ Can’t use gradient descent!

○ Need reinforcement learning!

 

 

Data Augmentation

원본의 이미지를 변형하는 과정이 추가되는 방법

- label은  변화 없이 pixel이 변화하게 됨.

- 변형된 data를 훈련 하게 됨

- 매우 폭넓게 사용되고 있음

 

1. Horizontal flips

이미지를 좌우반전 시켜 변형해주는 방법

- mirror 이미지

2.  Random crops / scales

이미지를 랜덤으로 작은 부분으로 잘라내어 사용하는 방법

이미지 전체가 아니라 부분에 대한 학습이 이뤄지기 때문에 test 시에도 이미지 전체가 아닌 crop을 이용해 test를 진행하게 된다. 

3. Color jitter

단순한 방법 : random으로 jitter

복잡한 방법 : 

1) training set의 [R, G, B]에 PCA를 적용한다.

2) 주성분 방향의 color offset를 샘플링한다.

3) training image의 모든 픽셀에 offset을 더해준다.

 

4. 그 외의 방법 ...

- translation

- rotation

- stretching

- shearing

- lens distortions ...

- etc

 

A general theme : 

1. Training : 랜덤한 노이즈를 적용

2. Testing : 노이즈들을 평균화하는 작용

 

Data Augmentation은 dropout, dropconnect 과 비슷하다고 볼 수 있다.

따라서 Data Augmentation은 구현하기가 간단하고, 특히 작은 dataset에서 유용하다.

또한 noise와 marginalization을 적용시키는 간단한 framework가 된다.

 

Transfer Learning

잘못된 믿음 ->  "CNN을 사용할려면 많은 데이터가 필요하다."

 

Transfer Learning with CNNs

데이터 셋이 작은 경우에는 미리 학습된 모델의 앞단의 부분을 freeze(파라미터 고정)하고 뒷부분으로 데이터셋으로 학습하는 방법을 적용할 수 있다. 데이터가 medium size인 경우에는 조금 더 많은 부분을 설정해서 학습 시킬 수 있다.

 

일반적으로는 이미 학습된 모델을 가져와 학습하는 것이 더 성능이 좋다...

-> 왜그럴까?...

 

앞단에서는 굉장히 low level feature(ex. edge, gabor filter...)를 학습하기 때문에 어떤 이미지를 학습하더라도 적용이 될 수 있다. 따라서 위와 같은 결과가 나오는 것!...

 

 

데이터의 유사성과 데이터의 수에 따른 대처 방법

 

사실 CNN에서의 Transfer Learning은 보편적이다...

ex) Object Detection(Faster R-CNN), Image Captioning  ...

 

 

All About Convolutions

Part 1 : How to stack them

- small filter의 power

 

예를 들어 3x3 conv layer를 3개 쌓는다면 이는 하나의 7x7 convolution과 동일한 효과를 낸다.

둘의 weight의 개수를 비교해보면, Cx(7x7xC) = 49C^2 , 3xCx(3x3xC)=27C^2 이다.

결국 3개의 3x3 conv layer가 parameter의 수도 적고 더 nonlinearity를 가지기 때문에 좋다고 볼 수 있다.

또한 곱셈 연산의 수를 비교해보면

(H x W x C) x (7 x 7 x C) = 49 HWC^2, 3 x (H x W x C) x (3 x 3 x C) = 27 HWC^2

마찬가지로 3개의 3x3 conv layer가 곱셈연산의 수도 더 적다.

 

그렇다면 1x1 filter는?...

위와 같은 과정을 bottleneck convolution 또는 network in network라 부른다.

 

이를 3x3 filter와 비교해보면 bottleneck conv가 더 nonlinear하고 더 적은 parameter, 더 적은 연산이 들게 된다.

 

 

하지만, 아직 3x3 filter를 사용하고 있다. 다른 방법?...

위와 같은 filter 들을 많은 곳에서 사용하고 있다.

 

Recap

- 큰 conv 대신 3x3의 conv를 사용하는 것이 효율적이다.

- 1x1 "bottleneck" conv도 효율적인 방법이다.

- nxn filterfmf 1xn, nx1로 나누어 사용할 수 있다.

- 위의 모든 방법들은 더 적은 parameter를 가지고, 연산량이 적으며 더 nonlenear하다.

 

Part 2 : How to compute them

Implementing Convolutions : im2col

대부분의 플랫폼에서는 matrix multiplication을 잘 최적화 해놓음.

그렇다면 convolution 연산을 matrix multiplication연산으로 표현 할 수 있을까?

=> im2col 사용!

 

Feature map : HxWxC

Con weights : D filters, each KxKxC 라고 하면, 먼저 K^2C 의 column vecter를 N번(receptive field의 개수) 만큼 반복한 형태를 만들어준다. 

 

filter를 K^2C의 row vector 로 reshape해서 Dx(K^2C)  matrix를 만들어준다. 이를 matrix multiply를 해주면 

DxN 결과가 나온다.

 

Implementing convolutions: FFT

f와 g를 convolution 연산한 것은 Fourier Trasform의 element product와 동일하다.

Fast Fourier Transform을 이용하면, 우리는 N차원의 벡터의 Discrete Fourier transform를 O(N log N)으로 계산할 수 있다.

 

1. Compute FFT of weights: F(W)

2. Compute FFT of image: F(X)

3. Compute elementwise product: F(W) ○ F(X)

4. Compute inverse FFT: Y = F-1(F(W) ○ F(X))

 

Implementing convolutions: Fast Algorithms

Naive matrix multiplication: Computing product of two N x N matrices takes O(N3 ) operations

Strassen’s Algorithm: Use clever arithmetic to reduce complexity to O(Nlog2(7)) ~ O(N2.81)

 

Recap 

im2col : 구현하기 쉽지만 memory overhead가 발생할 수 있음.

FFT : 작은 커널에서는 성능향상을 가져올 수 있음.

Fast Algorithms : 유망한 분야이지만, 아직 널리 사용되지는 않음.

 

 

Implementation Details

CPU...  GPU...

CPU : Few, fast cores (1 - 16) Good at sequential processing

GPU : Many, slower cores (thousands) Originally for graphics Good at parallel computation

 

GPU - CPU communication is a bottleneck.

=> CPU data prefetch+augment thread running while GPU performs forward/backward pass

 

CPU - disk bottleneck Hard disk is slow to read from

=> Pre-processed images stored contiguously in files, read as raw byte stream from SSD disk

 

Floating Point Precision

소수점의 정확도

보통은 64 bit "double" precision이 기본값이다.

하지만 CNN에서는 32bit "single" precision로 빠른 연산을 수행한다.

 

또한 stochastic rounding이라는 방법을 사용한 16-bit fixed point로 학습한 것이 높은 성능을 보임

 

 

 

Recurrent Neural Network

 

one to one : 일반적인 Neural Networks으로 고정된 사이즈의 input이 들어간다.(ex 이미지..) output에서도 마찬가지로 고정된 사이즈의 score를 반환한다.

 

one to many : 이미지를 input으로 받아 이미지를 설명하는 단어들의 sequence를 반환한다. 

image -> sequence of words

e.g. Image Captioning

 

many to one : 단어들로 구성된 sequence를 통해 하나의 class로 반환한다.

sequence of words -> sentiment

e.g.Sentiment Classification 

 

many to many : 한국어 문장을 영어 문장으로 번역

seq of words -> seq of words

e.g. Machine Translation, Video classification on frame level

 

모든 각각의 time step에 대한 예측은 현재의 프레임 + 지나간 프레임에 대한 함수로 이루어지게 된다.

 

Sequential Processing of fixed inputs

고정된 input을 sequential하게 처리한 경우

deepmind에서 번지수를 인식할 때 작은 cnn을 이용해서 sequential한 작업을 사용

 

Sequential Processing of fixed outputs

고정된 사이즈의 output을 sequential하게 처리한 경우

Generativate model, 숫자를 써나가듯이 output을 반환함.

 

 

=> one to one에 경우에도 recurrent neural net을 사용할 수 있다.

 

 

RNN에서는 연속적인 input을 받아 특정 time step에서의 vector를 예측하게 된다.

따라서 위와 같은 recurrence function을 이용한다. -> sequence를 처리할 수 있게 된다.

단, 매 time step 마다 동일한 함수, 파라미터 set을 사용해야 한다.

 

 

Vanilla Recurrent Neural Network

ex) Character-level language model example

 

input을 one-hot encoding, W_xh : x에서 h로, W_hh : h에서 h로, W_hy : h에서 y로

각각의 time step에는 softmax classifier가 존재해 loss를 구할 수 있다.

 W_xh, W_hh, W_hy는 모든 time step에서 동일하다.

 

코드 : https://gist.github.com/karpathy/d4dee566867f8291f086

 

Minimal character-level language model with a Vanilla Recurrent Neural Network, in Python/numpy

Minimal character-level language model with a Vanilla Recurrent Neural Network, in Python/numpy - min-char-rnn.py

gist.github.com

 

결과

Searching for interpretable cells

각 cell에서 activate되는 부분이 존재하는 것을 확인 가능

 

quote(따옴표) detection cell, line length tracking cell, ...

 

 

Image Captioning

CNN과 RNN 2개의 모듈로 이루어져 있음. 

CNN -> 이미지 처리 

RNN -> sequence 처리

=> 두 개의 모듈은 마치 1개의 모델처럼 back propagation이 진행됨(end to end)

이미지 정보를 기억하는 일, 다음 단어를 예측하는 일 모두 수행해야 함.

 

Image captioning의 과정

VGG-net의 뒷부분을 생략하고 rnn을 붙여준다.

기존의 RNN에서 W_ih(image to hidden)를 추가해준다.

 

 

ex) microsoft coco

 

RNN의 미래..

-> attention, 이미지의 부분을 보고 그 부분에 적합한 단어를 추출할 수 있음. 후에 어디 부분을 봐야하는 지도 예측

 

LSTM

RNN에 문제가 있어 보통 LSTM을 사용함.

LSTM에는 hidden state와 함께 cell state가 존재한다는 것이 차이점.

 

 

input, forget, output, g

 

 

RNN vs LSTM

RNN => transformative, LSTM => additive(+)

또한 RNN은 vanishing gradient 문제가 존재, LSTM 은 +가 있기 때문에 이는 distributer의 역할을 해 gradient를 그냥 전달할 수 있음.

Whh에 계속 해서 곱셈 연산이 일어나게 됨 -> explode or vanish

 

Recall : "PlainNets" vs "ResNets"

 

GRU... 같은 것도 존재

 

 

Summary

- RNNs allow a lot of flexibility in architecture design

- Vanilla RNNs are simple but don’t work very well

- Common to use LSTM or GRU: their additive interactions improve gradient flow

- Backward flow of gradients in RNN can explode or vanish. Exploding is controlled with gradient clipping. Vanishing is controlled with additive interactions (LSTM)

- Better/simpler architectures are a hot topic of current research

- Better understanding (both theoretical and empirical) is needed.

 

 

1. Visualize patches that maximally activate neurons

각 행은 pool5에서 추출한 임의의 neuron이 가장 activate 시키는 부분을 보여준다.

 

2. Visualize the filters/kernels(raw weights)

이미지에 직접 작용하는 필터는 conv1에 있는 필터이므로, 이것만 해석 가능하다. 

다음의 layer 들의 weight들은 시각화할 수 있지만 low image에 대한 것이 아닌 layer1의 activation에 대한 시각화이기 때문에 큰 의미가 있지는 않다.

3. Visualize the representation

classify 하기 직전의 fc7 layer에서 추출한 representation으로 시각화하는 방법이 있다.

 

대표적인 방법으로 t-sne 시각화 방법이 있다. cnn의 시각으로 볼 때 유사하는 것을 가깝게 위치시켜 준다.

MNIST data

4. Occlusion experiments

occlusder를 슬라이딩 시켜 어느 부분에 위치해 있을 때 정확하게 classify 하는 확률이 변하는지 확인

5. Visualizing Activations

1. Deconvolution-based approach

Q: how can we compute the gradient of any arbitrary neuron in the network w.r.t. the image?

임의의 뉴런이 있는 곳까지 forward pass를 해주고, activation을 구한다.

그 후 해당 layer의 뉴런의 gradient를 1, 그 외에는 gradient를 0로 둔 뒤 back propagation을 수행한다.

Guidied backpropagation을 사용하면 positve한 influence한 반영하게 되어 선명한 이미지를 얻을 수 있다.

relu 대신 modifed relu를 사용하면 Guidied backpropagation을 사용할 수 있다.

backward deconvnet은 relu의 영향을 받지 않아, -인 값들은 0으로 처리 된다.

 

 

2. Optimizationi-based approach

이미지를 파라미터로 이용하는 방법, weight의 update X

 

 

1. Find images that maximize some class score

2. Visualize the Data gradient

하얀 부분이 영향력을 주는 부분

이런 방법을 사용해 segmentation을 수행하는 grabcut이라는 알고리즘도 있다.

 

 

임의의 뉴런에 적용해보면 다음과 같은 과정을 수행할 수 있다.

L2 regularization 대신 blur된 이미지를 사용한다고 한다.

 

 

Question: Given a CNN code, is it possible to reconstruct the original image?

FC 7 layer의 code로 이미지를 복원할 수 있을까?

 

Find an image such that:

- Its code is similar to a given code

- It “looks natural” (image prior regularization)

 

예시

사실 FC 7 layer만이 아니라 다른 layer에서도 복원이 가능하다.

 

 

ex) 구글의 deep dream도 image에 대한 optimization 기법을 사용한다.

gradient를 activation 값으로 사용하게 되어 relu에서 boost 효과가 일어나 여러가지 그림을 합성한 듯한 이미지가 나타나게 됨

 

ex) NeuralStyle

1. content 이미지를 convnet에 넣고, 각각의 layer에서 low activation을 저장한다.

2. Style 이미지를 넣고, style gram matrices를 얻는다.

3. Optimize over image to have

- The content of the content image (activations match content)

- The style of the style image (Gram matrices of activations match style)

 

 

 

Question: Can we use this to “fool” ConvNets??(속이다)

=> Adversial Attack

 

 

0.5씩 조정하여 적대적인 X를 만들 수 있다.  class 0에 해당하는 이미지를 class 1로 분류하게 만들 수 있다.

이는 linear classifier의 본질적인 문제이다.

 

“primary cause of neural networks’ vulnerability to adversarial perturbation is their linear nature“

(and very high-dimensional, sparsely-populated input spaces)

 

Backpropping to the image is powerful. It can be used for:

- Understanding (e.g. visualize optimal stimuli for arbitrary neurons)

- Segmenting objects in the image (kind of)

- Inverting codes and introducing privacy concerns

- Fun (NeuralStyle/DeepDream)

- Confusion and chaos (Adversarial examples)

 

 

 

 

 

컴퓨터 비전의 주요 TASK

Classification + Localization

Classification

Input : image => Output : class label

평가지표 : Accuracy

 

Localization

Input : image => Output : box in the image

평가지표 : Intersection over Union

 

Idea #1 : Localization as Regression

 

Step 1 : Train (or download) a classification model (AlexNet, VGG, GoogLeNet)

Step 2 : Attach new fully-connected “regression head” to the network

Step 3 : Train the regression head only with SGD and L2 loss

Step 4 :  At test time use both heads

 

 

Per-class(클래스에 특화된) vs class agnostic regression(클래스에 범용적인)

Class specific: C x 4 numbers (one box per class)

Class agnostic: 4 numbers (one box) 

 

 

어디에 regression head를 붙여야 될까?

=> After conv layers, After last FC layer

 

Aside : Localizing multiple objects

정해진 수 K가 있다면 detection을 사용하지 않고 regression만으로도 localization이 가능하다.

 

Aside :  Human Pose Estimation

사람의 관절의 수를 정해져 있기 때문에 regression 만으로도 쉽게 localization이 가능하다.

 

Localization as Regression

- 매우 간단하다.

- 나름 강력하다.

 

 

Idea #2 : Sliding Window

- Run classification + regression network at multiple locations on a highresolution image

- Convert fully-connected layers into convolutional layers for efficient computation

- Combine classifier and regressor predictions across all scales for final prediction

 

대표적인 예시 : Overfeat

- Winner of ILSVRC 2013 localization challenge

 

window를 슬라이딩 시켜 regression head에서 bounding box 4개, classification head에서 score 4개를 다음과 같이 만들어 낸다.

 

 

위 bbox들을 merge하고, 최종 score도 산출해 낸다.

 

실제로도 4개보다 훨씬 많은 sliding window를 사용한다.

이렇게 되면 연산 자체가 heavy해져 효율적이지 못하다.

따라서 fc layer를 conv layer로 바꿔 주었다. 

 

 

 

 

ImageNet Classification+Localization

ResNet은 완전히 다른 방법인 RPN(Regional Proposal Network)를 사용해 엄청난 성능 향상을 이뤄냄.

 

 

Object Detection

Detection as Regression?

- 이미지에 따라서 object의 개수가 달라져 output의 개수도 달라지기 때문에 regression이 적당하지 않다.

- but,,, YOLO(You Only Look Once)에서는 regression을 사용하긴 한다.

 

Detection as Classification

box 영역을 보고 classification을 진행하여 detection을 하는 방법

 

Problem: Need to test many positions and scales

(다양한 사이즈의 많은 window를 필요로 하게 됨.)

Solution: If your classifier is fast enough, just do it

(무거운 classifier만 아니라면, 그냥 해라..)

 

Problem: Need to test many positions and scales, and use a computationally demanding classifier (CNN)

(무거운 연산인 CNN을 필요로 하는 경우)

Solution: Only look at a tiny subset of possible positions

(의심되는 지역만 보자... Region Proposals)

 

ex) HOG, DPM

 

Region Proposals

정확도, 클래스에 상관하지 않고 그냥 blobby한 영역을 매우 빠르게 잡아내는 것

- Find “blobby” image regions that are likely to contain objects

- “Class-agnostic” object detector 

- Look for “blob-like” regions

 

대표적인 방법으로는 Selective Search가 있다.

 

그 외에도 많은 방법들이 있다. (Edgeboxes를  추천해주심)

 

 

그래서 이런 Region Proposal과 CNN를 결합하여 사용한 것이 바로 R-CNN이다.

R-CNN

input 이미지를 받아 proposal method를 사용하여 ROI를 뽑아낸다.(약 2000개)

각각의 ROI는 다른 위치와 크기를 가지게 됨.

정사각형으로 warp을  시킴

Conv에 들어가게 됨.

그 후 regression과 SVM을 이용한 classify를 진행시킴.

 

 

Step 1: Train (or download) a classification model for ImageNet (AlexNet)

 

Step 2: Fine-tune model for detection

- Instead of 1000 ImageNet classes, want 20 object classes + background (21개의 class로 바꿔줘야함.)

- Throw away final fully-connected layer, reinitialize from scratch

- Keep training model using positive / negative regions from detection images

 

Step 3: Extract features

- Extract region proposals for all images

- For each region: warp to CNN input size, run forward through CNN, save pool5 features to disk

- Have a big hard drive: features are ~200GB for PASCAL dataset!

Step 4: Train one binary SVM per class to classify region features

ex) 고양이라면, 고양이인지? 아닌지? 2개 중 하나로 positive, netgative 분류를 함.

Step 5 (bbox regression): For each class, train a linear regression model to map from cached features to offsets to GT boxes to make up for “slightly wrong” proposals

(region proposal이 항상 정확한 것은 아니기 때문에, cache 해놓은 feature에서 regression을 이용해 정확도를 높혀주는 작업이다. 이는 mAP를 3~4% 정도 높혀준다.

 

 

Object Detection : Datasets

PASCAL VOC, ImageNet Detection, MS-COCO...

 

Object Detection : Evaluation

mean average precision (mAP)

R-CNN의 문제점

1. Slow at test-time: need to run full forward pass of CNN for each region proposal

2. SVMs and regressors are post-hoc: CNN features not updated in response to SVMs and regressors

3. Complex multistage training pipeline

 

 

Fast R-CNN

CNN과 region proposal 추출의 순서를 바꾼 것

이미지를 우선 CNN에 돌려 고해상도의 conv feature map을 생성한다. 

여기서 proposal method를 사용해 ROI를 추출하고, 이를  ROI Pooling이라는 기법을 사용해 

FC layer로 넘겨줘 classifier와 regression을 수행한다.

 

R-CNN Problem #1: Slow at test-time due to independent forward passes of the CNN

Solution: Share computation of convolutional layers between proposals for an image

 

R-CNN Problem #2: Post-hoc training: CNN not updated in response to final classifiers and regressors

R-CNN Problem #3: Complex training pipeline

Solution: Just train the whole system end-to-end all at once!

 

high-res conv feature = > low-res conv feature로 바꿔주는 것을 ROI Pooling이 해결해주게 됨.

 

ROI Pooling의 과정

 

 

 

Fast R-CNN 결과

R-CNN은 각각의 Region proposal에 대해 별개로 forward pass

Fast R-CNN은 Region proposal간의 conv layer의 computation을 share하기 때문에 빠르게 된다.

 

Fast R-CNN의 Problem

region proposal을 포함하게 되면 2초나 걸려 real-time으로는 사용하기 힘듬.

Fast R-CNN의 Solution:

Just make the CNN do region proposals too!

 

 

Faster R-CNN

이전까지는 Region Proposal을 외부에서 진행해왔음.

Region Proposal Network를 삽입하여 내부에서 Region Proposal을 수행하게 함.

 

 

 

Faster R-CNN : Region Proposal Network

기본적으로 Convolution Net이다. sliding  3x3 window로 Region Proposal을 생성해냄.

 

 

Faster R-CNN : Training

 

Faster R-CNN : Results

YOLO: You Only Look Once Detection as Regression

Detection을 Regression으로 간주하고 적용하는 기법 이전에는 Detection을 classification으로 간주했었음.

 

Divide image into S x S grid Within each grid cell(일반적으로 7x7)

predict: B Boxes: 4 coordinates + confidence Class scores: C numbers

Regression from image to 7 x 7 x (5 * B + C) tensor

 

Direct prediction using a CNN

 

Faster R-CNN 보다 빠르지만, 성능이 좋지는 않다.

 

Recap Localization:

- Find a fixed number of objects (one or many)

- L2 regression from CNN features to box coordinates

- Much simpler than detection; consider it for your projects!

- Overfeat: Regression + efficient sliding window with FC -> conv conversion

- Deeper networks do better

 

Object Detection:

- Find a variable number of objects by classifying image regions

- Before CNNs: dense multiscale sliding window (HoG, DPM)

- Avoid dense sliding window with region proposals

- R-CNN: Selective Search + CNN classification / regression

- Fast R-CNN: Swap order of convolutions and region extraction

- Faster R-CNN: Compute region proposals within the network

- Deeper networks do better

 

 

Convolution Layer

이미지의 width, height, depth
필터는 이미지의 depth와 같다.

이미지에 필터를 convolve, 이미지에 공간적으로 슬라이딩하여 dot product 연산을 수행하는 것

 

 

한 로케이션 당  75번의 연산으로 한 숫자를 만들어 낸다.

one filter, one activation map
re-representation 했다.
필터의 개수 = 다음 이미지의 depth, 필터의 depth = 이미지 depth

 

 

첫번째 필터는 이미지의 weight를 시각화한것, 뒤의 것들은 앞단의 filter에 기반해서 시각화한 것.

hierarchy 구조로 복잡한 이미지를 인식하게 됨.

 

 

필터와 signal(image), 2개의 signal이 convolution 작용을 하기 때문에 convolutional layer라고 불린다.

 

 

 

 

 output size의 일반화

 

 

패딩을 사용하여 size를 보존할 수 있다.

이미지의 사이즈가 계속 줄어들면 volume 자체가 shrink해버린다. 너무 빠른 shrinking은 좋지 않다...

 

Ex 1)

Input volume: 32x32x3 10 5x5 filters with stride 1, pad 2 Output volume size: ?

=> Output volume size: (32+2*2-5)/1+1 = 32 spatially, so 32x32x10

 

Ex 2)

Input volume: 32x32x3 10 5x5 filters with stride 1, pad 2 Number of parameters in this layer?

 each filter has 5*5*3 + 1 = 76 params (+1 for bias) => 76*10 = 760

 

 

1x1 filter? -> 의미가 있다.

 

 

각각은 input의 작은 부분과 연결되어 있다. -> local connectivity

모든 뉴런들을 동일한 파라미터를 공유한다.

 

위와 같은 그림의 뉴런들은 같은 local connectivity를 가지지만, 동일한 파라미터를 공유하고 있지 않다. 

 

즉, 동일한 depth내의 뉴런들은 parameter sharing을 하지만, 별개의 activation map에서 동일한 위치에 있는 뉴런들은 local connectivity를 가지는 같은 곳을 쳐다본다.

 

 

 

Pooling Layer

- representation을 작게, 더 관리할 수 있도록 만들어 준다.

- 각각의 activation map에 독립적으로 작용한다.

MAX pooling

Fully Connected Layer (FC layer)

- 열벡터화해서 fully connected하게 연결해 matrix multipication 연산을 해 마지막으로  softmax에서 분류를 하게끔 해준다.

 

Case Study

LeNet-5

AlexNet

Input: 227x227x3 images

First layer (CONV1): 96 11x11 filters applied at stride 4

=> Q: what is the output volume size?

(227-11)/4+1 = 55, [55x55x96]

=> Q: What is the total number of parameters in this layer?

Parameters: (11*11*3)*96 = 35K

 

Input: 227x227x3 images

After CONV1: 55x55x96

Second layer (POOL1): 3x3 filters applied at stride 2

=> Q: what is the output volume size?

(55-3)/2+1 = 27, [27x27x96]

=> Q: what is the number of parameters in this layer?

0, pooling layer에서는 파라미터가 없다.

 

 

 

ZFNet

 

VGGNet

FC가 유용하지 않다(param이 너무 많음)는 의견이 나와 요즘에는 average pooling을 자주 사용한다.

 

=> 성능이 좋지만 복잡하다. FC layer를 average pooling으로 대체하여 파라미터 수를 줄였음.

 

ResNet

기존의 net들이 layer가 많아짐에 따라 error가 커지는 경향이 보임을 지적함.

resnet은 layer가 많아짐에 따라 error가 적어지는 경향을 보임. 많은 layer를 사용함.(152)

 

 

- Batch Normalization after every CONV layer

- Xavier/2 initialization from He et al.

- SGD + Momentum (0.9)

- Learning rate: 0.1, divided by 10 when validation error plateaus

- Mini-batch size 256

- Weight decay of 1e-5

- No dropout used

 

 

요약

- ConvNets stack CONV,POOL,FC layers

- Trend towards smaller filters and deeper architectures

- Trend towards getting rid of POOL/FC layers (just CONV)

- Typical architectures look like [(CONV-RELU)*N-POOL?]*M-(FC-RELU)*K,SOFTMAX where N is usually up to ~5, M is large, 0 <= K <= 2.

- but recent advances such as ResNet/GoogLeNet challenge this paradigm

 

TODO

- parameter update schemes

- Learning rate schedules

- Dropout

- Gradient checking

- Model ensembles

 

 

Parameter update

Stochastic Gradient Descent(sgd)

현재는 단순한 gradient descent 방법을 사용하고 있지만, 앞으로 복잡한 방법에 대해 설명할 예정

단순한 Stochastic Gradient Descent(sgd)는 느리다.

sgd => mini-batch(일부 데이터의 모음)로 loss function을 계산

 

왜 이렇게 sgd는 느릴까??

수직으로는 경사가 가파르고 수평으로 완만한 loss function을 생각해보자.

Q: What is the trajectory along which we converge towards the minimum with SGD?

수직으로는 빠르게 수평으로는 느리게 이동하여 다음과 같이 이동하게 될 것 이다.

그래서 sgd가 느리게 이동하게 되는 것이다. 

 

Momentum update

x를 직접 업데이트 하는 것이 아닌, v(속도)를 업데이트 하여 v를 통해 x를 업데이트 해준다.

(언덕에서 공을 굴리는 느낌)

mu=> 마찰계수

처음에는 overshooting이 발생하지만 결국에는 minimum에 빠르게 도달하게 된다. 

 

Nesterov Momentum update

NAG(Nesterov Accelerated Gradient)라고도 함. momentum보다 항상 covergence rate가 좋다.

일반적으로 momentum은 2개의 part로 나누어져있다. 

mu*v(momentum step) - learningrate*dx(gradient step)

gradient step을 계산하기 전에 momentum step을 계산하고 그 종료점에 gradient step을 구해준다.

shift 해주는 부분만 차이가 있다.

 

하지만, 불편한 부분이 있다.

세타와 다른 위치에서의 gradient를 구하는 것이 일반적인 다른 코드들과의 호환성 측면에서 떨어지게 된다.

그래서 phi를 도입하여 치환하여 위와 같은 식을 구할 수 있게 된다.

 

AdaGrad update

cache라는 개념을 도입하게 된다. cache는 building up이 되는 양수

per-parameter adaptive learning rate method라고 한다.

파라미터들이 다른 값의 lr을 가지게 되는 방법

 

=> 위의 예시에서 AdaGrad를 사용하게 되면, 수직으로는 gradient가 커서 cache가 커지게 되고 lr이 작아지게 되고, 수평으로는 결과적으로 lr이 커지게 된다.

 

=> 하지만 시간이 흐름에 따라 lr이 0에 가까워지게 되고 학습이 종료되게 된다.(단점) 

이를 보완한 것이 바로 RMSProp이다.

 

RMSProp update

decay rate(parameter)를 도입해 cache의 값을 서서히 올라가게 함.

Adam update

momentum과 RMSProp을 결합한 형태

\

 

그럼 어떤 learning rate를 사용해야 할까?

=> 초기에는 크게 후에는 줄여서 사용해야한다.

보통 exponential decay를 사용

 

지금까지 배운 update 방법은 1st order optimization method 이다.

=> loss function을 구하는데 있어 gradient 정보만을 사용하는 방법

 

Secone order optimization methods

Hessian을 통해 경사뿐만아니라 곡면의 구성을 알 수 있어, 바로 최저점으로 갈 수 있게 된다.

그렇다면 learning rate도 필요가 없게 된다. 

장점 : learning rate가 필요가 없게 된다. convergence rate가 빠르다

단점 : 사실 neural net에서는 현실적이지 못하다. 엄청 큰 행렬을 역행렬 연산을 해야하기 때문에..

 

하지만 다른 방법으로 시도해보자는 시도가 있음.

ex) BGFS, L-BFGS

 

그래서 결론은,

보통 adam을 사용하는 것이 좋고, full batch update를 할 수 있는 환경이라면 L-BFGS를 사용해보자.

 

Evaluation : Model Ensembles

1. Train multiple independent models

2. At test time average their results

=> Enjoy 2% extra performance

=> 단점: 여러개의 모델 관리 이슈, test 속도가 느려짐.

 

여러개의 모델이 아리나 단일 모델에서 checkpoint 간의 앙상블을 하더라도 성능향상을 보일 수 있다.

parameter vector들 간의 앙상블도 성능 향상을 보인다.

Regularization (dropout)

일부 뉴런(노드)를 0으로 랜덤으로 설정해줌

어떻게 좋은 아이디어일 수 있을까?

-> redundant(중복)을 하게 된다.

tail 부분이 ear부분을 볼려고 노력을 하게 된다.

다른 해석으로는 Droppit도 하나의 큰 ensemble로 보게 된다는 것이다. 

 

test time은 어떻게 하게 될까?

-> 모든 뉴런을 turn on(no dropout)으로 test한다.

p=0.5로 할 때 activation이 inflate되게 된다. 따라서 scaling이 필요하다.

predict에서 p를 곱해줘서 scaling 해야한다.

이를 편리하게 하기 위해 inverted dropout을 사용해 먼저 /p를 해주는 것이 일반적인 방법이다.

 

Convolutional Neural Network

본격적으로 활용.. LeNet

 

history...

Hubel & Wiesel,,, 방향

Topographical mapping in the cortex,,, locality

이를 컴퓨터를 활용해 인위적으로 시뮬레이션 해보자!..

Neurocognitron[Fukuchima 1980]

Gradient-based learning applied to document recognition [LeCun, Bottou, Bengio, Haffner 1998]

-> LeNet

 

ConvNet의 비약적인 발전

ImageNet Classification with Deep Convolutional Neural Networks [Krizhevsky, Sutskever, Hinton, 2012]

-> AlexNet

 

 

 

 

mini-batch SGD

loop:

1. Sample a batch of data

2. Forward prop it through the graph, get loss

3. Backprop to calculate the gradients

4. Update the parameters using the gradient

 

Training Neural Networks (a bit of history)

- 1957, Mark 1 Perceptron -> back prop 불가

- 1960, perceptron의 stacking, Adaline/Madaline

 

1960~1980 신경망의 1번째 암흑기.. 

 

- 1986, Rumelhart et al, First time back-propagation became popular

-> 네트워크가 커질 수록 잘 동작이 안됨..

 

~ 2000 중반, 신경망의 2번째 암흑기 

 

- 2006, Hinton and Salakhutdinov

-> Restricted Boltzman Machine(RBM)을 이용하여 pretraining을 도입

-> 하나로 통합 후 backprop, 그 후 finetuning 사용

=> 제대로 동작하는 첫번째 backprop

 

 황금기(폭발적인 발전)

- 2010, Context-Dependent Pre-trained Deep Neural Networks for Large Vocabulary Speech Recognition

- 2012, Imagenet classification with deep convolutional neural networks

요인, 요소 : weight 초기화 방법 발전, GPU 환경, 데이터 증가

 

Activation Functions

 

Sigmoid

- 넓은 범위의 숫자들을 [0,1] 범위의 숫자로 squash해준다.

- 전통적으로 자주 사용해왔지만 더이상 잘 사용하진 않는다.

 

문제점

- 뉴런이 포화되어(0 또는 1에 가까워짐) gradient를 없애버릴 수 있다. (vanishing gradient)

(x의 값이 꽤 크거나 작은 경우에는 local gradient가 0에 가까워지게 됨 -> 그래프에서 saturated regime인 구역)

- Sigmoid의 결과는 zero-centered가 아니다. -> slow convergence를 가져오게 됨.

(w의 gradient가 항상 all positive이거나 negative이기 때문)

- exp()가 연산적으로 비쌈

 

 

tanh(x)

- [-1, 1] 범위로 숫자들을 squash 해준다.

- zero centered 되어 있다. 

- 여전히 뉴런이 포화되어(0 또는 1에 가까워짐) gradient를 없애버릴 수 있다. (vanishing gradient)

 

ReLU

 

- x가 양수인 지점에서는 포화되지 않음

- 연산적으로 효율적이다.

- sigmoid/tanh에 비해 수렴되는 속도가 6배정도 빠르다.

 

문제

- zero-centered가 아니다.

- 음수인 경우에 vanishing gradient가 발생

 

dead ReLU는 learning rate가 너무 크거나, weight 초기화가 운이 나쁘게 잘못되었을 때 발생함.

=> 이를 방지하기 위해 작은 양수 값으로 초기화하는 경우도 있음

 

Leaky ReLU

- saturate가 일어나지 않음

- 효율적인 연산

- converge가 빠름

- will not 'die' (gradient..)

 

Parametric Rectifier

alpha도 학습할 수 있음

Exponential Linear Units(ELU)

- ReLU의 장점을 가지고 있음

- not die

- zero mean outputs에 가까움

- 연산에서 exp()을 가지고 있음

 

Maxout "Neuron"

- Does not have the basic form of dot product -> nonlinearity

- ReLU와 Leaky ReLU를 일반화

- saturateX, note die

- 2배로 증가하는 연산과 파라미터

 

결론

- ReLU를 사용, 단 learning rate에 주의

- Leaky ReLU/ Maxout / ELU를 실험적으로 사용

- tanh를 실험적으로 사용하지만 기대X

- sigmoid는 사용X

 

Data Preprocessing

단, 이미지 데이터에서는 정규화는 진행하지 X

이미지는 기본적으로 [0~255]안에 들어가 있기 때문

 

PCA(주성분 분석), whitened data

=> 사실 이미지에 있어서 둘다 사용은 X

 

 

이미지에서는 정규화, PCA, whitening은  흔하게 사용하지 않고, 사실상 zero-centered만 신경 쓰면 된다. 

- 이미지의 평균 값을 빼준다. (e.g. AlexNet)

- 채널별 평균 값을 빼준다. (e.g. VGGNet)

 

Weight Initialization

Q : 만약 W=0으로 초기화 되어 있다면?..

모든 뉴런들이 동일한 연산을 수행하고, back prop을 수행함.

small random numbers

=> 네트워크가 작을 때에는 동작하지만, 커지게 되면 문제가 발생함.

standard variance이 0으로 수렴하게 되고 결과적으로 모든 activation이 0이 되어버림

=> vanishing gradient가 발생

 

0.01 대신 1을 쓴다면 거의 모든 뉴런들이 saturate 됨. -> Gradient가 0이 되어버림

 

Xavier initialization

input의 개수가 많으면 weight가 작아짐, 개수가 적으면 weight가 커짐

 

- 문제 : ReLU를 사용할 때 문제가 생김. (but when using the ReLU nonlinearity it breaks.)

 

He et al., 2015 (note additional /2)

 

 

Batch Normalization

vanishing gradient가 발생하지 않도록 하는 해결방법 중 하나

(activation 함수 변화, 가중치 초기화 방법이 아니라 학습하는 과정 자체를 안정화하는 것을 목표로 함.)

 

각 layer를 거칠 때마다 normalization을 진행

 

정규분포 적용

 

 

\

보통 Fully connected layer와 activation layer 사이에 위치하게 된다. 

 

 

 

1. Normalize

2. 정규화 된 것을 조정(r-> 스케일링 B->shift)

 

 

전체적인 flow

장점

- gradient flow를 향상

- 큰 lr도 허용시켜준다.

- 초기화에 대한 강한 의존성을 상쇄시켜준다. 

- regularization의 효과가 있음

 

주의

- training, test 할때 batch normalization을 다르게 해 줘야 한다. 

- mean/std를 구할 때 training은 batch를 기준, test는 전체를 기준 

 

Babysitting the learning process

1. 데이터 전처리 (zero-centered)

2.  choose the architecture (sanity check)

 

훈련 전, 데이터 중 일부만 가져와 regularization을 끄고 simple vanilla 'sgd'를 사용해 overfitting이 되는지 확인

(back prop이 잘 작동하고 있다는 뜻)

 

loss not going down : learning rate too low

loss exploding : learning rate too high

 

cross validation을 사용해 적절한 learning rate를 알아내야 함.

 

Hyperparameter Optimization

cross-validation 전략

First stage: only a few epochs to get rough idea of what params work

Second stage: longer running time, finer search

 

First stageg

 

-> random search 방법

 

기본적으로 grid search는 오히려 최적화된 parameter를 찾기 어렵다.

 

 

Hyperparameters to play with

- network architecture

- learning rate, its decay schedule, update type

- regularization (L2/Dropout strength)

 

 

hyperparameter를 조정한 뒤 loss curve를 관찰해야 한다.

 

 

다양한 그래프

 

- bad 초기화로 다음과 같은 그래프가 나옴.

hyperparameter를 조정한 뒤 accuracy를 관찰해야 한다.

 

 

weight updates/ weight magnitudes 를 관찰해야 한다.

+ Recent posts