OptionalExercises
3.多变量线性回归
本部分使用多变量线性回归来预测房价。假设你想卖房子并想知道一个合适的市场价应该是多少。一种方式就是如这样收集最近的房价并做一个房价模型。
Ex1data2.txt包含了Portland、Oregon等地房价作为训练集。第一列是房子尺寸(平方英尺),第二列是卧室的数量,第三列是房子的价格。
Ex1_multi.m已经为你准备好了来完成这个练习。
3.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;
% ============================