brunch

You can make anything
by writing

C.S.Lewis

by 라인하트 Oct 17. 2020

머신러닝 옥타브 실습 (1-1):단변수 선형회귀(상)

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



Programing Exercise 1 : Linear Regression

프로그래밍 실습 1 : 선형 회귀  


1. Simple Octave / MATLAB fuction 

(간단한 옥타브 기능)


   The first part of ex1.m gives you practice with Octave/MATLAB syntax and the homework submission process. In the file warmUpExercise.m, you will find the outline of an Octave/MATLAB function. Modify it to return a 5 x 5 identity matrix by filling in the following code: 


     A = eye(5);


   When you are finished, run ex1.m (assuming you are in the correct directory, type “ex1” at the Octave/MATLAB prompt) and you should see output similar to the following:


              ans =

               Diagonal Matrix 

                            1    0    0    0    0

                            0    1    0    0    0

                            0    0    1    0    0

                            0    0    0    1    0 

                            0    0    0    0    1


   ex1.m의 첫 번째 부분은 옥타브 및 매트랩 프로그램의 구문과 숙제 제출 프로세스를 연습하는 것입니다. warmUpExercise.m 파일 안에 옥타브 및 매트랩 기능의 개요를 찾습니다. 다음 코드를 채워서   5 X 5 항등 행렬을 반환하게 만드세요.  마칠 때, 옥타브 / 매트랩에서 ex1.m을 실행하세요. (올바른 디렉터리에 있다고 가정하고, 옥타브 / 매트랩 프롬프트에서 ex1을 입력하세요. 다음과 같은 출력을 얻을 것입니다. 



<관련 파일 다운로드>

다음 파일을 다운로드하여 설치합니다. 


<정답>

1) 파일에 있는 라이브러리가 있는 디렉터리로 이동합니다. 

2) warmUpExercise.m 파일 열기 


        function A = warmUpExercise()

        % 옥타브의 WARMUPEXERCISE 예제 함수 

        %   A = WARMUPEXERCISE() 는 5 X5 항등 행렬을 반환하는 예제 함수


        A = [];

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

        % Instructions: 5 X5 항등 행렬을 반환하시오  

        %               옥타브에서 파일 첫 줄에 있는 변수로 정의한 값을 반환 

        %               적절하게 설정하시오 

        %               

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


        end


3) 파일에 'A = eye(5):' 삽입하기


        function A = warmUpExercise()

        % 옥타브의 WARMUPEXERCISE 예제 함수 

        %   A = WARMUPEXERCISE() 는 5 X5 항등 행렬을 반환하는 예제 함수


        A = [];

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

        % Instructions: 5 X5 항등 행렬을 반환하시오  

        %               옥타브에서 파일 첫 줄에 있는 변수로 정의한 값을 반환 

        %               적절하게 설정하시오 

        %               

        A = eye(5);

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


        end



4) warmUpExercise를 실행하여 결과와 확인


   

1.1 Submitting Solutions (솔루션 제출하기)


   After completing a part of the exercise, you can submit your solutions for grading by typing submit at the Octave/MATLAB command line. The sub- mission 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.

   

   실습을 완료한 후 옥타브 매트랩 명령어를 'submit' 명령어로 채점 솔루션에 제출할 수 있습니다. 제출 스크립트는 로그인 이메일과 제출 토큰이 필요합니다. 웹페이지에서 제출 토큰을 확인합니다. 




2. Linear regression with one variable

   (단변수 선형 회귀)


   In this part of this exercise, you will implement linear regression with one variable to predict profits for a food truck. Suppose you are the CEO of a restaurant franchise and are considering different cities for opening a new outlet. The chain already has trucks in various cities and you have data for profits and populations from the cities.

   You would like to use this data to help you select which city to expand to next. 

   The file ex1data1.txt contains the dataset for our linear regression problem. The first column is the population of a city and the second column is the profit of a food truck in that city. A negative value for profit indicates a loss. 

   The ex1.m script has already been set up to load this data for you.


   이 실습에서 푸드트럭의 수익을 예측하기 위한 단변수 선형 회귀를 구현합니다. 여러분은 프랜차이즈 레스토랑의 사장이고, 새로운 매장을 열기 위해 다른 도시를 탐색중입니다. 프렌차이즈는 이미 여러 도시에 푸드 트럭이 있고 도시의 수익과 인구 데이터가 있습니다. 


   다음 확장할 도시를 선택하기 위해 데이터를 사용합니다. ex1data1.txt 파일에는 선형 회귀 문제에 대한 데이터셋이 있습니다. 첫 번째 칼럼은 도시의 인구이고, 두 번째 칼럼은 그 도시에서 푸드트럭의 수익입니다. 마이너스 표시는 손실을 나타냅니다. ex1.m 스크립트는 이미 이 데이터를 로드하도록 설정되어 있습니다. 



