regression & classification

18
1. Machine Learning Supervised Learning Regression Classification Unsupervised Learning Clustering 2. Regression/Classification Regression Linear Regression with One Variable Linear Regression with Multiple Variables Classification Logistic Regression 2.1 Linear Regression with One Variable 2.1.1 Model Representation univariate linear regression ( Linear regression with one variable) : Univariate linear regression is used when you want to predict a single output value from a single input value. 2.1.2 The Hypothesis Function General form : Linear Regression input data( , x) output data( , y) 은 은은은은 은은은은 은은 h 은은은 은은은은 은 은 은은 . Example: x (input) y (output) 0 4 1 7 2 7 3 8

Upload: -

Post on 10-May-2015

377 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Regression & Classification

1. Machine Learning Supervised Learning

Regression Classification

Unsupervised Learning Clustering

2. Regression/Classification Regression

Linear Regression with One Variable Linear Regression with Multiple Variables

Classification Logistic Regression

2.1 Linear Regression with One Variable

2.1.1 Model Representationunivariate linear regression (Linear regression with one variable) : Univariate linear regression is used when you want to predict a single output value from a single input value.

2.1.2 The Hypothesis FunctionGeneral form :

Linear Regression 은 input data(즉, x)를 output data(즉, y)로 적절하게 매핑하는 함수 h 를 만드는 것이라고 할 수 있다.

Example: x (input) y (output)

0 4

1 7

2 7

3 8

theta0=2, theta1=2 라고 하면 h(x) = 2 + 2x 가 된다.input 이 1 일 때 추정값(예측치) y 는 4 가 되고 실측치와의 차이는 3 이다.

2.1.3 Cost Function

Page 2: Regression & Classification

We can measure the accuracy of our hypothesis function by using a cost function. m 개의 input data 가 있을 때 각 input data 에 대한 예측치 h(x)와 실측치 y 의 평균 차이값을 최소화하는 theta 가 해당 input 과 output 을 가장 잘 표현하는 모델의 parameter 가 된다.

Cost function 은 다음과 같다.

※ 1/2 을 곱하는 이유는 차후 계산식에서 수학적으로 표현이 쉽기 때문이다.

Cost function 을 통해 얻고자 하는 goal 은

J()를 theta0 과 theta1 에 대해서 그려보면 아래와 같다.

2.1.4 Gradient Descent참고 :

Page 3: Regression & Classification

- http://personal.ee.surrey.ac.uk/Personal/J.Illingworth/eem.asp/ BayenSteepestDescentLecture.pdf

- http://www.evernote.com/shard/s143/sh/c274bc38-2944-4d88-b062- 9f3ded8f8691/55d622f8d2f8a9ae081bbebc50865787

Gradient descent algorithm :

※ α : learning rate

2.1.5 Gradient Descent for Linear Regression

편미분 부분만 전개해보면 아래와 같고,

\frac { \partial }{ \partial { \theta }_{ j } } J({ \theta }_{ 0 },{ \quad \theta }_{ 1 })\quad =\quad \frac { \partial }{ \partial { \theta }_{ j } } \frac { 1 }{ 2m } \sum _{ i=1 }^{ m }{ { (h }_{ \theta }({ x }^{ (i) }) } \quad -\quad { y }^{ (i) })^{ 2 }\\ \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad =\quad \frac { \partial }{ \partial { \theta }_{ j } } \frac { 1 }{ 2m } \sum _{ i=1 }^{ m }{ { { (\theta }_{ 0 }\quad +\quad { \theta }_{ 1 }x^{ (i) } } } \quad -\quad { y }^{ (i) })^{ 2 }

각 j 값에 대해서 아래와 같이 쓸 수 있다.

Page 4: Regression & Classification

j\quad =\quad 0\quad :\quad \frac { \partial }{ \partial { \theta }_{ 0 } } J({ \theta }_{ 0 },{ \quad \theta }_{ 1 })\quad =\quad \frac { 1 }{ m } \sum _{ i=1 }^{ m }{ { (h }_{ \theta }({ x }^{ (i) }) } \quad -\quad { y }^{ (i) })\\ j\quad =\quad 1\quad :\quad \frac { \partial }{ \partial { \theta }_{ 1 } } J({ \theta }_{ 0 },{ \quad \theta }_{ 1 })\quad =\quad \frac { 1 }{ m } \sum _{ i=1 }^{ m }{ { (h }_{ \theta }({ x }^{ (i) }) } \quad -\quad { y }^{ (i) })\cdot { x }^{ (i) }

그러므로 위 gradient descent algorithm 을 각각의 theta 에 대해 다시 써보면

repeat\quad until\quad convergence\quad \{ \\ \qquad { \theta }_{ 0 }\quad :={ \quad \theta }_{ 0 }\quad -\quad \alpha \frac { 1 }{ m } \sum _{ i=1 }^{ m }{ ({ h }_{ \theta }({ x }^{ (i) })-{ y }^{ (i) }) } \\ \qquad { \theta }_{ 1 }\quad :={ \quad \theta }_{ 1 }\quad -\quad \alpha \frac { 1 }{ m } \sum _{ i=1 }^{ m }{ ({ h }_{ \theta }({ x }^{ (i) })-{ y }^{ (i) }) } \cdot { x }^{ (i) }\\ \}

위 반복 과정을 그림으로 보기 편하게 나타내면,

(https://picasaweb.google.com/104059922827789076358/2011921#5766126981201681554)

Page 5: Regression & Classification

2.1.6 Implementation

- pythonfrom numpy import loadtxt, zeros, ones, array, linspace, logspacefrom pylab import scatter, show, title, xlabel, ylabel, plot, contour

#Evaluate the linear regressiondef compute_cost(X, y, theta): ''' Comput cost for linear regression ''' #Number of training samples m = y.size

predictions = X.dot(theta).flatten()

sqErrors = (predictions - y) ** 2

J = (1.0 / (2 * m)) * sqErrors.sum()

return J

def gradient_descent(X, y, theta, alpha, num_iters): ''' Performs gradient descent to learn theta by taking num_items gradient steps with learning rate alpha ''' m = y.size J_history = zeros(shape=(num_iters, 1))

for i in range(num_iters):

predictions = X.dot(theta).flatten()

errors_x1 = (predictions - y) * X[:, 0] errors_x2 = (predictions - y) * X[:, 1]

theta[0][0] = theta[0][0] - alpha * (1.0 / m) * errors_x1.sum() theta[1][0] = theta[1][0] - alpha * (1.0 / m) * errors_x2.sum()

J_history[i, 0] = compute_cost(X, y, theta)

return theta, J_history

#Load the datasetdata = loadtxt('ex1data1.txt', delimiter=',')

#Plot the datascatter(data[:, 0], data[:, 1], marker='o', c='b')title('Profits distribution')xlabel('Population of City in 10,000s')ylabel('Profit in $10,000s')#show()

Page 6: Regression & Classification

X = data[:, 0]y = data[:, 1]

#number of training samplesm = y.size

#Add a column of ones to X (interception data)it = ones(shape=(m, 2))it[:, 1] = X

#Initialize theta parameterstheta = zeros(shape=(2, 1))

#Some gradient descent settingsiterations = 1500alpha = 0.01

#compute and display initial costprint compute_cost(it, y, theta)

theta, J_history = gradient_descent(it, y, theta, alpha, iterations)

print theta#Predict values for population sizes of 35,000 and 70,000predict1 = array([1, 3.5]).dot(theta).flatten()print 'For population = 35,000, we predict a profit of %f' % (predict1 * 10000)predict2 = array([1, 7.0]).dot(theta).flatten()print 'For population = 70,000, we predict a profit of %f' % (predict2 * 10000)

#Plot the resultsresult = it.dot(theta).flatten()plot(data[:, 0], result)show()

#Grid over which we will calculate Jtheta0_vals = linspace(-10, 10, 100)theta1_vals = linspace(-1, 4, 100)

#initialize J_vals to a matrix of 0'sJ_vals = zeros(shape=(theta0_vals.size, theta1_vals.size))

#Fill out J_valsfor t1, element in enumerate(theta0_vals): for t2, element2 in enumerate(theta1_vals): thetaT = zeros(shape=(2, 1)) thetaT[0][0] = element thetaT[1][0] = element2 J_vals[t1, t2] = compute_cost(it, y, thetaT)

#Contour plotJ_vals = J_vals.T#Plot J_vals as 15 contours spaced logarithmically between 0.01 and 100contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20))xlabel('theta_0')ylabel('theta_1')

Page 7: Regression & Classification

scatter(theta[0][0], theta[1][0])show()※ 출처 : http://aimotion.blogspot.kr/2011/10/machine-learning-with-python-linear.html

- R

Page 8: Regression & Classification

2.2 Linear Regression with Multiple Variables

Multiple FeaturesLinear regression with multiple variables is also known as "multivariate linear regression."

Size Number of bedrooms

Number of floors

Age of home

price

x1 X2 X3 X4 y2104 5 1 45 4601416 3 2 40 2321534 3 2 30 315852 2 1 36 178… … … … …

n\quad =\quad \left| x^{ (i) } \right| \; { (the\quad number\quad of\quad features) }\\ x^{ (i) }\quad =\quad { input\quad features\quad of\quad the\quad i^{ th }\quad training\quad example }\\ x_{ j }^{ (i) }\quad ={ \quad value\quad of\quad feature\quad j\quad in\quad the\quad i^{ th }\quad training\quad example }

hypothesis function :

h_{ \theta }(x)\quad =\quad \theta _{ 0 }\quad +\quad \theta _{ 1 }x_{ 1 }\quad +\quad \theta _{ 2 }x_{ 2 }\quad +\quad \theta _{ 3 }x_{ 3 }\quad +\quad \cdots \quad +\quad \theta _{ n }x_{ n }

x 와 theta 를 아래와 같이 나타낼 수 있으므로

{ x\quad =\quad \left[ \begin{ matrix } { x }_{ 0 } \\ { x }_{ 1 } \\ { x }_{ 2 } \\ \vdots \\ { x }_{ n } \end{ matrix } \right] \quad \in \quad { \Re }^{ n+1 } },\quad { \theta \quad =\quad \left[ \begin{ matrix } { \theta }_{ 0 } \\ { \theta }_{ 1 } \\ { \theta }_{ 2 } \\ \vdots \\ { \theta }_{ n } \end{ matrix } \right] \quad \in \quad { \Re }^{ n+1 } }

위 hypothesis function 을 간단히 쓰면,

h_{ \theta }(x)\quad =\quad \theta ^{ T }x

Cost functionParameters :

{ \theta }_{ 0 },{ \quad \theta }_{ 1 },\quad ...\quad ,{ \quad \theta }_{ n }\quad \longrightarrow \quad \theta

Cost function :

Page 9: Regression & Classification

J({ \theta }_{ 0 },{ \theta }_{ 1 },...,{ \theta }_{ n })\quad =\quad \frac { 1 }{ 2m } \sum _{ i=1 }^{ m }{ { ({ h }_{ \theta }({ x }^{ (i) })\quad -\quad { y }^{ (i) }) }^{ 2 } }

Gradient Descent for Multiple VariablesGradient descent :

repeat\quad \{ \\ \qquad { \theta }_{ j }\quad :=\quad { \theta }_{ j }\quad -\quad \alpha \frac { \partial }{ \partial { \theta }_{ j } } J({ \theta }_{ 0 },{ \theta }_{ 1 },...,{ \theta }_{ n })\\ \}

Univariate linear regression 과 multivariate linear regression 의 Gradient Descent 구현을 비교해보면 아래와 같은 차이가 있는 것을 알 수 있다.

repeat\quad until\quad convergence:\quad \lbrace \newline \qquad \theta _{ j }\quad :=\quad \theta _{ j }\quad -\quad \alpha \frac { 1 }{ m } \sum _{ i=1 }^{ m } (h_{ \theta }(x^{ (i) })-y^{ (i) })\cdot x_{ j }^{ (i) }\qquad { for\quad j\quad :=\quad 0..n }\newline \rbrace

repeat\quad until\quad convergence:\; \lbrace \newline \qquad \theta _{ 0 }\quad :=\quad \theta _{ 0 }\quad -\quad \alpha \frac { 1 }{ m } \sum _{ i=1 }^{ m } (h_{ \theta }(x^{ (i) })-y^{ (i) })\cdot x_{ 0 }^{ (i) }\newline \qquad \theta _{ 1 }\quad :=\quad \theta _{ 1 }\quad -\quad \alpha \frac { 1 }{ m } \sum _{ i=1 }^{ m } (h_{ \theta }(x^{ (i) })-y^{ (i) })\cdot x_{ 1 }^{ (i) }\newline \qquad \theta _{ 2 }\quad :=\quad \theta _{ 2 }\quad -\quad \alpha \frac { 1 }{ m } \sum _{ i=1 }^{ m } (h_{ \theta }(x^{ (i) })-y^{ (i) })\cdot x_{ 2 }^{ (i) }\\ \qquad \cdots \newline \rbrace

repeat\quad until\quad convergence:\quad \lbrace \newline \qquad \theta _{ j }\quad :=\quad \theta _{ j }\quad -\quad \alpha \frac { 1 }{ m } \sum _{ i=1 }^{ m } (h_{ \theta }(x^{ (i) })-y^{ (i) })\cdot x_{ j }^{ (i) }\qquad { for\quad j\quad :=\quad 0..n }\newline \rbrace

Matrix Notation(내용과 연관성 적어서 skip 가능)

Univariate linear regression 챕터에서 알아본 바와 같이 Gradient Descent rule 은 아래와 같이 표현할 수 있다.

\theta \quad :=\quad \theta \quad -\quad \alpha \nabla J(\theta )

Page 10: Regression & Classification

여기서 ∇ J (θ)는 아래와 같은 column vector 이고,

\nabla J(\theta )\quad =\quad \begin{ bmatrix } \frac { \partial J(\theta ) }{ \partial \theta _{ 0 } } \newline \frac { \partial J(\theta ) }{ \partial \theta _{ 1 } } \newline \quad \quad \vdots \newline \frac { \partial J(\theta ) }{ \partial \theta _{ n } } \end{ bmatrix }

j 번째 component 는 아래와 같이 두 term 의 곱의 합으로 나타낼 수 있다.

\begin{ matrix } \frac { \partial J(\theta ) }{ \partial \theta _{ j } } \qquad & =\quad \frac { 1 }{ m } \sum _{ i=1 }^{ m } \left( h_{ \theta }(x^{ (i) })-y^{ (i) } \right) \cdot x_{ j }^{ (i) } \\ \quad & =\quad \frac { 1 }{ m } \sum _{ i=1 }^{ m } x_{ j }^{ (i) }\cdot \left( h_{ \theta }(x^{ (i) })-y^{ (i) } \right) \end{ matrix }

두 term 의 곱의 합은 두 vector 의 곱(내적)으로 나타낼 수 있으므로 아래와 같이 정리된다.

\begin{ eqnarray } \frac { \partial J(\theta ) }{ \partial \theta _{ j } } \qquad & = & \frac { 1 }{ m } \vec { x_{ j } } ^{ T }(X\theta -\vec { y } ) \\ \nabla J(\theta )\qquad & = & \frac { 1 }{ m } X^{ T }(X\theta -\vec { y } ) \end{ eqnarray }

결과적으로 위에서 정의한 Gradient Descent rule 은 아래와 같은 Matrix notation 으로 쓸 수 있다.

\theta \quad :=\quad \theta \quad -\quad \frac { \alpha }{ m } X^{ T }(X\theta -\vec { y } )

Gradient Descent in Practicefeature scaling and mean normalization. feature 들이 상이한 값의 범위를 가질 때 아래와 같이 수렴 속도가 늦어질 수 있다.

Page 11: Regression & Classification

이를 방지하기 위해 feature 들이 서로 비슷한 scale 을 가지도록 만들어 주어야 한다. feature scaling 와 mean normalization 두 가지 방법이 있다. Feature scaling 은 input 값을 input 의 range 로 나눠주어 새로운 값의 범위를 1 로 만들어 주는 방법이고, Mean normalization 은 비슷하지만 input 을 평균값으로 빼주어서 새로운 값의 평균을 0 으로 만들어준다.

그리고 적당한 α 값을 정하거나 convergence 판정을 어떻게 할 것인가도 중요한데 아래 그림과 같이 plotting 해보면 쉽게 정할 수 있다.

Page 12: Regression & Classification

Debugging gradient descent. Make a plot with number of iterations on the x-axis.

Now plot the cost function, J(θ) over the number of iterations of gradient descent.

If J(θ) ever increases, then you probably need to decrease α.

Automatic convergence test. Declare convergence if J(θ) decreases by less than E in

one iteration, where E is some small value such as 10−3.

It has been proven that if learning rate α is sufficiently small, then J(θ) will decrease on

every iteration. Andrew Ng recommends decreasing α by multiples of 3.

Features and Polynomial Regression개선안 2 가지 - Feature 잘 정하기

x₁ 과 x₂ 가 house 의 depth 와 frontage 라고 하면 그냥 하나의 feature x₁ 으로 합치면 좋다.- Hypothesis function 을 잘 정하기

Function 식의 x 를 중복해서 쓰거나 제곱, 세제곱, 제곱근의 형태를 갖는 식으로 표현하여 데이터를 더 잘 표현하는 function 을 찾을 수 있다.

Normal EquationNormal Equation 은 iteration 이 없는 최적값 찾기 알고리즘이라고 할 수 있다.

(증명)\theta \quad =\quad (X^{ T }X)^{ -1 }X^{ T }y

Normal equation 은 iteration 도, feature scaling 도 필요 없고 따로 최적의 α 값을 찾기 위한 작업도 할 필요가 없다. 하지만 O(n³) 복잡도를 가지기 때문에 n 이 커질 경우 매우 느려진다.

직관적인 이해는 아래 자료를 참고

Page 13: Regression & Classification

Gradient descent 방법과 비교하면 아래와 같은 장단점이 있다.Gradient Descent Normal Equation

Need to choose alpha No need to choose alphaNeeds many iterations No need to iterateWorks well when n is large Slow if n is very large

Need to compute (X T X )−1 (O(n³))

※ when n approaches 1,000,000 it might be a good time to go from a normal solution to an iterative process.

Page 14: Regression & Classification

2.3 Logistic RegressionDon't be confused by the named "Logistic Regression"; it is named that way for historical reasons and is actually an approach to classification problems, not regression problems.

Classification종속변수가 연속형(continuous)인 Regression 과 달리 Classification 은 종속변수가 범주적(categorical) 속성을 가진다. 예를 들어 output vector y 가 아래와 같이 오직 0 또는 1 의 값만 가질 수 있다면,

y\quad \in \quad \{ 0,\quad 1\}

y=0 일 때 negative class, y=1 일 때 positive class 이런 식으로 단 두 가지 범주로 나눌 수 있고 이런 경우 Binary Classification Problem 이라고 한다.

특정 threshold 값(0.5)을 기준으로 0/1 을 분류하면 Linear regression 기법을 classification 에 사용할 수는 있으나 아래와 같은 이유 등으로 보통은 쓰지 않는다.

이 두 가지를 모두 해결할 수 있는 방법이 바로 logistic regression 이다.

Hypothesis RepresentationLogistic regression 에서의 hypothesis function 이

를 만족하기 위해 아래와 같이 Sigmoid Function 이라는 개념을 도입한다. (= Logistic Function)

{ h }_{ \theta }(x)\quad =\quad g({ \theta }^{ T }x)\\ g(z)\quad =\quad \frac { 1 }{ 1+{ e }^{ -z } }

Page 15: Regression & Classification

※ linear regression 의 h-function 과 비교해보자.

Sigmoid function 은 아래와 같은 특성을 지닌다.

Interpretation of Hypothesis ouput : h(x) = input 이 x 일 때 y=1 일 추정 확률값

example :

Tell patient that 70% chance of tumor being malignant.(if probability that it is 1 is 70%, then the probability that it is 0(benign) is 30%)

formal 표현

Probability that y=1, given x, parameterized by θ

Decision Boundary

Page 16: Regression & Classification

2. 참고 자료- https://class.coursera.org/ml/class/index- http://aimotion.blogspot.kr/2011/10/machine-learning-with-python-linear.html