brunch

You can make anything
by writing

C.S.Lewis

by 라인하트 Dec 31. 2020

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

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



Programing Exercise 1 : Linear Regression

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


3. Linear regression with Multiple variable

   (다변수 선형 회귀)



In this part, you will implement linear regression with multiple variables to predict the prices of houses. Suppose you are selling your house and you want to know what a good market price would be. One way to do this is to first collect information on recent houses sold and make a model of housing prices.


The file ex1data2.txt contains a training set of housing prices in Port- land, Oregon. The first column is the size of the house (in square feet), the second column is the number of bedrooms, and the third column is the price of the house.


The ex1 multi.m script has been set up to help you step through this exercise.


   여기서 주택 가격을 예측하기 위해 여러 변수를 사용하여 선형 회귀를 구현합니다. 주택을 좋은 시장 가격에 팔려고 합니다. 먼저 최근 판매된 주택에 대한 정보를 수집하고 주택 가격 모델을  만듭니다.


   ex1data2.txt 파일은 오리건 주 포틀랜드의 주택 가격 학습 셋입니다. 첫 번째 열은 주택 크기, 두 번째 열은 침 수, 세 번째 열은 주택 가격입니다. 


   단변수 선형 회귀 때와 마찬기로 스크립트가 준비되었고, 마지막에 ex1_multi.m 으로 최종 확인할 수 있습니다. 



3.1 Feature Normalization (피처 정규화)


   The ex1 multi.m script will start by loading and displaying some values from this dataset. By looking at the values, note that house sizes are about 1000 times the number of bedrooms. When features differ by orders of mag- nitude, first performing feature scaling can make gradient descent converge much more quickly.

Your task here is to complete the code in featureNormalize.m to


• Subtract the mean value of each feature from the dataset.


• After subtracting the mean, additionally scale (divide) the feature values by their respective “standard deviations.”


The standard deviation is a way of measuring how much variation there is in the range of values of a particular feature (most data points will lie within ±2 standard deviations of the mean); this is an alternative to taking the range of values (max-min). In Octave/MATLAB, you can use the “std” function to compute the standard deviation. For example, inside featureNormalize.m, the quantity X(:,1) contains all the values of x1 (house sizes) in the training set, so std(X(:,1)) computes the standard deviation of the house sizes. At the time that featureNormalize.m is called, the extra column of 1’s corresponding to x0 = 1 has not yet been added to X (see ex1 multi.m for details).


You will do this for all the features and your code should work with datasets of all sizes (any number of features / examples). Note that each column of the matrix X corresponds to one feature.


   ex1_multi.m 스크립트는 데이터 셋에서 일부 값을 옥타브 프로그램으로 로드하는 것으로 시작합니다. 주택 크기의 값의 범위는 방의 개수의 값의 범위보다 약 1,000배가 큽니다. 피처 스케일링을 적용하면 경사 하강법을 훨씬 더 빠르게 수렴할 수 있습니다. 


   여기서 featureNormalization.m 파일에 코드를 작성합니다. 

•  데이터 셋에서 각 피처의 평균값을 뺍니다.

•  평균을 뺀 피처의 값에 표준 편차로 나누어 줍니다. 


   표준 편차는 피처의 값의 범위에 얼마나 많은 변화가 있는 지를 측정합니다. 대부분의 데이터는 평균을 기준으로 +2와 -2 사이의 표준 편차 내에 있습니다. 이 값의 범위 (최대값 - 최소값)를 취하는 대신 사용할 수 있습니다.  옥타브에서 std 함수는 표준 편차를 계산합니다. 예를 들어, featureNormalize.m 내부의 X(:,1) 은 주택 크기 x1 값이 모두 포함되어 있습니다. 


     std(X(:,1));  % 주택 크기의 표준 편차를 계산


   featureNormalize.m 함수를 호출할 때 x0 = 1에 해당하는 열을 추가하지 않았습니다. (상세 내용은 ex1_multi.m 파일을 참조)

 

   코드는 모든 피처에 대해 작동해야 합니다. 즉, 모든 크기의 데이터 셋에서 작동해야 합니다. 행렬 X의 각

니다. 



Implementation Note: When normalizing the features, it is important to store the values used for normalization - the mean value and the stan- dard deviation used for the computations. After learning the parameters from the model, we often want to predict the prices of houses we have not seen before. Given a new x value (living room area and number of bed- rooms), we must first normalize x using the mean and standard deviation that we had previously computed from the training set.


    구현 참고 사항 : 피처를 정규화할 때 사용하는 평균값과 표준편차를 저장하는 것이 중요합니다. 파라미터를 학습한 후 새로운 예제에 대해 주택 가격을 예측합니다. 새로운 예제가 주어지면 먼저 학습 셋에서 기존에 사용한 평균 및 표준 편차를 사용해서 정규화하기 때문입니다. 

   


<해설>

   다변수 선형 회귀의 가설과 벡터화 구현은 다음과 같습니다.


(1) 데이터 업로드 및 기본 변수 설정


clear ;             % 옥타브 프로그램에 모든 변수를 제거

close all;         % 터미널 이외의 창을 닫음

clc                   % 터미널을 깨끗이 정리 

data = load ('ex1data2.txt');  

X = data (:,1:2); 

y = data (:,3);

m = length(y);


   옥타브 프로그램에 변수들이 제대로 생성되었지를 확인합니다. 

 

>> whos


Variables in the current scope:


   Attr Name        Size              Bytes  Class

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

        X                   47x2              752  double

        data             47x3               1128  double

        m                  1x1                 8  double

        y                   47x1               376  double


Total is 283 elements using 2264 bytes


(2) 필요한 추가적인 변수를 선언하고 초기화


X_norm = X;                            % 변수 X_norm의 초기값은 원래 X 데이터 값

mu = zeros(1, size(X, 2));        % 변수 mu는 각 피처 별 평균값 0 



(3) 평균 구하기


  평균을 구하는 함수는 mean()입니다. mean 함수는 입력값에 대한 평균을 계산합니다. 


    mean (x) = SUM_i x(i) / N


   mean 함수는 입력값이 행렬일 경우 열단우로 평균을 구합니다. mean 함수에 추가적인 변수가 있습니다.


          mean(X, 'a')      % 산술 평균 (ordinary mean)

          mean(X, 'g')     %  기하평균 (geometric mean)

          mean(X, 'h').     %  조화 평균 (harmonic mean)


    물론, mean 함수를 쓰지 않을 경우 행렬을 행의 개수로 나눌 수 있습니다. 


      mu = sum(X) / length(X);


   따라서 행렬의 열 단위로 평균은 다음과 같이 구합니다.  


    mu = mean(X);          % mean(X)는 각 열 별로 평균을 반환 


(4) 표준편차 구하기


   표준 편차를 구하는 함수는 std() 함수입니다. std() 함수는 입력값에 평균을 구합니다.  


    std (x) = sqrt ( 1/(N-1) SUM_i (x(i) - mean(x))^2 )


    mean() 함수는 행렬일 경우 열 단위로 표준편차를 구합니다. 행렬의 열 단위로 표준편차는 다음과 같이 구합니다.


    sigma = std(X);         % std(X)는 각 열 별로 표준 편차를 반환  


(3) 벡터화 구현 - 피처 스케일링



>> mu = mean(X)

mu =

   2.8346e-17   3.1889e-17


>> sigma = std(X)

sigma =

   1.0000   1.0000


피처 스케일링은 다음과 같습니다.


X_norm = (X - mean(X)) ./std(X)


>> X_norm = (X - mean(X)) ./ std(X)

warning: operator -: automatic broadcasting operation applied

warning: quotient: automatic broadcasting operation applied

X_norm = 

   1.3001e-01  -2.2368e-01

  -5.0419e-01  -2.2368e-01

   5.0248e-01  -2.2368e-01

-7.3572e-01  -1.5378e+0



<정답>


(1) featureNormalize.m 파일을 열고 정답을 입력합니다. 


function [X_norm, mu, sigma] = featureNormalize(X)

%FEATURENORMALIZE 파일은 X의 피처를 정규화 

%   FEATURENORMALIZE(X) 는 다음 값을 반환 

%   X_norm   : 정규화된 X의 값  

%   mu           : 각 피처의 평균 0

%   sigma       : 표준 편차 1 

%  다음 값을 올바르게 설정하여 초기화 

X_norm = X;                            % 변수 X_norm은 원래 X 데이터 값으로 초기화

mu = zeros(1, size(X, 2));        % 변수 mu는 각 피처 별 평균값 0으로 초기화

sigma = zeros(1, size(X, 2));    % 변수 sigma는 각 피처 별 표준 편차 0으로 초기화


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

% Instructions: 

%               우선 각 피처의 평균값을 구하고 데이터 셋에서 빼라 

%               변수 mu에 평균값을 저장하라 

%               각 피처의 표준 편차를 계산하라 

%               각 피처를 표준 편차로 나누어라 

%               변수 sigma에 표준 편차를 저장하라  

%

%               변수 X의 각 열은 피처의 값이고, 각 행은 학습 예제이다.

%               각 피처에 대해 정규화 (normalization)을 실행하라  

%               

% Hint:  평균을 구하기 위해 mean 명령어를 이용하라

%           표준편차를 구하기 위해 std 명령어를 이용하라    


    mu = mean(X);          

    sigma = std(X);      


    X_norm = (X - mean(X)) ./std(X);

   


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


end


 


3.2 Gradient Descent (경사 하강법) 



Previously, you implemented gradient descent on a univariate regression problem. The only difference now is that there is one more feature in the matrix X. The hypothesis function and the batch gradient descent update rule remain unchanged.


You should complete the code in computeCostMulti.m and gradientDescentMulti.m to implement the cost function and gradient descent for linear regression with
multiple variables. If your code in the previous part (single variable) already
supports multiple variables, you can use it here too.


Make sure your code supports any number of features and is well-vectorized. You can use ‘size(X, 2)’ to find out how many features are present in the dataset.


   전에 단변수 선형 회귀 문제에 경사 하강법을 적용하였습니다. 다변수 선형 회귀 문제는 행렬 X 에 피처가 하나 더 있습니다. 가설 함수와 배치 경사 하강 업데이트 공식은 같습니다. 


    다변수 선형 회귀를 위한 비용 함수와 경사 하강법을 구현하기 위해 computeCostMulti.m 파일과 gradientDescentMulti.m 파일에 코드를 작성해야 합니다. 단변수 선형 회귀에서 사용했던 코드를 그대로 사용할 수 있습니다. 


   코드가 여러 피처를 지원하고 벡터화 구현이 잘 되었는 지를 점검하십시오. size(X,2) 명령어를 사용하여 데이터 셋에 있는 피처의 개수를 확인할 수 있습니다. 


   

Implementation Note: In the multivariate case, the cost function can also be written in the following vectorized form:

The vectorized version is efficient when you’re working with numerical computing tools like Octave/MATLAB. If you are an expert with matrix operations, you can prove to yourself that the two forms are equivalent.


   구현 참고 사항 : 다변수 선형 회귀의 비용 함수를 벡터화로 구현할 수 있습니다. 옥타브 프로그램은 벡터화된 버전이 훨씬 효율적입니다. 행렬 연산 전문가는 벡터화 구현이 기존 함수와 차이가 없다는 것을 증명합니다. 



3.2.1 Optional exercise : Selecting Learning rate (학습률 결정하기)


In this part of the exercise, you will get to try out different learning rates for the dataset and find a learning rate that converges quickly. You can change the learning rate by modifying ex1 multi.m and changing the part of the code that sets the learning rate.


The next phase in ex1 multi.m will call your gradientDescent.m func- tion and run gradient descent for about 50 iterations at the chosen learning rate. The function should also return the history of J(θ) values in a vector J. After the last iteration, the ex1 multi.m script plots the J values against the number of the iterations.


If you picked a learning rate within a good range, your plot look similar Figure 4. If your graph looks very different, especially if your value of J(θ) increases or even blows up, adjust your learning rate and try again. We rec- ommend trying values of the learning rate α on a log-scale, at multiplicative steps of about 3 times the previous value (i.e., 0.3, 0.1, 0.03, 0.01 and so on). You may also want to adjust the number of iterations you are running if that will help you see the overall trend in the curve.



   이번 실습은 데이터 셋에 다양한 학습률을 시도하고 빠르게 수렴하는 학습률을 찾습니다. ex1_multi.m 파일을 수정하고 학습률을 설정하는 코드 부분을 변경하여 학습률을 변경할 수 있습니다. 


   ex1_multi.m 파일의 다음 단계는 gradientDescent.m 함수를 호출하고 선택한 학습률로 약 50회를 반복하는 동안 경사 하강을 실행합니다. 비용 함수 J(θ)의 값을 반환합니다. 마지막 반복 후  ex1_multi.m 파일 스크립트는 반복회수에 대한 비용 함수 J(θ)를 도식화합니다. 


   괜찮은 범위 내에 학습률을 선택하면 그래프가 지속적으로 하강하는 그래프가 될 것입니다. 그래프가 매우 다르게 보인다면 J(θ) 값이 증가할 때는 학습률을 조정해야 합니다. 학습률 α의 값을 이전 값의 약 3배(0.3, 0.1, 0.03, 0.01 등)의 곱셈 단계에서 로그 스케일로 시도합니다. 곡선 전체의 추세를 확인하는 것에 도움이 된다면 반복 횟수를 조정할 수 있습니다.



Implementation Note: If your learning rate is too large, J(θ) can di- verge and ‘blow up’, resulting in values which are too large for computer calculations. In these situations, Octave/MATLAB will tend to return NaNs. NaN stands for ‘not a number’ and is often caused by undefined operations that involve −∞ and +∞.


   구현 참고 사항 : 학습률 α 가 너무 크면 비용 함수 J(θ)가 폭발적으로 증가하여 컴퓨터 계산이 힘들 수 있습니다. 이럴 때 옥타브 프로그램은 NaN (Not a number, 숫자가 아님) 값을 반환합니다. 종종 -∞ 와 +∞를 포함하는 정 되지 않은 연산을 수행하려다가 발생합니다. 



Octave/MATLAB Tip: To compare how different learning learning rates affect convergence, it’s helpful to plot J for several learning rates on the same figure. In Octave/MATLAB, this can be done by perform- ing gradient descent multiple times with a ‘hold on’ command between plots. Concretely, if you’ve tried three different values of alpha (you should probably try more values than this) and stored the costs in J1, J2 and J3, you can use the following commands to plot them on the same figure:

              plot(1:50, J1(1:50), ‘b’);  
              hold on;
               plot(1:50, J2(1:50), ‘r’);   
               plot(1:50, J3(1:50), ‘k’); 

The final arguments ‘b’, ‘r’, and ‘k’ specify different colors for the plots.

 

   옥타브 프로그램 팁 : 다양한 학습률 α가 비용 함수 J(θ)가 수렴하는 것에 어떤 영향을 미치는 지를 확인하기 위해 동일한 그림에서 여러 학습률에 대한 비용 함수 J(θ)를 같이 표시하는 것이 좋습니다. 옥타브 프로그램에서 'hold on' 명령은 한 그림 창에 그래프를 같이 그려줍니다. 세 가지 그림을 한 도표에 그릴 때 다음과 같이 합니다. 


      plot(1:50, J1(1:50), ‘b’);  

      hold on;

       plot(1:50, J2(1:50), ‘r’);   

       plot(1:50, J3(1:50), ‘k’); 

   

   

Notice the changes in the convergence curves as the learning rate changes. With a small learning rate, you should find that gradient descent takes a very long time to converge to the optimal value. Conversely, with a large learning rate, gradient descent might not converge or might even diverge!


Using the best learning rate that you found, run the ex1 multi.m script to run gradient descent until convergence to find the final values of θ. Next, use this value of θ to predict the price of a house with 1650 square feet and 3 bedrooms. You will use value later to check your implementation of the normal equations. Don’t forget to normalize your features when you make this prediction!


   학습률 α가 변경에 따라 수렴 곡선의 변화를 확인합니다. 학습률 α가 작으면 경사 하강법이 최적 값으로 수렴하는 데 매우 오랜 시간이 걸립니다. 반대로 학습률 α가 크면 경사 하강법은 수렴하지 않거나 증가할 수도 있습니다. 


   최적의 학습률을 ex1_multi.m 스크립트에서 실행하여 수렴할 때까지 경사 하강 알고리즘을 실행하여 최적의 파라미터 θ값을 찾습니다. 다음으로 파라미터 벡터 θ를 사용하여 주택 크기 1,650 평방피트와 방의 개수가 3개인 집값의 가격을 예측합니다. 나중에 정규 방정식을 구현하여 확인합니다. 예측을 할 때 피처 스케일을 잊지 마십시오



