Top Banner
Linear Regression Logistic Regression
52

2.linear regression and logistic regression

Jan 21, 2018

Download

Technology

Haesun Park
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 2.linear regression and logistic regression

Linear RegressionLogistic Regression

Page 2: 2.linear regression and logistic regression

Outlook

• Part 1: 파이썬과 텐서플로우 소개

• Part 2: 회귀 분석과 로지스틱 회귀

• Part 3: 뉴럴 네트워크 알고리즘

• Part 4: 콘볼루션 뉴럴 네트워크

2

Page 3: 2.linear regression and logistic regression

지난 시간에...

3

Page 4: 2.linear regression and logistic regression

리스트• 대괄호로 초기화a = [0, 1]

• 리스트에 원소 추가a.append(2)

• 리스트의 길이len(a)

• 리스트 슬라이스a[0:2]

딕셔너리• 순서가 없는 인덱스를 가짐(문자열

가능)

• 중괄호로 초기화b = {‘sun’: 0}

• 키를 지정해 원소 추가b[‘mon’] = 1

• 딕셔너리 참조는 리스트와 동일b[’mon’]

Python-data type

4

Page 5: 2.linear regression and logistic regression

if i == 10:

print(10)

elif i < 10:

print(0)

else:

print(100)

for a in lst:

print(a)

for k in dct:

print(dct[k])

for k, v in dct.items():

print(k, v)

Python-if, for

5

Page 6: 2.linear regression and logistic regression

TensorFlow Graph 와 Session

• 텐서플로우의 연산자를 사용하여 계산 구조를 정의합니다.

a = tf.constant(2)

b = tf.constant(3)

x = tf.add(a, b)

• 세션 객체를 만들어 만들어진 계산 그래프를 실행합니다.

x

<tf.Tensor 'Add:0' shape=() dtype=int32>

tf.Session().run(x)

56

Page 7: 2.linear regression and logistic regression

zeros(), ones()

• 0으로 채워진 텐서를 만듭니다.

e = tf.zeros([2, 3])

tf.Session().run(e)

array([[ 0., 0., 0.], [ 0., 0., 0.]], dtype=float32)

• 1로 채워진 텐서를 만듭니다.

f = tf.ones([2, 3], dtype=tf.int32)

tf.Session().run(f)

array([[1, 1, 1], [1, 1, 1]], dtype=int32)

7

Page 8: 2.linear regression and logistic regression

tf.Variable()

• 상수가 아니라 계산 그래프에서 변하는 값을 담는 도구입니다.

• 변수는 초깃값이 주어져야 하고 사용하기 전에 초기화 되어야 합니다.

a = tf.Variable(tf.constant(2))

a

<tensorflow.python.ops.variables.Variable at ...>

init = tf.global_variables_initializer()

sess = tf.Session()

sess.run(init)

sess.run(a)

28

Page 9: 2.linear regression and logistic regression

행렬(matrix)

• 2×3 행렬

1 −2 23 −1 1

a = tf.Variable([[1, -2, 2], [3, -1, 1]])

sess = tf.Session()

sess.run(tf.global_variables_initializer())

sess.run(a)

[[1 -2 2], [3 -1 1]]9

행(row)

열(column)

Page 10: 2.linear regression and logistic regression

행렬 내적

• 행렬의 덧셈

• 2×3 + 2×3 = [2×3]

1 −2 23 −1 1 + −1 3 2

2 4 1 = 0 1 45 3 2

• 행렬의 곱셈:내적,점곱(dotproduct)• 2×3 ⋅ 3×2 = [2×2]

1 −2 23 −1 1

2 −14 31 2

= −4 −33 −4

10

행(row)

열(column)

Page 11: 2.linear regression and logistic regression

tf.matmul()

• 두개의 텐서를 입력 받아 행렬 내적을 계산합니다.

a = tf.Variable([[1, -2, 2], [3, -1, 1]])

b = tf.Variable([[2, -1], [4, 3], [1, 2]])

dot = tf.matmul(a, b)

