Linear Regression with Octave

2019. 1. 31. 19:25Artificial Intelligence

* 업로드한 사진의 모든 저작권은 COURSERA에 있음을 미리 밝힙니다


이번 시간에는 Week1, Week2 를 마치고 그동안 배웠던 내용들을 Octave 코드로 표현하여 프로그램을 실행하는 과제를 수행하였다.

과제에서 Octave Programming을 통해서 제출해야 하는 내용은 다음과 같다.



%% Machine Learning Online Class - Exercise 1: Linear Regression


%  Instructions

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

%

%  This file contains code that helps you get started on the

%  linear exercise. You will need to complete the following functions

%  in this exericse:

%

%     warmUpExercise.m

%     plotData.m

%     gradientDescent.m

%     computeCost.m

%     gradientDescentMulti.m

%     computeCostMulti.m

%     featureNormalize.m

%     normalEqn.m

%

%  For this exercise, you will not need to change any code in this file,

%  or any other files other than those mentioned above.

%

% x refers to the population size in 10,000s

% y refers to the profit in $10,000s

%


1. warmUpExercise .m

이 과제는 Octave를 설치해서 실행할 줄 아는지를 묻는 아주 간단한 문제였다. 

Octave 에서 A = eye(5) 명령어를 실행하면 5 * 5 크기의 단위행렬을 A에 저장하게 된다.

즉 5*5 단위행렬을 warmUpExercise() 함수가 실행되었을 때 반환하면 되는 것이다.


function A = warmUpExercise()

%WARMUPEXERCISE Example function in octave

%   A = WARMUPEXERCISE() is an example function that returns the 5x5 identity matrix



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

% Instructions: Return the 5x5 identity matrix 

%               In octave, we return values by defining which variables

%               represent the return values (at the top of the file)

%               and then set them accordingly. 





A = eye(5);



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



end



2. plotData.m

Octave 는 GUI를 통해 데이터를 시각화하는 기능을 제공한다. 

plot(x, y, 'rx', 'MarkerSize', 10);이 함수는 x의 데이터를 가로축으로, y의 데이터를 세로축으로 그래프 위에 표현해 주며

'rx', ;MarkerSize' 는 데이터를 빨간색으로 10만큼의 크기를 갖도록 표현하라는 의미이다.

xlabel, ylabel 함수는 x축의 이름, y축의 이름을 지정하는 역할을 한다.



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);



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

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

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



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


end



3. gradientDescent.m, computeCost.m

각각 선형 보간법과 비용함수를 계산하여 리턴하도록 만드는 함수이다.


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

%GRADIENTDESCENT Performs gradient descent to learn theta

%   theta = GRADIENTDESCENT(X, y, theta, alpha, num_iters) updates theta by 

%   taking num_iters gradient steps with learning rate alpha


% Initialize some useful values

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

J_history = zeros(num_iters, 1);


for iter = 1: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 (computeCost) and gradient here.

    %


h = X * theta;

error = alpha * (1/m) * sum((h-y) .* X)';

theta -= error;


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


    % Save the cost J in every iteration    

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


end


end


먼저 gradientDescent 함수의 경우 가설함수 h를 먼저 구해야 하기 때문에 X * theta 값을 통해 선형대수학적으로 값을 구한다.

그 다음 알파값과, 1/m, 그리고 비용함수를 미분한 값에 element-wise하게 X행렬을 곱해 편차들에 x값을 각각 곱해준다.

그리고 그 error값만큼 theta값에서 빼주면 된다.


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.



h = X * theta;

squaredErrors = (h-y).^2;

J = (1/(2*m)) * sum(squaredErrors);


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


end


computeCost는 비용함수를 구하는 함수이기 때문에 마찬가지로 먼저 가설함수를 구하고, 

가설함수에 y를 뺀 값을 각각 제곱하고 J함수를 구하는 식을 넣어서 구해주면 된다.

벡터와 선형대수를 이용해 모든 과정이 진행되기 때문에 Multiple variables를 갖는 경우에도 동일하게 구현할 수 있다.


4. featureNormalize() 

featureNormalize 함수는 gradient Descent 방법을 통해 theta 벡터를 구할 때, 파라미터들의 범위가 너무 다르면 계산하는데 오랜 시간이 걸릴 뿐더러 효율성이 떨어진다는 단점이 있기 때문에 각각의 파라미터들의 범위를 비슷한 범위로 바꾸어주기 위해 사용하는 함수이다.

실제로 이 featureNormalize함수를 실행한 후에 gradientDescent 함수를 실행하면, 조금 더 빠르게 결과값을 도출해 낼 수 있다.


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

%FEATURENORMALIZE Normalizes the features in X 

%   FEATURENORMALIZE(X) returns a normalized version of X where

%   the mean value of each feature is 0 and the standard deviation

%   is 1. This is often a good preprocessing step to do when

%   working with learning algorithms.


% You need to set these values correctly

X_norm = X;

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

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


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

% Instructions: First, for each feature dimension, compute the mean

%               of the feature and subtract it from the dataset,

%               storing the mean value in mu. Next, compute the 

%               standard deviation of each feature and divide

%               each feature by it's standard deviation, storing

%               the standard deviation in sigma. 

%

%               Note that X is a matrix where each column is a 

%               feature and each row is an example. You need 

%               to perform the normalization separately for 

%               each feature. 

%

% Hint: You might find the 'mean' and 'std' functions useful.

%       


mu = mean(X);

sigma = std(X)

X_norm = (X-mu) ./ sigma;

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


end



5. normalEqn.m

말 그래도 gradientDescent 함수처럼 동일한 알고리즘을 여러 번 반복적으로 수행하면서 theta값을 찾아가는 것이 아니라 

선형대수학, 즉 역행렬의 성질을 이용하여 단숨에 theta벡터를 찾아버리는 함수이다.

단, 데이터의 개수가 10만개를 넘어가면 그때부터는 시간이 굉장히 오래 소요될 수 있으니 gradient Descent와 잘 섞어서 사용해야 한다.


function [theta] = normalEqn(X, y)

%NORMALEQN Computes the closed-form solution to linear regression 

%   NORMALEQN(X,y) computes the closed-form solution to linear 

%   regression using the normal equations.


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









반응형