斯坦福大学机器学习课程线性回归编程作业二(多变量2)

来源:互联网 发布:js appendchild的用法 编辑:程序博客网 时间:2024/06/05 09:20

gradientDescentMulti函数代码为:

function [theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters)%GRADIENTDESCENTMULTI Performs gradient descent to learn theta%   theta = GRADIENTDESCENTMULTI(x, y, theta, alpha, num_iters) updates theta by%   taking num_iters gradient steps with learning rate alpha% Initialize some useful valuesm = length(y); % number of training examplesJ_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 (computeCostMulti) and gradient here.    %    theta = theta - alpha / m * X' * (X * theta - y);    % ============================================================    % Save the cost J in every iteration        J_history(iter) = computeCostMulti(X, y, theta);endend

所作出的图像为:


4.normal equations

%% ================ Part 3: Normal Equations ================fprintf('Solving with normal equations...\n');% ====================== YOUR CODE HERE ======================% Instructions: The following code computes the closed form %               solution for linear regression using the normal%               equations. You should complete the code in %               normalEqn.m%%               After doing so, you should complete this code %               to predict the price of a 1650 sq-ft, 3 br house.%%% Load Datadata = csvread('ex1data2.txt');X = data(:, 1:2);y = data(:, 3);m = length(y);% Add intercept term to XX = [ones(m, 1) X];% Calculate the parameters from the normal equationtheta = normalEqn(X, y);% Display normal equation's resultfprintf('Theta computed from the normal equations: \n');fprintf(' %f \n', theta);fprintf('\n');% Estimate the price of a 1650 sq-ft, 3 br house% ====================== YOUR CODE HERE ======================price = 0; % You should change this% ============================================================fprintf(['Predicted price of a 1650 sq-ft, 3 br house ' ...         '(using normal equations):\n $%f\n'], price);

其中normalEqn代码为:

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


阅读全文
0 0
原创粉丝点击