brunch

You can make anything
by writing

C.S.Lewis

by 라인하트 Oct 20. 2020

앤드류 응의 머신러닝(6-6):로지스틱회귀 고급최적화

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


Logistic Regression

로지스틱 회귀


Logistic Regrassion Model (로지스틱 회귀 모델) 


Advanced Optimization (고급 최적화)  



   In the last video, we talked about gradient descent for minimizing the cost function J of theta for logistic regression. In this video, I'd like to tell you about some advanced optimization algorithms and some advanced optimization concepts.


   지난 강의에서 로지스틱 회귀에서 비 용 함수 J(θ)를 최소화하는 경사 하강법을 설명했습니다. 이번 강의에서 몇 가지 고급 최적화 알고리즘과 개념을 설명합니다.   

 

   Using some of these ideas, we'll be able to get logistic regression to run much more quickly than it's possible with gradient descent. And this will also let the algorithms scale much better to very large machine learning problems, such as if we had a very large number of features.

 

    어떤 알고리즘들은 경사 하강법보다 훨씬 더 빠르게 로지스틱 회귀를 실행합니다. 매우 많은 피처를 가진 매우 큰 머신 러닝 문제도  다룰 수 있습니다.



   Here's an alternative view of what gradient descent is doing. We have some cost function J and we want to minimize it. So what we need to is, we need to write code that can take as input the parameters theta and they can compute two things: J of theta and these partial derivative terms for, you know, J equals 0, 1 up to N. Given code that can do these two things, what gradient descent does is it repeatedly performs the following update. Right? 


   So given the code that we wrote to compute these partial derivatives, gradient descent plugs in here and uses that to update our parameters theta. So another way of thinking about gradient descent is that we need to supply code to compute J of theta and these derivatives, and then these get plugged into gradient descents, which can then try to minimize the function for us. For gradient descent, I guess technically you don't actually need code to compute the cost function J of theta. You only need code to compute the derivative terms. But if you think of your code as also monitoring convergence of some such, we'll just think of ourselves as providing code to compute both the cost function and the derivative terms. So, having written code to compute these two things, one algorithm we can use is gradient descent.


   여기 경사 하강법의 동작 방식에 대한 새로운 관점이 있습니다. 여기 비용 함수 J(θ)와 비용 함수를 최소화하기 위한 편미분항이 있습니다. 파라미터 θ가 있을 때 두 가지를 계산할 수 있는 코드가 필요합니다. 하나는 비용 함수 J(θ)를 계산하는 코드이고, 다른 하나는 j가 0,1,..., n개가 있을 때 비용 함수 J(θ)를 편미분 하는 편미분항을 계산하는 코드입니다. 두 가지가 가능한 코드는 경사 하강법 업데이트를 반복적으로 실행합니다. 


   따라서, 편미분을 계산하는 코드는 파라미터 θ를 업데이트하기 위해 경사 하강법을 활용합니다. 즉, J(θ)와 편미분항을 계산하는 코드는 비용 함수를 최소화하기 위해 경사 하강법을 사용합니다. 경사 하강법 공식은  엄밀하게 J(θ)를 계산하는 코드는 필요 없고, 단지 편미분항을 계산할 코드만 필요합니다. 그러나, 경사 하강법이 최소값으로 수렴하는지 여부를 모니터링하기 위해 비용 함수를 계산하는 코드가 필요합니다. 결국 두 가지를 계산하는 코드가 필요하지만 경사 하강법을 계산하는 알고리즘만을 사용합니다. 



    

   But gradient descent isn't the only algorithm we can use. And there are other algorithms, more advanced, more sophisticated ones, that, if we only provide them a way to compute these two things, then these are different approaches to optimize the cost function for us. So conjugate gradient, BFGS and L-BFGS are examples of more sophisticated optimization algorithms that need a way to compute J of theta, and need a way to compute the derivatives, and can then use more sophisticated strategies than gradient descent to minimize the cost function.


   그러나, 경사 하강법 외에도 더 발전되고 더 정교한 알고리즘이 있습니다.  비용 함수 J(θ)와 미분항을 계산하는 방법을 제공할 때 더 정교한 알고리즘은 비용 함수를 최적화하는 다른 접근법입니다. 더 정교한 고급 최적화 알고리즘은 Conjugate gradient,  BFGS and L-BFGS입니다. 단지 비용 함수 비용 함수 J(θ)와 미분항을 계산하는 방법이 필요할 뿐입니다. 비용 함수를 최소화하기 위해 경사 하강법보다 더 정교한 전략을 사용할 수 있는 고급 최적화 알고리즘입니다.  

      


   The details of exactly what these three algorithms is well beyond the scope of this course. And in fact you often end up spending, you know, many days, or a small number of weeks studying these algorithms. If you take a class and advance the numerical computing. But let me just tell you about some of their properties. These three algorithms have a number of advantages. 


   One is that, with any of this algorithms you usually do not need to manually pick the learning rate alpha.So one way to think of these algorithms is that given is the way to compute the derivative and a cost function. You can think of these algorithms as having a clever inter-loop. And, in fact, they have a clever inter-loop called a line search algorithm that automatically tries out different values for the learning rate alpha and automatically picks a good learning rate alpha so that it can even pick a different learning rate for every iteration. And so then you don't need to choose it yourself. These algorithms actually do more sophisticated things than just pick a good learning rate, and so they often end up converging much faster than gradient descent. These algorithms actually do more sophisticated things than just pick a good learning rate, and so they often end up converging much faster than gradient descent, but detailed discussion of exactly 

