1
0
Fork 0

Add programming exercise 5

master
neingeist 10 years ago
parent eccdcc0d81
commit d93d111106

Binary file not shown.

@ -0,0 +1,220 @@
%% Machine Learning Online Class
% Exercise 5 | Regularized Linear Regression and Bias-Variance
%
% Instructions
% ------------
%
% This file contains code that helps you get started on the
% exercise. You will need to complete the following functions:
%
% linearRegCostFunction.m
% learningCurve.m
% validationCurve.m
%
% For this exercise, you will not need to change any code in this file,
% or any other files other than those mentioned above.
%
%% Initialization
clear ; close all; clc
%% =========== Part 1: Loading and Visualizing Data =============
% We start the exercise by first loading and visualizing the dataset.
% The following code will load the dataset into your environment and plot
% the data.
%
% Load Training Data
fprintf('Loading and Visualizing Data ...\n')
% Load from ex5data1:
% You will have X, y, Xval, yval, Xtest, ytest in your environment
load ('ex5data1.mat');
% m = Number of examples
m = size(X, 1);
% Plot training data
plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);
xlabel('Change in water level (x)');
ylabel('Water flowing out of the dam (y)');
fprintf('Program paused. Press enter to continue.\n');
pause;
%% =========== Part 2: Regularized Linear Regression Cost =============
% You should now implement the cost function for regularized linear
% regression.
%
theta = [1 ; 1];
J = linearRegCostFunction([ones(m, 1) X], y, theta, 1);
fprintf(['Cost at theta = [1 ; 1]: %f '...
'\n(this value should be about 303.993192)\n'], J);
fprintf('Program paused. Press enter to continue.\n');
pause;
%% =========== Part 3: Regularized Linear Regression Gradient =============
% You should now implement the gradient for regularized linear
% regression.
%
theta = [1 ; 1];
[J, grad] = linearRegCostFunction([ones(m, 1) X], y, theta, 1);
fprintf(['Gradient at theta = [1 ; 1]: [%f; %f] '...
'\n(this value should be about [-15.303016; 598.250744])\n'], ...
grad(1), grad(2));
fprintf('Program paused. Press enter to continue.\n');
pause;
%% =========== Part 4: Train Linear Regression =============
% Once you have implemented the cost and gradient correctly, the
% trainLinearReg function will use your cost function to train
% regularized linear regression.
%
% Write Up Note: The data is non-linear, so this will not give a great
% fit.
%
% Train linear regression with lambda = 0
lambda = 0;
[theta] = trainLinearReg([ones(m, 1) X], y, lambda);
% Plot fit over the data
plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);
xlabel('Change in water level (x)');
ylabel('Water flowing out of the dam (y)');
hold on;
plot(X, [ones(m, 1) X]*theta, '--', 'LineWidth', 2)
hold off;
fprintf('Program paused. Press enter to continue.\n');
pause;
%% =========== Part 5: Learning Curve for Linear Regression =============
% Next, you should implement the learningCurve function.
%
% Write Up Note: Since the model is underfitting the data, we expect to
% see a graph with "high bias" -- slide 8 in ML-advice.pdf
%
lambda = 0;
[error_train, error_val] = ...
learningCurve([ones(m, 1) X], y, ...
[ones(size(Xval, 1), 1) Xval], yval, ...
lambda);
plot(1:m, error_train, 1:m, error_val);
title('Learning curve for linear regression')
legend('Train', 'Cross Validation')
xlabel('Number of training examples')
ylabel('Error')
axis([0 13 0 150])
fprintf('# Training Examples\tTrain Error\tCross Validation Error\n');
for i = 1:m
fprintf(' \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i));
end
fprintf('Program paused. Press enter to continue.\n');
pause;
%% =========== Part 6: Feature Mapping for Polynomial Regression =============
% One solution to this is to use polynomial regression. You should now
% complete polyFeatures to map each example into its powers
%
p = 8;
% Map X onto Polynomial Features and Normalize
X_poly = polyFeatures(X, p);
[X_poly, mu, sigma] = featureNormalize(X_poly); % Normalize
X_poly = [ones(m, 1), X_poly]; % Add Ones
% Map X_poly_test and normalize (using mu and sigma)
X_poly_test = polyFeatures(Xtest, p);
X_poly_test = bsxfun(@minus, X_poly_test, mu);
X_poly_test = bsxfun(@rdivide, X_poly_test, sigma);
X_poly_test = [ones(size(X_poly_test, 1), 1), X_poly_test]; % Add Ones
% Map X_poly_val and normalize (using mu and sigma)
X_poly_val = polyFeatures(Xval, p);
X_poly_val = bsxfun(@minus, X_poly_val, mu);
X_poly_val = bsxfun(@rdivide, X_poly_val, sigma);
X_poly_val = [ones(size(X_poly_val, 1), 1), X_poly_val]; % Add Ones
fprintf('Normalized Training Example 1:\n');
fprintf(' %f \n', X_poly(1, :));
fprintf('\nProgram paused. Press enter to continue.\n');
pause;
%% =========== Part 7: Learning Curve for Polynomial Regression =============
% Now, you will get to experiment with polynomial regression with multiple
% values of lambda. The code below runs polynomial regression with
% lambda = 0. You should try running the code with different values of
% lambda to see how the fit and learning curve change.
%
lambda = 0;
[theta] = trainLinearReg(X_poly, y, lambda);
% Plot training data and fit
figure(1);
plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);
plotFit(min(X), max(X), mu, sigma, theta, p);
xlabel('Change in water level (x)');
ylabel('Water flowing out of the dam (y)');
title (sprintf('Polynomial Regression Fit (lambda = %f)', lambda));
figure(2);
[error_train, error_val] = ...
learningCurve(X_poly, y, X_poly_val, yval, lambda);
plot(1:m, error_train, 1:m, error_val);
title(sprintf('Polynomial Regression Learning Curve (lambda = %f)', lambda));
xlabel('Number of training examples')
ylabel('Error')
axis([0 13 0 100])
legend('Train', 'Cross Validation')
fprintf('Polynomial Regression (lambda = %f)\n\n', lambda);
fprintf('# Training Examples\tTrain Error\tCross Validation Error\n');
for i = 1:m
fprintf(' \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i));
end
fprintf('Program paused. Press enter to continue.\n');
pause;
%% =========== Part 8: Validation for Selecting Lambda =============
% You will now implement validationCurve to test various values of
% lambda on a validation set. You will then use this to select the
% "best" lambda value.
%
[lambda_vec, error_train, error_val] = ...
validationCurve(X_poly, y, X_poly_val, yval);
close all;
plot(lambda_vec, error_train, lambda_vec, error_val);
legend('Train', 'Cross Validation');
xlabel('lambda');
ylabel('Error');
fprintf('lambda\t\tTrain Error\tValidation Error\n');
for i = 1:length(lambda_vec)
fprintf(' %f\t%f\t%f\n', ...
lambda_vec(i), error_train(i), error_val(i));
end
fprintf('Program paused. Press enter to continue.\n');
pause;

Binary file not shown.

@ -0,0 +1,17 @@
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.
mu = mean(X);
X_norm = bsxfun(@minus, X, mu);
sigma = std(X_norm);
X_norm = bsxfun(@rdivide, X_norm, sigma);
% ============================================================
end

@ -0,0 +1,175 @@
function [X, fX, i] = fmincg(f, X, options, P1, P2, P3, P4, P5)
% Minimize a continuous differentialble multivariate function. Starting point
% is given by "X" (D by 1), and the function named in the string "f", must
% return a function value and a vector of partial derivatives. The Polack-
% Ribiere flavour of conjugate gradients is used to compute search directions,
% and a line search using quadratic and cubic polynomial approximations and the
% Wolfe-Powell stopping criteria is used together with the slope ratio method
% for guessing initial step sizes. Additionally a bunch of checks are made to
% make sure that exploration is taking place and that extrapolation will not
% be unboundedly large. The "length" gives the length of the run: if it is
% positive, it gives the maximum number of line searches, if negative its
% absolute gives the maximum allowed number of function evaluations. You can
% (optionally) give "length" a second component, which will indicate the
% reduction in function value to be expected in the first line-search (defaults
% to 1.0). The function returns when either its length is up, or if no further
% progress can be made (ie, we are at a minimum, or so close that due to
% numerical problems, we cannot get any closer). If the function terminates
% within a few iterations, it could be an indication that the function value
% and derivatives are not consistent (ie, there may be a bug in the
% implementation of your "f" function). The function returns the found
% solution "X", a vector of function values "fX" indicating the progress made
% and "i" the number of iterations (line searches or function evaluations,
% depending on the sign of "length") used.
%
% Usage: [X, fX, i] = fmincg(f, X, options, P1, P2, P3, P4, P5)
%
% See also: checkgrad
%
% Copyright (C) 2001 and 2002 by Carl Edward Rasmussen. Date 2002-02-13
%
%
% (C) Copyright 1999, 2000 & 2001, Carl Edward Rasmussen
%
% Permission is granted for anyone to copy, use, or modify these
% programs and accompanying documents for purposes of research or
% education, provided this copyright notice is retained, and note is
% made of any changes that have been made.
%
% These programs and documents are distributed without any warranty,
% express or implied. As the programs were written for research
% purposes only, they have not been tested to the degree that would be
% advisable in any important application. All use of these programs is
% entirely at the user's own risk.
%
% [ml-class] Changes Made:
% 1) Function name and argument specifications
% 2) Output display
%
% Read options
if exist('options', 'var') && ~isempty(options) && isfield(options, 'MaxIter')
length = options.MaxIter;
else
length = 100;
end
RHO = 0.01; % a bunch of constants for line searches
SIG = 0.5; % RHO and SIG are the constants in the Wolfe-Powell conditions
INT = 0.1; % don't reevaluate within 0.1 of the limit of the current bracket
EXT = 3.0; % extrapolate maximum 3 times the current bracket
MAX = 20; % max 20 function evaluations per line search
RATIO = 100; % maximum allowed slope ratio
argstr = ['feval(f, X']; % compose string used to call function
for i = 1:(nargin - 3)
argstr = [argstr, ',P', int2str(i)];
end
argstr = [argstr, ')'];
if max(size(length)) == 2, red=length(2); length=length(1); else red=1; end
S=['Iteration '];
i = 0; % zero the run length counter
ls_failed = 0; % no previous line search has failed
fX = [];
[f1 df1] = eval(argstr); % get function value and gradient
i = i + (length<0); % count epochs?!
s = -df1; % search direction is steepest
d1 = -s'*s; % this is the slope
z1 = red/(1-d1); % initial step is red/(|s|+1)
while i < abs(length) % while not finished
i = i + (length>0); % count iterations?!
X0 = X; f0 = f1; df0 = df1; % make a copy of current values
X = X + z1*s; % begin line search
[f2 df2] = eval(argstr);
i = i + (length<0); % count epochs?!
d2 = df2'*s;
f3 = f1; d3 = d1; z3 = -z1; % initialize point 3 equal to point 1
if length>0, M = MAX; else M = min(MAX, -length-i); end
success = 0; limit = -1; % initialize quanteties
while 1
while ((f2 > f1+z1*RHO*d1) | (d2 > -SIG*d1)) & (M > 0)
limit = z1; % tighten the bracket
if f2 > f1
z2 = z3 - (0.5*d3*z3*z3)/(d3*z3+f2-f3); % quadratic fit
else
A = 6*(f2-f3)/z3+3*(d2+d3); % cubic fit
B = 3*(f3-f2)-z3*(d3+2*d2);
z2 = (sqrt(B*B-A*d2*z3*z3)-B)/A; % numerical error possible - ok!
end
if isnan(z2) | isinf(z2)
z2 = z3/2; % if we had a numerical problem then bisect
end
z2 = max(min(z2, INT*z3),(1-INT)*z3); % don't accept too close to limits
z1 = z1 + z2; % update the step
X = X + z2*s;
[f2 df2] = eval(argstr);
M = M - 1; i = i + (length<0); % count epochs?!
d2 = df2'*s;
z3 = z3-z2; % z3 is now relative to the location of z2
end
if f2 > f1+z1*RHO*d1 | d2 > -SIG*d1
break; % this is a failure
elseif d2 > SIG*d1
success = 1; break; % success
elseif M == 0
break; % failure
end
A = 6*(f2-f3)/z3+3*(d2+d3); % make cubic extrapolation
B = 3*(f3-f2)-z3*(d3+2*d2);
z2 = -d2*z3*z3/(B+sqrt(B*B-A*d2*z3*z3)); % num. error possible - ok!
if ~isreal(z2) | isnan(z2) | isinf(z2) | z2 < 0 % num prob or wrong sign?
if limit < -0.5 % if we have no upper limit
z2 = z1 * (EXT-1); % the extrapolate the maximum amount
else
z2 = (limit-z1)/2; % otherwise bisect
end
elseif (limit > -0.5) & (z2+z1 > limit) % extraplation beyond max?
z2 = (limit-z1)/2; % bisect
elseif (limit < -0.5) & (z2+z1 > z1*EXT) % extrapolation beyond limit
z2 = z1*(EXT-1.0); % set to extrapolation limit
elseif z2 < -z3*INT
z2 = -z3*INT;
elseif (limit > -0.5) & (z2 < (limit-z1)*(1.0-INT)) % too close to limit?
z2 = (limit-z1)*(1.0-INT);
end
f3 = f2; d3 = d2; z3 = -z2; % set point 3 equal to point 2
z1 = z1 + z2; X = X + z2*s; % update current estimates
[f2 df2] = eval(argstr);
M = M - 1; i = i + (length<0); % count epochs?!
d2 = df2'*s;
end % end of line search
if success % if line search succeeded
f1 = f2; fX = [fX' f1]';
fprintf('%s %4i | Cost: %4.6e\r', S, i, f1);
s = (df2'*df2-df1'*df2)/(df1'*df1)*s - df2; % Polack-Ribiere direction
tmp = df1; df1 = df2; df2 = tmp; % swap derivatives
d2 = df1'*s;
if d2 > 0 % new slope must be negative
s = -df1; % otherwise use steepest direction
d2 = -s'*s;
end
z1 = z1 * min(RATIO, d1/(d2-realmin)); % slope ratio but max RATIO
d1 = d2;
ls_failed = 0; % this line search did not fail
else
X = X0; f1 = f0; df1 = df0; % restore point from before failed line search
if ls_failed | i > abs(length) % line search failed twice in a row
break; % or we ran out of time, so we give up
end
tmp = df1; df1 = df2; df2 = tmp; % swap derivatives
s = -df1; % try steepest
d1 = -s'*s;
z1 = 1/(1-d1);
ls_failed = 1; % this line search failed
end
if exist('OCTAVE_VERSION')
fflush(stdout);
end
end
fprintf('\n');

@ -0,0 +1,66 @@
function [error_train, error_val] = ...
learningCurve(X, y, Xval, yval, lambda)
%LEARNINGCURVE Generates the train and cross validation set errors needed
%to plot a learning curve
% [error_train, error_val] = ...
% LEARNINGCURVE(X, y, Xval, yval, lambda) returns the train and
% cross validation set errors for a learning curve. In particular,
% it returns two vectors of the same length - error_train and
% error_val. Then, error_train(i) contains the training error for
% i examples (and similarly for error_val(i)).
%
% In this function, you will compute the train and test errors for
% dataset sizes from 1 up to m. In practice, when working with larger
% datasets, you might want to do this in larger intervals.
%
% Number of training examples
m = size(X, 1);
% You need to return these values correctly
error_train = zeros(m, 1);
error_val = zeros(m, 1);
% ====================== YOUR CODE HERE ======================
% Instructions: Fill in this function to return training errors in
% error_train and the cross validation errors in error_val.
% i.e., error_train(i) and
% error_val(i) should give you the errors
% obtained after training on i examples.
%
% Note: You should evaluate the training error on the first i training
% examples (i.e., X(1:i, :) and y(1:i)).
%
% For the cross-validation error, you should instead evaluate on
% the _entire_ cross validation set (Xval and yval).
%
% Note: If you are using your cost function (linearRegCostFunction)
% to compute the training and cross validation error, you should
% call the function with the lambda argument set to 0.
% Do note that you will still need to use lambda when running
% the training to obtain the theta parameters.
%
% Hint: You can loop over the examples with the following:
%
% for i = 1:m
% % Compute train/cross validation errors using training examples
% % X(1:i, :) and y(1:i), storing the result in
% % error_train(i) and error_val(i)
% ....
%
% end
%
% ---------------------- Sample Solution ----------------------
% -------------------------------------------------------------
% =========================================================================
end

@ -0,0 +1,37 @@
function [J, grad] = linearRegCostFunction(X, y, theta, lambda)
%LINEARREGCOSTFUNCTION Compute cost and gradient for regularized linear
%regression with multiple variables
% [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lambda) computes the
% cost of using theta as the parameter for linear regression to fit the
% data points in X and y. Returns the cost in J and the gradient in grad
% Initialize some useful values
m = length(y); % number of training examples
% You need to return the following variables correctly
J = 0;
grad = zeros(size(theta));
% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost and gradient of regularized linear
% regression for a particular choice of theta.
%
% You should set J to the cost and grad to the gradient.
%
% =========================================================================
grad = grad(:);
end

@ -0,0 +1,28 @@
function plotFit(min_x, max_x, mu, sigma, theta, p)
%PLOTFIT Plots a learned polynomial regression fit over an existing figure.
%Also works with linear regression.
% PLOTFIT(min_x, max_x, mu, sigma, theta, p) plots the learned polynomial
% fit with power p and feature normalization (mu, sigma).
% Hold on to the current figure
hold on;
% We plot a range slightly bigger than the min and max values to get
% an idea of how the fit will vary outside the range of the data points
x = (min_x - 15: 0.05 : max_x + 25)';
% Map the X values
X_poly = polyFeatures(x, p);
X_poly = bsxfun(@minus, X_poly, mu);
X_poly = bsxfun(@rdivide, X_poly, sigma);
% Add ones
X_poly = [ones(size(x, 1), 1) X_poly];
% Plot
plot(x, X_poly * theta, '--', 'LineWidth', 2)
% Hold off to the current figure
hold off
end

@ -0,0 +1,25 @@
function [X_poly] = polyFeatures(X, p)
%POLYFEATURES Maps X (1D vector) into the p-th power
% [X_poly] = POLYFEATURES(X, p) takes a data matrix X (size m x 1) and
% maps each example into its polynomial features where
% X_poly(i, :) = [X(i) X(i).^2 X(i).^3 ... X(i).^p];
%
% You need to return the following variables correctly.
X_poly = zeros(numel(X), p);
% ====================== YOUR CODE HERE ======================
% Instructions: Given a vector X, return a matrix X_poly where the p-th
% column of X contains the values of X to the p-th power.
%
%
% =========================================================================
end

@ -0,0 +1,577 @@
function submit(partId, webSubmit)
%SUBMIT Submit your code and output to the ml-class servers
% SUBMIT() will connect to the ml-class server and submit your solution
fprintf('==\n== [ml-class] Submitting Solutions | Programming Exercise %s\n==\n', ...
homework_id());
if ~exist('partId', 'var') || isempty(partId)
partId = promptPart();
end
if ~exist('webSubmit', 'var') || isempty(webSubmit)
webSubmit = 0; % submit directly by default
end
% Check valid partId
partNames = validParts();
if ~isValidPartId(partId)
fprintf('!! Invalid homework part selected.\n');
fprintf('!! Expected an integer from 1 to %d.\n', numel(partNames) + 1);
fprintf('!! Submission Cancelled\n');
return
end
if ~exist('ml_login_data.mat','file')
[login password] = loginPrompt();
save('ml_login_data.mat','login','password');
else
load('ml_login_data.mat');
[login password] = quickLogin(login, password);
save('ml_login_data.mat','login','password');
end
if isempty(login)
fprintf('!! Submission Cancelled\n');
return
end
fprintf('\n== Connecting to ml-class ... ');
if exist('OCTAVE_VERSION')
fflush(stdout);
end
% Setup submit list
if partId == numel(partNames) + 1
submitParts = 1:numel(partNames);
else
submitParts = [partId];
end
for s = 1:numel(submitParts)
thisPartId = submitParts(s);
if (~webSubmit) % submit directly to server
[login, ch, signature, auxstring] = getChallenge(login, thisPartId);
if isempty(login) || isempty(ch) || isempty(signature)
% Some error occured, error string in first return element.
fprintf('\n!! Error: %s\n\n', login);
return
end
% Attempt Submission with Challenge
ch_resp = challengeResponse(login, password, ch);
[result, str] = submitSolution(login, ch_resp, thisPartId, ...
output(thisPartId, auxstring), source(thisPartId), signature);
partName = partNames{thisPartId};
fprintf('\n== [ml-class] Submitted Assignment %s - Part %d - %s\n', ...
homework_id(), thisPartId, partName);
fprintf('== %s\n', strtrim(str));
if exist('OCTAVE_VERSION')
fflush(stdout);
end
else
[result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...
source(thisPartId));
result = base64encode(result);
fprintf('\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...
homework_id(), thisPartId);
saveAsFile = input('', 's');
if (isempty(saveAsFile))
saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);
end
fid = fopen(saveAsFile, 'w');
if (fid)
fwrite(fid, result);
fclose(fid);
fprintf('\nSaved your solutions to %s.\n\n', saveAsFile);
fprintf(['You can now submit your solutions through the web \n' ...
'form in the programming exercises. Select the corresponding \n' ...
'programming exercise to access the form.\n']);
else
fprintf('Unable to save to %s\n\n', saveAsFile);
fprintf(['You can create a submission file by saving the \n' ...
'following text in a file: (press enter to continue)\n\n']);
pause;
fprintf(result);
end
end
end
end
% ================== CONFIGURABLES FOR EACH HOMEWORK ==================
function id = homework_id()
id = '5';
end
function [partNames] = validParts()
partNames = { 'Regularized Linear Regression Cost Function', ...
'Regularized Linear Regression Gradient', ...
'Learning Curve', ...
'Polynomial Feature Mapping' ...
'Validation Curve' ...
};
end
function srcs = sources()
% Separated by part
srcs = { { 'linearRegCostFunction.m' }, ...
{ 'linearRegCostFunction.m' }, ...
{ 'learningCurve.m' }, ...
{ 'polyFeatures.m' }, ...
{ 'validationCurve.m' } };
end
function out = output(partId, auxstring)
% Random Test Cases
X = [ones(10,1) sin(1:1.5:15)' cos(1:1.5:15)'];
y = sin(1:3:30)';
Xval = [ones(10,1) sin(0:1.5:14)' cos(0:1.5:14)'];
yval = sin(1:10)';
if partId == 1
[J] = linearRegCostFunction(X, y, [0.1 0.2 0.3]', 0.5);
out = sprintf('%0.5f ', J);
elseif partId == 2
[J, grad] = linearRegCostFunction(X, y, [0.1 0.2 0.3]', 0.5);
out = sprintf('%0.5f ', grad);
elseif partId == 3
[error_train, error_val] = ...
learningCurve(X, y, Xval, yval, 1);
out = sprintf('%0.5f ', [error_train(:); error_val(:)]);
elseif partId == 4
[X_poly] = polyFeatures(X(2,:)', 8);
out = sprintf('%0.5f ', X_poly);
elseif partId == 5
[lambda_vec, error_train, error_val] = ...
validationCurve(X, y, Xval, yval);
out = sprintf('%0.5f ', ...
[lambda_vec(:); error_train(:); error_val(:)]);
end
end
% ====================== SERVER CONFIGURATION ===========================
% ***************** REMOVE -staging WHEN YOU DEPLOY *********************
function url = site_url()
url = 'http://class.coursera.org/ml-007';
end
function url = challenge_url()
url = [site_url() '/assignment/challenge'];
end
function url = submit_url()
url = [site_url() '/assignment/submit'];
end
% ========================= CHALLENGE HELPERS =========================
function src = source(partId)
src = '';
src_files = sources();
if partId <= numel(src_files)
flist = src_files{partId};
for i = 1:numel(flist)
fid = fopen(flist{i});
if (fid == -1)
error('Error opening %s (is it missing?)', flist{i});
end
line = fgets(fid);
while ischar(line)
src = [src line];
line = fgets(fid);
end
fclose(fid);
src = [src '||||||||'];
end
end
end
function ret = isValidPartId(partId)
partNames = validParts();
ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);
end
function partId = promptPart()
fprintf('== Select which part(s) to submit:\n');
partNames = validParts();
srcFiles = sources();
for i = 1:numel(partNames)
fprintf('== %d) %s [', i, partNames{i});
fprintf(' %s ', srcFiles{i}{:});
fprintf(']\n');
end
fprintf('== %d) All of the above \n==\nEnter your choice [1-%d]: ', ...
numel(partNames) + 1, numel(partNames) + 1);
selPart = input('', 's');
partId = str2num(selPart);
if ~isValidPartId(partId)
partId = -1;
end
end
function [email,ch,signature,auxstring] = getChallenge(email, part)
str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});
str = strtrim(str);
r = struct;
while(numel(str) > 0)
[f, str] = strtok (str, '|');
[v, str] = strtok (str, '|');
r = setfield(r, f, v);
end
email = getfield(r, 'email_address');
ch = getfield(r, 'challenge_key');
signature = getfield(r, 'state');
auxstring = getfield(r, 'challenge_aux_data');
end
function [result, str] = submitSolutionWeb(email, part, output, source)
result = ['{"assignment_part_sid":"' base64encode([homework_id() '-' num2str(part)], '') '",' ...
'"email_address":"' base64encode(email, '') '",' ...
'"submission":"' base64encode(output, '') '",' ...
'"submission_aux":"' base64encode(source, '') '"' ...
'}'];
str = 'Web-submission';
end
function [result, str] = submitSolution(email, ch_resp, part, output, ...
source, signature)
params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...
'email_address', email, ...
'submission', base64encode(output, ''), ...
'submission_aux', base64encode(source, ''), ...
'challenge_response', ch_resp, ...
'state', signature};
str = urlread(submit_url(), 'post', params);
% Parse str to read for success / failure
result = 0;
end
% =========================== LOGIN HELPERS ===========================
function [login password] = loginPrompt()
% Prompt for password
[login password] = basicPrompt();
if isempty(login) || isempty(password)
login = []; password = [];
end
end
function [login password] = basicPrompt()
login = input('Login (Email address): ', 's');
password = input('Password: ', 's');
end
function [login password] = quickLogin(login,password)
disp(['You are currently logged in as ' login '.']);
cont_token = input('Is this you? (y/n - type n to reenter password)','s');
if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')
return;
else
[login password] = loginPrompt();
end
end
function [str] = challengeResponse(email, passwd, challenge)
str = sha1([challenge passwd]);
end
% =============================== SHA-1 ================================
function hash = sha1(str)
% Initialize variables
h0 = uint32(1732584193);
h1 = uint32(4023233417);
h2 = uint32(2562383102);
h3 = uint32(271733878);
h4 = uint32(3285377520);
% Convert to word array
strlen = numel(str);
% Break string into chars and append the bit 1 to the message
mC = [double(str) 128];
mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];
numB = strlen * 8;
if exist('idivide')
numC = idivide(uint32(numB + 65), 512, 'ceil');
else
numC = ceil(double(numB + 65)/512);
end
numW = numC * 16;
mW = zeros(numW, 1, 'uint32');
idx = 1;
for i = 1:4:strlen + 1
mW(idx) = bitor(bitor(bitor( ...
bitshift(uint32(mC(i)), 24), ...
bitshift(uint32(mC(i+1)), 16)), ...
bitshift(uint32(mC(i+2)), 8)), ...
uint32(mC(i+3)));
idx = idx + 1;
end
% Append length of message
mW(numW - 1) = uint32(bitshift(uint64(numB), -32));
mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));
% Process the message in successive 512-bit chs
for cId = 1 : double(numC)
cSt = (cId - 1) * 16 + 1;
cEnd = cId * 16;
ch = mW(cSt : cEnd);
% Extend the sixteen 32-bit words into eighty 32-bit words
for j = 17 : 80
ch(j) = ch(j - 3);
ch(j) = bitxor(ch(j), ch(j - 8));
ch(j) = bitxor(ch(j), ch(j - 14));
ch(j) = bitxor(ch(j), ch(j - 16));
ch(j) = bitrotate(ch(j), 1);
end
% Initialize hash value for this ch
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
% Main loop
for i = 1 : 80
if(i >= 1 && i <= 20)
f = bitor(bitand(b, c), bitand(bitcmp(b), d));
k = uint32(1518500249);
elseif(i >= 21 && i <= 40)
f = bitxor(bitxor(b, c), d);
k = uint32(1859775393);
elseif(i >= 41 && i <= 60)
f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));
k = uint32(2400959708);
elseif(i >= 61 && i <= 80)
f = bitxor(bitxor(b, c), d);
k = uint32(3395469782);
end
t = bitrotate(a, 5);
t = bitadd(t, f);
t = bitadd(t, e);
t = bitadd(t, k);
t = bitadd(t, ch(i));
e = d;
d = c;
c = bitrotate(b, 30);
b = a;
a = t;
end
h0 = bitadd(h0, a);
h1 = bitadd(h1, b);
h2 = bitadd(h2, c);
h3 = bitadd(h3, d);
h4 = bitadd(h4, e);
end
hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);
hash = lower(hash);
end
function ret = bitadd(iA, iB)
ret = double(iA) + double(iB);
ret = bitset(ret, 33, 0);
ret = uint32(ret);
end
function ret = bitrotate(iA, places)
t = bitshift(iA, places - 32);
ret = bitshift(iA, places);
ret = bitor(ret, t);
end
% =========================== Base64 Encoder ============================
% Thanks to Peter John Acklam
%
function y = base64encode(x, eol)
%BASE64ENCODE Perform base64 encoding on a string.
%
% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending
% sequence to use; it is optional and defaults to '\n' (ASCII decimal 10).
% The returned encoded string is broken into lines of no more than 76
% characters each, and each line will end with EOL unless it is empty. Let
% EOL be empty if you do not want the encoded string broken into lines.
%
% STR and EOL don't have to be strings (i.e., char arrays). The only
% requirement is that they are vectors containing values in the range 0-255.
%
% This function may be used to encode strings into the Base64 encoding
% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The
% Base64 encoding is designed to represent arbitrary sequences of octets in a
% form that need not be humanly readable. A 65-character subset
% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per
% printable character.
%
% Examples
% --------
%
% If you want to encode a large file, you should encode it in chunks that are
% a multiple of 57 bytes. This ensures that the base64 lines line up and
% that you do not end up with padding in the middle. 57 bytes of data fills
% one complete base64 line (76 == 57*4/3):
%
% If ifid and ofid are two file identifiers opened for reading and writing,
% respectively, then you can base64 encode the data with
%
% while ~feof(ifid)
% fwrite(ofid, base64encode(fread(ifid, 60*57)));
% end
%
% or, if you have enough memory,
%
% fwrite(ofid, base64encode(fread(ifid)));
%
% See also BASE64DECODE.
% Author: Peter John Acklam
% Time-stamp: 2004-02-03 21:36:56 +0100
% E-mail: pjacklam@online.no
% URL: http://home.online.no/~pjacklam
if isnumeric(x)
x = num2str(x);
end
% make sure we have the EOL value
if nargin < 2
eol = sprintf('\n');
else
if sum(size(eol) > 1) > 1
error('EOL must be a vector.');
end
if any(eol(:) > 255)
error('EOL can not contain values larger than 255.');
end
end
if sum(size(x) > 1) > 1
error('STR must be a vector.');
end
x = uint8(x);
eol = uint8(eol);
ndbytes = length(x); % number of decoded bytes
nchunks = ceil(ndbytes / 3); % number of chunks/groups
nebytes = 4 * nchunks; % number of encoded bytes
% add padding if necessary, to make the length of x a multiple of 3
if rem(ndbytes, 3)
x(end+1 : 3*nchunks) = 0;
end
x = reshape(x, [3, nchunks]); % reshape the data
y = repmat(uint8(0), 4, nchunks); % for the encoded data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Split up every 3 bytes into 4 pieces
%
% aaaaaabb bbbbcccc ccdddddd
%
% to form
%
% 00aaaaaa 00bbbbbb 00cccccc 00dddddd
%
y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)
y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)
y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)
y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)
y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)
y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now perform the following mapping
%
% 0 - 25 -> A-Z
% 26 - 51 -> a-z
% 52 - 61 -> 0-9
% 62 -> +
% 63 -> /
%
% We could use a mapping vector like
%
% ['A':'Z', 'a':'z', '0':'9', '+/']
%
% but that would require an index vector of class double.
%
z = repmat(uint8(0), size(y));
i = y <= 25; z(i) = 'A' + double(y(i));
i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));
i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));
i = y == 62; z(i) = '+';
i = y == 63; z(i) = '/';
y = z;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Add padding if necessary.
%
npbytes = 3 * nchunks - ndbytes; % number of padding bytes
if npbytes
y(end-npbytes+1 : end) = '='; % '=' is used for padding
end
if isempty(eol)
% reshape to a row vector
y = reshape(y, [1, nebytes]);
else
nlines = ceil(nebytes / 76); % number of lines
neolbytes = length(eol); % number of bytes in eol string
% pad data so it becomes a multiple of 76 elements
y = [y(:) ; zeros(76 * nlines - numel(y), 1)];
y(nebytes + 1 : 76 * nlines) = 0;
y = reshape(y, 76, nlines);
% insert eol strings
eol = eol(:);
y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));
% remove padding, but keep the last eol string
m = nebytes + neolbytes * (nlines - 1);
n = (76+neolbytes)*nlines - neolbytes;
y(m+1 : n) = '';
% extract and reshape to row vector
y = reshape(y, 1, m+neolbytes);
end
% output is a character array
y = char(y);
end

@ -0,0 +1,20 @@
% submitWeb Creates files from your code and output for web submission.
%
% If the submit function does not work for you, use the web-submission mechanism.
% Call this function to produce a file for the part you wish to submit. Then,
% submit the file to the class servers using the "Web Submission" button on the
% Programming Exercises page on the course website.
%
% You should call this function without arguments (submitWeb), to receive
% an interactive prompt for submission; optionally you can call it with the partID
% if you so wish. Make sure your working directory is set to the directory
% containing the submitWeb.m file and your assignment files.
function submitWeb(partId)
if ~exist('partId', 'var') || isempty(partId)
partId = [];
end
submit(partId, 1);
end

@ -0,0 +1,21 @@
function [theta] = trainLinearReg(X, y, lambda)
%TRAINLINEARREG Trains linear regression given a dataset (X, y) and a
%regularization parameter lambda
% [theta] = TRAINLINEARREG (X, y, lambda) trains linear regression using
% the dataset (X, y) and regularization parameter lambda. Returns the
% trained parameters theta.
%
% Initialize Theta
initial_theta = zeros(size(X, 2), 1);
% Create "short hand" for the cost function to be minimized
costFunction = @(t) linearRegCostFunction(X, y, t, lambda);
% Now, costFunction is a function that takes in only one argument
options = optimset('MaxIter', 200, 'GradObj', 'on');
% Minimize using fmincg
theta = fmincg(costFunction, initial_theta, options);
end

@ -0,0 +1,53 @@
function [lambda_vec, error_train, error_val] = ...
validationCurve(X, y, Xval, yval)
%VALIDATIONCURVE Generate the train and validation errors needed to
%plot a validation curve that we can use to select lambda
% [lambda_vec, error_train, error_val] = ...
% VALIDATIONCURVE(X, y, Xval, yval) returns the train
% and validation errors (in error_train, error_val)
% for different values of lambda. You are given the training set (X,
% y) and validation set (Xval, yval).
%
% Selected values of lambda (you should not change this)
lambda_vec = [0 0.001 0.003 0.01 0.03 0.1 0.3 1 3 10]';
% You need to return these variables correctly.
error_train = zeros(length(lambda_vec), 1);
error_val = zeros(length(lambda_vec), 1);
% ====================== YOUR CODE HERE ======================
% Instructions: Fill in this function to return training errors in
% error_train and the validation errors in error_val. The
% vector lambda_vec contains the different lambda parameters
% to use for each calculation of the errors, i.e,
% error_train(i), and error_val(i) should give
% you the errors obtained after training with
% lambda = lambda_vec(i)
%
% Note: You can loop over lambda_vec with the following:
%
% for i = 1:length(lambda_vec)
% lambda = lambda_vec(i);
% % Compute train / val errors when training linear
% % regression with regularization parameter lambda
% % You should store the result in error_train(i)
% % and error_val(i)
% ....
%
% end
%
%
% =========================================================================
end