순서 

1. 통계 - 카운팅,min,max,평균,중앙값,산포도,분산,편차,공분산,상관관계 

2. 가설과 추론 (베이지언 - 사후확률,우도) 

3. 군집화 (K-Means)

4. 연관 (Apriori)

5. 함수형으로 데이터 다루기 

6. 경사하강법

7. 회귀분석

8. 은닉 마코프법 (HMM) 

9. k-NN

10. DTW 

 * 참고로 "밑바닥부터 배우는 데이터과학" 서적은 numpy,scikit-learn 등의 외부라이브러리를 활용은 배제되었습니다.


여기서 배울 베이즈 이론의 경우 데이터 분석 및 요즘 유행하고 있는 딥러닝 및 뇌과학에서도 핵심에 있는 중요한 이론입니다.박문호 박사님의 아래 동영상에서는 모든것은 베이즈로 이루어져 있다고도 말합니다. 시간 날때 함 보세요 재밌습니다.

-> 뇌과학으로 본 인공지능의 현주소와 미래 01

그리고 분류를 위해 사용하는 머신러닝중  스팸 필터링을 위해서 나이브베이즈 모형을 주로 사용하는데 베이즈 이론을 공부하고 나면 나이브베이즈도 쉽게 이해할 수 있을 것입니다.


베이즈 확률


두개의 상자가 있다고 해보자.
 
A 상자에는 빨강색 공 3개와 파랑색 공 7개가 있다.
A 상자에서 눈을 감고 하나를 골라내었을 경우 빨강색 공일 경우의 확률은? 

간단히 3/10 이다. 

자 B 상자가 있다, 빨강색 공 7개와 파랑색 공 3개가 있다.
B 상자에서 눈을 감고 하나를 골라내었을 경우 빨강색 공일 경우의 확률은? 

간단히 7/10 이다.

이 경우는 너무 쉽다. 
하지만 반대로 되면 어떨까? 

즉 빨강공을 당신에게 주고서, 이 빨간공이 A,B상자 중에서 A상자에서 나왔을 확률을 계산하라고 하면?

말문이 막힐거 같다. ㅎㅎ (이 글을 다 읽으면 쉽게 구할 수 있게 된다. 하지만 중요한것은 공식이 아니라 이런 경우에는 베이지언을 사용한다는 것이다. 즉 베이지언 확률이 필요한 경우에 대한 감을 잡는게 중요하다.) 

즉 빨강공이라는 조건이 있을 때 A 상자에서 나왔을 조건부확률을 구하는 것이다.
반대로 A상자라는 조건이 있을 때 빨강공이 나올 조건부확률은 위에 구했다시피 3/10이다. 


무한도전 

무한도전에서 박명수는 시민들에게 무작위로 선물을 주기 위해 선물트럭을 몰고 시내로 나갔습니다. 트럭에는 3개의 칸막이가 있고, 지나가던 시민은 그 중 하나를 선택하면 그 칸막이 뒤에 있는 선물을 받게 됩니다.

하나의 칸막이에는 벤츠자동차가 있으며 , 나머지 칸막이에는 각각 박명수,유재석의 사인 카드가 있습니다.

일단 시민이 칸막이 A를 선택했고 , 박명수는 나머지 칸막이 중 자동차가 없는 칸막이 하나 (B)를 보여 주며 긴장감을 고조 시킵니다. 그리고 시민에게 묻습니다.


" 혹시 선택을 나머지 C 로 바꾸겠습니까?" 


처음 선택한 칸막이를 고수 할 것인가?  나머지 하나의 칸막이로 바꿀 것인가?  당신의 선택은 ??  

자!! 이 문제의 답은 게시글 마지막에 함께 풀어보도록 하며 , 먼저 확률에 대해서 알아 보도록 합시다. 


확률

확률은 매우 간단합니다. 주사위로 생각해 봅시다.

주사위 1개를 던저 나오는 눈의 수를 생각 할때 , 주사위 던지는 조작을 "시행"이라고 합니다.

이 시행으로 얻어진 결과 중에서 조건에 맞는 결과 집합을 "사상" 이라고 합니다.

만약 홀수가 나오는 사상이라면 시행의 결과가 1,3,5 인 눈의 집합이 됩니다.

결국 공식을 다음과 같이 정의 할 수 있습니다.

확률 P =   문제 삼고 있는 사상이 일어나는 경우의 수 (A) /  일어날 수 있는 모든 경우의 수 (U) 


곱사상

두 사상 A,B 가 있다고 합시다.

- A 는 4 이하의 눈이 나오는 사상 

- B 는 짝수가 나오는 사상 

A 와 B 가 동시에 일어나는 "동시확률" 은 ?

A 는 4/6 

B 는 3/6  

A * B = 1/3     즉 두개의 사상이 함께 일어날 확률은 두 사상을 곱하여 계산합니다. 


조건부 확률

어떤 사상 A 가 일어났다고 하는 조건 아래서 사상 B 가 일어나는 확률을 , A 의 조건 아래서 B 가 일어나는 "조건부 확률" 이라고 합니다.

P(B|A) 라고 합니다. ( A 가 일어난 후에 B가 일어날 확률 ) 


P(B | A)    =  '4 이하의 눈이 나왔을 때 그 눈이 짝수 일 확률' =   2/4 

P(A | B)    = '짝수의 눈이 나왔을때 그 눈이 4이하일 확률' = 2/3


승법정리

P(A∩B) = P(A)P(B|A) = P(B)P(A|B) 

검증해볼가요?  (위의 주사위 확률을 문제로 삼고 진행해 봅시다) 

A 사상과 B 의 사상이 함께 일어날 확률은?  위 곱사상 편에서 보면  1/3 이었습니다.

P(A) 는 ?  4/6  이 었지요.

P(B|A) 는 ? 2/4 였습니다 ( 위의 조건부 확률에서 확인) 

P(A)와 P(B|A) 를 곱하면 ?   네 1/3 이 됩니다. 


베이즈 정리는 이 승법정리에서 간단히 유도 됩니다.


베이즈 정리 

위의 승법정리를 토대로 간단히 다음과 같은 식이 얻어집니다.

P(AB)=P(B)P(A)P(BA)



위에서 A 나 B 로 하면 먼가 이해하기 힘들거 같아서 

A 를 H 로 바꾸고 (Hypothesis :  '원인' 혹은 '가정' )

B 를 D 로 바꾸어 보겠습니다. ( Data :  '결과' 혹은 '데이터') 


P(HD)=P(D)P(H)P(DH)


여기서 좀 상상해 보는 시간을 갖도록 하겠습니다.

위의 정리는 이렇게 말하고 있습니다.

P(H | D) :   결과 데이터가 이렇게 이렇게 나왔는데 , 이렇게 결과 나오려면 어떤 원인이 있었던 것일까??

P(D)    :      모든 결과 (어떤 가설에든 포함되는 데이터의 비율로 , 한정 상수라고도 한다) 

P (H)   :    (결과 데이터 D 를 얻기 전에)  원인인 H가 성립될 확률 

P(D | H) : 원인 H 가 일어났을때 데이터 D 가 얻어질 확률 


정리하면 아래와 같다.

 확률 기호 

 명칭 

 의미  

 P(H | D)

 사후 확률 

 데이터 D 가 얻어졌을때 그 원인이 H 일 확률 

 P(D | H)

 가능도 (우도,likelihood)

 원인 H 가 일어났을때 데이터 D 가 얻어질 확률 

 P (H)

 사전확률

 (결과 데이터 D 를 얻기 전에)  원인인 H가 성립될 확률


사후확률이라는 이름을 딱 보면 먼가 일어나고 나서 발생하는 확률이라고 착각하기 쉬운데 ..
무엇인가 나중에 일어났을때 그게 일어나는 원인을 찾는 확률이다. 헥깔리기 쉽다.

또한 우도라고 주로 표현하는데 개인적으로 가능도가 더 마음에 든다.


예1 ) 

실생활적으로 생각해보면 음성인식에서 어떤 데이터의 값들이 얻어졌을때 그 원인이 "아" 라고 발음해서인 확률인것이다.

예2 ) 

어느 지역의 기상통계에서 4월 1일 흐릴 확율은 0.6이고, 다음 날인 2일 비가 올 확률은 0.4 였다. 또한 1일 날 흐릴 때 다음날 2일에 비가 올 확률은 0.5 이다. 이 지역에서 2일에 비가 왔을 때 전날인 1일 날 흐릴 확률은 ? 

예3 ) 

다른 구체적인예로는 색깔이 있는 초콜렛인  M&Ms 는 1994년에는 노랑이 20% 녹색이 10% 였고 , 1996년에는 노랑이 14%, 녹색이 20% 비율로 들어가 있다. 당신이 M&M 두 봉지를 샀을때 각각 1994 년과 1996년 제품이 었다. 각 봉지에서 하나씩 꺼냈을때 한 알은 노란색이고 , 한알은 녹색이었다. 이 때 노랑 초콜렛이 1994년에 생산된 봉지에서 나왔을 확률은 ??


무한도전 문제 풀이 (일명 : 몬티 홀 문제) 

" 혹시 선택을 바꾸겠습니까?" 

대부분의 사람들은 그냥 선택을 바꾸거나 안바꾸거나 고급자동차를 뽑을 확률은 1/2 의 이라고 생각하기 쉽다. 

하지만 그렇지 않다. 베이즈 확률을 이용하여 계산하여 보자.

먼저 3개의 가설을 정의 한다. A,B,C 는 자동차가 A,B,C 칸막이 뒤에 있다는 가설이다. 

    사전 확률   P (H) 

 가능도 P(D | H) 

 P(H) P(D | H) 

  한정상수 P(D) 

  사후 확률P(H|D) 

           A

    1/3

  1/2

    1/6

     1/2

   1/3

           B

    1/3

   0

    0

     1/2

    0

           C

    1/3

   1

    1/3

     1/2

   2/3 

상품은 임의로 놓여진다고 했으므로 차는 어느 문 뒤에든 동일한 1/3 확률로 있으므로 사전확률은 쉽다.

가능도만 좀 헥깔릴 수 있는데 , 다음처럼 생각해보자