sess = tf.Session()

sess.run(tf.global_variables_initializer())

sess.run(dot)

array([[-4, -3],

[ 3, -4]], dtype=int32)

11

1 −2 23 −1 12 −14 31 2

−4 −33 −4

Page 12: 2.linear regression and logistic regression

선형 회귀 분석

12

Page 13: 2.linear regression and logistic regression

회귀 분석

• 숫자 결과를 예측합니다.

• 출력 값은 연속적인 속성을 가집니다.

• Regression Analysis

ex)

• 환자의 당뇨병 데이터를 이용하여 1년뒤 악화 정도를 측정

• 과거 주식시장의 데이터를 이용하여 내일 주가를 예측

• 지역, 방 개수, 평수 등의 데이터를 이용하여 주택 가격 예측

13

Page 14: 2.linear regression and logistic regression

1차 선형 함수

𝑦; = 𝑤×𝑥 + 𝑏

가중치 편향

14

Page 15: 2.linear regression and logistic regression

Hyperplane

TVRadio

Sales 𝑆𝑎𝑙𝑒𝑠 = 𝑎D×𝑅𝑎𝑑𝑖𝑜 + 𝑎I×𝑇𝑉 + 𝑏

• 기본 베이스 모델

• 대량의 데이터셋

• 특성이 비교적 많을 때

15

Page 16: 2.linear regression and logistic regression

일반화

• n 개의 특성이 있을 때 선형 회귀의 일반 방정식𝑦; = 𝛽D𝑥D + 𝛽I𝑥I +⋯+ 𝛽N𝑥N + 𝛽O

• 𝑥O = 1인항을추가𝑦;D = 𝛽D𝑥D + 𝛽I𝑥I +⋯+ 𝛽N𝑥N + 𝛽O𝑥O⋮𝑦;Q = 𝛽D𝑥QD + 𝛽I𝑥QI +⋯+ 𝛽N𝑥QN + 𝛽O𝑥QO

𝑦; =𝑥DD ⋯ 𝑥DO⋮ ⋱ ⋮

𝑥QD ⋯ 𝑥QO

𝛽D⋮𝛽O

,𝑚 = 데이터개수 → 𝒚V = 𝑿𝜷Y

16

Page 17: 2.linear regression and logistic regression

솔루션

• 최소제곱법(Ordinary Least Squares)를 사용하여 평균제곱오차(Mean Squared Error)를 최소화하는 파라미터를 찾음.

• 평균제곱오차1𝑚Z 𝑦 − 𝑦; I, 𝑦; = 𝑋𝛽

Q

\]D

• 최소제곱법�̂� = 𝑋_𝑋 `D𝑋_𝑦

오차의 제곱

모든 훈련 데이터의오차 제곱을 더함

훈련 데이터갯수로 나눔

• 데이터가 아주 많은 경우 문제• 역행렬을 구할 수 없는 경우 문제

17

Page 18: 2.linear regression and logistic regression

경사하강법(Gradient Descent)

• 오차함수의 낮은 지점을 찾아가는 최적화 방법

• 낮은 쪽의 방향을 찾기 위해 오차함수를 현재 위치에서 미분함

𝐽 =12𝑚Z 𝑦 − 𝑦; I, ∇𝐽 =

1𝑚 (𝑦 − 𝑦;)

Q

\]D

18

Page 19: 2.linear regression and logistic regression

복잡한 오차함수(신경망)

𝑱

19

Page 20: 2.linear regression and logistic regression

뉴런

20

Page 21: 2.linear regression and logistic regression

뉴런처럼 보이게

Neuron𝑦;

𝑤 𝑦; = 𝑤×𝑥 + 𝑏

𝑥

𝑏

×

+

𝒚

21

Page 22: 2.linear regression and logistic regression

낮은 곳으로

Neuron𝑦;

𝑤

𝑥

𝑏

×

+

𝒚

𝜕𝐽𝜕𝑤 =

1𝑚 𝑦 − 𝑦;

𝜕𝑦;𝜕𝑤 =

1𝑚 (𝑦 − 𝑦;)𝑥

𝜕𝐽𝜕𝑏 =

1𝑚 𝑦 − 𝑦;

𝜕𝑦;𝜕𝑏 =

1𝑚 (𝑦 − 𝑦;)

𝐽 =12𝑚Z 𝑦 − 𝑦; I

Q

\]D

22

Page 23: 2.linear regression and logistic regression

파라미터 업데이트

Neuron𝑦;

𝑤 = 𝑤 + ∆𝑤 = 𝑤 +1𝑚 (𝑦 − 𝑦;)𝑥

𝑥 ×

+

𝒚

𝑏 = 𝑏 + ∆𝑏 = 𝑏 +1𝑚 (𝑦 − 𝑦;)

(𝑦 − 𝑦;)

23

Page 24: 2.linear regression and logistic regression

적당한 속도

• 파라미터 w, b 의 업데이트가 클 경우 최저점(local minima)을 지나칠 수있습니다.

• 학습 속도(learning rate)로 그래디언트 업데이트를 조절합니다.

𝑤 = 𝑤 + 𝜶1𝑚 (𝑦 − 𝑦;)𝑥 𝑏 = 𝑏 + 𝜶

1𝑚 (𝑦 − 𝑦;)

24

Page 25: 2.linear regression and logistic regression

하이퍼파라미터

• 하이퍼파라미터(Hyperparameter)는 알고리즘이 데이터로부터 학습할 수없는 파라미터입니다.

• 모델 파라미터는 알고리즘이 데이터로 부터 학습하는 파라미터입니다. 예를 들면, w, b 입니다.

• 학습속도(learning rate)은 하이퍼파라미터입니다.

• 이 외외에도 신경망의 레이어수나 유닛수, k-NN 알고리즘의 k 값 등 알고리즘마다 여러가지의 모델 파라미터를 가지고 있습니다.

• 최적의 하이퍼파라미터를 찾기위해서 반복적인 학습, 검증 과정을 거쳐야합니다.

25

Page 26: 2.linear regression and logistic regression

텐서플로우선형 회귀 구현

26

Page 27: 2.linear regression and logistic regression

데이터 생성

세션 객체 생성

평균 0, 표준편차 0.55 인 x 샘플 1000개 생성

0.1*x + 0.3 방정식을 만족하는 y 데이터를 생성하되,평균 0, 표준편차 0.03을 가지도록 함.

27

Page 28: 2.linear regression and logistic regression

샘플 데이터 시각화

28

Page 29: 2.linear regression and logistic regression

계산 그래프 생성

가중치 W, b 변수를 0으로 초기화

y_hat 계산

손실 함수인 MSE 계산

경사하강법 객체 생성손실함수 노드를 최적화하는 학습노드 생성

𝐽 =12𝑚Z 𝑦 − 𝑦; I

Q

\]D

train

loss

y_hat

W x b

29

Page 30: 2.linear regression and logistic regression

계산 그래프 실행

변수 초기화

학습 노드 실행

학습된 파라미터와 손실함수 값 출력

30

Page 31: 2.linear regression and logistic regression

결과 그래프

w = 0.099, b = 0.298 31

Page 32: 2.linear regression and logistic regression

선형 회귀 정리

• 선형 회귀 분석은 선형 함수를 사용하여 연속적인 결과를 예측합니다.

• 선형 회귀의 대표적인 비용함수는 MSE(mean square error) 함수입니다.

• 최소제곱법 대신 경사하강법을 사용하여 점진적으로 최적의 파라미터를찾았습니다.

• 특성이 많을 경우 높은 성능을 낼 수 있습니다. 이럴 경우 오히려 성능을제한해야 할 때가 많습니다.

• 비교적 대량의 데이터셋에서도 잘 작동합니다.

• 데이터 분석을 할 때 처음 시도할 모델로서 좋습니다.

32

Page 33: 2.linear regression and logistic regression

로지스틱 회귀

33

Page 34: 2.linear regression and logistic regression

분류(Classification)

• 클래스 레이블을 예측합니다.

• 출력 결과는 이산적입니다.

• Binary Classification(이진 분류), Multiclass Classification(다중 분류)

ex)

• 스팸 분류

• 암 진단

• 붓꽃의 품종 판별

• 손글씨 숫자 분류

34

Page 35: 2.linear regression and logistic regression

로지스틱 회귀 (이진 분류)

• 이진 분류는 샘플을 True(1), 또는 False(0)으로 분류합니다.

• 회귀의 선형 함수를 그대로 이용합니다.

• 선형 함수의 결과를 0~1 사이의 확률로 변환합니다.

• 0.5 이상일 경우 True, 아니면 False 로 분류합니다.

𝑦; = 𝑤×𝑥 + 𝑏

35

Page 36: 2.linear regression and logistic regression

로지스틱 함수

• 로지스틱(logistic) 또는 시그모이드(sigmoid) 함수는 -∞~+∞입력에 대해0~1 사이의 값을 출력합니다.

𝑦; = 1

1 +𝑒`(g×hij)=