what they do is beyond the scope of this course.


   In fact, I actually used to have used these algorithms for a long time, like maybe over a decade, quite frequently, and it was only, you know, a few years ago that I actually figured out for myself the details of what conjugate gradient, BFGS and O-BFGS do. So it is actually entirely possible to use these algorithms successfully and apply to lots of different learning problems without actually understanding the inter-loop of what these algorithms do.


   If these algorithms have a disadvantage, I'd say that the main disadvantage is that they're 

quite a lot more complex than gradient descent. And in particular, you probably should 

not implement these algorithms - conjugate gradient, L-BGFS, BFGS - yourself unless you're an expert in numerical computing. Instead, just as I wouldn't recommend that you write your own code to compute square roots of numbers or to compute inverses of matrices, for these algorithms also what I would recommend you do is just use a software library. So, you know, to take a square root what all of us do is use some function that someone else has written to compute the square roots of our numbers. And fortunately, Octave and the closely related language MATLAB - we'll be using that - Octave has a very good. It has a pretty reasonable library implementing some of these advanced optimization algorithms. And so if you just use the built-in library, you know, you get pretty good results.


   I should say that there is a difference between good and bad implementations of these algorithms. And so, if you're using a different language for your machine learning application, if you're using C, C++, Java, and so on, you might want to try out a couple of different libraries to make sure that you find a good library for implementing these algorithms. Because there is a difference in performance between a good implementation of, you know, contour gradient or LPFGS versus less good implementation of contour gradient or LPFGS.


   세 가지 고급 최적화 알고리즘에 대한 자세한 설명은 이 과정의 범위를 많이 벗어납니다. 고급 최적화 알고리즘을 제대로 공부하려면 며칠 또는 몇 주가 걸리기 때문입니다. 간단하게 필요한 속성들만 설명합니다. 세 가지 고급 최적화 알고리즘은 여러 장점이 있습니다. 


   우선 학습률 α를 직접 선택할 필요가 없습니다. 고급 최적화 알고리즘은 미분항과 비용 함수 J(θ)를 계산하는 잘 만들어진 내부 프로세스인 가 있다고 생각해도 무방합니다. 학습률 α를 선택하기 위해 자동으로 학습률 α를 선택하는 뛰어난 라인 검색 알고리즘( line search algorithm)이 있습니다. 반복할 때마다 다른 학습률 α를 선택할 수도 있습니다. 고급 최적화 알고리즘에 학습률 α를 선택하는 과정을 맡길 수 있습니다. 고급 최적화 알고리즘은 직접 학습률 α를 선택하는 것보다 훨씬 더 정교하게 동작합니다. 종종 경사 하강법보다 훨씬 빠르게 최저값을 수렴합니다. 


    저는 세 가지 고급 최적화 알고리즘을 오랫동안 사용했습니다. 아마도 10년 넘게 꽤 자주 사용했습니다. 몇 년 전까지만 해도 Conjugate grdient,  BFGS와 L-BFGS의 동작 방식을 직접 공부했습니다. 하지만, 알고리즘의 동작 방식을 이해하지 못해도 많은 학습 문제에 적용하는 것에 문제가 없습니다.  


   세 알고리즘의 가장 큰 단점은 경사 하강법보다 훨씬 더 복잡하다는 것입니다. 계산 전문가가 아니라면 세 알고리즘을 직접 구현할 필요가 없습니다. 숫자의 제곱근이나 역행렬을 계산하기 위해 코드를 직접 작성하지 않고 다른 사람들이 이미 구현한 함수를 사용하는 것과 마찬가지입니다. 소프트웨어 라이브러리를 사용하는 것이 훨씬 더 현명한 방법입니다. 다행히도 옥타브와 매트랩 프로그램은 매우 좋은 고급 최적화 알고리즘을 구현한 라이브러리가 있습니다.  


   고급 최적화 알고리즘을 잘 구현한 라이브러리와 잘 구현하지 못한 라이브러리는 차이가 있습니다. 머신 러닝 응용 프로그램에 C, C++ 또는 Java와 같은 다른 언어를 사용하는 경우  몇 가지 라이브러리를 테스트해 보고 잘 구현한 라이브러리를 사용합니다.  


     


   So now let's explain how to use these algorithms, I'm going to do so with an example.       