- 만약 차가 실제로 문 A 뒤에 있다면 박명수는 문 B 나 C 를 안전하게 열 수 있다. 따라서 박명수가 문 B 를 선택할 확률은 B 와 C 둘 중 하나 선택하면 되므로 1/2 이다. 그리고 차가 문 A 뒤에 있으므로 차가 문 B 뒤에 없을 확률은 1이다.

- 만약 차가 문 B 뒤에 있다면 박명수는 문 C 를 열어야 하므로 박명수가 문 B를 열 확률은 0이다.

- 마지막으로 차가 문 C 뒤에 있다면 박명수는 1의 확률 (당연히) 로 문 B 를 열 것이고, 1의 확률로 차가 없을 것이다.

이제 나머지는 초딩도 할 수 있는 산수이다. 한정 상수 1/2 는 P(H) P(D | H)  를 모두 합한 수다. 

결국 사후 확률은 C 로 결정을 바꾸는 결과가 2/3 으로 훨씬 높다. 즉 바꾸는게 유리하다. 


* 막간 코너 )  베이즈파와 빈도론파의 확률을 둘러싼 대립 

둘의 차이는 한마디로 '확률을 미리 상정하는가', '상정하지 않는가' 로 표현 할 수 있다.

예를 들어보면  여기 두종류의 동전이 있다고 가정하자. 하나는 앞면과 뒷면이 나올 확률이 반반인 동전이며, 다른 하나는 앞면이 나올 확률이 80%인 가짜 동전이다. 둘다 외형적으로는 전혀 구별되지 않는다고 가정하고 몇번인가 던진 회수를 집계 분석해 진짜 동전인지 가짜 동전인지 판단해보자.

빈도론파 )

10 번 던진 중 10번 모두 앞면이 나왔다는 데이터를 얻었다고 하자. 이 동전이 진짜 동전이라고 말 할수 있을까? 누군가 이 동전을 진짜라 했다고 가정하자. 그 가정 아래서 10번 중 전부가 앞면이 되는 확률을 계산하면 

' 1/2 의 확률로 나오는 앞면이 우연히 10번 전부 나올 확률은 2^10 분의 1 , 즉 0.10% 이다.  이 0.10% 라는 확률이 이른바 p- 값이다. 다시 말해 이런 기적 같은 확률이 실제로 일어났다고 생각하기보다는, 본래의 '이 동전은 진짜' 라는 가정을 '생각하기 어렵다' 라며 버리는 편이 이치에 합당하다고 판단한다.

즉 빈도론은 확률을 이렇게 ' 몇번 중 몇번' 처럼 '빈도' 로 파악한다는 의미이다.

베이즈파 )

베이즈론자가 이 동전을 분별할 때는 우선 아무 정보도 없는 시점에서 어느 정도의 확률로 이 동전은 가짜인가 진짜인가를 생각한다.이 시점에서의 확률을 '사전확률' 이라고 부른다. 사전 확률은 아무 값으로 설정해도 상관없다. 베이즈론자는 진짜인 경우와 가짜인 경우 등 각각의 상황에서 사전확률과 조건부 확률의 곱셈을 한다. 사전확률과 데이터에 근거해 산출된 '사후확률' 을 계산한다. 

사회조사,역학,생물통계학등은 빈도론자가 많고, 계량경제학자 중에는 베이즈론자가 증가하고 있다. 데이터마이닝 머신러닝 분야에서는 베이즈론 쪽으로 치우치는 경향이 있다.  둘은 뿌리 깊은 대립 구도를 형성하고 있다. 빈도론자들은 베이즈론자들을 향해서 '사전확률을 설정' 하는 것은 도무지 말이 되지 않는다라고 한다. 


- 빅데이터를 지배하는 통계의 힘에서 발췌 



레퍼런스) 

그림으로 설명하는 개념 쏙쏙 통계학

Think Bayes (파이썬을 활용한 베이지안 통계) 






요즘 데이터분석과 관련하여 신경망(특히 딥러닝) 과 스파크(ML)등의 머신러닝 솔루션들이 굉장히 유행하고 있습니다. 물론 저것들이 그 동안 해결해주지 못했던 것을 좀 더 잘 해주기 때문에 인기를 끄는 것은 당연하지만,  데이터 분석이라는 바운더리에서 저런 것 들은 아주 작은 부분인 것이 사실입니다. 대부분의 데이터 분석은 저런 거창한 것 말고 평균,편차 같은 기본적인 개념으로 부터 시작되고 있으며 이러한 개념을 조금씩 변경해가며 더 의미있는 가치를 찾기 위해 빠르게 적용해보는 과정을 거쳐야하는데  그러기 위해서는 

1. 직접 코딩해서 기본적인 데이터분석 유틸리티 함수들을 만들어봐야한다. 

2. SQL문을 잘 다루어야한다. 

3. 엑셀을 잘 다루어야 한다. 

이 3가지는 기본이라고 생각해서 항상 공부해야 한다고 생각합니다. 소규모 데이터를 가지고 이리저리 반복해서 돌려보는 과정은 매우 중요하며 이런 기본적인 것들도 못하면서 하둡,텐서플로우나 깔짝대고, 데이터 분석 한다 라고 칭할 수는 없겠지요. 그래서 이것들 중 1번에 대하여  "밑바닥부터 시작하는 데이터과학" 등의 좋은책의 내용을 통해서 살펴보는 시간을 갖도록 하겠습니다. 통계,확률,패턴인식 분야의 내용들의 수식은 외우기가 힘듭니다. 외워도 금방 까먹어지는게 통계관련 공식인거 같습니다. (예를들어 정규분포라는 개념은 매우 쉽게 수긍이 가지만 , 그 식을 외우는건 좀 .;;) 또한 체득하고 나면 당연한거 아냐? 라고 느껴지는 알고리즘(수식) 인데 글로 설명하면 매우 산만해지는거 학문인거 같습니다. 하지만  우리들은 소프트웨어 개발자이기 때문에 수많은 기술변화도 따라가야하는 운명에 있는데 쓸때 없이 공식 및 수학을 외우고 있을 수는 없지 않겠습니까? 

제가 초등학교 5학년때 만(10,000) 단위 암산을 했었는데요. 주산,암산을 배워보신분은 아시겠지만 그것이 가능한것은 기억의 매개로 주판을 이용한 것 입니다. 마찬가지로 우리 개발자들은 그 기억의 매개체로 코드를 이용하면 개념과 함정(예를들어 K-Means 를 통해 군집화하면 길이차를 가지고 구분짓는 것이기 때문에 문제가 생기는 도메인 또한 많다) 에 대한 이해가 더 오래갈 것이라 보며 덤으로 가져다 사용도 할 수 있을것입니다.

* 그 상상의 매개체로써의 언어로 "파이썬" 을 선택했으며 정말 좋은 언어라고 생각합니다.

순서 

1. 통계 - 카운팅,min,max,평균,중앙값,산포도,분산,편차,공분산,상관관계 

2. 가설과 추론 (베이지언 - 사후확률,우도) 

3. 군집화 (K-Means)

4. 연관 (Apriori)

5. 함수형으로 데이터 다루기 

6. 경사하강법

7. 회귀분석

8. 은닉 마코프법 (HMM) 

9. k-NN

10. DTW 

 * 참고로 "밑바닥부터 배우는 데이터과학" 서적은 numpy,scikit-learn 등의 외부라이브러리를 활용은 배제되었습니다.


통계

하마 스타트업을 창업한 후에 승승장구하여 꽤 많이 성장하게 되었다. 이 회사는 데이트 매칭 회사로 사용자들이 몇 명의 친구를 가지고 있고, 그것에 관해 어떤 내용들을 담고 있는지 설명해 달라고 데이터 분석팀에게 요청이 날라왔다. 해결해볼까?


1.  일단 데이터 그 자체를 1차원 리스트로 보여줄 수 있습니다.

num_friends = [100,40,30,54,25, 3, ..........]     # 100 명의 친구를 가진 사람도 있고 3명의 친구를 가진 사람도 있다.

회원 수가 몇명 안되면 이렇게 보여 줄 수 도 있지만 만명 정도 되면 이렇게 보여 주기 힘들다.


2. 동일한 친구수를 가진 사람들을 모아서 보여 줍니다. 보통 몇명의 친구들을 가지고 있는지? 

100명의 친구를 가진 사람이 4명이고  3명의 친구를 가진 사람이 3명이면 100:4, 3:3 이렇게 보여주고 싶습니다.
이럴때 코드는 다음과 같이 작성 할 수 있습니다.

import collections

num_firends = [100,40,30,54,25,3,100,100,100,3,3]
friend_counts = collections.Counter(num_firends)
print('friends:', friend_counts)

결과 : ('friends:', Counter({100: 4, 3: 3, 40: 1, 54: 1, 25: 1, 30: 1}))
Counter 를 활용하여 동일한 아이템을 카운팅해 줍니다.

즉 

friend_counts[100] 은 4 이고 
friend_counts[3] 은 3 입니다. 


3. 차트를 이용해서 가시화(visualization) 해서 보여주면 더 좋겠지요?

matplotlib 를 이용하여 손쉽게 막대그래프로 보여줍니다.

#-*- coding: utf-8 -*-

import collections
import matplotlib.pyplot as plt

num_firends = [100,40,30,30,30,30,30,30,30,30,54,54,54,54,54,54,54,54,25,3,100,100,100,3,3]
friend_counts = collections.Counter(num_firends)
print('friends:', friend_counts)

# 가시화 추가

xs = range(101)
ys = [friend_counts[x] for x in xs] # 파이썬에는 이렇게 List구축을 할 수 있습니다. list comprehension 라고 말합니다.

plt.bar(xs,ys)
plt.axis([0,101,0,25])
plt.xlabel("# of friends")
plt.ylabel("# of people")
plt.show()


결과 : 100명의 친구를 가진 사람 숫자 4명에 대한 막대등이 그려져 있습니다. 



4. 가장 많은 친구수는? 가장 적은 친구 수는?  궁금합니다.

당연하게도 이런 통계치가 가장 기본적으로 필요 합니다.   (len, max, min 함수를 사용합니다) 

num_firends = [100,40,30,30,30,30,30,30,30,30,54,54,54,54,54,54,54,54,25,3,100,100,100,3,3]
num_points = len(num_firends)
print num_points # 25

max_value = max(num_firends)
print max_value # 100 
min_value = min(num_firends)
print min_value # 3



5. 조금 변형하여  두번째혹은 세번째 많은 친구 수도 필요 할 때가 있겠지요? 

어떤 연속된 데이터에서 가장 크거나 가장 작은 값이 너무 튈 경우 문제가 생길 수 있습니다. 따라서 두번째 큰 수를 구하고 싶을때가 있는데요 이때는 정렬을 해서 사용할 수 있습니다.

num_firends = [100,40,30,30,30,30,30,30,30,30,54,54,54,54,54,54,54,54,25,3,100,100,100,3,3]

sorted_values = sorted(num_firends)    # 오름차순으로 정렬된 리스트를 반환한다 
second_smallest_value = sorted_values[1]  # 두번째로 작은 값
second_largest_value = sorted_values[-2]  # 두번째로 큰 값 , 파이선에서 -1 은 가장 뒤를 말한다  



6. 회원들의 친구 수의 평균을 알고 싶습니다. 보통 몇명의 친구를 가지고 있을까요?


from __future__ import division # 이것을 써주어야 값이 더 정확하게 계산된다네요. 

num_firends = [100,40,30,30,30,30,30,30,30,30,54,54,54,54,54,54,54,54,25,3,100,100,100,3,3]

def mean(x) :
return sum(x) / len(x)

avgOfFriends = mean(num_firends)
print avgOfFriends

#파이썬 기본 모듈에 평균을 구하는것은 없는 듯 합니다.그래서 주로 numpy를 이용합니다.


7. 친구 수의 중앙값(median)을 알고 싶다. 중앙값은 머죠? 

중간값은 보통  평균보다 더 내가 원하는 바를 잘 말해주곤 하는데요. 미국 모 대학교 지리학과의 84년 졸업생의 평균연봉은 어느 한 졸업생에 의해 크게 상승하였는데... 그 사람은 바로 마이클 조던 입니다. 

그런 특이케이스는 평균이라는 수치를 신뢰하게 어렵게 만듭니다. (회사의 누구 한사람때문에 회사연봉이 크게 올라가는것 처럼) 이럴 경우 중간값을 사용합니다. 

중간값은 최고와 최소가 얼마나 크게 차이가 나는지는 전혀 중요치 않습니다. 

#-*- coding: utf-8 -*-

from __future__ import division

num_firends = [1200,15,10,10,9,4,3,3,2,1]


def mean(x) :
return sum(x) / len(x)

avgOfFriends = mean(num_firends)
print avgOfFriends


def median(v) :
n = len(v)
sorted_v = sorted(v) # 정렬해준뒤에 
midpoint = n // 2 # // 로 나누면 int형이 됨. / 로 나누면 float 

if n % 2 == 1:
return sorted_v(midpoint) # 리스트가 홀 수면 가운데 값 
else :
lo = midpoint - 1 # 짝수면 가운데의 2개의 값의 평균 
hi = midpoint
return (sorted_v[lo]+sorted_v[hi]) / 2



medianOfFriends = median(num_firends)
print medianOfFriends
결과

평균: 125.7
중앙값: 6.5



8. 친구 수라는 데이터의 분포(산포도) 는 어떻게 될까요?  분산, 표준편차등을 알아보아요.

8-1 . 최대,최소 사이의 범위

num_firends = [100,15,10,10,9,4,3,3,2,1]

def data_range(x) :
    return max(x) - min(x)

data_range(num_firends) # 99


8-2. 이상(異常) 치를 제외하고 평범한 데이터 사이의 범위차이

상,하위 25% 사이의 차이

def quantile(x,p) :
    p_index = int(p * len(x))
    return sorted(x) [p_index]

def interquartile_range(x):
    return quantile(x,0.75) - quantile(x,0.25)


8-3. 분산 (variance)  : 데이터들 사이에 얼마나 차이가 큰가? 

import math

num_firends = [100,15,10,10,9,4,3,3,2,1]

def mean(x) :
return sum(x) / len(x)

def dot(v,w) :
return sum(v_i * w_i for v_i, w_i in zip (v,w))

def sum_of_squares(v) :
return dot(v,v)


def de_mean(x) : # 요소들과 평균의 차이
x_bar = mean(x)
return [x_i - x_bar for x_i in x]

def variance(x) : 
n = len(x)
deviations = de_mean(x)
return sum_of_squares(deviations) / (n-1) # n으로 나누기보다 n-1로 나누어야 정확하게 보정됨 (위키참조)


print variance(num_firends)


8-4. 표준편차  (standard deviation) :  분산은 데이터의 차이에 제곱을 해주기때문에 그 값을 sqrt 를 해줘서 현실적으로 바꿔줌.

def standard_deviation(x) :
  return math.sqrt(variance(x)) 



9. 상관 관계 : 두 특성사이의 연관관계를 말해줌. (친구의 수와 연봉간에 연관관계가 있을까요?)

9-1 . 공분산 (covariance) 

다른 예를들어 보면 

- 사람들의 okky 싸이트의 접속 시간의 리스트가 있다고 하자.

- 사람들의 경력기간 리스트가 있다고 하자.

위의 두가지 요소들 즉 접속시간이 길 수록 경력도 길다라는게 말이 될까?  이것을 알고 싶을때 사용하는게 공분산이다.

def covariance(x,y):
    n = len(x)
    return dot(de_mean(x), de_mean(y)) / (n-1)


covariance(connection_time, working_time)

위의 코드의 포인트는  x 요소들의 분산과 y 요소들의 분산을 내적(dot) 하는데 있다.
서로의 분산이 유사한 증가 혹은 감소 패턴을 보인다면 dot 의 크기가 매우 커질 것이다. 
즉 리턴하는 값이 클 수록 상관관계가 있다고 볼 수 있다. ( 하지만 위의 공분산도 데이터의 속성에 따라 잘못된 정보를 즐 수 있음을 유념하자) 


9-2 . 상관관계 (correleation)

def correlation(x,y) :
stdev_x = standard_deviation(x)
stdev_y = standard_deviation(y) 

if stdev_x > 0 and stdev_y > 0 :
return covariance(x,y) / stdev_x / stdev_y
else :
return 0 # 편차가 존재하지 않는다면 상관관계는 0

상관관계는 단위가 없으며, 항상 - 1 에서 1 사이의 값을 갖는다. 예를들어 , 상관관계가 0.25 라면 상대적으로 약한 양의 상관관계를 의미한다. -1 혹은 1 에 가까울때 상관관계가 크다고 말 할 수 있다.



지금까지 통계에 관한 기본적인 내용에 대해 다루어봤습니다. 이러한 통계에는 구멍도 있다는 것을 관련 서적들을 참고 해서 찾아보세요. 다음에 여유가 되면 기초 확률, 통계적 검증(p-value) , 회귀분석, 베이즈 모형 등에 대해서 알아 보겠습니다. 


참고:

그림으로 설명하는 개념쑥쑥 통계학

밑바닥부터 시작하는 데이터 과학

패턴인식

딥러닝 관심있던 개발자 여러분 그동안 영어 이해하랴 이론 이해하랴 정말 수고 많으셨습니다.  

괜찮은 한국어 동영상이 있어서 링크 해 봅니다.  정말 쉽게 딥러닝의 이론에 대해서 설명합니다.


매우 감사한 일입니다.


이 동영상으로 기반을 이해하고, Caffe 등을 통한 다양한 실제 적용을 통해 통찰력과 직관을 기르면  일반 개발자 입장에서  딥러닝을 본인의 프로젝트에 좋은 서브무기로 사용 할 수 있으리라 봅니다.


* 이래서 동강동강하나 봅니다. 



제공 : 모두의 연구소 - 이찬우 연구원



[딥러닝] 1. Introduction

[딥러닝] 2. 선형회귀와 Gradient Descent

[딥러닝] 3. Gradient Descent & Normal Eq.

[딥러닝] 4. 로지스틱 회귀

[딥러닝] 5. 로지스틱 회귀의 비용함수

[딥러닝] 6. 신경망의 표현

[딥러닝] 7. 신경망의 역전파

[딥러닝] 8. 소프트맥스

[딥러닝] 그래프 개론

[딥러닝]RNN Introduction

[딥러닝] RNN : LSTM Basic

[딥러닝] RNN : LSTM 구조

[딥러닝] RNN : Back Propagation

[딥러닝] RNN 학습 메커니즘

[딥러닝] Convolutional NeuralNet 1

[딥러닝] Convolutional NeuralNet 2

[딥러닝] CNN Back Propagation




기타 좋은 강의 모음


유다시티 딥러닝 코스 

스탠포드 이미지 인식을 위한 CNN

딥러닝북 





마스터 알고리즘을 읽고 정리했습니다. 머신러닝 처음 입문하는 사람이 보기엔 그닥이고 어느정도 학습 후 보시길 권합니다. 예를들어 1,2,4,5 의 평균 을 구하는것을 배우려면 더하기랑 나누기를 배우면 됩니다만 이 책은 그런 간결하고 명쾌한 해답을 알려주는 책이 아니라 여러가지 이론을 말로 주저리주저리 풀면서 연관시키는데 목적을 두고 있습니다. 그 주저리주저리는 아마도 님을 주화입마에 빠지게 할 거에요 -.-;;  저도 치명상을 입고 누워있..


AR-HMM 에 대한 논문을 읽다가 통계학에 관해 공부를 조금 했는데 

(배워서 써먹는게 아니라 내 경우는 써먹으려고 배운 경우라 시간이 없어 기초/체계가 부족하다) 


관련 교과서들이 why 에 대해 설명한 교재는 거의 없더라 ... 몇권있다

일본인이 쓴 "빅데이터를 지배하는 통계의 힘"이란 책이 why 에 대한 책 중 하나


참고로 


주파수 해석에 관한 책으론 "수학으로 배우는 파동의 법칙" 이 

패턴인식으로는 "패턴인식 - 오일석 저" 가 참 좋다.  이해시키려고 책을 썼다는 느낌이 든다...

팔아먹으려고 혹은 자신이 성취한것을 자랑하기 위해 쓰여진 국내 책들이 너무나 많다. 



그 와중에 통계학에 대한 편견이 생겼는데  쉬운걸 어렵게 설명하는데 있어선 최고인 학문같다라는 점.

학문 자체가 '글월 (문장)' 으로 설명하는데 많이 수고스러울거 같긴하더라..작가가 그 why 나 설명 부분을 적절하게 말하기가 어렵고 귀찮으니 단지 수식이나 남발하며  SAS 나 SPSS 사용법만으로 책을 가득 채웠겠지 싶다..


학(저)자란 '쉬운걸 어렵게 말하는 사람들' 이란 예가 딱 맞지 싶다..


특히 시계열 관련 교재중 제대로 된 교재는 없다고 느꼈는데  그나마  송근원 선생님이 지으신 

"회귀분석과 아리마 시계열 분석" 인데  이 분은 한글화를 주창하시는 분인데 개인적으로 공감하며 

절로 존경의 마음이 생기더라..  ( 이 책은 특정부분 설명은 좋은데, 너무 얇아서 많은 생략이 있어 아쉽다) 


한글화 번역 


white-noise : 없소리 (백색소음)

stochastic : 제멋대로 (확율적) 

co-variation : 함께 변하기 (공변)

linear  : 곧은 줄꼴  (선형)

scatter-gram : 펼친그림 (산포도)

homoscedasticity : 같게퍼짐 (등분산성) 

residuals : 찌꺼기 (잔차)

mising value : 빠진 값 (결측치)

differencing : 차이화 (차분)

outlier : 삐진자 


일반 번역 

parametric : 모수 

nominal variable  : 명목변수 

intervening variable : 매개변수

timeliness : 적시성

time lag : 시차

asymptotic : 점근적

unbiasedness : 불편성 

spurious relation : 거짓관계 

estimator : 추정값

stationarity : 정태성 

disturbance term : 교란항 




자 이제 제목에 충실해보자. 
다음 글은  여기 저기서 발췌하여 정리 한 것이란걸 밝힌다.  (처음엔 내가 풀어서 쓰려고 했는데.. GG) 

자동 상관 (autocorrelation) 

위키정의)

Autocorrelation, also known as serial correlation, is the correlation of a signal with itself at different points in time. Informally, it is the similarity between observations as a function of the time lag between them. It is a mathematical tool for finding repeating patterns, such as the presence of a periodic signal obscured by noise, or identifying the missing fundamental frequency in a signal implied by its harmonic frequencies. It is often used in signal processing for analyzing functions or series of values, such as time domain signals.



예1 )
나는 상수동에서 커피숍을 운영하는데 , 날씨(온도) 에 따라서 커피 판매량이 달라진다.
더우면 많이 팔리는데,  온도에 따른 판매량을 회귀식으로 나타낼 수 있다.
여기서 판매량은 온도에 따라서만 달라지는데, 즉 시간의 흐름하고는 무관하다.
근데 어제 많이 팔리면 오늘도 많이 팔리는 경향이 있다고 하자. 
이건 t (오늘) 은  t-1 (하루전) 에 영향을 받았다고 할 수 있다. 이렇게 이 전날의 결과가
현재에 영향을 미칠때  자동 상관 되었다고 본다. 
회귀분석에서는 자동 상관이 되면 정확한 계산을 할 수 없다고 한다. 

예2 )

시계열 자료의 경우 과거의 상태가 현재의 상태에 영향을 미치는 경우가 흔하다.
예를들어 정부 예산의 경우 전년도 예산을 바탕으로 새 예산을 짜는 까닭에 연도별 예산액들 사이에는 점증주의 예산의 특징이 나타나고 이러한 것들이 자동 상관으로 타나난다.  
이런 경우 만들어낸 회귀모형에서는 오차항들 사이에 자동상관의 문제가 발생한다.

자동상관 발견모형 )

기어리 검증 / 더빈-와슨의 d 값 

자동상관 해결 방법 )

일반화된 최소제곱법 /  코크란스-오커트 방법 / 1차 차이화하는 방법 

자동 회귀 (autoregressive) 
자동 회귀는 ARIMA 시계열 분석방법에서 사용되는데 
ARIMA 자체가 'AR (자동회귀)' 과 'MA(움직평균)' 와 '차이화'를 섞어놓은 모형이다.

위키정의 )

In statistics and signal processing, an autoregressive (ARmodel is a representation of a type of random process; as such, it describes certain time-varying processes in natureeconomics, etc. The autoregressive model specifies that the output variable depends linearly on its own previous values and on a stochastic term (an imperfectly predictable term); thus the model is in the form of a stochastic difference equation.

Together with the Moving-Average (MA) model, it is a special case and key component of the more general ARMA and ARIMA models of time series, which have a more complicated stochastic structure; it is also a special case of the vector autoregressive model (VAR), which consists of a system of more than one stochastic difference equation.


WHY)


 AR 모형은 아래 가설에 의해 제안되었다. 


○ 과거의 패턴이 지속된다면 시계열 데이터 관측치 Yt 는 과거 관측치 , ,... 2 , Yt−1 Yt− Yt− p 에 의해 

    예측할 수 있을 것이다. 


○ 어느 정도의 멀리 있는 과거 관측치까지 이용할 것인가? 그리고 멀어질수록 영향력을 줄어들 것이다. 

   이런 상황을 고려할 수 있는 가중치를 사용해야 하지 않을까?


AR(1) 모형 )


현재 시점의 값은 이전 시점의 값에 상수(a)를 곱해준 것과 유사하고, 찌꺼기 정도의 차이만 있다고 함 끄적여본 것 이다. 이 모형을 AR (Autoregressive) 모형이라 하고 , 바로 이전 시점 (t-1 시점) 까지만 고려하면  AR(1), 그 이전 까지 모두 고려해 주면 일반적으로 AR(p) 모형이라 한다. AR 모형은 아래와 같다. 






자동회귀와 자동상관의 차이는 무엇인가요?


 'Autoregression' is a variable regressed against lagged values of itself plus any other terms and their lagged values. You could have a model like: 

y(t) = C + ay(t-1) + by(t-2)....cx(t) + dx(t-1) + ex(t-2) + u(t) 


First of all 'Autocorrelation' is a word that is applicable to the error terms of time series regressions. 'Autocorrelation' means that the errors terms are correlated, which violates one of the assumptions of OLS testing. 

You could model it like so: 

e(t) = C + ae(t-1) + be(t-2) + ce(t-3)... 

What is e? e is a random variable that represents the error term in any particular regression model. If the paramters a, b, c etc... are significant, then you have serial correlation. I don't think you can use OLS for this, but check the text. Certainly in practice it is often done to get an idea if there is a problem. 

There is some very simple algebra that shows if the cov between 2 error terms is zero or not, but alas, my memory fails.


결론

기계적으로 사용하는 곳(적용처)이 다르다. 라는 뻔한 말 말고 느낌을 말하자면 

과거의 값들로 현재를 말하고 미래를 예측한다라는 뽄새는 동일하나  

자동상관은 오차항,교란항과 밀접한 관계가 있는 경우를 특별히 지칭하는게 아닌가 싶다. 

별거 아닌걸 가지고 너무 헥깔려하는건가 싶기도 하다 -.-;;




Wavelet Regression in Python

Last week I needed to get my head around wavelet regression techniques for a project I am working on. This post will show how to do basic wavelet regression in Python using PyWavelets. For references I used Chapter 9 in Wasserman's All of Non-Parametric Statistics, Ogden's Essential Wavelets for Statistical Applications and Data Analysis, and Donoho and Johnstone's "Ideal spational adaptation by wavelet shrinkage" [pdf]. I also recommend "An Introduction to Wavelets" [pdf] by Amara Graps for a high level overview and a brief historical treatment of the development of wavelet analysis. These references will provide much more detail and guidance than I will here.

Wavelets are mathematical functions that provide an orthonormal basis for functions in the L2 space. The use of wavelets is akin to the use of sines and cosines to represent L2 functions in Fourier analysis. In fact, many treatments on wavelets start the discussion by reviewing Fourier series represenations of functions. Legendre polynomials are another complete orthonormal system.

The simplest wavelet is the Haar wavelet. It is not much used in practice but it is convenient to fix ideas. The Haar function is given

