一元線性回歸梯度下降算法的Octave仿真
在梯度下降算法理論篇中,曾經(jīng)感嘆推導(dǎo)過(guò)程如此蒼白,如此期待仿真來(lái)給我更加直觀的感覺(jué)。當(dāng)我昨晚Octave仿真后,那種成就感著實(shí)難以抑制。分享一下仿真的過(guò)程和結(jié)果,并且將上篇中未理解透澈的內(nèi)容補(bǔ)上。
在Gradient Descent Algorithm中,我們利用不斷推導(dǎo)得到兩個(gè)對(duì)此算法非常重要的公式,一個(gè)是J(θ)的求解公式,另一個(gè)是θ的求解公式:
我們?cè)诜抡嬷?,直接使用這兩個(gè)公式,來(lái)繪制J(θ)的分布曲面,以及θ的求解路徑。
命題為:我們?yōu)橐患疫B鎖餐飲企業(yè)新店開張的選址進(jìn)行利潤(rùn)估算,手中掌握了該連鎖集團(tuán)所轄店鋪當(dāng)?shù)厝丝跀?shù)據(jù),及利潤(rùn)金額,需要使用線性回歸算法來(lái)建立人口與利潤(rùn)的關(guān)系,進(jìn)而為新店進(jìn)行利潤(rùn)估算,以評(píng)估店鋪運(yùn)營(yíng)前景。
首先我們將該企業(yè)的數(shù)據(jù)繪制在坐標(biāo)圖上,如下圖所示,我們需要建立的模型是一條直線,能夠在最佳程度上,擬合population與profit之間的關(guān)系。其模型為:
在逼近θ的過(guò)程中,我們?nèi)缦聦?shí)現(xiàn)梯度下降:進(jìn)行了1500次的迭代(相當(dāng)于朝著最佳擬合點(diǎn)行走1500步),我們?cè)?500步后,得到θ=[-3.630291,1.166362];在3000次迭代后,其值為[-3.878051,1.191253];而如果運(yùn)行10萬(wàn)次,其值為[-3.895781,1.193034]??梢?jiàn),最初的步子走的是非常大的,而后,由于距離最佳擬合點(diǎn)越來(lái)越近,梯度越來(lái)越小,所以步子也會(huì)越來(lái)越小。為了節(jié)約運(yùn)算時(shí)間,1500步是一個(gè)完全夠用的迭代次數(shù)。之后,我們繪制出擬合好的曲線,可以看得出,擬合程度還是不錯(cuò)的。
下圖是J(θ)的分布曲面:
接來(lái)下是我們求得的最佳θ值在等高線圖上所在的位置,和上一張圖其實(shí)可以重合在一起:
關(guān)鍵代碼如下:
1、計(jì)算j(theta)
- function J = computeCost(X, y, theta)
- %COMPUTECOST Compute cost for linear regression
- % J = COMPUTECOST(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.
- h = X*theta;
- e = h-y;
- J = e'*e/(2*m)
- % =========================================================================
- end
2、梯度下降算法:
- function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
- %GRADIENTDESCENT Performs gradient descent to learn theta
- % theta = GRADIENTDESENT(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 (computeCost) and gradient here.
- %
- h=X*theta;
- e=h-y;
- theta = theta-alpha*(X'*e)/m;
- % ============================================================
- % Save the cost J in every iteration
- J_history(iter) = computeCost(X, y, theta);
- end
- end