11 +𝑒`k

𝑧 = 𝑤×𝑥 + 𝑏

36

Page 37: 2.linear regression and logistic regression

뉴런처럼 보이게

Neuron Sigmoid

0 ~ 1

𝑤

𝑦; = 𝜎(𝑧)

𝑥

𝑏

×

+

𝒚

𝑧 = 𝑤×𝑥 + 𝑏

-∞~+∞

𝜎(𝑧) = 1

1 +𝑒`k37

Page 38: 2.linear regression and logistic regression

분류에서의 손실 함수는

• 분류는 크로스 엔트로피(cross-entropy) 손실 함수를 사용합니다.

• 크로스 엔트로피 손실함수를 미분하면

• 선형회귀의 MSE 손실함수의 미분 결과와 동일합니다.

𝐽 = −1𝑚Z𝑦𝑙𝑜𝑔 𝑦;

Q

\]D

= −1𝑚Z[𝑦𝑙𝑜𝑔 𝑦; + 1 − 𝑦 log(1 − 𝑦;)]

Q

\]D

𝜕𝐽𝜕𝑤 = −

1𝑚Z 𝑦 − 𝑦; 𝑥

Q

\]D

𝜕𝐽𝜕𝑏 = −

1𝑚Z 𝑦 − 𝑦;

Q

\]D

38

Page 39: 2.linear regression and logistic regression

낮은 곳으로

Neuron Sigmoid

𝑤

𝑥

𝑏

×

+

𝒚

𝑦; = 𝜎(𝑧) = 1