Let's say that you have a problem with two parameters equals theta zero and theta one. 

And let's say your cost function is J of theta equals theta one minus five squared, plus theta two minus five squared. So with this cost function. You know the value for theta 1 and theta 2. If you want to minimize J of theta as a function of theta. The value that minimizes it is going to be theta 1 equals 5, theta 2 equals equals five.Now, again, I know some of you know more calculus than others, but the derivatives of the cost function J turn out to be these two expressions. I've done the calculus.So if you want to apply one of the advanced optimization algorithms to minimize cost function J. So, you know, if we didn't know the minimum was at 5, 5, but if you want to have a cost function 5 the minimum numerically using something like gradient descent but preferably more advanced than gradient descent, what you would do is implement an octave function like this,


   여기 알고리즘을 사용하는 방법에 대한 예제가 있습니다. 


   두 개의 파라미터 θ0와  θ1을 가진 머신 러닝 문제입니다. 여러분은 비용 함수 J(θ)를 최소화하는 파라미터  θ0와  θ1의 값을 압니다. 파라미터 θ1과 θ2의 값은 각각 5입니다. 여기서 비용 함수 J(θ)를 파라미터 θ1에 대해 미분을 하고 파라미터 θ2에 대해 미분합니다. 비용 함수 J(θ)를 최소화하기 위한 고급 최적화 알고리즘 중 하나를 적용하는 방법은 옥타브 프로그램의 라이브러리를 사용하는 것입니다. 이것이 파라미터 θ 의 값을 모르더라도 경사 하강법보다 나은 고급 최적화 알고리즘을 사용하는 방법입니다.  



  So we implement a cost function, cost function theta function like that, and what this does is that it returns two arguments, the first J-val, is how we would compute the cost function J. And so this says J-val equals, you know, theta one minus five squared plus theta two minus five squared. So it's just computing this cost function over here. And the second argument that this function returns is gradient. So gradient is going to be a two by one vector, and the two elements of the gradient vector correspond to the two partial derivative terms over here.


   그래서 파라미터 θ 에 대한 비용 함수 J(θ)를 구현합니다. 이 비용 함수는 두 개의 변수를 반환합니다. 첫 번째 변수 jVal은 비용 함수 J(θ)를 계산하는 코드입니다.  


   jVal = (theta(1) -5)^2 + (theta(2)-5)^2;


   두 번째 변수 gradient는 기울기(경사)이자 알고리즘이 도달할 최소값입니다. 이것은 2 X1 벡터이고, 두 성분은 두 개의 편미분항에 해당합니다.  


    gradient = zeros(2,1);

    gradient(1) = 2 * (theta(1) - 5);

    gradient(2) = 2 * (theta(2) - 5);



   Having implemented this cost function, you would, you can then call the advanced optimization function called the fminunc - it stands for function minimization unconstrained in Octave -and the way you call this is as follows. You set a few options. This is a options as a data structure that stores the options you want. So grant up on, this sets the gradient objective parameter to on. It just means you are indeed going to provide a gradient to this algorithm. I'm going to set the maximum number of iterations to, let's say, one hundred. 

