brunch

You can make anything
by writing

C.S.Lewis

by 라인하트 Oct 23. 2020

앤드류 응의 머신러닝(7-4): 정규화된 로지스틱 회귀

  온라인 강의 플랫폼 코세라의 창립자인 앤드류 응 (Andrew Ng) 교수는 인공지능 업계의 거장입니다. 그가 스탠퍼드 대학에서 머신 러닝 입문자에게 한 강의를 그대로 코세라 온라인 강의 (Coursera.org)에서 무료로 배울 수 있습니다. 이 강의는 머신러닝 입문자들의 필수코스입니다. 인공지능과 머신러닝을 혼자 공부하면서 자연스럽게 만나게 되는 강의입니다. 


Regularization

정규화


Solving the Problem of Overfitting 

(과적합 문제 해결하기) 


Regularized Logistic Regression (정규화된 로지스틱 회귀)  

   

   For logistic regression, we previously talked about two types of optimization algorithms. We talked about how to use gradient descent to optimize as cost function J of theta. And we also talked about advanced optimization methods. Ones that require that you provide a way to compute your cost function J of theta and that you provide a way to compute the derivatives. In this video, we'll show how you can adapt both of those techniques, both gradient descent and the more advanced optimization techniques in order to have them work for regularized logistic regression.


   로지스틱 회귀에서 두 가지 유형의 최적화 알고리즘을 설명했습니다. 하나는 비용 함수 J(θ)를 최적화하는 경사 하강  알고리즘입니다. 다른 하나는 비용 함수 J(θ)를 계산하는 방법과 미분항을 계산하는 방법을 제공해야 하는 고급 최적화 알고리즘입니다. 이번 강의에서 정규화된 로지스틱 회귀를 위한 경사 하강법과 고급 최적화를 모두 살펴보겠습니다. 



   So, here's the idea. We saw earlier that Logistic Regression can also be prone to overfitting if you fit it with a very, sort of, high order polynomial features like this. Where G is the sigmoid function and in particular you end up with a hypothesis, you know, whose decision bound to be just sort of an overly complex and extremely contortive function that really isn't such a great hypothesis for this training set, and more generally if you have logistic regression with a lot of features. Not necessarily polynomial ones, but just with a lot of features you can end up with overfitting.


   여기 로지스틱 회귀 예제가 있습니다. 

   학습 데이터의 가설 hθ(x) = g(x)는 매우 복잡한 고차 다항식입니다. 고차 다항식은 학습 데이터 셋에 과적합(Overfit)할 수 있습니다. g(z)는 시그모이드 함수이고 z가 고차 다항식일 때 결정 경계는 매우 복잡하고 극도로 왜곡됩니다. 로지스틱 회귀가 너무 많은 피처가 있다면 고차 다항식 없어도 과적합 확률이 높습니다. 


    


   This was our cost function for logistic regression. And if we want to modify it to use regularization, all we need to do is add to it the following term plus londer over 2M, sum from J equals 1, and as usual sum from J equals 1. Rather than the sum from J equals 0, of theta J squared. And this has to effect therefore, of penalizing the parameters theta 1 theta 2 and so on up to theta N from being too large. And if you do this, then it will the have the effect that even though you're fitting a very high order polynomial with a lot of parameters.


   이것은 로지스틱 회귀의 비용 함수입니다. 

   정규화를 위해 정규화 항을 추가합니다. 정규화 항은 θ1, θ2,... , θn까지 페널티를 부과하는 효과가 있습니다. 정규화 항은 많은 파라미터를 가진 고차 다항식에서 조차 과적합 문제를 방지하는 효과가 있습니다.  



 So long as you apply regularization and keep the parameters small you're more likely to get a decision boundary. You know, that maybe looks more like this. It looks more reasonable for separating the positive and the negative examples. So, when using regularization even when you have a lot of features, the regularization can help take care of the overfitting problem.


   정규화를 적용하고 파라미터를 작게 유지하면 분홍색 곡선의 결정 경계를 얻을 가능성이 큽니다. 분홍색 곡선이 파지티브 예제와 네거티브 예제를 분리하는 합리적인 선입니다.  피처가 많은 학습 문제에도 정규화는 과적합 문제를 해결할 수 있습니다. 



   How do we actually implement this? Well, for the original gradient descent algorithm, this was the update we had. We will repeatedly perform the following update to theta J. This slide looks a lot like the previous one for linear regression. 


    경사 하강법을 어떻게 구현할 수 있을 까요? 여기 경사 하강 알고리즘의 업데이트 공식입니다. 


   경사 하강법은 θj에 대한 반복적으로 업데이트합니다. 로지스틱 회귀의 경사 하강법은 선형 회귀의 경사 하강법과 매우 유사합니다.  



   But what I'm going to do is write the update for theta 0 separately. So, the first line is for update for theta 0 and a second line is now my update for theta 1 up to theta N. Because I'm going to treat theta 0 separately. And in order to modify this algorithm, to use a regularized cos function, all I need to do is pretty similar to what we did for linear regression is actually to just modify this second update rule as follows. And, once again, this, you know, cosmetically looks identical what we had for linear regression. But of course is not the same algorithm as we had, because now the hypothesis is defined using this. So this is not the same algorithm as regularized linear regression. Because the hypothesis is different. Even though this update that I wrote down. It actually looks cosmetically the same as what we had earlier. We're working out gradient descent for regularized linear regression. And of course, just to wrap up this discussion, this term here in the square brackets, so this term here, this term is, of course, the new partial derivative for respect of theta J of the new cost function J of theta. Where J of theta here is the cost function we defined on a previous slide that does use regularization. So, that's gradient descent for regularized logistic regression


   여기서 θ0과 θj에 대한 경사 하강 업데이트를  분리합니다. 


   첫 번째 줄은  θ0에 대한 업데이트이고, 두 번째 줄은 θ1,... , θn까지에 대한 업데이트입니다. θ0에 대한 경사 하강 업데이트는 정규화를 하지 않기 때문에 별도로 처리합니다. 선형 회귀와 마찬가지로 정규화된 비용 함수 J(θ)를 미분한 경사 하강 업데이트 공식입니다. 




   θj에 대한 경사 하강 업데이트 공식에 정규화 항을 추가하였습니다. 정규화된 선형 회귀의 경사 하강법 업데이트와 동일하게 보이지만 전혀 다른 알고리즘입니다. 가설 함수가 다르기 때문입니다. 

   여기서, 경사 하강 업데이트의 정규화 항은 정규화된 비용 함수 J(θ)의 정규화 항을 미분한 것입니다. 이것이 정규화된 로지스틱 회귀의 경사 하강법입니다.  


  

   Let's talk about how to get regularized linear regression to work using the more advanced optimization methods. 


   고급 최적화 방법을 활용하여 정규화된 로지스틱 회귀를 작동시키는 방법을 설명합니다. 



   And just to remind you for those methods what we needed to do was to define the function that's called the cost function, that takes us input the parameter vector theta and once again in the equations we've been writing here we used 0 index vectors. So we had theta 0 up to theta N. But because Octave indexes the vectors starting from 1.Theta 0 is written in Octave as theta 1. Theta 1 is written in Octave as theta 2, and so on down to theta N plus 1.


  costFunction() 함수를 정의합니다. 파라미터 벡터 theta(θ)를 입력받습니다. 참고로, 수학 공식의 방정식은 0-인덱스 벡터를 사용합니다.  파라미터 벡터 θ = [θ0; θ1; θ2;... ; θn]까지이지만, 옥타브 프로그램은 theta(1), theta(2),..., theta(n)과 같은 1-인덱스 벡터를 사용합니다. 수학 공식에서 θ0는 옥타브 프로그램의 θ1입니다. 수학 공식에서 θ1은 옥타브 프로그램에서 θ2입니다. 마지막 θn 은 옥타브 프로그램에서 θ(n+1)입니다



   And what we needed to do was provide a function. Let's provide a function called cost function that we would then pass in to what we have, what we saw earlier. We will use the fminunc and then you know @costFunction, and so on, right. But the fminunc was F min unconstrained and this will work with fminunc was what will take the cost function and minimize it for us.


   costFunction() 함수에 파라미터 벡터 theta를 제공합니다. fminunc(@costFunction,...) 함수를 사용합니다. fminunc()는 F min unconstrained를 줄인 것으로 costFunction() 함수를 호출하고 파라미터 theta의 값을 최소화합니다.  


   So the two main things that the cost function needed to return were first J-val. And for that, we need to write code to compute the cost function J of theta. Now, when we're using regularized logistic regression, of course the cost function j of theta changes and, in particular, now a cost function needs to include this additional regularization term at the end as well. So, when you compute j of theta be sure to include that term at the end.


   And then, the other thing that this cost function thing needs to derive with a gradient. So gradient one needs to be set to the partial derivative of J of theta with respect to theta 