ψ(x)={1,x[0,1)1,x[12,1)0,otherwise

In [1]:
import pywt
import matplotlib.pyplot as plt
In [2]:
w = pywt.Wavelet('Haar')
phi, psi, x = w.wavefun(level=10)

fig, ax = plt.subplots()
ax.set_xlim(-.02,1.02)
ax.plot(x, psi);

The location in the domain and the range of this mother wavelet function can be conrolled by a translation index k and a dilation index j, respectively.

ψj,k(x)=2j/2ψ(2jxk)

A wavelet system is fully defined once a scaling function, or father wavelet, is defined. The scaling function ensures that the orthonormal basis covers the original space of a function without having to use an infinite number of mother wavelets. The father wavelet for the Haar system is

ϕ(x)=I[0,1)(x)

where IA(x) is an indicator function that equals 1 if x is in the set A. You can see that any dilation and translation can cover the original function space. While the Haar function is a good introduction, the rest of the code will use the most nearly symmetric Debauchies wavelet with N=8.

In [3]:
db8 = pywt.Wavelet('db8')
scaling, wavelet, x = db8.wavefun()

fig, axes = plt.subplots(1, 2, sharey=True, figsize=(8,6))
ax1, ax2 = axes

ax1.plot(x, scaling);
ax1.set_title('Scaling function, N=8');
ax1.set_ylim(-1.2, 1.2);

ax2.set_title('Wavelet, N=8');
ax2.tick_params(labelleft=False);
ax2.plot(x-x.mean(), wavelet);

fig.tight_layout()

For the current purposes, the objective of wavelet analysis is to recover the unknown function f from noisy data

yi=f(xi)+ei,i{1,,n}

with xi=i/n without loss of generality and eiN(0,σ2). The expansion of the function f as a finite sum of wavelets can be achieved as

fJ(x)=αϕ(x)+j=0J1k=02j1βjkψjk(x)

where

α=01f(x)ϕ(x)dxβjk=01f(x)ψjk(x)dx.

α and βjk are called the scaling coefficients and the detail coefficients, respectively. The basic idea is that the detail coefficients capture the coarser details of the function while the scaling, or smoothing, coefficients capture the overall functional form.

Donoho and Johnstone use four functions that mimic properties of empirical data in domains where wavelets might be useful, Bumps, Blocks, HeaviSine, and Doppler. For completeness, they are defined here.

In [4]:
def doppler(x):
    """
    Parameters
    ----------
    x : array-like
        Domain of x is in (0,1]
 
    """
    if not np.all((x >= 0) & (x <= 1)):
        raise ValueError("Domain of doppler is x in (0,1]")
    return np.sqrt(x*(1-x))*np.sin((2.1*np.pi)/(x+.05))
 
def blocks(x):
    """
    Piecewise constant function with jumps at t.
 
    Constant scaler is not present in Donoho and Johnstone.
    """
    K = lambda x : (1 + np.sign(x))/2.
    t = np.array([[.1, .13, .15, .23, .25, .4, .44, .65, .76, .78, .81]]).T
    h = np.array([[4, -5, 3, -4, 5, -4.2, 2.1, 4.3, -3.1, 2.1, -4.2]]).T
    return 3.655606 * np.sum(h*K(x-t), axis=0)
 
def bumps(x):
    """
    A sum of bumps with locations t at the same places as jumps in blocks.
    The heights h and widths s vary and the individual bumps are of the
    form K(t) = 1/(1+|x|)**4
    """
    K = lambda x : (1. + np.abs(x)) ** -4.
    t = np.array([[.1, .13, .15, .23, .25, .4, .44, .65, .76, .78, .81]]).T
    h = np.array([[4, 5, 3, 4, 5, 4.2, 2.1, 4.3, 3.1, 2.1, 4.2]]).T
    w = np.array([[.005, .005, .006, .01, .01, .03, .01, .01, .005, .008, .005]]).T
    return np.sum(h*K((x-t)/w), axis=0)
 
def heavisine(x):
    """
    Sinusoid of period 1 with two jumps at t = .3 and .72
    """
    return 4 * np.sin(4*np.pi*x) - np.sign(x - .3) - np.sign(.72 - x)
In [5]:
x = np.linspace(0,1,2**11)
dop = doppler(x)
blk = blocks(x)
bmp = bumps(x)
hsin = heavisine(x)
In [6]:
fig, axes = plt.subplots(2, 2, figsize=(10,10))
ax1 = axes[0,0]
ax2 = axes[0,1]
ax3 = axes[1,0]
ax4 = axes[1,1]

ax1.plot(x,dop)
ax1.set_title("Doppler")

ax2.plot(x,blk)
ax2.set_title("Blocks")

ax3.plot(x,bmp)
ax3.set_title("Bumps")

ax4.set_title("HeaviSine")
ax4.plot(x,hsin)

for ax in fig.axes:
    ax.tick_params(labelbottom=False, labelleft=False, bottom=False, 
                   top=False, left=False, right=False)

fig.tight_layout();

The wavelet coefficients fully describe some data. First, generate some data from the noisy doppler function and apply a discrete wavelet transform to recover the smoothing and detail coefficients, then have a look at a common diagnostic plot of the wavelet coefficients using coef_pyramid_plot.

In [7]:
def coef_pyramid_plot(coefs, first=0, scale='uniform', ax=None):
    """
    Parameters
    ----------
    coefs : array-like
        Wavelet Coefficients. Expects an iterable in order Cdn, Cdn-1, ...,
        Cd1, Cd0.
    first : int, optional
        The first level to plot.
    scale : str {'uniform', 'level'}, optional
        Scale the coefficients using the same scale or independently by
        level.
    ax : Axes, optional
        Matplotlib Axes instance

    Returns
    -------
    Figure : Matplotlib figure instance
        Either the parent figure of `ax` or a new pyplot.Figure instance if
        `ax` is None.
    """

    if ax is None:
        import matplotlib.pyplot as plt
        fig = plt.figure()
        ax = fig.add_subplot(111, axisbg='lightgrey')
    else:
        fig = ax.figure

    n_levels = len(coefs)
    n = 2**(n_levels - 1) # assumes periodic

    if scale == 'uniform':
        biggest = [np.max(np.abs(np.hstack(coefs)))] * n_levels
    else:
        # multiply by 2 so the highest bars only take up .5
        biggest = [np.max(np.abs(i))*2 for i in coefs]

    for i in range(first,n_levels):
        x = np.linspace(2**(n_levels - 2 - i), n - 2**(n_levels - 2 - i), 2**i)
        ymin = n_levels - i - 1 + first
        yheight = coefs[i]/biggest[i]
        ymax = yheight + ymin
        ax.vlines(x, ymin, ymax, linewidth=1.1)

    ax.set_xlim(0,n)
    ax.set_ylim(first - 1, n_levels)
    ax.yaxis.set_ticks(np.arange(n_levels-1,first-1,-1))
    ax.yaxis.set_ticklabels(np.arange(first,n_levels))
    ax.tick_params(top=False, right=False, direction='out', pad=6)
    ax.set_ylabel("Levels", fontsize=14)
    ax.grid(True, alpha=.85, color='white', axis='y', linestyle='-')
    ax.set_title('Wavelet Detail Coefficients', fontsize=16,
            position=(.5,1.05))
    fig.subplots_adjust(top=.89)

    return fig

Generate the data and get the coefficients using the multilevel discrete wavelet transform. Plot the true coefficients and the noisy ones.

In [8]:
from scipy import stats
import numpy as np

np.random.seed(12345)
blck = blocks(np.linspace(0,1,2**11))
nblck = blck + stats.norm().rvs(2**11)

true_coefs = pywt.wavedec(blck, 'db8', level=11, mode='per')
noisy_coefs = pywt.wavedec(nblck, 'db8', level=11, mode='per')

fig, axes = plt.subplots(2, 1, figsize=(9,14), sharex=True)

fig = coef_pyramid_plot(true_coefs[1:], ax=axes[0]) # omit smoothing coefs
axes[0].set_title("True Wavelet Detail Coefficients");

fig = coef_pyramid_plot(noisy_coefs[1:], ax=axes[1]) ;
axes[1].set_title("Noisy Wavelet Detail Coefficients");

fig.tight_layout()

Notice that most of the coefficients of the true signal are zero. This is the idea of sparseness, most functions, smooth or otherwise, have a sparse respresentation in a wavelet basis. The detail coefficients are non-zero where the block function is not flat. The detail coefficients of the noisy signal have many more non-zero coefficients at the higher resolutions from the added noise. To recover the signal from the noisy coefficients, you threshold the coefficients. Essentially, thresholding sets many of the coefficients to zero by assuming that they are noise. There are a number of ways to go about performing thresholding. Details can be found in the given references. I will simply apply soft thresholding using the universal threshold. The universal threshold is defined

λ=σ^2log(N)

where σ^ is a robust estimator of the standard deviation of the finest level detail coefficients. Here, I use the standardized median absolute deviation available from statsmodels.

σ^=MAD(βJ1,)

In [9]:
from statsmodels.robust import stand_mad

sigma = stand_mad(noisy_coefs[-1])
uthresh = sigma*np.sqrt(2*np.log(len(nblck)))

denoised = noisy_coefs[:]

denoised[1:] = (pywt.thresholding.soft(i, value=uthresh) for i in denoised[1:])

We can recover the signal by applying the inverse discrete wavelet transform to the thresholded coefficients.

In [10]:
signal = pywt.waverec(denoised, 'db8', mode='per')

fig, axes = plt.subplots(1, 2, sharey=True, sharex=True,
                         figsize=(10,8))
ax1, ax2 = axes

ax1.plot(signal)
ax1.set_xlim(0,2**10)
ax1.set_title("Recovered Signal")
ax1.margins(.1)

ax2.plot(nblck)
ax2.set_title("Noisy Signal")

for ax in fig.axes:
    ax.tick_params(labelbottom=False, top=False, bottom=False, left=False, 
                 right=False)
    
fig.tight_layout()

PyWavelets is a really cool project. But it could use a little more attention. It would be nice if some of the library functions were wrapped up so that they return wavelet objects that would be easier to work with. For instance, if wavedec returned a discrete wavelet object that the thresholding functions also accepted, this would save me some keystrokes in the above. I do not have time to take on another project, but it is low hanging fruit if someone else does. The code is MIT licensed and might even find a nice home in SciPy.


1편가기    (현재 블록체인 분야에 집중하고 있어서 2편 번역 할 시간이 없네요.. 죄송합니다 ㅜㅜ) 

Part II: Advanced concepts

We now have a very good intuition of what convolution is, and what is going on in convolutional nets, and why convolutional nets are so powerful. But we can dig deeper to understand what is really going on within a convolution operation. In doing so, we will see that the original interpretation of computing a convolution is rather cumbersome and we can develop more sophisticated interpretations which will help us to think about convolutions much more broadly so that we can apply them on many different data. To achieve this deeper understanding the first step is to understand the convolution theorem.

The convolution theorem

To develop the concept of convolution further, we make use of the convolution theorem, which relates convolution in the time/space domain — where convolution features an unwieldy integral or sum — to a mere element wise multiplication in the frequency/Fourier domain. This theorem is very powerful and is widely applied in many sciences. The convolution theorem is also one of the reasons why the fast Fourier transform (FFT) algorithm is thought by some to be one of the most important algorithms of the 20th century.

convolution theorem

The first equation is the one dimensional continuous convolution theorem of two general continuous functions; the second equation is the 2D discrete convolution theorem for discrete image data. Here {\otimes} denotes a convolution operation, {\mathcal{F}} denotes the Fourier transform, {\mathcal{F}^{-1}} the inverse Fourier transform, and {\sqrt{2\pi}} is a normalization constant. Note that “discrete” here means that our data consists of a countable number of variables (pixels); and 1D means that our variables can be laid out in one dimension in a meaningful way, e.g. time is one dimensional (one second after the other), images are two dimensional (pixels have rows and columns), videos are three dimensional (pixels have rows and columns, and images come one after another).

To get a better understanding what happens in the convolution theorem we will now look at the interpretation of Fourier transforms with respect to digital image processing.

Fast Fourier transforms

The fast Fourier transform is an algorithm that transforms data from the space/time domain into the frequency or Fourier domain. The Fourier transform describes the original function in a sum of wave-like cosine and sine terms. It is important to note, that the Fourier transform is generally complex valued, which means that a real value is transformed into a complex value with a real and imaginary part. Usually the imaginary part is only important for certain operations and to transform the frequencies back into the space/time domain and will be largely ignored in this blog post. Below you can see a visualization how a signal (a function of information often with a time parameter, often periodic) is transformed by a Fourier transform.

Fourier_transform_time_and_frequency_domains
Transformation of the time domain (red) into the frequency domain (blue).Source

You may be unaware of this, but it might well be that you see Fourier transformed values on a daily basis: If the red signal is a song then the blue values might be the equalizer bars displayed by your mp3 player.

The Fourier domain for images

fourier Transforms
Images by Fisher & Koryllos (1998)Bob Fisher also runs an excellent website aboutFourier transforms and image processing in general.

How can we imagine frequencies for images? Imagine a piece of paper with one of the two patterns from above on it. Now imagine a wave traveling from one edge of the paper to the other where the wave pierces through the paper at each stripe of a certain color and hovers over the other. Such waves pierce the black and white parts in specific intervals, for example, every two pixels — this represents the frequency. In the Fourier transform lower frequencies are closer to the center and higher frequencies are at the edges (the maximum frequency for an image is at the very edge). The location of Fourier transform values with high intensity (white in the images) are ordered according to the direction of the greatest change in intensity in the original image. This is very apparent from the next image and its log Fourier transforms (applying the log to the real values decreases the differences in pixel intensity in the image — we see information more easily this way).

fourier_direction_detection
Images by Fisher & Koryllos (1998)Source

We immediately see that a Fourier transform contains a lot of information about the orientation of an object in an image. If an object is turned by, say, 37% degrees, it is difficult to tell that from the original pixel information, but very clear from the Fourier transformed values.

This is an important insight: Due to the convolution theorem, we can imagine that convolutional nets operate on images in the Fourier domain and from the images above we now know that images in that domain contain a lot of information about orientation. Thus convolutional nets should be better than traditional algorithms when it comes to rotated images and this is indeed the case (although convolutional nets are still very bad at this when we compare them to human vision).

Frequency filtering and convolution

The reason why the convolution operation is often described as a filtering operation, and why convolution kernels are often named filters will be apparent from the next example, which is very close to convolution.

Images by Fisher & Koryllos (1998)Source

If we transform the original image with a Fourier transform and then multiply it by a circle padded by zeros (zeros=black) in the Fourier domain, we filter out all high frequency values (they will be set to zero, due to the zero padded values). Note that the filtered image still has the same striped pattern, but its quality is much worse now — this is how jpeg compression works (although a different but similar transform is used), we transform the image, keep only certain frequencies and transform back to the spatial image domain; the compression ratio would be the size of the black area to the size of the circle in this example.

If we now imagine that the circle is a convolution kernel, then we have fully fledged convolution — just as in convolutional nets. There are still many tricks to speed up and stabilize the computation of convolutions with Fourier transforms, but this is the basic principle how it is done.

Now that we have established the meaning of the convolution theorem and Fourier transforms, we can now apply this understanding to different fields in science and enhance our interpretation of convolution in deep learning.

Insights from fluid mechanics

Fluid mechanics concerns itself with the creation of differential equation models for flows of fluids like air and water (air flows around an airplane; water flows around suspended parts of a bridge). Fourier transforms not only simplify convolution, but also differentiation, and this is why Fourier transforms are widely used in the field of fluid mechanics, or any field with differential equations for that matter.  Sometimes the only way to find an analytic solution to a fluid flow problem is to simplify a partial differential equation with a Fourier transform. In this process we can sometimes rewrite the solution of such a partial differential equation in terms of a convolution of two functions which then allows for very easy interpretation of the solution. This is the case for the diffusion equation in one dimension, and for some two dimensional diffusion processes for functions in cylindrical or spherical polar coordinates.

Diffusion

You can mix two fluids (milk and coffee) by moving the fluid with an outside force (mixing with a spoon) — this is called convection and is usually very fast. But you could also wait and the two fluids would mix themselves on their own (if it is chemically possible)  — this is called diffusion and is usually a very slow when compared to convection.

Imagine an aquarium that is split into two by a thin, removable barrier where one side of the aquarium is filled with salt water, and the other side with fresh water. If you now remove the thin barrier carefully, the two fluids will mix together until the whole aquarium has the same concentration of salt everywhere. This process is more “violent” the greater the difference in saltiness between the fresh water and salt water.

Now imagine you have a square aquarium with 256×256 thin barriers that separate 256×256 cubes each with different salt concentration. If you remove the barrier now, there will be little mixing between two cubes with little difference in salt concentration, but rapid mixing between two cubes with very different salt concentrations. Now imagine that the 256×256 grid is an image, the cubes are pixels, and the salt concentration is the intensity of each pixel. Instead of diffusion of salt concentrations we now have diffusion of pixel information.

It turns out, this is exactly one part of the convolution for the diffusion equation solution: One part is simply the initial concentrations of a certain fluid in a certain area — or in image terms — the initial image with its initial pixel intensities. To complete the interpretation of convolution as a diffusion process we need to interpret the second part of the solution to the diffusion equation: The propagator.

Interpreting the propagator

The propagator is a probability density function, which denotes into which direction fluid particles diffuse over time. The problem here is that we do not have a probability function in deep learning, but a convolution kernel — how can we unify these concepts?

We can apply a normalization that turns the convolution kernel into a probability density function. This is just like computing the softmax for output values in a classification tasks. Here the softmax normalization for the edge detector kernel from the first example above.

softmax
Softmax of an edge detector: To calculate the softmax normalization, we taking each value [latex background="ffffff"]{x}[/latex] of the kernel and apply [latex background="ffffff"]{e^x}[/latex]. After that we divide by the sum of all [latex background="ffffff"]{e^x}[/latex]. Please note that this technique to calculate the softmax will be fine for most convolution kernels, but for more complex data the computation is a bit different to ensure numerical stability (floating point computation is inherently unstable for very large and very small values and you have to carefully navigate around troubles in this case).

Now we have a full interpretation of convolution on images in terms of diffusion. We can imagine the operation of convolution as a two part diffusion process: Firstly, there is strong diffusion where pixel intensities change (from black to white, or from yellow to blue, etc.) and secondly, the diffusion process in an area is regulated by the probability distribution of the convolution kernel. That means that each pixel in the kernel area, diffuses into another position within the kernel according to the kernel probability density.

For the edge detector above almost all information in the surrounding area will concentrate in a single space (this is unnatural for diffusion in fluids, but this interpretation is mathematically correct). For example all pixels that are under the 0.0001 values, will very likely flow into the center pixel and accumulate there. The final concentration will be largest where the largest differences between neighboring pixels are, because here the diffusion process is most marked. In turn, the greatest differences in neighboring pixels is there, where the edges between different objects are, so this explains why the kernel above is an edge detector.

So there we have it: Convolution as diffusion of information. We can apply this interpretation directly on other kernels. Sometimes we have to apply a softmax normalization for interpretation, but generally the numbers in itself say a lot about what will happen. Take the following kernel for example. Can you now interpret what that kernel is doing? Click here to find the solution (there is a link back to this position).

softmax_quiz

Wait, there is something fishy here

How come that we have deterministic behavior if we have a convolution kernel with probabilities? We have to interpret that single particles diffuse according to the probability distribution of the kernel, according to the propagator, don’t we?

Yes, this is indeed true. However, if you take a tiny piece of fluid, say a tiny drop of water, you still have millions of water molecules in that tiny drop of water, and while a single molecule behaves stochastically according to the probability distribution of the propagator, a whole bunch of molecules have quasi deterministic behavior —this is an important interpretation from statistical mechanics and thus also for diffusion in fluid mechanics. We can interpret the probabilities of the propagator as the average distribution of information or pixel intensities;  Thus our interpretation is correct from a viewpoint of fluid mechanics. However, there is also a valid stochastic interpretation for convolution.

Insights from quantum mechanics

The propagator is an important concept in quantum mechanics. In quantum mechanics a particle can be in a superposition where it has two or more properties which usually exclude themselves in our empirical world: For example, in quantum mechanics a particle can be at two places at the same time —  that is a single object in two places.

However, when you measure the state of the particle — for example where the particle is right now — it will be either at one place or the other. In other terms, you destroy the superposition state by observation of the particle. The propagator then describes the probability distribution where you can expect the particle to be. So after measurement a particle might be — according to the probability distribution of the propagator — with 30% probability in place A and 70% probability in place B.

If we have entangled particles (spooky action at a distance), a few particles can hold hundreds or even millions of different states at the same time — this is the power promised by quantum computers.

So if we use this interpretation for deep learning, we can think that the pixels in an image are in a superposition state, so that in each image patch, each pixel is in 9 positions at the same time (if our kernel is 3×3). Once we apply the convolution we make a measurement and the superposition of each pixel collapses into a single position as described by the probability distribution of the convolution kernel, or in other words: For each pixel, we choose one pixel of the 9 pixels at random (with the probability of the kernel) and the resulting pixel is the average of all these pixels. For this interpretation to be true, this needs to be a true stochastic process, which means, the same image and the same kernel will generally yield different results. This interpretation does not relate one to one to convolution but it might give you ideas how to the apply convolution in stochastic ways or how to develop quantum algorithms for convolutional nets. A quantum algorithm would be able to calculate all possible combinations described by the kernel with onecomputation and in linear time/qubits with respect to the size of image and kernel.

Insights from probability theory

Convolution is closely related to cross-correlation. Cross-correlation is an operation which takes a small piece of information (a few seconds of a song) to filter a large piece of information (the whole song) for similarity (similar techniques are used on youtube to automatically tag videos for copyrights infringements).

Relation between cross-correlation and convolution: Here [latex background="ffffff"]{\star}[/latex] denotes cross correlation and [latex background="ffffff"]{f^*}[/latex] denotes the complex conjugate of [latex background="ffffff"]{f}[/latex].

While cross correlation seems unwieldy, there is a trick with which we can easily relate it to convolution in deep learning: For images we can simply turn the search image upside down to perform cross-correlation through convolution. When we perform convolution of an image of a person with an upside image of a face, then the result will be an image with one or multiple bright pixels at the location where the face was matched with the person.

crosscorrelation_Example
Cross-correlation via convolution: The input and kernel are padded with zeros and the kernel is rotated by 180 degrees. The white spot marks the area with the strongest pixel-wise correlation between image and kernel. Note that the output image is in the spatial domain, the inverse Fourier transform was already applied. Images taken from Steven Smith’s excellent free online book about digital signal processing.

This example also illustrates padding with zeros to stabilize the Fourier transform and this is required in many version of Fourier transforms. There are versions which require different padding schemes: Some implementation warp the kernel around itself and require only padding for the kernel, and yet other implementations perform divide-and-conquer steps and require no padding at all. I will not expand on this; the literature on Fourier transforms is vast and there are many tricks to be learned to make it run better — especially for images.

At lower levels, convolutional nets will not perform cross correlation, because we know that they perform edge detection in the very first convolutional layers. But in later layers, where more abstract features are generated, it is possible that a convolutional net learns to perform cross-correlation by convolution. It is imaginable that the bright pixels from the cross-correlation will be redirected to units which detect faces (the Google brain project has some units in its architecture which are dedicated to faces, cats etc.; maybe cross correlation plays a role here?).

Insights from statistics

What is the difference between statistical models and machine learning models? Statistical models often concentrate on very few variables which can be easily interpreted. Statistical models are built to answer questions: Is drug A better than drug B?

Machine learning models are about predictive performance: Drug A increases successful outcomes by 17.83% with respect to drug B for people with age X, but 22.34% for people with age Y.

Machine learning models are often much more powerful for prediction than statistical models, but they are not reliable. Statistical models are important to reach accurate and reliable conclusions:  Even when drug A is 17.83% better than drug B, we do not know if this might be due to chance or not; we need statistical models to determine this.

Two important statistical models for time series data are the weighted moving average and the autoregressive models which can be combined into the ARIMA model (autoregressive integrated moving average model). ARIMA models are rather weak when compared to models like long short-term recurrent neural networks, but ARIMA models are extremely robust when you have low dimensional data (1-5 dimensions). Although their interpretation is often effortful, ARIMA models are not a blackbox like deep learning algorithms and this is a great advantage if you need very reliable models.

It turns out that we can rewrite these models as convolutions and thus we can show that convolutions in deep learning can be interpreted as functions which produce local ARIMA features which are then passed to the next layer. This idea however, does not overlap fully, and so we must be cautious and see when we really can apply this idea.

autoregression_weighted_average

Here {C(\mbox{kernel})} is a constant function which takes the kernel as parameter; white noise is data with mean zero, a standard deviation of one, and each variable is uncorrelated with respect to the other variables.

When we pre-process data we make it often very similar to white noise: We often center it around zero and set the variance/standard deviation to one. Creating uncorrelated variables is less often used because it is computationally intensive, however, conceptually it is straight forward: We reorient the axes along the eigenvectors of the data.

eigenvector_decorrelation
Decorrelation by reorientation along eigenvectors: The eigenvectors of this data are represented by the arrows. If we want to decorrelate the data, we reorient the axes to have the same direction as the eigenvectors. This technique is also used in PCA, where the dimensions with the least variance (shortest eigenvectors) are dropped after reorientation.

Now, if we take {C(\mbox{kernel})} to be the bias, then we have an expression that is very similar to a convolution in deep learning. So the outputs from a convolutional layer can be interpreted as outputs from an autoregressive model if we pre-process the data to be white noise.

The interpretation of the weighted moving average is simple: It is just standard convolution on some data (input) with a certain weight (kernel). This interpretation becomes clearer when we look at the Gaussian smoothing kernel at the end of the page. The Gaussian smoothing kernel can be interpreted as a weighted average of the pixels in each pixel’s neighborhood, or in other words, the pixels are averaged in their neighborhood (pixels “blend in”, edges are smoothed).

While a single kernel cannot create both, autoregressive and weighted moving average features, we usually have multiple kernels and in combination all these kernels might contain some features which are like a weighted moving average model and some which are like an autoregressive model.

Conclusion

In this blog post we have seen what convolution is all about and why it is so powerful in deep learning. The interpretation of image patches is easy to understand and easy to compute but it has many conceptual limitations. We developed convolutions by Fourier transforms and saw that Fourier transforms contain a lot of information about orientation of an image. With the powerful convolution theorem we then developed an interpretation of convolution as the diffusion of information across pixels. We then extended the concept of the propagator in the view of quantum mechanics to receive a stochastic interpretation of the usually deterministic process. We showed that cross-correlation is very similar to convolution and that the performance of convolutional nets may depend on the correlation between feature maps which is induced through convolution. Finally, we finished with relating convolution to autoregressive and moving average models.

Personally, I found it very interesting to work on this blog post. I felt for long time that my undergraduate studies in mathematics and statistics were wasted somehow, because they were so unpractical (even though I study applied math). But later — like an emergent property — all these thoughts linked together and practically useful understanding emerged. I think this is a great example why one should be patient and carefully study all university courses — even if they seem useless at first.

convolution_quiz
Solution to the quiz above: The information diffuses nearly equally among all pixels; and this process will be stronger for neighboring pixels that differ more. This means that sharp edges will be smoothed out and information that is in one pixel, will diffuse and mix slightly with surrounding pixels. This kernel is known as a Gaussian blur or as Gaussian smoothing. Continue reading. Sources: 1 2


평소 무엇인가를 쉽게 설명하는 능력이 있다고 생각해서  , CNN (convolutional neural network) 도 그렇게 해볼까 했는데 역시 무리. 쉽게 설명한다는것은 그것에 대해 확실한 이해를 가지고 있다고 생각될때 가능한것인데 아직 CNN 라는 풍랑에서 표류중이기 때문에 대신해서 좋은 해외 블로그글을 번역하고자 한다. 일반 소프트웨어 엔지니어 입장에서 딥러닝을 활용하기 위해서 수학적인 이해는 필요 없다고 생각하며, 대신 직관적인 이해는 반드시 해야하는데 이 글은 좋은 지침이 될거 같다. 


이 글을 이해하기 위해서 선수학습으로 다음의 것을 알고 있으면 좋다. (물론 이것들도 직관적인 이해만 하면 된다. 옆에서 누가 설명해주면 반나절이면 족할 내용이지만 아마 직접 책을 통해 공부한다면 꽤나 오래 걸릴수도 있겠다.)

- 퍼셉트론
- 하강경사법 
- Overfitting
- 오류역전파 알고리즘
- 소벨마스크 
- 선형회귀/로지스틱 회귀 
- Sigmoid

(오토인코더나,RBM 같은 어려운것들은 나중에~) 


* 딥러닝 처음 접한 사람을 위한 팁 

이 포스트에서 설명할 CNN 은 딥러닝은 한 종류로 주로 이미지를 인식하는데 사용됩니다. ( 음성 및 1차원 타임시리즈 데이타도 가능) 2012년 세계적인 이미지 인식 경연 대회 (ILSVRC) 에서 세계 유수의 기관을 제치고 난데없이 큰 격차로 캐나다의 토론토 대학의 슈퍼비전이 우승하게 되는데 그때 사용된 방법이 CNN 에 기반합니다. (그 동안은 SIFT,HOG방식등 ) 
이 대회는 천만장의 이미지데이터를 기계학습으로 하급하고 15만장의 이미지를 사용해서 테스트하여 정답율을 측정합니다.
즉 고양이 이미지를 고양이로 인식하면 성공~

이 고양이 인식에는 '특징표현 학습(feature representation learning)' 이라는 엄청난 발명이 사용되었는데, 컴퓨터 스스로가 특징표현을 만들어 내는것이다. 

다음은 구글의 고양이 연구 및 기타 자료들로써 어느정도 직관적인 이해를 할 수 있을것이다.  아래층에서는 점이나 엣지등의 이미지에 자주 검출되는 '모양' 을 인식하는것 뿐이지만 위로 가면서 원이나 삼각등의 모형을 인식할수 있으며 그 위로는 얼굴과 같은 형상을 얻게되며, 새로운 이미지를 분류할때 저러한  형상이 나올 확율이 높으면  = 고양이다 라고 분류 하는것이다. 





위에것은 CONV 1 레이어이고 아래것은 CONV 5 레이어이다. AlexNet 아키텍쳐에서 고양이 이미지를 학습한것이며 각각의 박스는 각 필터들과 연관된 엑티베이션 맵을 보여준다.  액티베이션은 Sparse (대부분 0 이며 위 이미지에서는 검정으로 보여진다.) 이고 대부분 local 이다. 


딥러닝에서 Convolution 을  이해해보자.

2015-03-26 by Tim Dettmers 

현재 컨볼루션 은 아마도 딥러닝에 관해서  가장 중요한 개념일것이다. 대부분의 기계학습의 전면에  컨볼루션 과 컨볼루션 nets 은 딥러닝을  스타덤에 올려놓았다. 근데 무엇이 컨볼루션을 그렇게  강력하게 만들까? 어떻게 작동할까?  이런 질문에 대해 이 블로그에서 다른 컨셉들과 비교하며 설명할것이다. 컨볼루션에 대한 직관적인 이해를 할수 있는데  도움이 될것이다.

이미 몇몇의 컨볼루션 관련 블로그들이 있지만, 그것들은 굳이 필요없는 (이해하는데 전혀 도움이 된다는 방식의) 수학적 상세표현을 통해 매우 큰 혼동만 주고 있다고 생각한다.  이 블로그에도 수학표현이 없다고 말하지는 않겠으나, 적어도 나는 그것들을 모든사람이 이해할수있는 이미지와 함께 표현하여 개념적 이해를 도울것이다. 이 블로그의 첫번째 장에서는 누구나 컨볼루션과 Convolutional Neural Network 를 직관적으로 이해할수 있도록 하는게 목표이다. 두번째 장에서는 좀 더 깊숙한 개념을 설명하여 연구자나 깊이있는 이해를 하고 싶어하는 사람들에게 도움이 되는 글들로 채울것이다. 

컨볼루션이 무엇인가?

전체 블로그는 이 질문에 대한 정확한 대답을 드리기 위해 채워져 있다. 먼저 방향설정을 잡아보자. 그래 컨볼루션의 대략적인 의미는 무엇인가? 

먼저 당신은 정보를 섞는것으로서 컨볼루션을 상상할수 있다. 2개의 양동이에 어떤 정보가 가득 차있고, 그것을 하나의 양동이에 쏟아넣는것을 상상해보자. 그리고 어떤 특정한 룰 따라서 섞어보자. 각각의 양동이는 그 자신의 레시피를 가지고 있고,  그것을 통해 어떻게 정보들이 하나의 양동이에 서로서로 섞이는지 알려준다. 즉  컨볼루션은 2개의 정보가 서로 섞이는 순서가 있는 절차이다. (역주 : 두 벡터의 내적을 생각해보자)

컨볼루션은 또한 수학적으로 표현될 수 있다. 사실, 더하기,곱하기,미분하기등과 같은 수학적인 연산이다. 복잡한 방정식을 간단하게 하기 위한 좋은 도구가 될 수 있다. 컨볼루션들은 물리학이나 엔지니어링에서 중요하게 사용되는데, 그런 복잡한 방정식을 간소화 할 경우가 많기 때문이다. 두번째 장에서  이러한 두 분야에서의 관계와 통합에 대해 알아 볼 예정이다. 그러나 지금은 현실적인 관점에서만 컨볼션을 살펴볼것이다.

어떻게 컨볼루션을 이미지에 적용할 수 있을까?

우리가 이미지에 컨볼루션을 적용할때, 우리는 2차원으로 생각해 볼수 있다. 즉 너비와 높이를 가진 이미지.우리가 2개의 양동이를 섞을때, 첫번째 양동이에는 원본 이미지 (3차원 행렬의 픽셀 전체) 가 들어가고, 빨강,녹생,파랑의 색상 채널들이 하나의 행렬이 된다. (역주: 3가지 색상을 하나의 그레이스케일로 줄여도 된다) 하나의 픽셀은 각각의 색상 채널에서 0~255 사이의 정수로 구성된다. 두번째 양동이에는 컨볼루션 커널이 있고, 이것은 실수의 단일 행렬로 이루어져 있고 이것은  어떻게 원본 이미지와 커널을 컨볼루션 연산에 의해서 섞는지에 대한 레시피로써 크기와 패턴들이 구성된다. 이 커널의 출력은 '피쳐 맵' 이라고 불리는 이미지이다. 커널 하나당 각각의 색상 채널에는 각각의 피처맵이 생길것이다. (역주: 2번째 양동이, 즉 커널종류가 다양할 수록 다양한 피처맵이 생긴다.)

convolution

원본이미지 와 경계선 추출 커널 (두번째 양동이) 을 섞어서 만들어진 피처맵.
(역주:  CNN 은 이 커널을 자동으로 만들어 준다는게 핵심이다) 


이 두가지 정보들을 컨볼루션을 통해 엮었다.  여기서 컨볼루션을 적용하는 한가지 방식은 이미지 패치를 원본이미지로 부터 커널 사이즈 만큼 가져와서 이미지 패치 와 컨볼루션 커널을 연산한다. (역주:  위에 원본 이미지가 100*100 사이즈 이고 3*3 크기 컨볼루션  커널을 행렬 곱 할때, 원본 이미지에서 커널과 곱할 부분을 떼어내게 되는데 이 떼어낸것을 패치라고 한다.)  

하나의 연산의 합이 피쳐맵에서 하나의 픽셀에 사상된다. 피처맵의 하나의 픽셀이 계산되고 난 후에는 이미지 패치가 하나씩 오른쪽으로 이동하면서 새로운 패치 정의되고 그 패치는 커널과 연산하여 새로운 픽셀이 계산되어진다. 이 절차를 아래 이미지를 통해 이해해 보자.

Calculating convolution by operating on images patches.

(역주: 이렇게 커널이 패치와 연산될때, 패딩/슬라이딩값들을 조절한다던가, 커다란 이미지를 1/4 같이  줄이는 풀링이라든지 , 아예 DropOut 시킨다던가 레이어간에 부분적으로만 연결한다던가, 파라미터들을 그룹핑하여 공유한다던가 하는 것들이 있는데 전체적인 직관력을 기르고 난후에 접근하시면 됩니다. 일단은 원본이미지에서 어떤 필터를 중간에 껴서 새로운 이미지 집합을 만들어낸다는것에 집중하면 될거 같습니다.)

왜 이미지의 컨볼루션이 머신러닝에서 중요한가?

이미지에는 다양하게 추출될수있는 정보들이 포함되어있다. 좋은 예로 내가 참여한 프로젝트를 살펴보자. Burda Bootcamp 는 빠른속도의 학생들이 기술적으로 위험한 프로젝트들을 매우 짧은 기간안에 만들기위한 해커튼 스타일의 환경의 프로토 타이핑 랩인데 우리는 11개의 프로덕트를 2달만에 만들었다. 하나의 프로젝트에서 나는 딥 오토엔코더와 함께 패션 이미지 탐색을 만들길 원했다. 당신은 패션 아이템의 이미지를 업로드하고 오토엔코더는 비슷한 스타일의 옷을 포함한 이미지를 찾아야했다.

지금 만약 당신이 옷의 스타일에 관한 차이점에 대해서 설명할때 그 옷의 색깔은 그것을 하기에 별로 유용하진 않을것이다. 또한 상표의 엠블램같은것 또한 마찬가지이다. 가장 중요한것은 옷의 윤곽/모양그 자체일것인데 일반적으로 브라우스의 모양은 셔츠,자켓등의 모양과는 아주 다르다. 그래서 만약 우리가 필요없는 정보를 추출하는 필터를 설계하면 그것은 필요없는 것들에 의해 구분되어지는 참사를 막을 수 있을것이다. 결국 우리는 좀 더 쉽게 커널과 함께 컨볼루션을 수행할 것이다. 

나의 동료는 데이타를 전처리하고 소벨 윤곽선 검출기를 적용하였다. (첫번째 그림에서 윤곽선 검출한것과 비슷) 객체의 모양의 외곽선을 제외하고 이미지로부터 모드것을 제거하는 필터이며, 이것은 왜 컨볼루션의 어플리케이션이 종종 필터라고 불리는지 말해준다. 그리고 커널들도 필터라고도 불리운다. 결과로 만들어진 피쳐맵은 당신이 다양한 종류의 옷을 구분할때 매우 큰 도움을 줄것이다. 아래 이미지들을 보자.

autoencoder_fashion_features_and_results

이런 종류의 절차를 사용하는것이  -  입력을 받고, 변환하고 , 변형된 이미지를 알고리즘으로 먹이고 - 피처 엔지니어링 이라고 불린다. 피쳐 엔지니어링은 매우 어려운데, 이런 기술을 익히기 위해 당신을 도울 리소스는  별로 없기 때문이다.  결과적으로 아주 소수의 사람들이 피쳐 엔지니어링을 넓은 범위의 업무에서 잘 적용할 수 있는데. 그냥 피쳐 엔지니어링을 잘하는 방법을 살펴봄으로써 느껴보자.  the most important skill to score well in Kaggle competitions

피쳐 엔지니어링은 너무 어렵다. 각각의 데이타 타입과 각각 문제의 타입에 대해 다른 피쳐들이 적합하기 때문이다. 이미지 업무에 관한 피처 엔지니어링의 지식은 타임시리즈 데이터에는 쓸모가 없을때가 많으며, 심지어 우리는 비슷한 이미지 업무에 대해서도 좋은 피처들을 엔지니어링하기 쉽지 않다. 이미지 안의 객체들이 우리가 무엇을 하려고하는지에 관해서 다르게 결정되기 때문이다. 굉장히 오랜기간의 경험이 필요한 일이다. 그래서 피처 엔지니어링은 매우 어려우며 당신 앞에 닥치게된 업무는  빈바닥에서 시작해서 새롭게 시작해야 한다는것을 의미한다. 그러나 그러나 !!!!  그런 커널들이 대부분의 업무에 맞춰서 자동적으로 적합하게 찾아진다면 어떨까?? 

CNN (Convolutional Neural Network)  으로 

우리의 커널이 정확하게 고정된 값을 갖게하는 대신해서 (역주: 엔지니어가 직접 커널을 선택해주는것을 대신해서) 컨볼루셔널 넷이 정확하게 그것을 한다.  우리의 컨볼루션넷을 학습 시킴으로써 , 커널은 점점 더 주어진 이미지(혹은 주어진 피처맵) 를 필터링을 잘 하게될것이다. 이 프로세스는 자동적으로 이루어지므로 피처 학습이라고 불리운다. 피처 학습은 자동적으로 각각의 목적에 대해 생성된다. 우리는 단지 새로운 목적과 부합한 필터를 찾기위해 우리의 네트워크를 간단하게 학습시키기만 하면 된다. (역주 : 이미 CaffeNet, GoogleNet 등의 아키텍처 모델들이 존재함. 물론 파인튜닝도 필요하고, 전혀 다른 도메인이라면 어려운 도전이 필요합니다)  이것이 컨볼루션 넷을 강력하게 만드는 것이라고 볼수있습니다. 피쳐엔지니어링은 더 이상 어렵지 않아요. 자동적으로 만들어지니깐!

보통 우리는 컨볼루션 넷에서 싱글 커널을 학습하진 않습니다. 대신해 우리는 다층의 커널들의 계층에 대해 학습하게 되는데 예를들어 32*16*16 의 커널이 256*256 이미지에 적용되면 32 개의 피처맵들을 241*241 사이즈로 생성하게 됩니다. 자동적으로 우리는 32개의 새로운 피처 (우리의 목적에 부합되는 형태를 가진) 들을 학습하게되며 이러한 피처들은 다음 커널의 입력으로 사용됩니다. (즉 여러개의 커널을 거침. 인간의 뇌가 여러 레이어의 신경망으로 되어 있는것 처럼 ) 일단 계층적인 특징(feature)들을 배우게 되면 우리는 간단히 그것들을 fully connected 로 통과하게 하고 , 이미지에서 특정 클래스(고양이, 자전거) 로의 분류를 위해  그것들을 합칩니다.  (역주 : 특정 표현들이 얼마만큼 존재하냐에 따라서 확율적으로 선택해줍니다. 소프트맥스라는 회귀방법이 주로 사용됩니다.)  

이것들이 개념적인 수준에서 CNN 을 이해할수있는 거의 모든 것 이며 , 2편에서는 좀 더 상세한 얘기들을 해 볼 것 입니다.

2편가기   원본가기  가시화를 통한 이해 


+ Recent posts