2.1 Plotting the Data (데이터를 그래프로 도식화하기)


<문제>

   Before starting on any task, it is often useful to understand the data by visualizing it. For this dataset, you can use a scatter plot to visualize the data, since it has only two properties to plot (profit and population). (Many other problems that you will encounter in real life are multi-dimensional and can’t be plotted on a 2-d plot.)

   In ex1.m, the dataset is loaded from the data file into the variables X and y:


data = load('ex1data1.txt');        % read comma separated data
X = data(:, 1); y = data(:, 2);
m = length(y);                               % number of training examples 


   Next, the script calls the plotData function to create a scatter plot of the data. Your job is to complete plotData.m to draw the plot; modify the file and fill in the following code:


plot(x, y, 'rx', 'MarkerSize', 10);                   % Plot the data 
ylabel('Profit in $10,000s');                         % Set the y−axis label
 xlabel('Population of City in 10,000s');     % Set the x−axis label


   작업을 하기 전에 데이터 시각화를 위해 데이터를 이해하는 것은 유용합니다. 이 데이터 세트의 경우 그래프를 그릴 속성이 수익과 인구 두 개뿐입니다. (실생활에 직면할 다른 많은 문제는 다차원 적이며 2차원 도면에 그릴 수 없습니다.)


   ex1.m 파일을 실행하면 변수 X 및 y가 로드합니다. 


    data = load('ex1data1.txt');       % ex1data1.txt 데이터 업로드. 콤마(,)는 데이터를 분리

    X = data(:, 1); y = data(:, 2);      %

    m = length(y);                            % 학습 예제의 수를 계산


   다음으로,  plotData.m 파일을 열고 다음 명령어를 입력합니다. plotData.m 파일은 입력된 데이터를 기반으로 좌표에 데이터를 찎습니다. . 


   plot(X, y, 'rx', 'MarkerSize', 10);             % 데이터를 도식화

   ylabel('Profit in $10,000s');                    % y축 레이블 지정 

   xlabel('Population of City in 10,000s');  % x축 레이블 지정 


<정답>

1) ex1data1.txt 의 데이터를 옥타브 프로그램으로 업로드


     data = load('ex1data1.txt');


2) PlotData 함수에 제공할 X, y를 지정

  

       X = data(:, 1);           % 변수 data의 첫번째 열을 행렬 X로 입력

      y = data(:, 2);           % 변수 data의 두 번째 열을 벡터 y로 입력 

       

3) plotData.m 파일을 열기



        function plotData(x, y)

        %   PLOTDATA Plots the data points x and y into a new figure 

        %   PLOTDATA(x,y) plots the data points and gives the figure axes labels of

        %   population and profit.


        figure;       % open a new figure window


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

        % Instructions: Plot the training data into a figure using the 

        %               "figure" and "plot" commands. Set the axes labels using

        %               the "xlabel" and "ylabel" commands. Assume the 

        %               population and revenue data have been passed in

        %               as the x and y arguments of this function.

        %

        % Hint: You can use the 'rx' option with plot to have the markers

        %       appear as red crosses. Furthermore, you can make the

        %       markers larger by using plot(..., 'rx', 'MarkerSize', 10);


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


         end



4) 데이터를 그리기 위해 다음의 세 명령어를 삽입



        function plotData(x, y)

        %   PLOTDATA 는 데이터를 x축과 y축을 기준으로 도식화  

        %   PLOTDATA(x,y) 함수는 데이터 포인트를 그리고 인구와 수익으로 축을 표시 

        %   


        figure;       % 새로운 그림 창을 열기 


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

        % Instructions: 

        %               "figure" 와 "plot" 명령어를 사용하여 훈련 데이타를 도식화하시오

        %               "xlabel"와 "ylabel" 명령어로 축에 레이블을 다시오.  Assume the 

        %               x축은 인구(population) 레이블 

        %               y축은 수익 (revenue ) 레이블 

        %

        % Hint:  

        %       plot 명령어의 'rx' 옵션을 적용하면 빨간색 십자가로 데이터 표시 

        %       'MakerSize' 10' 옵션을 적용하면 데이터를 크게 표시 

        %        plot(..., 'rx', 'MarkerSize', 10);


   plot(x, y, 'rx', 'MarkerSize', 10);  

   ylabel('Profit in $10,000s');        

   xlabel('Population of City in 10,000s'); 


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


    end


<결과> 

 



2.2 Gradient Descent (경사 하강법) 


   In this part, you will fit the linear regression parameters θ to our dataset using gradient descent.

  

   이 부분에서 선형 회귀의 파라미터 θ 를 경사 하강을 사용하여 데이터 셋에 적합시킬 것입니다.


2.2.1 업데이트 방정식


   Recall that the parameters of your model are the θj values. These are the values you will adjust to minimize cost J(θ). One way to do this is to use the batch gradient descent algorithm. In batch gradient descent, each iteration performs the update.


   With each step of gradient descent, your parameters θj come closer to the optimal values that will achieve the lowest cost J(θ)


    선형 회귀의 목적은 비용 함수 J(θ)를 최소화하는 것입니다. 



   이 선형회귀 모델의 파라미터 θj를 기억하세요. θj는 비용 함수 J(θ)를 최소화하기 위해 조정할 값입니다. 비용 함수를 최소화하기 위해 경사 하강 알고리즘을 사용합니다. 배치 경사 하강 알고리즘은 반복할 때마다 동시 업데이트를 수행합니다. 경사 하강법의 각 단계에서 파라미터 θj는 최저 비용 J(θ)를 달성할 최적 값에 더 가까워집니다. 


<구현 노트>

    We store each example as a row in the the X matrix in Octave/MATLAB. To take into account the intercept term (θ0), we add an additional first column to X and set it to all ones. This allows us to treat θ0 as simply another ‘feature’.


   옥타브 / 매트랩 프로그램의 X 행렬에 학습 예제를 행으로 저장합니다. θ0를 고려하여 X의 첫 번째 열에 모든 값을 1로 추가합니다. 이것은 θ0x0를 하여 피처로 취급합니다.  


2.2.2 Implementation (구현)


   In ex1.m, we have already set up the data for linear regression. In the following lines, we add another dimension to our data to accommodate the θ0 intercept term. We also initialize the initial parameters to 0 and the learning rate alpha to 0.01.


X = [ones(m, 1), data(:,1)];    % Add a column of ones to x
theta = zeros(2, 1);                 % initialize fitting parameters  
iterations = 1500; 
alpha = 0.01; 


   ex1.m 파일에서 이미 선형 회귀 데이터를 설정했습니다. 다음 줄에서는 θ0 항을 수용하기 위해 데이터에 다른 차원을 추가합니다. 초기 파라미터를 0으로 초기화하고 학습 비율 알파를 0.01로 초기화합니다. 


  X = [ones(m, 1), data(:,1)];    % 변수 X 의 데이터 오른쪽에 1을 추가 

  theta = zeros(2, 1);                % 파라미터 θ0, θ1을 0으로 초기화 theta = [0;0]; 과 동일

  iterations = 1500;                  % 경사하강법 반복 횟수 1,500번 설정

  alpha = 0.01;                          % 학습률 α를 0.01로 설정