zero, gradient two needs to be set to that, and so on. Once again, the index is off by one. 

Right, because of the indexing from one Octave users. And looking at these terms. 


   costFunction() 함수는 두 개의 변수를 반환합니다.

   첫 번째 변수는 jVal입니다. 변수 jVal은 비용 함수 J(θ)를 최소화하는 비용을 반환합니다. 정규화된 로지스틱 회귀를 사용할 때 일반적인 비용 함수 J(θ)의 마지막에 정규화 항을 추가합니다. J(θ)를 계산할 때 정규화 항이 추가되었는 지를 확인합니다. 


   두 번째 변수 gradient입니다. 변수 gradient는 비용 함수 J(θ)를 편미분 한 값입니다. gradient(1)은 θ0에 대한 J(θ)의 편미분입니다. gradient(2)는 θ1에 대한 J(θ)의 편미분입니다. 다시 한번 인덱스 번호가 하나씩 달라집니다. 옥타브 프로그램의 인덱싱 때문입니다. 


           



   This term over here. We actually worked this out on a previous slide is actually equal to this. It doesn't change. Because the derivative for theta zero doesn't change. Compared to the version without regularization.  And the other terms do change. And in particular the derivative respect to theta one. We worked this out on the previous slide as well. Is equal to, you know, the original term and then minus londer M times theta 1. Just so we make sure we pass this correctly. And we can add parentheses here. Right, so the summation doesn't extend. And similarly, you know, this other term here looks like this, with this additional term that we had on the previous slide, that corresponds to the gradient from their regularization objective. 


   So if you implement this cost function and pass this into fminunc or to one of those advanced optimization techniques, that will minimize the new regularized cost function J of theta. And the parameters you get out will be the ones that correspond to logistic regression with regularization. 


   분홍색 박스는 미분항입니다. 파라미터 θ0는 정규화하지 않기 때문에 정규화하지 않은 버전과 같습니다. 그러나 파라미터 θ1의 미분은 정규화 항이 추가됩니다. 원래 수식과 똑같고 단지 정규화 항이 추가된 것입니다. 따라서, 하나의 식으로 합산할 수 없습니다. 경사 하강 업데이트가 제대로 기울기를 계산하는 지를 확인합니다. θ2와 다른 항들도 마찬가지입니다. 


   따라서, costFunction() 함수와 fminunc() 또는 다른 고급 최적화 기법을 구현한다면, 새로운 정규화된 비용 함수 J(θ)의 최소화할 것입니다. fminunc()에 의해 반환되는 변수들은 정규화된 로지스틱 회귀의 파라미터가 될 것입니다.   


   So, now you know how to implement regularized logistic regression. When I walk around Silicon Valley, I live here in Silicon Valley, there are a lot of engineers that are frankly, making a ton of money for their companies using machine learning algorithms. And I know we've only been, you know, studying this stuff for a little while. But if you understand linear regression, the advanced optimization algorithms and regularization, by now, frankly, you probably know quite a lot more machine learning than many, certainly now, but you probably know quite a lot more machine learning right now than frankly, many of the Silicon Valley engineers out there having very successful careers. You know, making tons of money for the companies. Or building products using machine learning algorithms. So, congratulations. You've actually come a long ways. And you can actually, you actually know enough to apply this stuff and get to work for many problems.So congratulations for that. 


   But of course, there's still a lot more that we want to teach you, and in the next set of videos after this, we'll start to talk about a very powerful cause of non-linear classifier. So whereas linear regression, logistic regression, you know, you can form polynomial terms, but it turns out that there are much more powerful nonlinear quantifiers that can then sort of polynomial regression. And in the next set of videos after this one, I'll start telling you about them. So that you have even more powerful learning algorithms than you have now to apply to different problems.


   지금까지 정규화된 로지스틱 회귀를 구현하는 법을 설명했습니다. 실리콘 밸리에는 머신 러닝 알고리즘을 사용하여 엄청난 돈을 벌고 있는 많은 엔지니어들이 있습니다. 여러분들은 잠시 동안 머신 러닝을 공부했습니다. 선형 회귀, 고급 최적화 알고리즘, 정규화 등을 이해한다면 확실히 많이 알고 있는 것입니다. 많은 실리콘 밸리 엔지니어들은 세상에서 성공적인 경력을 쌓고 있습니다. 회사에서 머신 러닝 알고리즘을 이용하여 제품을 만들거나 엄청난 돈을 벌고 있습니다. 그래서, 축하합니다. 여러분들은 실제로 먼 길을 왔습니다. 실제로 머신 러닝을 활용해 많은 문제를 해결할 수 있을 만큼  충분히 알고 있을 수도 있습니다. 


   하지만 아직도 여러분에게 가르치고 싶은 것이 많습니다. 다음 강의에서 비선형 분류기를 다룰 것입니다. 선형 회귀와 로지스틱 회귀는 다항식 항으로 표현할 수 있지만,  일종의 다항 회귀라고 할 수 있는 훨씬 더 강력한 비선형 연산자가 있습니다. 다음 강의에 하나씩 설명합니다. 따라서, 다른 문제에 적용할 수 있는 지금보다 훨씬 더 경력한 학습 알고리즘을 배울 것입니다.



앤드류 응의 머신러닝 동영상 강의



정리하며 


   로지스틱 회귀 가설 함수 hθ(x) = 1/(1+e^(-θTX)에 대한 비용 함수 J(θ)는 볼록 함수가 아닌 비볼록 함수입니다. 매우 복잡한 비선형 함수로 전역 최소값에 도달한다는 보장이 없습니다. 따라서, 전역 최소값을 찾을 수 있는 볼록한 비용 함수가 필요합니다. 


    J(θ) = cost(hθ(x), y) 일 때

                                            y = 1 일 때 -log(hθ(x))

                                            y = 0 일 때 -log(1-hθ(x))


   분류 문제에 있어서 훈련용 데이터 셋 예제의 y의 값은 항상 0 또는 1 이기 때문에 로지스틱 회귀의 비용 함수 J(θ) = cost(hθ(x), y)를 간단하게 만들 수 있습니다. 


                     cost(h(x), y) =  -y*log(h(x)) -(1-y)*log(1-h(x)) 


       따라서, 비용 함수  J(θ) = 1/m * Cost(hθ(x), y)

                                             = -1/m * [∑(y*log(h(x)) + (1-y)*log(1-h(x))]


   g()가 시그모이드 함수이고 고차 다항식의 가설 함수일 때 결정 경계는 매우 복잡하고 극도로 왜곡됩니다. 일반적으로 로지스틱 회귀가 너무 많은 Feature가 있다면 다항식이 아니더라도 과적합일 확률이 높습니다. 

정규화를 적용하고 파라미터를 작게 유지하면 분홍색 곡선의 결정 경계를 얻을 가능성이 큽니다. 


            정규화된 로지스틱 회귀 비용 함수

                      J(θ) = 1/m * Cost(hθ(x), y)

                                   = -1/m * [∑(y*log(h(x)) + (1-y)*log(1-h(x))] + λ /(2m) * Σ θj^2

                           

   정규화 항은  θ1, θ2,... , θn까지 페널티를 부과하는 효과가 있습니다.


   비용 함수 J(θ)를 최소화하는 파라미터 θ를 구하기 위한 경사 하강 알고리즘은 다음과 같습니다. 


           Repeat {

                        θj := θj - α* ∂/(θj) *J(θ)         ( 동시 업데이트   θj)

                                                   (j = 1,2,3,... , n)        

           }


   여기서 정규화된 로지스틱 회귀는θ0와  θ1, θ2, θ3,... θn로 분리합니다. 이유는 θ0는 페널티를 부과하지 않기 때문입니다


           Repeat {

                        θ0 := θ0 - α* ∂/(∂θ0) *J(θ)         

                        θj := θj - α* ∂/(θj) *J(θ)         ( 동시 업데이트   θj)

                                                    (j = 1,2,3,... , n)

           }


미분항에 비용 함수 J(θ)를  미분하면 다음과 같습니다. 

            

           Repeat {   

                            θ0 := θ0 - α* 1/m * ∑(hθ(x^(i)) - y^(i))*x^(i) 0 

                       θj := θj - α* [1/m * ∑(hθ(x^(i)) - y^(i))*x^(i) j)]

                                                            (j = 1,2,3,... , n)

             }


   하지만, 미분항에 비용 함수 J(θ)를 정규화된 비용 함수 J(θ)로 대체한 후 미분합니다. 정규화된 비용 함수 J(θ)는 정규화 항이 이미 포함되어 있습니다. 


        Repeat {   

                        θ0 := θ0 - α [ 1/m * Σ(hθ(x^(i)) - y^(i))*x^(i)0]

                     θj := θj - α [ 1/m * Σ(hθ(x^(i)) - y^(i))*x^(i)j +  λ /m * θj ]

                                                           (j = 1,2,3,... , n)

             }


   여기서, θj 업데이트 공식은 정규화된 선형 회귀와 동일합니다. 하지만,  가설 함수가 다릅니다.


         선형 회귀의 가설 함수         :hθ(x) = θ^TX

          로지스틱 회귀의 가설 함수 : hθ(x) = 1/(1+e^(-θ^Tx)



정리하며 - 정규화된 고급 최적화


   고급 최적화 기법을 사용할 때 경사 하강 알고리즘을 정규화된 경사 하강 알고리즘을 사용합니다. 정규화된 고급 최적화를 위한 비용 함수를 계산하기 위한 costFunction.m 함수 파일은 다음과 같이 작성합니다.


        function [jVal, gradient] = costFunction(theta) 


        jVal = [J(θ)를 계산하는 코드]


        gradient(1) = [∂/(∂θ0) *J(θ)를 계산하는 코드];

        gradient(2) = [∂/(∂θ1) *J(θ)를 계산하는 코드];

        gradient(3) = [∂/(∂θ2) *J(θ)를 계산하는 코드];

 

        gradient(n+1) = [∂/(∂θ(n+1)) *J(θ)를 계산하는 코드];    


    end


[J(θ)를 계산하는 코드]를 계산하는 식

       J(θ) = [-1/m * ∑(y^(i)*log(h(x^(i))) + (1-y(i))*log(1-h(x^(i)))] + λ /(2m) * Σ θj^2]     

    

 [∂/(∂θ0) *J(θ)를 계산하는 코드]를 계산하는 식

       ∂/(∂θ0) *J(θ) = 1/m * ∑(hθ(x^(i)) - y^(i))*x^(i) 0


[∂/(∂θ1) *J(θ)를 계산하는 코드]를 계산하는 식

      ∂/(∂θ1) *J(θ) = [1/m * ∑(hθ(x^(i)) - y^(i))*x^(i) 1)] +  λ /m * θ1


[∂/(∂θ2) *J(θ)를 계산하는 코드]를 계산하는 식

      ∂/(∂θ2) *J(θ) = [1/m * ∑(hθ(x^(i)) - y^(i))*x^(i) 2)] +  λ /m * θ2


costFunction 함수는 두 변수의 값을 반환합니다.


      jVal : 비용 함수 J(θ)를 계산하는 코드

      gradient : 알고리즘이 도달할 최소값   



   옥타브 프로그램에서는 다음과 같이 명령어를 입력합니다.


   options = optimset('GradObj', 'on', 'MaxIter', '100');

   initialTheta = [초기값 0으로 세팅] 

   [optTheta, functionVal, exitFlag] = fminunc(@costFunction, initialTheta, options) 


     fminunc() : 옥타브에서 특정 함수에서 최적화 문제를 해결하는 함수

     optimset ('GradObj', 'on') : 전역 최소값을 구하는 함수의 gradient 값을 반환한다는 의미

     optimset ('MzxIter', 'on') : 최대 반복 횟수를 100으로 설정

     exitFlag : 알고리즘이 최적 값에 수렵되었는지 여부를 표시  


   costFunction() 함수와 fminunc() 또는 다른 고급 최적화 기술을 활용한다면 새로운 정규화된 비용 함수 J(θ)의 최소값을 얻을 수 있습니다. 


문제 풀이


   정규화된 로지스틱 회귀를 사용할 때 경사 하강법이 잘 동작하는 지 확인하는 가장 좋은 방법은?

정답은 3번입니다. 

매거진의 이전글 앤드류 응의 머신러닝(7-3): 정규화된 선형 회귀
작품 선택
키워드 선택 0 / 3 0
댓글여부
afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari