梯度下降是最小化代价函数\(J(\theta)\)的一种方式,这里提出了另一种方式即正则方式不使用迭代方式:\(\theta = (X^TX)^{-1}X^Ty\)。举例如下(m=4)
在正则方式中不需要对正则方程做尺度缩放。下表给出了对于正则方程与梯度下降方法中差异:
梯度下降正则方程需要选择学习速率alpha不需选择alpha需要更多的步骤不需要更多的迭代算法复杂度(\(kn^2\))算法复杂度(\(n^3\)),且需要计算\(X^TX\)n值很大时,本方法以上很好运行n的数值越大,计算越慢从最后一项可以看出,随n的增大,计算的速度越慢。实际操作中,当n超过10000时,利用梯度下降将是比正则方程更优的选择。
一般可能是以下两种原因导致\(X^TX\)不可逆的情形出现:
冗余特征出现:即特征集中出现了两个特征非常密切相关的(可以说是线性相关的)含有太多的特征(如\(m\leq n\))。此时可以对特征做适量的删减或使用正规则化(此部分在后面会接触)实际的编程工具中,我们一般使用octave或matlab软件,而取逆函数名选取"pinv"而非"inv",此时即使不可逆仍然能够给出一个值。
假如你是一家餐饮业老总,你想在不同的城市开设餐馆,从以往的餐馆中,你获取了相应的餐馆在每个城市的利润和人口数据。因此,你需要借助这些数据帮助你来决定下一步在何地开设。
首先根据已有的数据绘出关于人口--利润的图形,代码如下: figure; % 绘图 plot(x,y,'rx', 'MarkerSize', 10); xlabel('Polulation of City in 10,000s'); ylabel('Profit in $10,000S'); 梯度下降的计算:目的在于根据以下代价函数公式\(J(\theta)=\frac{1}{2m}\sum_{i=1}^{m}(h_\theta(x^{(i)})-y^{(i)})^2\)使其最小化,
这里假设函数设为一阶线性:\(h_\theta(x)=\theta^Tx=\theta_0+\theta_1x_1\),在批量梯度算法中,每一步都进行更新:
经过梯度下降,参数\(\theta_j\)逐渐接近最适值,此时代价函数\(J(\theta)\)取得最小值。
代价函数计算代码如下:
% Initialize some useful values m = length(y); % number of training examples % You need to return the following variables correctly J = 0; % ====================== YOUR CODE HERE ====================== % Notice: we must add an additional first column to X and set it to all ones. for i = 1:m J = J + ( (theta(1)*X(i,1)+theta(2)*X(i,2))-y(i) )^2; end J = J/2/m; % =============================================================梯度下降计算代码如下:
在程序中,确保理解需要优化的内容和正在更新的内容。记住J成本函数由向量θ是决定而不是X和y。也就是说,我们最小化J(θ)的价值通过改变向量θ的值,而不是通过改变X或y,验证梯度下降是否正确工作的一个好方法是看J(θ)在每一步的运算中是否减少。
% 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 (computeCost) and gradient here. % v1 = 0; v2 = 0; for i = 1:m v1 = v1 + ((theta(1)*X(i,1)+theta(2)*X(i,2))-y(i))*X(i,1); v2 = v2 + ((theta(1)*X(i,1)+theta(2)*X(i,2))-y(i))*X(i,2); end theta(1) = theta(1) - alpha * v1 / m; theta(2) = theta(2) - alpha * v2 / m; % ============================================================ % Save the cost J in every iteration J_history(iter) = computeCost(X, y, theta);经过梯度下降后初步的到的参数做回归图线为:
利用contour函数描述随参数theta的变化,代价函数的取值: % initialize J_vals to a matrix of 0's J_vals = zeros(length(theta0_vals), length(theta1_vals)); % Fill out J_vals for i = 1:length(theta0_vals) for j = 1:length(theta1_vals) t = [theta0_vals(i); theta1_vals(j)]; J_vals(i,j) = computeCost(X, y, t); end end % Because of the way meshgrids work in the surf command, we need to % transpose J_vals before calling surf, or else the axes will be flipped J_vals = J_vals'; % Surface plot figure; surf(theta0_vals, theta1_vals, J_vals) xlabel('\theta_0'); ylabel('\theta_1'); % Contour plot figure; % Plot J_vals as 15 contours spaced logarithmically between 0.01 and 100 contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20)) xlabel('\theta_0'); ylabel('\theta_1'); hold on; plot(theta(1), theta(2), 'rx', 'MarkerSize', 10, 'LineWidth', 2);显示如下:
假设你在出售你的房子和你想知道一个好的市场价格是多少。一种方法是首先收集最近出售的房屋的信息并建立一个住房模型价格。这节我们主要通过引入两个特征元素:房子尺寸和起居室的数量,输出结果或期望得到为房屋的价格。
这里起居室的尺寸是起居室数量的1000倍大概,故首先要对特征集进行标准化处理。因此应计算所有特征元素的平均值以及它们的标准差。octave有专用的函数"mean"、"std"以计算。
代码如下:
% You need to set these values correctly X_norm = X; mu = zeros(1, size(X, 2));%size -->1 disp the row, 2 disp the column , 3 disp the page sigma = zeros(1, size(X, 2)); mu = mean(X); sigma = std(X); m = size(X,1); n = size(X,2); for i = 1:n for j = 1:m X_norm(j,i) = (X(j,i) - mu(i))/sigma(i); end end 梯度下降之前,在单变量回归上实现了梯度下降问题。现在唯一的区别是,还有一个特性矩阵x,假设函数和批梯度下降更新规则保持不变。
代码如下: %compute the costmulti m = length(y); J = 0; J=(X*theta-y)'*(X*theta-y)/2/m; % the multi of grad descent m = length(y); % number of training examples J_history = zeros(num_iters, 1); for iter = 1:num_iters i = size(X,2); v = 0; for i = 1:i; for j = 1:m v = v + ((theta(1)*X(j,1)+theta(2)*X(j,2)+theta(3)*X(j,3))-y(j))*X(j,i); end theta(i) = theta(i) - alpha * v / m; end % Save the cost J in every iteration J_history(iter) = computeCostMulti(X, y, theta); end之后绘出代价函数的递减曲线:
正则方程\(\theta=(X^TX)^{-1}X^Ty\)
代码如下:
theta = zeros(size(X, 2), 1);%size(X,2)返回列colum的值 theta = pinv(X'*X)*X'*y;转载于:https://www.cnblogs.com/SrtFrmGNU/p/6964190.html