2.2.3  Computing the cost J(θ)(비용 J(θ) 계산하기)


   As you perform gradient descent to learn minimize the cost function J(θ), it is helpful to monitor the convergence by computing the cost. In this section, you will implement a function to calculate J(θ) so you can check the convergence of your gradient descent implementation.

   Your next task is to complete the code in the file computeCost.m, which is a function that computes J(θ). As you are doing this, remember that the variables X and y are not scalar values, but matrices whose rows represent the examples from the training set.

   Once you have completed the function, the next step in ex1.m will run computeCost once using θ initialized to zeros, and you will see the cost printed to the screen.

   You should expect to see a cost of 32.07.


   You should now submit your solutions. 


   비용 함수 J(θ)를 최소화하기 위해 경사 하강법을 실행할 때 비용을 계산하여 최소값에 수렴하는 것을 모니터링해야 합니다. 여기서는 경사 하강 법 구현의 수렴을 확인할 수 있는 J(θ)를 계산하는 함수를 구현합니다.


   다음 작업은 J(θ)를 계산하는 함수인 computeCost.m 파일 코드 작성을 완료합니다. 변수 X와 y는 스칼라 값이 아니라 학습 데이터 셋의 예제를 행으로 나타내는 행렬입니다. 


   함수를 완료하면 ex1.m의 다음 단계에서 0으로 초기화된 θ를 사용하여 computeCost를 한 번 실행하고 비용이 화면에 인쇄는 것을 볼 수 있습니다. 비용은 32.07입니다.



<정답>

1) 파라미터 하나를 가진 가설 hθ(x) 는 다음과 같습니다.

 

     hθ(x) = θ0x0 + θ1x1 = θ^TX

    

     따라서, 피처들의 집합인 행렬 X와 실제 값을 가진 벡터 y가 필요합니다. 옥타브 프로그램에서 X, y, theta를 정의합니다. 


   X = [ones(m, 1), data(:,1)];    % 변수 X 의 데이터 오른쪽에 1을 추가 

   y = data(:, 2);           % 변수 data의 두 번째 열을 벡터 y로 입력 

  theta = zeros(2, 1);                % 파라미터 θ0, θ1을 0으로 초기화 theta = [0;0]; 과 동일


2) computeCost.m 파일  열기


        function J = computeCost(X, y, theta)

        %   COMPUTECOST 함수는 선형회귀의 비용을 계산 

        %   J = COMPUTECOST(X, y, theta) 함수는 데이터 X, y에 적합한 선형회귀의 파라미터 theta를 

        %    사용하여 비용을 계산 


        % 변수 m을 초기화 

        m = length(y);         % 학습 예제의 수 


        % 변수 J의 값을 올바르게 반환해야 함  

        J = 0;


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

        % Instructions:   theta의 값에 따른 비용을 계산하시오

        %                           비용 함수 J를 설정하시오 



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


        end  



3)  J(θ) 구하는 식을 추가합니다.  


        function J = computeCost(X, y, theta)

        %   COMPUTECOST Compute cost for linear regression

        %   J = COMPUTECOST(X, y, theta) computes the cost of using theta as the

        %   parameter for linear regression to fit the data points in X and y


        % Initialize some useful values

        m = length(y); % number of training examples


        % You need to return the following variables correctly 

        J = 0;


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

        % Instructions: Compute the cost of a particular choice of theta

        %               You should set J to the cost.

 

          J = 1/(2*m) *(X * theta- y)'*(X * theta- y)


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


        end  


<해설>

   비용 함수 J(θ)는 다음과 같습니다.


   옥타브 프로그램이 비용 함수 J(θ)을 다음과 같이 정의할 수 있습니다.  


     J = 1/(2*m) *(X * theta- y)'*(X * theta- y)

       

   '행렬과 벡터의 곱셈'에서 배웠듯이 행렬 A 를 제곱하기 위한 방법이 필요합니다.


    A .^2    % 행렬의 모든 성분의 값을 각각 제곱. 따라서 합산이 필요

    A'A       % 전치행렬을 이용하면 모든 성분의 값을 각각 제곱하고 모두 값을 더한 효과


   따라서, 벡터화 구현을 하지 않을 때 비용 함수 J(θ)는 다음과 같습니다. 


   J = 1/(2*m) * sum(X*theta - y).^2) 



<결과>

   파라미터 θ0 = 0, θ1 = 1 일때 비용 함수 J(θ)는 32.7 입니다. 




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