We're going give it an initial guess for theta. There's a 2 by 1 vector. And then this command calls fminunc. This at symbol presents a pointer to the cost function that we just defined up there. And if you call this, this will compute, you know, will use one of the more advanced optimization algorithms. And if you want to think it as just like gradient descent. But automatically choosing the learning rate alpha for so you don't have to do so yourself. But it will then attempt to use the sort of advanced optimization algorithms. Like gradient descent on steroids. To try to find the optimal value of theta for you. 


    fminunc라는 고급 최적화 함수를 호출합니다. fminunc 함수는 옥타브에서 특정 함수에 대한 최적화 문제를 해결하는 함수입니다. fmimunc를 호출하는 방법은 다음과 같습니다. 


   options = optimet('GradObj', 'on', 'MaxIter', '100');  % 데이터 구조를 정의


     몇 가지 옵션을 설정하기 위해 변수 options을 사용합니다. 

   optimset ('GradObj', 'on') 은 'GradObj 값을 'On'으로 설정하는 것이고 전역 최소값을 구하는 함수의 gradient 값을 반환한다는 의미입니다. 즉, 이 알고리즘이 실제로 gradient 값을 제공한다는 뜻입니다. optimset ('MzxIter', '100') 은 최대 반복 횟수를 100으로 설정합니다.  


   initialTheta = zeros(2,1);


   initialTheta = zeros(2,1); 는 θ 파라미터 벡터의 두 값을 [0;0]으로 초기화합니다. 


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


   그리고 fminunc 함수를 호출합니다. @costFuction'은 방금 정의한 비용 함수를 가리키는 포인터입니다. fminunc 함수는 급 최적화 알고리즘 중 하나를  사용합니다. 경사 하강법은 학습률 α를 결정해야 합니다. 고급 최적화 알고리즘은 자동으로 학습률 α를 선택하고 자동으로 최적의 파라미 θ값을 찾습니다. 


        

   Let me actually show you what this looks like in Octave. So I've written this cost function of theta function exactly as we had it on the previous line. It computes J-val which is the cost function. And it computes the gradient with the two elements being the partial derivatives of the cost function with respect to, you know, the two parameters, theta one and theta two.


   옥타브 프로그램에서 코드의 형태를 보여드리겠습니다. 비용 함수 J(θ)와 미분항의 값을 반환하는 costFunction.m 파일입니다. JVal은 비용 함수 J(θ)를 계산하고, gradient는 두 파라미터 θ1과 θ2의 미문항을 계산하고 기울기를 구합니다.    



 Now let's switch to my Octave window. I'm gonna type in those commands I had just now. So, options equals optimset. This is the notation for setting my parameters on my options, for my optimization algorithm. Grant option on, maxIter, 100 so that says 100 iterations, and I am going to provide the gradient to my algorithm. Let's say initial theta equals zero's two by one. So that's my initial guess for theta. And now I have of theta, function val exit flag equals fminunc constraint. A pointer to the cost function. and provide my initial guess. And the options like so. And if I hit enter this will run the optimization algorithm. And it returns pretty quickly. 


   This funny formatting that's because my line, you know, my code wrapped around. So, this funny thing is just because my command line had wrapped around. But what this says is that numerically renders, you know, think of it as gradient descent on steroids, they found the optimal value of a theta is theta 1 equals 5, theta 2 equals 5, exactly as we're hoping for. The function value at the optimum is essentially 10 to the minus 30. So that's essentially zero, which is also what we're hoping for. And the exit flag is 1, and this shows what the convergence status of this. And if you want you can do help fminunc to read the documentation for how to interpret the exit flag. But the exit flag let's you verify whether or not this algorithm thing has converged. So that's how you run these algorithms in Octave.


  여기 옥타브 창으로 전환합니다. 위에서 고급 최적화 알고리즘을 활용하는 fminunc 함수를 호출합니다. 


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

   initialTheta = zeros(2,1)

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


   options는 optimset 설정과 같습니다. 이것은 고급 최적화 알고리즘에 필요한 파라미터에 대한 옵션을  설정합니다. 'MaxIter 100'은 반복 횟수를 100회로 제한하고 gradient의 값을 제공할 것입니다. 초기 파라미터 세타의 값을 2X1 벡터로 각각 0으로 초기화합니다. [optTheta, functionVal, exitFlag] 값은 fminunc 함수의 제약 조건입니다. '@costFunction'은 조금 저에 작성한 costFunction.m 함수 파일을 가리키는 포인터입니다. 리고, 엔터 키를 치면 최적화 알고리즘이 실행됩니다. 빠르게 답을 반환합니다. 


   재미있는 점은 fminunc 함수를 세 가지 변수가 감싼다는 것입니다. 


   OptThta = 

        5.0000

        5.0000


   OptTheta는 수치적으로 랜더링 하는 것으로 경사 하강법에서 파라미터 θ의 최적값을 계산한 값  θ1 = 5, θ2 = 5 계산입니다. 


   functionVal = 1.5777e-30


    fumctionVal은 전역 최소값입니다. 우리가 원하는 값인 0입니다. 


    exitFlag = 1


    이것은  수렴 상태를 보여줍니다. 따로 fminunc가 exitFlag를 해석하는 방법에 대한 문서가 있습니다. exitFlag는 알고리즘이 최적 값에 수렴되었는지 여부를 알려줍니다. 이것이 옥타브 프로그램에서 실행하는 방법입니다. 



 

   I should mention, by the way, that for the Octave implementation, this value of theta, your parameter vector of theta, must be in rd for d greater than or equal to 2. So if theta is just a real number. So, if it is not at least a two-dimensional vector or some higher than two-dimensional vector, this fminunc may not work, so and if in case you have a one-dimensional function that you use to optimize, you can look in the octave documentation for fminunc for additional details.


   그런데 옥타브 프로그램에서 파라미터 벡터 θ가 R^d차원일 때 d는 2 보다 크거나 같아야 합니다. 적어도 2차원 벡터가 아니거나 2차원 벡터보다 높은 경우 fminunc가 작동하지 않을 수 있습니다. 1차원 함수를 최적할 때는 세부 사항을 확인하기 위해 fminunc 명령어 대한 옥타브 문서를 참조할 필요가 있습니다. 

        


   So, that's how we optimize our trial example of this simple quick driving cost function. 

However, we apply this to let's just say progression. In logistic regression we have a parameter vector theta, and I'm going to use a mix of octave notation and sort of math notation. But I hope this explanation will be clear, but our parameter vector theta comprises these parameters theta 0 through theta n because octave indexes, vectors using indexing from 1, you know, theta 0 is actually written theta 1 in octave, theta 1 is gonna be written. So, if theta 2 in octave and that's gonna be a written theta n+1, right? And that's because Octave indexes is vectors starting from index of 1 and so the index of 0. So what we need 

to do then is write a cost function that captures the cost function for logistic regression. 


   Concretely, the cost function needs to return J-val, which is, you know, J-val as you need some codes to compute J of theta and we also need to give it the gradient. So, gradient 1 is going to be some code to compute the partial derivative in respect to theta 0, the next partial 

derivative respect to theta 1 and so on. Once again, this is gradient 1, gradient 2 and so on, rather than gradient 0, gradient 1 because octave indexes is vectors starting from one rather than from zero.But the main concept I hope you take away from this slide is, that what you need to do, is write a function that returns the cost function and returns the gradient. And so in order to apply this to logistic regression or even to linear regression, if you want to use these optimization algorithms for linear regression. What you need to do is plug in the appropriate code to compute these things over here. 


   이것이 간단하게 비용 함수를 빠르게 최적화하는 방법입니다. 로지스틱 회귀에서 파라미터 벡터 θ는 옥타브 표기법과 수학 표기법을 혼용하여 사용합니다. 파라미터 벡터 θ는 θ0에서부터 θn까지의 파라미터로 구성합니다. 옥타브 프로그램에서 인덱스는 1부터 시작합니다. θ0는 실제로 θ1입니다. 그래서,   θ2는 옥타브에서  n+1로 전환됩니다. 1-인덱스 벡터와 0-인덱스 벡터의 차이 때문입니다. 


    비용 함수는 jVal을 반환합니다. 즉, jVal을 계산하려면 J(θ)를 계산하는 코드가 필요하고 경사도 제공해야 합니다. gradient1 은  θ0에 대한 편미분을 계산하는 코드이고,  gradient2는 θ1에 대한 편미분을 계산하는 코드입니다. 왜냐하면 0 이 아닌 1에서 시작하는 벡터이기 때문입니다. 이 슬라이드에서 중요한 핵심 개념은 다음과 같습니다. 비용 함수와 미분항의 값을 반환하는 함수를 작성하는 것입니다. 따라서, 로지스틱 회귀 또는 선형 회귀에 최적화 알고리즘을 적용할 경우 적절한 코드를 사용합니다.  


   So, now you know how to use these advanced optimization algorithms. Because, using, because for these algorithms, you're using a sophisticated optimization library, it makes the just a little bit more opaque and so just maybe a little bit harder to debug. But because these algorithms often run much faster than gradient descent, often quite typically whenever I have a large machine learning problem, I will use these algorithms instead of using gradient descent.And with these ideas, hopefully, you'll be able to get logistic regression and also linear regression to work on much larger problems. So, that's it for advanced optimization concepts.


   지금까지 고급 최적화 알고리즘을 사용한 방법을 설명했습니다. 고급 최적화 알고리즘은 정교한 최적화 라이브러리를 사용하기 때문에 약간 불투명하고 디버깅하는 것이 조금 더 어렵습니다. 하지만, 고급 최적화 알고리즘은 경사 하강법보다 훨씬 더 빠르게 실행되기 때문에 큰 머신 러닝 문제가 있을 때 경사 하강법 대신에 사용합니다. 더 큰 문제를 해결할 때도 로지스틱 회귀와 선형 회귀를 활용할 수 있습니다. 이것이 고급 최적화 기법의 개념입니다.


   And in the next and final video on Logistic Regression, I want to tell you how to take the logistic regression algorithm that you already know about and make it work also on multi-class classification problems.


   다음 강의는 로지스틱 회귀에 대한 마지막 강의입니다. 이미 알고 있는 로지스틱 회귀 알고리즘을 활용하여 다중 클래스 분류 문제를 해결하는 방법을 공부합니다.