<해설>


다변수 선형 회귀의 가설, 비용 함수, 경사 하강법 알고리즘입니다. 


(1) 행렬 X에 x0를 추가 


% X에 인터셉트 항을 추가 

X = [ones(m, 1) X];    


 행렬 X는 47 X2 차원 행렬입니다. 피처 x0는 항상 1입니다. x0를 삽입하여   47 X3 차원 행렬을 만듭니다. 


>> size (X)

ans =

   47    2


>> m

m =  47


>> X = [ones(m,1),X]

X =


      1   2104      3

      1   1600      3

      1   2400      3

      1   1416      2

      1   3000      4

      1   1985      4




(2) ComputeCostMulti.m 파일을 열고 비용 함수 계산 


function J = computeCostMulti(X, y, theta)

% COMPUTECOSTMULTI 는 다변수 선형 회귀의 비용을 계산 

%   J = COMPUTECOSTMULTI(X, y, theta)는 데이터 X와 y에 대한 선형 회귀에 적용하는  

%                파라미터 theta의 비용을 계산 


% 변수를 초기화 

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


%  비용 함수 J의 값을 초기화

J = 0;


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

% Instructions: theta의 값을 선택했을 때 비용을 구하라 

%                        비용 함수 J의 식을 적으세요 



J = 1/(2*m) *(X * theta - y)'*(X * theta- y)    % 단변수 선형 회귀의 비용 함수와 동일



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


end

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




(3) gradientDescentMulti.m 파일을 열고 비용 함수 계산 




function [theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters)

%   GRADIENTDESCENT 파일은 최적의 파라미터 θ 값을 학습  

%   theta = GradientDescentMulti(X, y, theta, alpha, num_iters)는

%  변수 alpha는 학습률, num_iters는 경사 하강 알고리즘 반복 회수, theta는 동시 업데이트 


% 변수 초기화

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

J_history = zeros(num_iters, 1);  % 경사 하강을 반복할 때마다 비용 함수 값을 저장

                                                      % 기본 값으로 0으로 저장 

