多变量线性回归featureNormalize gradientDescentMulti normalEqn computeCostMulti

OptionalExercises
1.多变量线性回归
本部分使用多变量线性回归来预测房价。假设你想卖房子并想知道一个合适的市场价应该是多少。一种方式就是如这样收集最近的房价并做一个房价模型。Ex1data2.txt包含了Portland、Oregon等地房价作为训练集。第一列是房子尺寸(平方英尺),第二列是卧室的数量,第三列是房子的价格。

Ex1_multi.m已经为你准备好了来完成这个练习。

1.1FeatureNormalization
ex1_multi.m一开始会加载并显示一些数据集中的值。通过看这些值,注意到房价是卧室数的近1000倍。当特征之间的量级不一样,第一个特征的规模能够使梯度下降收敛的更快。

你的任务是完成featureNormalize.m中的code来:

A.    数据集中的每个特征值减去他们的平均值。

B.    减后,用这些值除他们各自的标准差。

标准差是一种表示一个特征的波动范围的测量方式;这是一种可供选择的计算值的范围(max-min)。Octave/matlab中你可以使用‘std’命令来计算标准差。例如,featureNormalize.m中X(:,1)的值包含所有的x1(房价)的值,所以std(X(:,1))计算了所以房价的标准差。此时,额外的列x0=1还没有加入到X中(详细看ex1_multi.m)。

你会为所有特征都执行这种操作,因此你的code应该可用于所有尺寸的数据集。注意到矩阵X的每一列对应一个特征。

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);   % 1 x n;
sigma=std(X); % 1 x n;
mu_temp=((mu')*ones(1,m))';  % m x n
sigma_temp=(sigma'*ones(1,m))' ; % m x n
X_norm=(X-mu_temp)./sigma_temp;
% ============================================================
end


1.2GradientDescent
在之前已经在单变量回归问题使用了梯度下降。不同之处是,这里多了一个变量。假设函数和批量梯度下降更新准则没有变。需要完成computeCostMulti.m和gradientDescentMulti.m中的代码用于多变量线性回归。确保你的代码支撑任意特征值并很好的向量化了。可以使用‘size(X,2)’来看数据中有多少个特征。

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 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 (computeCostMulti) and gradient here.
    %
predictions = X*theta;
errors = (predictions-y);
sums = X'*errors;
delta = 1/m*sums;
theta = theta - alpha*delta;
    % ============================================================
    % Save the cost J in every iteration    
    J_history(iter) = computeCostMulti(X, y, theta);
end
end
function J = computeCostMulti(X, y, theta)
%COMPUTECOSTMULTI Compute cost for linear regression with multiple variables
%   J = COMPUTECOSTMULTI(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.
m = size(X,1);
predictions = X*theta;
errors = predictions-y;
J = 1/(2*m)*(errors)'*errors;
% =========================================================================
end

注意,在多变量情况下,cost函数也能被写为以下向量格式:


1.2.1Optional(ungraded)exercise:selecting learning raets
本部分中,对于数据集使用不同的学习速率并寻找最快收敛的学习速率。通过修改ex1_multi.m和改变部分关于学习速率的代码来改变学习速率。

ex1_multi.m中的下一部分会调用你的gradientDescentMulti.m函数,并在选择的学习速率下迭代50次。函数还会在向量J中返回J(theta)的历史值。最后一次迭代之后,画出J(theta)相对于迭代次数的J的值。如果你选择一个好的学习速率,你画出来的应类似图4.如果你的图看起来非常不同,尤其是如果你的J(theta)的值增加或者波动,修改你的学习速率并再次尝试。我们推荐以log的规模,3倍增加的形式来选学习速率(如0.3,0.1,0.03,0.01)。

1.3normalEquations
在课程视频中, 学习到了和线性回归相似的解法是使用这个公式,不需要任何特征scaling,并且你会在一次计算中得到一个额外的解:这里也没有像梯度下降中的“循环直到收敛”。完成normalEqn.m中的代码使用上述的公式计算θ。记得你不用缩放你的特征,我们依旧需要加一个全1列在X中,来获得截断项(theta_0)。
 

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
%% Machine Learning Online Class
%  Exercise 1: Linear regression with multiple variables
%
%  Instructions
%  ------------
%  This file contains code that helps you get started on the
%  linear regression 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 part of the exercise, you will need to change some
%  parts of the code below for various experiments (e.g., changing
%  learning rates).
%
%% Initialization
%% ================ Part 1: Feature Normalization ================
%% Clear and Close Figures
clear ; close all; clc
fprintf('Loading data ...\n');
%% Load Data
data = load('ex1data2.txt');
X = data(:, 1:2);
y = data(:, 3);
m = length(y);
% Print out some data points
fprintf('First 10 examples from the dataset: \n');
fprintf(' x = [%.0f %.0f], y = %.0f \n', [X(1:10,:) y(1:10,:)]');
fprintf('Program paused. Press enter to continue.\n');
pause;
% Scale features and set them to zero mean
fprintf('Normalizing Features ...\n');
[X mu sigma] = featureNormalize(X);
% Add intercept term to X
X = [ones(m, 1) X];
%% ================ Part 2: Gradient Descent ================
% ====================== YOUR CODE HERE ======================
% Instructions: We have provided you with the following starter
%               code that runs gradient descent with a particular
%               learning rate (alpha). 
%
%               Your task is to first make sure that your functions - 
%               computeCost and gradientDescent already work with 
%               this starter code and support multiple variables.
%
%               After that, try running gradient descent with 
%               different values of alpha and see which one gives
%               you the best result.
%
%               Finally, you should complete the code at the end
%               to predict the price of a 1650 sq-ft, 3 br house.
%
% Hint: By using the 'hold on' command, you can plot multiple
%       graphs on the same figure.
%
% Hint: At prediction, make sure you do the same feature normalization.
%
fprintf('Running gradient descent ...\n');
% Choose some alpha value
alpha = 0.01;
num_iters = 400;
% Init Theta and Run Gradient Descent 
theta = zeros(3, 1);
[theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters);
 
% Plot the convergence graph
figure;
plot(1:numel(J_history), J_history, '-b', 'LineWidth', 2);
xlabel('Number of iterations');
ylabel('Cost J');
 
% Display gradient descent's result
fprintf('Theta computed from gradient descent: \n');
fprintf(' %f \n', theta);
fprintf('\n');
 
% Estimate the price of a 1650 sq-ft, 3 br house
% ====================== YOUR CODE HERE ======================
% Recall that the first column of X is all-ones. Thus, it does
% not need to be normalized.
% price = 0; % You should change this
price = [1 (([1650 3]-mu) ./ sigma)] * theta ;
% ============================================================
fprintf(['Predicted price of a 1650 sq-ft, 3 br house ' ...
         '(using gradient descent):\n $%f\n'], price);
fprintf('Program paused. Press enter to continue.\n');
pause;
%% ================ 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 Data
data = csvread('ex1data2.txt');
X = data(:, 1:2);
y = data(:, 3);
m = length(y);
% Add intercept term to X
X = [ones(m, 1) X];
% Calculate the parameters from the normal equation
theta = normalEqn(X, y);
% Display normal equation's result
fprintf('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
price = [1 1650 3] * theta ;
% ============================================================
fprintf(['Predicted price of a 1650 sq-ft, 3 br house ' ...
         '(using normal equations):\n $%f\n'], price);

 

-----------------
作者:思念铭心 
来源:CSDN 
原文:https://blog.csdn.net/sinat_38930882/article/details/77934734 
版权声明:本文为博主原创文章,转载请附上博文链接!

你可能感兴趣的:(编程算法,octave,线性回归)