1 +𝑒`k

𝜕𝐽𝜕𝑤 =

1𝑚 𝑦 − 𝑦;

𝜕𝑦;𝜕𝑤 =

1𝑚 (𝑦 − 𝑦;)𝑥

𝜕𝐽𝜕𝑏 =

1𝑚 𝑦 − 𝑦;

𝜕𝑦;𝜕𝑏 =

1𝑚 (𝑦 − 𝑦;)

𝐽 = −1𝑚Z[𝑦𝑙𝑜𝑔 𝑦; + 1 − 𝑦 log(1 − 𝑦;)]

Q

\]D

𝑦;𝑧

39

Page 40: 2.linear regression and logistic regression

그래디언트 업데이트

Neuron Sigmoid𝑥 ×

+

𝒚𝑦;

𝑤 = 𝑤 + ∆𝑤 = 𝑤 +1𝑚 (𝑦 − 𝑦;)𝑥

𝑏 = 𝑏 + ∆𝑏 = 𝑏 +1𝑚 (𝑦 − 𝑦;)

(𝑦 − 𝑦;)

40

Page 41: 2.linear regression and logistic regression

로지스틱 정리

• 분류에 사용하는 모델입니다.

• 선형 함수 결과를 시그모이드 함수를 사용하여 0~1 사이로 압축합니다.

• 이진 분류는 0.5 보다 높을 때는 True 로하고 그 이하는 False 로 하여 모델을 학습시킵니다.

• 시그모이드 함수를 사용한 크로스 엔트로피 비용함수의 미분 결과는 선형함수를 사용한 MSE 비용함수의 미분과 동일합니다.

• 로지스틱 회귀는 다중 분류도 지원합니다.

41

Page 42: 2.linear regression and logistic regression

텐서플로우로지스틱 회귀 구현

42

Page 43: 2.linear regression and logistic regression

위스콘신 유방암 데이터

사이킷런의 데이터셋 이용

넘파이

위스콘신 유방암 데이터 로드샘플 데이터를 가지고 있는scikit-learn의 Bunch 오브젝트

43

Page 44: 2.linear regression and logistic regression

넘파이(NumPy)

• 데이터 과학을 위한 다차원 배열 패키지로 많은 배열 연산을 제공합니다.

• 넘파이는 파이썬 리스트와는 달리 다른 종류의 데이터 타입을 담을 수 없습니다.

• scikit-learn, tensorflow 등 많은 머신 러닝 패키지들이 입력 값으로 넘파이배열을 받을 수 있습니다.

44

Page 45: 2.linear regression and logistic regression

cancer 특성

30개의 특성

특성의 이름

𝑦; = 𝑤D𝑥D + 𝑤I𝑥I +⋯+𝑤qO𝑥qO + 𝑏

45

Page 46: 2.linear regression and logistic regression

cancer 데이터

y

X569개의데이터

행벡터

열벡터

특별한 경우가 아니면 float32형 권장

46

Page 47: 2.linear regression and logistic regression

선형 함수 계산

0.20.6 ⋯ 0.1

0.2⋮ ⋱ ⋮0.5 ⋯ 0.4

⋅0.1⋮0.3

=

1.55.9⋮0.7

+ 0.1 =

1.66.0⋮0.8

30개 가중치:569개 샘플에모두 적용

569개 샘플

𝑥×𝑊 + 𝑏 = 𝑦;[569, 30] x [30, 1] = [569, 1] + [1] = [569, 1]

1개 편향(bias):569개 샘플에모두 적용(브로드캐스팅)

30개 특성

569개 결과(logits)

47

Page 48: 2.linear regression and logistic regression

손실 함수와 최적화로지스틱(시그모이드) 크로스 엔트로피 손실함수

학습속도 매우 낮게

변수 초기화

48

Page 49: 2.linear regression and logistic regression

학습

• 여기서는 예를 간단히 하기위해 학습 데이터로 모델의 성능을평가했습니다만 실전에서는 이렇게 해서는 안됩니다

prediction 의 모든 원소에 적용, 0.5보다 크면 True, 작으면 False[569, 1] 크기

5000번 학습하면서손실함수 값 기록

92% 정확도

49

Page 50: 2.linear regression and logistic regression

정리

• 선형 모델을 이용해 회귀와 분류 학습을 했습니다.

• 분류는 로지스틱 함수를 이용해 확률로 변환하여 레이블을 예측합니다.

• 회귀에서는 임의의 샘플 데이터 1000개, 특성 1개를 사용했고 분류에서는샘플 데이터 569개, 특성 30개를 사용했습니다.

• 회귀에서 학습한 모델 파라미터는 가중치 w 1개, 편향 b 1개 입니다.

• 분류에서 학습한 모델 파라미터는 가중치 w 30개, 편향 b 1개 입니다.

• 선형 함수를 표현하는 계산 그래프를 만들고 텐서플로우에서 제공하는 손실함수를 사용했습니다.

• 경사하강법 최적화 알고리즘을 적용하여 최적값을 찾았습니다.

50

Page 51: 2.linear regression and logistic regression

Materials

• Github : https://github.com/rickiepark/tfk-notebooks/tree/master/tensorflow_for_beginners

• Slideshare :

https://www.slideshare.net/RickyPark3/

51

Page 52: 2.linear regression and logistic regression

감사합니다.

52