for iter = 1:num_iters                   % For 루프를 num_iters 만큼 반복 


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

    % Instructions: Perform a single gradient step on the parameter vector

    %               theta. 

    %

    % Hint: While debugging, it can be useful to print out the values

    %       of the cost function (computeCostMulti) and gradient here.

    %

   

        Delta = 1/m * (X'*(X*theta - y));

        theta = theta - alpha*Delta;


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


    % 매 반복마다 비용 함수 값을 저장     

    J_history(iter) = computeCostMulti(X, y, theta);


end


end



단변수 선형 회귀의 경사 하강을 계산할 때  For 루프를 이용했습니다. 


     Update = 0;

     For i =1:m;

           Update = Update + alpha/m*(X(i,:)*theta - y(i))*X(i,:)';

      end


       theta = theta - Update;


여기서는 벡터화 구현으로 정리합니다.  경사 하강법을 벡터와 구현하기 위한 식은 다음과 같습니다.




여기서 델타 (δ)를 다음과 같이 적을 수 있습니다. 

  

  Delta = 1/m * (X'*(X*theta - y));


가설 h(x)를 구하는 식은 다음과 같이 둘 중에 하나를 쓸 수 있습니다.


    theta' * X'        % 전치 행렬 theta'은 1 X 3 행렬. 전치 행렬 X'은 3 X 47 행렬

    X * theta   % X는 47 X 3 행렬. theta는 3 X 1 벡터는 열 벡터


여기서,  ((X* theta - y)와 행렬 X를 곱해야 합니다. (X * theta - y)는 47 X 1 행렬이고 행렬 X는 47 X 3 행렬입니다. 앞의 행렬을 전치시키면 서로 곱셈을 하여 1 X 3 행렬을 만들 수 있습니다.



>>  ( X' (X* theta - y))

ans =

  -1.5999e+07  -3.5918e+10  -5.2657e+07


   파라미터 벡터 theta 가 1 X 3차원 열 벡터이므로 계산의 편리성을 위해 전체 값을 전치합니다. 이렇게 delta 값을 구합니다. 


  Delta = 1/m * (X'*(X*theta - y));


  그리고, theta의 값을 업데이트합니다.

 

        Delta = 1/m * (X'*(X*theta - y));

        theta = theta - alpha*Delta;



(4) ex1_multi.m 파일의 Part2: Grdient Descent을 실행



%% ================ Part 2: Gradient Descent ================


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

% Instructions: 

%               특정 학습률 alpha를 가진 경사 하강 알고리즘을 실행하는 코드를 제공

%              

%               다변수 선형 회귀를 지원하는 CompuCost와 gradientDescent 

%               함수는 이미 정의되었으므로 확인 

%               

%               학습률 alpha를 변경하면서 경사 하강 알고리즘을 실행 

%               최고의 결과를 나타내는 학습률 alpha를 확인 

%               

%              마지막으로 1,650 평방피트와 방 3개가 있는 주택의 가격을 예측하라

%            

%

% Hint:  hold on 명령어를 사용하면 한 그림 창에서 다수의 그래프를 볼 수 있음 

% Hint:  예측을 시도할 때 피처 정규화를 하시오 

%


fprintf('Running gradient descent...\n');


% 학습률 alpha와 경사 하강 업데이트 반복 회수를 초기화 

alpha = 0.01;

num_iters = 400;


% 변수 Theta를 0으로 초기화하고 gradientDescentMulti() 함수 호출  

theta = zeros(3, 1);

[theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters);


% 반복 회수에 따른 경사 하강 그래프 작성

figure;

plot(1:numel(J_history), J_history, '-b', 'LineWidth', 2);

xlabel('Number of iterations');

ylabel('Cost J');


% 경사 하강 결과 표시 

fprintf('Theta computed from gradient descent: \n');

fprintf(' %f \n', theta);

fprintf('\n');


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


(5) 결과 확인



>> ex1_multi

Loading data ...

First 10 examples from the dataset:

 x = [2104 3], y = 399900

 x = [1600 3], y = 329900

 x = [2400 3], y = 369000

 x = [1416 2], y = 232000

 x = [3000 4], y = 539900

 x = [1985 4], y = 299900

 x = [1534 3], y = 314900

 x = [1427 3], y = 198999

 x = [1380 3], y = 212000

 x = [1494 3], y = 242500

Program paused. Press enter to continue.

Normalizing Features ...

Running gradient descent ...

J =    6.4301e+10

J =    6.3037e+10

J =    6.1799e+10

J =    6.0587e+10

J =    5.9400e+10

J =    5.8238e+10

J =    5.7100e+10

...

Theta computed from gradient descent:

 312819.314507

 89586.814703

 12174.034349




(6) 각 학습률 alpha에 따른 비용 함수 그래프


   학습률 alpha의 값이 변함에 따라 수렴하는 곡선의 변화를 확인합니다. 학습률 alpha가 작을수록 경사 하강 업데이트 알고리즘은 최소값에 느리게 수렴하고, 학습률 alpha가 클수록 최소값에 빠르게 수렵합니다. 예를 들면, 그림의 맨 위의 직선은 학습률 alpha의 값은 0.01이고 100번을 반복해도 최소값에 수렴하지 못했지만, 그림의 맨 아래의 점선은 학습률 alpha의 값은 0.3이고 10번의 반복 만에 최소값에 수렴합니다. 



alpha = 0.01;

num_iters = 100; 

theta = zeros(3, 1);

[theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters); 

figure;

plot(1:numel(J_history), J_history, '-b', 'LineWidth', 2);

xlabel('Number of iterations');

ylabel('Cost J');


alpha = 0.03; 

theta = zeros(3, 1);

[theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters); 

hold on

plot(1:numel(J_history), J_history, '-b', 'LineWidth', 2,'linestyle','--');


alpha = 0.1; 

theta = zeros(3, 1);

[theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters); 

plot(1:numel(J_history), J_history, '-b', 'LineWidth', 2,'linestyle','-.');


alpha = 0.3; 

theta = zeros(3, 1);

[theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters); 

plot(1:numel(J_history), J_history, '-b', 'LineWidth', 2,'linestyle',':')



   학습률이 3일 때 비용 함수 그래프는 상승합니다. 



(6) 신규 데이터 주택 크기 1650과 방의 개수 3일 때 가격을 예측하기



%% ================ Part 2: Gradient Descent ================

%  1650 평방피트와 방 3일 때 판매 가격 예측 

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

% 행렬 X의 첫 열은 항상 1이다. 정규화가 필요가 없다. 


new_data = [1650 3];


for i = 1:size(new_data,2)

   new_data(i) = (new_data(i) - mu(i)) / sigma(i);

end 


new_data = [1 new_data];

price = new_data*theta;


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


fprintf(['Predicted price of a 1650 sq-ft, 3 br house ' ...

         '(using gradient descent):\n $%f\n'], price);


fprintf('Program paused. Press enter to continue.\n');

pause;


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



<결과>


>> ex1_multi


Theta computed from gradient descent:

 334302.063993

 100087.116006

 3673.548451


Predicted price of a 1650 sq-ft, 3 br house (using gradient descent):

 $289314.620338



3.3 Normal Equations (정규 방정식)



In the lecture videos, you learned that the closed-form solution to linear regression is


    


Using this formula does not require any feature scaling, and you will get an exact solution in one calculation: there is no “loop until convergence” like in gradient descent.


Complete the code in normalEqn.m to use the formula above to calcu- late θ. Remember that while you don’t need to scale your features, we still need to add a column of 1’s to the X matrix to have an intercept term (θ0). The code in ex1.m will add the column of 1’s to X for you.


 강의에서 선형 회귀에 대한 정규 방정식이 있습니다. 정규 방정식 공식은 피처 스케일링 없이 한 번의 계산으로 정확한 파라미터 θ의 값을 얻을 수 있습니다. 경사 하강법도 필요 없습니다.


   정규 방정식 공식을 사용하여 계산하려면 normalEqun.m의 코드를 작성하십시오. 피처를 확장할 필요는 없지만, 인터셉트 항 θ0 가 필요하면 추가할 수 있습니다. ex1.m에서 열을 추가힙니다.



<정답>


(1) normalEqun.m 파일을 열고 정규 방정식 공식 입력


function [theta] = normalEqn(X, y)

%NORMALEQN 은 선형 회귀에 대한 정규 방정식을 계산  

%   NORMALEQN(X,y) 정규 방정식으로 선형 회귀에서 파라미터 값을 찾음  


theta = zeros(size(X, 2), 1);


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

% Instructions: Complete the code to compute the closed form solution

%               to linear regression and put the result in theta.

%


% ---------------------- Sample Solution ----------------------



   theta = pinv((X'* X))*X'*y


% -------------------------------------------------------------



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


end



(2) 신규 데이터 주택 크기 1650과 방의 개수 3일 때 가격을 예측하기



%% ================ Part 2: Gradient Descent ================

%  1650 평방피트와 방 3일 때 판매 가격 예측 

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

% 행렬 X의 첫 열은 항상 1이다. 정규화가 필요가 없다. 


     price = 0;  이 값을 변경

     predict_data  = [ 1 1650 3];   % 신규 데이터 정의

     price = predict_data * theta;


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


fprintf(['Predicted price of a 1650 sq-ft, 3 br house ' ...

         '(using gradient descent):\n $%f\n'], price);


fprintf('Program paused. Press enter to continue.\n');

pause;


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



<결과 >



>> ex1_multi


Solving with normal equations...

theta =


   8.9598e+04

   1.3921e+02

  -8.7380e+03


Theta computed from the normal equations:

 89597.909542

 139.210674

 -8738.019112


Predicted price of a 1650 sq-ft, 3 br house (using normal equations):

 $293081.464335



정리하며


  최종 점수를 확인합니다. 


>> submit




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