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!

https://ocw.mit.edu/courses/18-06-linear-algebra-spring-2010/resources/lecture-14-orthogonal-vectors-and-subspaces/

 

Lecture 14: Orthogonal vectors and subspaces | Linear Algebra | Mathematics | MIT OpenCourseWare

Vectors are easier to understand when they’re described in terms of orthogonal bases. In addition, the Four Fundamental Subspaces are orthogonal to each other in pairs. If A is a rectangular matrix, Ax = b is often unsolvable. These video lectures of Pro

ocw.mit.edu

해당 강의를 참고하여 공부한 내용을 정리하였습니다.

새 창에서 열기

 

 

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로 학습한 것이 높은 성능을 보임

https://ocw.mit.edu/courses/18-06-linear-algebra-spring-2010/resources/lecture-13-quiz-1-review/

 

Lecture 13: Quiz 1 review | Linear Algebra | Mathematics | MIT OpenCourseWare

By approaching what we’ve learned from new directions, the questions in this exam review session test the depth of your understanding. This unit reached the key ideas of subspaces—a higher level of linear algebra. These video lectures of Professor Gilb

ocw.mit.edu

해당 강의를 참고하여 공부한 내용을 정리하였습니다.

새 창에서 열기

https://ocw.mit.edu/courses/18-06-linear-algebra-spring-2010/resources/lecture-12-graphs-networks-incidence-matrices/

 

Lecture 12: Graphs, networks, incidence matrices | Linear Algebra | Mathematics | MIT OpenCourseWare

This session explores the linear algebra of electrical networks and the Internet, and sheds light on important results in graph theory. These video lectures of Professor Gilbert Strang teaching 18.06 were recorded in Fall 1999 and do not correspond precise

ocw.mit.edu

해당 강의를 참고하여 공부한 내용을 정리하였습니다.

새 창에서 열기

 

 

 

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.

https://ocw.mit.edu/courses/18-06-linear-algebra-spring-2010/resources/lecture-11-matrix-spaces-rank-1-small-world-graphs/

 

Lecture 11: Matrix spaces; rank 1; small world graphs | Linear Algebra | Mathematics | MIT OpenCourseWare

As we learned last session, vectors don’t have to be lists of numbers. In this session we explore important new vector spaces while practicing the skills we learned in the old ones. Then we begin the application of matrices to the study of networks. Thes

ocw.mit.edu

해당 강의를 참고하여 공부한 내용을 정리하였습니다.

새 창에서 열기

https://ocw.mit.edu/courses/18-06-linear-algebra-spring-2010/resources/lecture-10-the-four-fundamental-subspaces/

 

Lecture 10: The four fundamental subspaces | Linear Algebra | Mathematics | MIT OpenCourseWare

For some vectors b the equation Ax = b has solutions and for others it does not. Some vectors x are solutions to the equation Ax = 0 and some are not. To understand these equations we study the column space, nullspace, row space and left nullspace of the m

ocw.mit.edu

해당 강의를 참고하여 공부한 내용을 정리하였습니다.

새 창에서 열기

+ Recent posts