changeset 0:0f14514e907f

initial commit
author Jordi Gutiérrez Hermoso <jordigh@octave.org>
date Sun, 20 Nov 2011 23:26:16 -0500
parents
children 9a9f76850dc6
files ex5.m ex5data1.mat featureNormalize.m fmincg.m learningCurve.m linearRegCostFunction.m plotFit.m polyFeatures.m submit.m submitWeb.m trainLinearReg.m validationCurve.m
diffstat 12 files changed, 1333 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
new file mode 100644
--- /dev/null
+++ b/ex5.m
@@ -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;
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..5a17abdbb0c1ff969b288e6fae7b795a309f40b1
GIT binary patch
literal 1321
zc%1Wf4DoSvQZUssQ1EpO(M`+DN!3vZ$Vn_o%P-2cQgHY2i*PhE(NS<NN=+<DO;O0t
zvr=#?%2e>nFH=x3Q7|&HGBUR^GE*=zFf>#k5il@%`tma{FmwZP#hk~<2?;Y8j^sF;
zVO;9iAbRRKW0IReT1p4Qr8y3B7>*Qw^OBoa9{=A#D)~>4Z|QC3G(WDcb3%T66VopL
z|9k)WlZ5H1`!>(L``F>)_Zi7K{UZE19CMG@)vlX&_^!Up`pb)C_+u{mSAW0!Y4%^M
z<M}b4+Va?UY&Oc)|9r|KBTB{0THdUff#IyHb_>W!UHF`|f(7EFKXrdjHXZ8WtC}V3
zzuw~4$$xC?S6wfUb#LFGeR7lEO+UVE`<t%Iu1YArQIYw+SO31GOhsr~#kv#MN-J*t
z+V$|6w^;jxuXdll$A7l+SoZTz&W@w6CnVoEx?!{DImd$CvrheCPUB<n`>Dkaa?u^Q
ziz<*@B+i=Troq<fI%SF2bcReng*e6|Hrw^waw8uWDEO@UbLF7EANv{>XS-`>KG_uf
zIchig@mnGGdwS+|g~v}`dFb-?(T8*?J@yzAbKNqrtF{~7%v<}^sGObs^!3yKpUuBg
zG-LCl*z2*H=I!RJ{F9Ar?B4!=Xz={?A-=QB`{i8={v;Kba6B=LH>~d4-0XPpi2B^i
z|8M(0oGrJ`_Wren%MZT_JD2sDd1lR<@SQiN@P%~hMNRm0__xFUlSdbv-7drLGN)qy
zg-M||85t65!%abcyn)Y;q0<n4?BDjs>&NYbPaiD&`EBdhl0f$6+*8Nz=h!5?KWn%0
z%%c@8&dVY;{wOkZZkM0Oc3#b|HuL^#?WkqOlg}zDyxOMqyhfVc|Cy#9{|;VRr>A>D
zd(Eq?r<|F;;g)H@0mTmsznnRw$I5>CM!{`u$8UW5-%dMy#HX-~!{Ysi%DsI}&JiK{
z?u&a`o0FOgUj6Al!?(O<uJ$xbZ_5p;Gi4G2rWa_K@4F*Z9dhDfOZ&f>_q9W08FpK_
zX@UHA6YjqqjHv!INK5R{@ILd9Wm7mq;rq$|@27r~mZ>QG(|=d1^e*$q@?N3HIWn^E
zWc03n$ttlg_#S%i8Mmn)U(N3QqVZhimH}FmDwN-Be9*}9bNRhut2Huld-p}DPJLFj
zAhG+|dgYJP`1W6ad-tera(#niasLC>`s{Ysuluj5pDvJ%`1E=63$Ks+f4>i#U!x`c
zxX2;?>4ERPJ@eR|uKK=9Nt2Qb@Sgpx<er#ZdkdHO)4l@9cGfdKt3yNX$nGl3`w^7A
z@-+j)MXr!VAP-*0=fM>^Fb|&U-c)nGl!>qD{Ni15J2)(Sj6V0~?a6;{V0rM%y8U}s
z9nO1MxpmF;H?k)Bnwyry372IQ$Nty)KW9Pn%EF5~ZS&IjczE`&nP#-%{dAk(UO&^D
zI}dky_vhR1JN;atB6(ej=bDYp;dioc&X+yJ_g?I;#qRR~XBQ?;)_uQHdJ|uo4x3mm
z_x{`2>+b#gevC1UeRaBzwffzl(hZ@vr(NFad9d;6(*B(hUDKJX9X9{Go*Tu-P|EE6
F0suJ_R{j70
new file mode 100644
--- /dev/null
+++ b/featureNormalize.m
@@ -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
new file mode 100644
--- /dev/null
+++ b/fmincg.m
@@ -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');
new file mode 100644
--- /dev/null
+++ b/learningCurve.m
@@ -0,0 +1,68 @@
+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. 
+%               The vector numex_vec contains the number of training 
+%               examples to use for each calculation of training error and 
+%               cross validation error, 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
new file mode 100644
--- /dev/null
+++ b/linearRegCostFunction.m
@@ -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
new file mode 100644
--- /dev/null
+++ b/plotFit.m
@@ -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
new file mode 100644
--- /dev/null
+++ b/polyFeatures.m
@@ -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
new file mode 100644
--- /dev/null
+++ b/submit.m
@@ -0,0 +1,337 @@
+function submit(partId)
+%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
+  
+  % 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
+
+  [login password] = loginPrompt();
+  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)
+    % Submit this part
+    partId = submitParts(s);
+    
+    % Get Challenge
+    [login, ch, signature] = getChallenge(login);
+    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, partId, output(partId), ...
+                                 source(partId), signature);
+                                 
+    fprintf('\n== [ml-class] Submitted Homework %s - Part %d - %s\n', ...
+            homework_id(), partId, partNames{partId});
+    fprintf('== %s\n', strtrim(str));
+    if exist('OCTAVE_VERSION') 
+      fflush(stdout);
+    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)
+  % 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
+
+function url = challenge_url()
+  url = 'http://www.ml-class.org/course/homework/challenge';
+end
+
+function url = submit_url()
+  url = 'http://www.ml-class.org/course/homework/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});
+          while ~feof(fid)
+            line = fgets(fid);
+            src = [src line];
+          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', ...
+          homework_id());
+  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] = getChallenge(email)
+  str = urlread(challenge_url(), 'post', {'email_address', email});
+
+  str = strtrim(str);
+  [email, str] = strtok (str, '|');
+  [ch, str] = strtok (str, '|');
+  [signature, str] = strtok (str, '|');
+end
+
+
+function [result, str] = submitSolution(email, ch_resp, part, output, ...
+                                        source, signature)
+
+  params = {'homework', homework_id(), ...
+            'part', num2str(part), ...
+            'email', email, ...
+            'output', output, ...
+            'source', source, ...
+            'challenge_response', ch_resp, ...
+            'signature', 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 [str] = challengeResponse(email, passwd, challenge)
+  salt = ')~/|]QMB3[!W`?OVt7qC"@+}';
+  str = sha1([challenge sha1([salt email passwd])]);
+  sel = randperm(numel(str));
+  sel = sort(sel(1:16));
+  str = str(sel);
+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
new file mode 100644
--- /dev/null
+++ b/submitWeb.m
@@ -0,0 +1,352 @@
+function submitWeb(partId)
+%SUBMITWEB Generates a base64 encoded string for web-based submissions
+%   SUBMITWEB() will generate a base64 encoded string so that you can submit your
+%   solutions via a web form
+
+  fprintf('==\n== [ml-class] Submitting Solutions | Programming Exercise %s\n==\n', ...
+          homework_id());
+  if ~exist('partId', 'var') || isempty(partId)
+    partId = promptPart();
+  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));
+    fprintf('!! Submission Cancelled\n');
+    return
+  end
+
+  [login] = loginPrompt();
+  if isempty(login)
+    fprintf('!! Submission Cancelled\n');
+    return
+  end
+  
+  [result] = submitSolution(login, partId, output(partId), ...
+                            source(partId));
+  result = base64encode(result);
+
+  fprintf('\nSave as submission file [submit_ex%s_part%d.txt]: ', ...
+          homework_id(), partId);
+  saveAsFile = input('', 's');
+  if (isempty(saveAsFile))
+    saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), partId);
+  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
+
+% ================== 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)
+  % 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
+
+% ========================= SUBMIT 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});
+          while ~feof(fid)
+            line = fgets(fid);
+            src = [src line];
+          end
+          fclose(fid);
+          src = [src '||||||||'];
+      end
+  end
+end
+
+function ret = isValidPartId(partId)
+  partNames = validParts();
+  ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames));
+end
+
+function partId = promptPart()
+  fprintf('== Select which part(s) to submit:\n', ...
+          homework_id());
+  partNames = validParts();
+  srcFiles = sources();
+  for i = 1:numel(partNames)
+    fprintf('==   %d) %s [', i, partNames{i});
+    fprintf(' %s ', srcFiles{i}{:});
+    fprintf(']\n');
+  end
+  fprintf('\nEnter your choice [1-%d]: ', ...
+          numel(partNames));
+  selPart = input('', 's');
+  partId = str2num(selPart);
+  if ~isValidPartId(partId)
+    partId = -1;
+  end
+end
+
+
+function [result, str] = submitSolution(email, part, output, source)
+
+  result = ['a:5:{' ...
+            p_s('homework') p_s64(homework_id()) ...
+            p_s('part') p_s64(part) ...
+            p_s('email') p_s64(email) ...
+            p_s('output') p_s64(output) ...
+            p_s('source') p_s64(source) ...
+            '}'];
+
+end
+
+function s = p_s(str)
+   s = ['s:' num2str(numel(str)) ':"' str '";'];
+end
+
+function s = p_s64(str)
+   str = base64encode(str, '');
+   s = ['s:' num2str(numel(str)) ':"' str '";'];
+end
+
+% =========================== LOGIN HELPERS ===========================
+
+function [login] = loginPrompt()
+  % Prompt for password
+  [login] = basicPrompt();
+end
+
+
+function [login] = basicPrompt()
+  login = input('Login (Email address): ', 's');
+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
new file mode 100644
--- /dev/null
+++ b/trainLinearReg.m
@@ -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
new file mode 100644
--- /dev/null
+++ b/validationCurve.m
@@ -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