정리하며 - 고급 최적화 알고리즘


   비용 함수 J(θ)의 최소값을 찾기 위해 경사 하강법은 다음과 같습니다.


           Repeat {

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

           }


     미분항을 미분하면 다음과 같습니다. 

            

           Repeat {   

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

             }


     경사 하강법 업데이트 공식 계산하는 코드를 짠다고 가정해 봅시다. 여러분은 지금까지 배운 대로 경사 하강법이 최저값으로 수렴하는지 여부를 모니터링하는 것도 필요하고, 비용 함수와 미분항을 계산하는 코드도 필요하다고 생각할 것입니다. 하지만, 경사 하강법 공식을 보면 엄밀하게 J(θ)를 계산하는 코드는 필요 없고, 단지 편미분항을 계산할 코드만 필요합니다.


경사 하강법 외에 더 발전되고 정교한 고급 최적화 알고리즘들이 있습니다.  


         Conjugate grdient,  BFGS and L-BFGS. 


    고급 최적화 알고리즘은 우선 학습 비율 알파를 수동으로 선택할 필요 없이 자동으로 계산하고, 경사 하강법보다 훨씬 빠르게 최저값에 수렴합니다. 고급 최적화 알고리즘이 어떻게 동작하는 지를 알지 못해도 실제 적용할 수 있고 더 나은 결과를 얻을 수 있습니다. 


   하지만, 세 알고리즘은 경사 하강법보다 훨씬 더 복잡합니다. 세 알고리즘을 직접 구현하지 말고 소프트웨어 라이브러리를 사용하는 것이 훨씬 현명한 방법입니다. 옥타브 프로그램을 사용할 경우 아래의 코드를 활용해서 고급 최적화 알고리즘을 사용합니다.  사용하는 방법은 다음과 같습니다. 


 J(θ) = (θ1 -5)^2 + (θ2 - 5)^2이라고 가정할 때, costFunction.m 함수 파일은 다음과 같이 작성합니다.


        function [jVal, gradient] = costFunction(theta) 


        jVal = (theta(1)-5)^2 + (theta(2)-5)^2;


        gradient = zeros(2,1);

        gradient(1) = 2 * (theta(1)-5);

        gradient(2) = 2 * (theta(2)-5);         


    end


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


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

      gradient : 알고리즘이 도달할 최소값, 2 X1 벡터,   


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


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

   initialTheta = zeros(2,1). %θ 파라미터 벡터의 두 값을 [0;0]으로 초기화

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


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

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

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

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


   정교한 최적화 라이브러리를 사용하는 고급 최적화 알고리즘은 약간 불투명하고 디버깅하는 것이 어렵습니다. 하지만, 고급 최적화 알고리즘은 경사 하강법보다 훨씬 더 빠르게 실행되기 때문에 큰 머신 러닝 문제가 있을 때 경사 하강법 대신에 사용합니다. 



문제 풀이


고급 최적화 알고리즘은 로지스틱 회귀의 비용 함수를 최소화합니다. 다음 코드에서 CODE #1이 무엇을 계산할까요?

정답은 3번입니다. 

매거진의 이전글 앤드류 응의 머신러닝(6-5):로지스틱회귀 경사 하강법
작품 선택
키워드 선택 0 / 3 0
댓글여부
afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari