brunch

You can make anything
by writing

C.S.Lewis

by 라인하트 Jan 01. 2021

머신러닝 옥타브 실습 (2-1) : 로지스틱 회귀

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



Programing Exercise 2 : Logistic Regression

프로그래밍 실습 2 : 로지스틱 회귀  


1. Logistic Regression (로지스틱 회귀) 


   In this part of the exercise, you will build a logistic regression model to predict whether a student gets admitted into a university. 

   Suppose that you are the administrator of a university department and you want to determine each applicant’s chance of admission based on their results on two exams. You have historical data from previous applicants that you can use as a training set for logistic regression. For each training example, you have the applicant’s scores on two exams and the admissions decision. 

   Your task is to build a classification model that estimates an applicant’s probability of admission based the scores from those two exams. This outline and the framework code in ex2.m will guide you through the exercise.


   이번 실습은 학생이 대학에 입학할 수 있는지 여부를 예측하는 로지스틱 회귀 모델을 구축하는 것입니다.   

   여러분은 대학 부서의 관리자이고 두 개의 시험 결과를 가지고 각 지원자의 입학 여부를 결정한다고 가정합니다. 학습 셋은 과거 지원자들의 기록 데이터입니다. 각 학습 예제에 대해 두 개의 시험 성정과 입학 결정 여부가 있습니다.   

   여러분의 임무는 두 시험 성적을 바탕으로 지원자의 입학 확률을 추정하는 분류 모델을 구축하는 것입니다. ex2.m은 프레임워크 코드와 연습 과정을 안내할 것입니다. 



1.1 Visualizing the data (데이터 시각화)


   Before starting to implement any learning algorithm, it is always good to visualize the data if possible. In the first part of ex2.m, the code will load the data and display it on a 2-dimensional plot by calling the function plotData.

   You will now complete the code in plotData so that it displays a figure like Figure 1, where the axes are the two exam scores, and the positive and negative examples are shown with different markers.


   To help you get more familiar with plotting, we have left plotData.m empty so you can try to implement it yourself. However, this is an optional (ungraded) exercise. We also provide our implementation below so you can copy it or refer to it. If you choose to copy our example, make sure you learn what each of its commands is doing by consulting the Octave/MATLAB documentation.


   학습 알고리즘을 구현하기 전에 항상 데이터를 시각화하는 것이 좋습니다. ex2.m의 첫 부분의 코드는 데이터를 로드하고 plotData 함수를 호출하여 2차원 그림을 표시합니다. 

   PlotData에서 코드를 완성하여 그림 1과 같은 그림을 그리시오. 여기 축은 두 개의 시험 점수이고 파지티브 및 네거티브 예제는 서로 다른 마커로 표시합니다. 


   그림을 도식화하는 것에 익숙해지는 것을 돕기 위해 plotData.m을 비워두고 직접 구현할 수 있습니다. 점수와 상관없는 선택적인 실습입니다. 또한, 아래의 코드를 복사하거나 참조할 수 있습니다. 예제를 복사할 때 옥타브 문서를 참조하여 명령어를 확인하세요.



<해설>


(1) 데이터를 업로드 

       ex2data1의 파일을 확인하고 옥타브 프로그램으로 업로드합니다. 


data = load ('ex2data1.txt');

X = [data(:,1:2)];

y = [data(:,3)];

 m = length(y);


   기본적인 변수가 제대로 생성되었는 지를 확인합니다.


>> whos

Variables in the current scope:


   Attr Name        Size                     Bytes  Class

   ==== ====        ====                     =====  =====

        X                  100x2                       1600  double

        ans              1x82                        82  char

        data            100x3                       2400  double

        m                 1x1                          8  double

        y                  100x1                        800  double


Total is 683 elements using 4890 bytes



(2) 그림대로 도식화를 위해 plot 명령어를 확인


   Plot 명령어의 포맷 형식은 다음과 같다.


 Format arguments:


     linestyle


          '-'  Use solid lines (default).

          '--' Use dashed lines.

          ':'  Use dotted lines.

          '-.' Use dash-dotted lines.


     markerstyle


          '+'  crosshair             

          'o'  circle

          '*'  star

          '.'  point

          'x'  cross

          's'  square

          'd'  diamond

          '^'  upward-facing triangle

          'v'  downward-facing triangle

          '>'  right-facing triangle

          '<'  left-facing triangle

          'p'  pentagram

          'h'  hexagram


     color


          'k'  blacK

          'r'  Red

          'g'  Green

          'b'  Blue

          'm'  Magenta

          'c'  Cyan

          'w'  White


 여기서 데이터 스타일을 'r+'로 선택한다


(3) 데이터를 도식화


>> plot (X(:,1), X(:,2),'r+');

>> xlabel ('Exam 1 score');

>> ylabel ('Exam 2 score');



>> plot (X(:,1),X(:,2), 'ko','MarkerFaceColor','y')



>> plot (X(:,1),X(:,2),'k+','LineWidth',2)

   


(4) 이진 분류 문제에 따라 데이터를 분리를 위한 명령어 find

      학습 예제를 y = 1과 y =0의 예제로 분리해야 합니다. 예제를 분리하기 위해 사용하는 함수가 find()입니다. find() 명령어는 0이 아닌 값을 가진 인덱스를 반환합니다. 


>> y (1:5)           % 벡터 y의 1번부터 5번까지 데이터를 반환

ans =

   0

   0

   0

   1

   1


>> find (y(1:5)). % Find는 0 아닌 값을 가진 벡터의 성분의 위치인 인덱스를 반환

ans =

    4

    5


    find(y(1:5) 명령어는 y(1:5)에서 0이 아닌 1의 값을 가진 4번과 5번의 값을 반환합니다.  find 명령어에 대해 좀 더 알아봅니다.


>> [i,j] = find(y(1:5)) % i는 0 아닌 값을 가진 성분의 인덱스를 반환, j는 그 값을 반환

i =

   4

   5


j =

   1

   1


 >> find (y == 0)     % y의 값이 0 인 성분의 인덱스를 반환

ans =

    1

    2

    3


 >> find (y == 1)     % y의 값이 1 인 성분의 인덱스를 반환

ans =

    1

    2

    3


정리하면, 다음과 같이 인덱스를 만듭니다.

>> positive = find (y==1);    % y=1인 학습 예제의 인덱스를 반환

>> negative = find(y==0);     % y=0인 학습 예제의 인덱스를 반환


(5) 데이터를 이진 분류에 맞게 도식화 


positive = find (y==1);

negative = find(y==0);

plot (X(positive,1),X(positive,2),'k+','LineWidth',2);

hold on;

plot (X(negative,1),X(negative,2), 'ko','MarkerFaceColor','y');



(6) 레이블 입력


xlabel ('Exam 1 score');

ylabel ('Exam 2 score');

legend('Admitted', 'Not admitted')






<정답>


function plotData(X, y)

%. PLOTDATA  데이터를 도식화  

%   PLOTDATA(x,y) 파지티브 예제는 + 표시, 네거티브 예제는 O로 표시

%   


% 새로운 그림 창을 생성하고 겹쳐서 그림

figure; hold on;


% ====================== YOUR CODE HERE ======================

% Instructions:

%               파지티브 예제는 'k+' 옵션을, 네거티브 예제는 'ko' 옵션을 사용할 것

%              


positive = find (y==1);

negative = find(y==0);

plot (X(positive,1),X(positive,2),'k+','LineWidth',2);

plot (X(negative,1),X(negative,2), 'ko','MarkerFaceColor','y');


% =========================================================================


hold off;   % 그림을 겹쳐서 그리는 것 해제 


end





1.2 Implementation (구현)


1.2.1 Warmup exercise: sigmoid function (시그모이드 함수)


   Before you start with the actual cost function, recall that the logistic regression hypothesis is defined as:


                                  hθ(x) = g(θT x),
where function g is the sigmoid function. The sigmoid function is defined as:


                                  g(z) = 1 /(1+e−z)


   Your first step is to implement this function in sigmoid.m so it can be called by the rest of your program. When you are finished, try testing a few values by calling sigmoid(x) at the Octave/MATLAB command line. For large positive values of x, the sigmoid should be close to 1, while for large negative values, the sigmoid should be close to 0. Evaluating sigmoid(0) should give you exactly 0.5. Your code should also work with vectors and matrices. For a matrix, your function should perform the sigmoid function on every element.

   You can submit your solution for grading by typing submit at the Oc- tave/MATLAB command line. The submission script will prompt you for your login e-mail and submission token and ask you which files you want to submit. You can obtain a submission token from the web page for the assignment.


   비용 함수를 시작하기 전에 로지스틱 회귀 가설은 다음과 같습니다. 로지스틱 회귀는 시그모이드 함수 g(z)를 사용합니다. 

   첫 번째 단계는 sigmoid.m 에서 함수를 구현합니다. 다른 프로그램에서 호출할 것입니다. 완료 후에서 옥타브 프로그램 창에서 sigmoid(x)를 테스트해 보세요. 


  sigmod(x) >> 0 : 큰 양수일 때 시그모이드는 1에 가깝다

  sigmod x) << 0 : 큰 음수일 때 시그모이드는 0에 가깝다

  sigmod(x) = 0   : 0 일 때 정확히 0.5의 값이다. 


   코드는 벡터 및 행렬에서 작동해야 합니다. 행렬일 때 모든 성분에 대해 시그모이드 함수가 작동해야 합니다. 옥타브 명령어에서 submit을 입력하여 솔루션을 제출하세요. 스크립트를 제출하기 위해서는 이메일과 제출 토큰이 필요합니다. 웹 페이제에서 얻을 수 있습니다.


<해설>


(1) 데이터 행렬 X에 인터셉트 항 x0를 적용


>> X(1,:)              % 데이터 행렬 X의 첫 번째 학습 예제를 확인

ans =

   34.624   78.025


>> X = [ones(m,1), X]    % 데이터 행렬 X에 인터셉트 항 x0를 적용

X =

    1.0000   34.6237   78.0247

    1.0000   30.2867   43.8950

    1.0000   35.8474   72.9022

    1.0000   60.1826   86.3086


(2) 시그모이드 함수 식을 수식으로 표현


    시그모이드 함수를 계산하는 함수는 exp()입니다. e^(-z)를 나타내는 함수는 exp(-z)입니다.

    따라서,  로지스틱 회귀 가설은 다음과 같습니다.


     1/ (1 + exp(-z))


(3) 테스트


>> z = 0;                    % z 가 실수 0일 때 0.5 값 이어 햠

>> 1/ (1 + exp(-z))

ans =  0.50000


>> z = 100                 %  z가 양의 큰 수 일 때 1이어야 함

>> 1/ (1 + exp(-z))

ans =  1


>> z = -100;               % z 가 음의 큰 수 일 때 0이어야 함

>> 1/ (1 + exp(-z))

ans =    3.7201e-44


>> z = y                              %  z 가 벡터일 때 동작 

>>   1 / (1 + exp(-z))

 시그모이드 함수의 특징을 만족합니다.


>>  z = X                        % z 가 행렬일 때 에러 발생

 >> g = 1 / (1 + exp(-z))

error: operator /: nonconformant arguments (op1 is 1x1, op2 is 100x3)


여기서 문제가 발생합니다. 행렬 나눗셈 연산을 정리합니다. 


>> [1,1]/10

ans =

   0.10000   0.10000


>> 10 / [1,1]

error: operator /: nonconformant arguments (op1 is 1x1, op2 is 1x2)


>> 10 ./ [1,1]

ans =


   10   10


원하는 연산은 행렬의 각 성분의 역수를 구하는 것입니다. 따라서, './' 연산자를 이용합니다.


>>  z = X                      

 >> g = 1 ./ (1 + exp(-z));

ans =

   0.73106   1.00000   1.00000

   0.73106   1.00000   1.00000

   ...



<정답>

(1) sigmod.m 파일 열기

function g = sigmoid(z)

% SIGMOID 는 시그모이드 함수를 계산 

%   g = SIGMOID(z) z에 대한 시그모이드 함수 계산 


% 다음 변수를 g를 반환  

g = zeros(size(z));     % 벡터 또는 행렬의 크기만큼 벡터 g를 초기화    


% ====================== YOUR CODE HERE ======================

% Instructions: 

%               sigmoid(z)를 계산하시오 스칼라, 벡터, 행렬일 수 있음


g = 1 ./ (1 + exp(-z));


% =============================================================


end



<결과 확인>


>> sigmoid(X)

ans =

   0.73106   1.00000   1.00000

...


>> submit

==

==                                                      Part Name |    Score | Feedback

==                                                               --------- |     ----- | --------  

==                                           Sigmoid Function |   5 /   5 | Nice work!

==                               Logistic Regression Cost |   0 /  30 |

==                       Logistic Regression Gradient |   0 /  30 |

==                                                             Predict |   0 /   5 |

==        Regularized Logistic Regression Cost |   0 /  15 |

==    Regularized Logistic Regression Gradient |   0 /  15 |

==                                   --------------------------------

==                                             |   5 / 100 |

==

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