Stanford ML 笔记1-Linear Regression与Logistic Regression

[+]

转载请注明出处:  http://xiahouzuoxin.github.io/notes/

Stanford机器学习课程的主页是: http://cs229.stanford.edu/

课程计划

主讲人Andrew Ng是机器学习界的大牛,创办最大的公开课网站coursera,前段时间还听说加入了百度。他讲的机器学习课程可谓每个学计算机的人必看。整个课程的大纲大致如下:

  1. Introduction (1 class) Basic concepts.
  2. Supervised learning. (6 classes) Supervised learning setup. LMS. Logistic regression. Perceptron. Exponential family. Generative learning algorithms. Gaussian discriminant analysis.
    Naive Bayes. Support vector machines. Model selection and feature selection. Ensemble methods: Bagging, boosting, ECOC.
  3. Learning theory. (3 classes) Bias/variance tradeoff. Union and Chernoff/Hoeffding bounds. VC dimension. Worst case (online) learning. Advice on using learning algorithms.
  4. Unsupervised learning. (5 classes) Clustering. K-means. EM. Mixture of Gaussians. Factor analysis. PCA. MDS. pPCA. Independent components analysis (ICA).
  5. Reinforcement learning and control. (4 classes) MDPs. Bellman equations. Value iteration. Policy iteration. Linear quadratic regulation (LQR). LQG. Q-learning. Value function approximation. Policy search. Reinforce. POMDPs.

本笔记主要是关于Linear Regression和Logistic Regression部分的学习实践记录。

Linear Regression与预测问题

举了一个房价预测的例子,

Area(feet^2) #bedrooms Price(1000$)
2014 3 400
1600 3 330
2400 3 369
1416 2 232
3000 4 540
3670 4 620
4500 5 800

Assume:房价与“面积和卧室数量”是线性关系,用线性关系进行放假预测。因而给出线性模型, hθ(x) = ∑θTx ,其中 x = [x1, x2] , 分别对应面积和卧室数量。 为得到预测模型,就应该根据表中已有的数据拟合得到参数 θ 的值。课程通过从概率角度进行解释(主要用到了大数定律即“线性拟合模型的误差满足高斯分布”的假设,通过最大似然求导就能得到下面的表达式)为什么应该求解如下的最小二乘表达式来达到求解参数的目的,

上述 J(θ) 称为cost function, 通过 minJ(θ) 即可得到拟合模型的参数。

解 minJ(θ) 的方法有多种, 包括Gradient descent algorithm和Newton's method,这两种都是运筹学的数值计算方法,非常适合计算机运算,这两种算法不仅适合这里的线性回归模型,对于非线性模型如下面的Logistic模型也适用。除此之外,Andrew Ng还通过线性代数推导了最小均方的算法的闭合数学形式,

Gradient descent algorithm执行过程中又分两种方法:batch gradient descent和stochastic gradient descent。batch gradient descent每次更新 θ 都用到所有的样本数据,而stochastic gradient descent每次更新则都仅用单个的样本数据。两者更新过程如下:

  1. batch gradient descent

  2. stochastic gradient descent

    for i=1 to m

两者只不过一个将样本放在了for循环上,一者放在了。事实证明,只要选择合适的学习率 α , Gradient descent algorithm总是能收敛到一个接近最优值的值。学习率选择过大可能造成cost function的发散,选择太小,收敛速度会变慢。

关于收敛条件,Andrew Ng没有在课程中提到更多,我给出两种收敛准则:

  1. J小于一定值收敛
  2. 两次迭代之间的J差值,即|J-J_pre|<一定值则收敛

下面是使用batch gradient descent拟合上面房价问题的例子,

<code class="sourceCode matlab" style="margin: 0px; padding: 0.5em; font-stretch: normal; line-height: normal; font-family: Monaco, 'Courier New', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace; color: rgb(51, 51, 51); border: none; display: block; background: rgb(248, 248, 255);">clear all;
clc

<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">%% 原数据</span>
x = [<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2014</span>, <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1600</span>, <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2400</span>, <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1416</span>, <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">3000</span>, <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">3670</span>, <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">4500</span>;...
    <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">3</span>,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">3</span>,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">3</span>,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">4</span>,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">4</span>,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">5</span>;];
y = [<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">400</span> <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">330</span> <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">369</span> <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">232</span> <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">540</span> <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">620</span> <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">800</span>];

error = Inf;
threshold = <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">4300</span>;
alpha = <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">10</span>^(-<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">10</span>);
x = [zeros(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>,size(x,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>)); x];  <span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% x0 = 0,拟合常数项</span>
theta = [<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">0</span>;<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">0</span>;<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">0</span>]; <span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% 常数项为0</span>
J = <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>/<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>*sum((y-theta'*x).^<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>);
costs = [];
while error > threshold
    tmp = y-theta'*x;
    theta(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>) = theta(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>) + alpha*sum(tmp.*x(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>,:));
    theta(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>) = theta(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>) + alpha*sum(tmp.*x(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>,:));
    theta(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">3</span>) = theta(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">3</span>) + alpha*sum(tmp.*x(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">3</span>,:));
<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">%     J_last = J;</span>
    J = <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>/<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>*sum((y-theta'*x).^<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>);
<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">%     error = abs(J-J_last);</span>
    error = J;
    costs =[costs, error];
end

<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">%% 绘制</span>
figure,
subplot(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">211</span>);
plot3(x(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>,:),x(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">3</span>,:),y, <span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'*'</span>);
grid on;
xlabel(<span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'Area'</span>);
ylabel(<span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'#bedrooms'</span>);
zlabel(<span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'Price(1000$)'</span>);

hold on;
H = theta'*x;
plot3(x(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>,:),x(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">3</span>,:),H,<span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'r*'</span>);

hold on
hx(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>,:) = zeros(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">20</span>);
hx(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>,:) = <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1000</span>:<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">200</span>:<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">4800</span>;
hx(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">3</span>,:) = <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>:<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">20</span>;
[X,Y] = meshgrid(hx(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>,:), hx(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">3</span>,:));
H = theta(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>:<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">3</span>)'*[X(:)'; Y(:)'];
H = reshape(H,[<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">20</span>,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">20</span>]);
mesh(X,Y,H);

legend(<span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'原数据'</span>, <span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'对原数据的拟合'</span>, <span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'拟合平面'</span>);

subplot(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">212</span>);
plot(costs, <span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'.-'</span>);
grid on
title(<span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'error=J(\theta)的迭代收敛过程'</span>);
xlabel(<span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'迭代次数'</span>);
ylabel(<span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'J(\theta)'</span>);</code>

拟合及收敛过程如下:

不管是梯度下降,还是线性回归模型,都是工具!!分析结果更重要,从上面的拟合平面可以看到,影响房价的主要因素是面积而非卧室数量。

很多情况下,模型并不是线性的,比如股票随时间的涨跌过程。这种情况下, hθ(x) = θTx 的假设不再成立。此时,有两种方案:

  1. 建立一个非线性的模型,比如指数或者其它的符合数据变化的模型
  2. 局部线性模型,对每段数据进行局部建立线性模型。Andrew Ng课堂上讲解了Locally Weighted Linear Regression,即局部加权的线性模型

Locally Weighted Linear Regression

其中权值的一种好的选择方式是:

Logistic Regression与分类问题

Linear Regression解决的是连续的预测和拟合问题,而Logistic Regression解决的是离散的分类问题。两种方式,但本质殊途同归,两者都可以算是指数函数族的特例。

在分类问题中,y取值在{0,1}之间,因此,上述的Liear Regression显然不适应。修改模型如下

该模型称为Logistic函数或Sigmoid函数。为什么选择该函数,我们看看这个函数的图形就知道了,

Sigmoid函数范围在[0,1]之间,参数 θ 只不过控制曲线的陡峭程度。以0.5为截点,>0.5则y值为1,< 0.5则y值为0,这样就实现了两类分类的效果。

假设 P(y = 1|x; θ) = hθ(x) , P(y = 0|x; θ) = 1 − hθ(x) , 写得更紧凑一些,

对m个训练样本,使其似然函数最大,则有

同样的可以用梯度下降法求解上述的最大值问题,只要将最大值求解转化为求最小值,则迭代公式一模一样,

最后的梯度下降方式和Linear Regression一致。我做了个例子(数据集链接),下面是Logistic的Matlab代码,

function Logistic

clear all;
close all
clc

data = load('LogisticInput.txt');
x = data(:,1:2);
y = data(:,3);

% Plot Original Data
figure,
positive = find(y==1);
negtive = find(y==0);
hold on
plot(x(positive,1), x(positive,2), 'k+', 'LineWidth',2, 'MarkerSize', 7);
plot(x(negtive,1), x(negtive,2), 'bo', 'LineWidth',2, 'MarkerSize', 7);

% Compute Likelihood(Cost) Function
[m,n] = size(x);
x = [ones(m,1) x];
theta = zeros(n+1, 1);
[cost, grad] = cost_func(theta, x, y);
threshold = 0.1;
alpha = 10^(-1);
costs = [];
while cost > threshold
    theta = theta + alpha * grad;
    [cost, grad] = cost_func(theta, x, y);
    costs = [costs cost];
end

% Plot Decision Boundary 
hold on
plot_x = [min(x(:,2))-2,max(x(:,2))+2];
plot_y = (-1./theta(3)).*(theta(2).*plot_x + theta(1));
plot(plot_x, plot_y, 'r-');
legend('Positive', 'Negtive', 'Decision Boundary')
xlabel('Feature Dim1');
ylabel('Feature Dim2');
title('Classifaction Using Logistic Regression');

% Plot Costs Iteration
figure,
plot(costs, '*');
title('Cost Function Iteration');
xlabel('Iterations');
ylabel('Cost Fucntion Value');

end

function g=sigmoid(z)
g = 1.0 ./ (1.0+exp(-z));
end

function [J,grad] = cost_func(theta, X, y)
% Computer Likelihood Function and Gradient
m = length(y); % training examples
hx = sigmoid(X*theta);
J = (1./m)*sum(-y.*log(hx)-(1.0-y).*log(1.0-hx));
grad = (1./m) .* X' * (y-hx);
end

判决边界(Decesion Boundary)的计算是令h(x)=0.5得到的。当输入新的数据,计算h(x):h(x)>0.5为正样本所属的类,h(x)< 0.5 为负样本所属的类。

特征映射与过拟合(over-fitting)

这部分在Andrew Ng课堂上没有讲,参考了网络上的资料。

上面的数据可以通过直线进行划分,但实际中存在那么种情况,无法直接使用直线判决边界(看后面的例子)。

为解决上述问题,必须将特征映射到高维,然后通过非直线判决界面进行划分。特征映射的方法将已有的特征进行多项式组合,形成更多特征,

上面将二维特征映射到了2阶(还可以映射到更高阶),这便于形成非线性的判决边界。

但还存在问题,尽管上面方法便于对非线性的数据进行划分,但也容易由于高维特性造成过拟合。因此,引入泛化项应对过拟合问题。似然函数添加泛化项后变成,

此时梯度下降算法发生改变,

最后来个例子,样本数据链接,对应的含泛化项和特征映射的matlab分类代码如下:

<code class="sourceCode matlab" style="margin: 0px; padding: 0.5em; font-stretch: normal; line-height: normal; font-family: Monaco, 'Courier New', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace; color: rgb(51, 51, 51); border: none; display: block; background: rgb(248, 248, 255);">function LogisticEx2

clear all;
close all
clc

data = load(<span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'ex2data2.txt'</span>);
x = data(:,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>:<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>);
y = data(:,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">3</span>);

<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% Plot Original Data</span>
figure,
positive = find(y==<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>);
negtive = find(y==<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">0</span>);
subplot(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>);
hold on
plot(x(positive,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>), x(positive,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>), <span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'k+'</span>, <span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'LineWidth'</span>,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>, <span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'MarkerSize'</span>, <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">7</span>);
plot(x(negtive,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>), x(negtive,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>), <span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'bo'</span>, <span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'LineWidth'</span>,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>, <span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'MarkerSize'</span>, <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">7</span>);

<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% Compute Likelihood(Cost) Function</span>
[m,n] = size(x);
x = mapFeature(x);
theta = zeros(size(x,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>), <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>);
lambda = <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>;
[cost, grad] = cost_func(theta, x, y, lambda);
threshold = <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">0.53</span>;
alpha = <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">10</span>^(-<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>);
costs = [];
while cost > threshold
    theta = theta + alpha * grad;
    [cost, grad] = cost_func(theta, x, y, lambda);
    costs = [costs cost];
end

<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% Plot Decision Boundary </span>
hold on
plotDecisionBoundary(theta, x, y);
legend(<span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'Positive'</span>, <span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'Negtive'</span>, <span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'Decision Boundary'</span>)
xlabel(<span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'Feature Dim1'</span>);
ylabel(<span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'Feature Dim2'</span>);
title(<span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'Classifaction Using Logistic Regression'</span>);

<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% Plot Costs Iteration</span>
<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% figure,</span>
subplot(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>);plot(costs, <span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'*'</span>);
title(<span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'Cost Function Iteration'</span>);
xlabel(<span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'Iterations'</span>);
ylabel(<span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'Cost Fucntion Value'</span>);

end

function f=mapFeature(x)
<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% Map features to high dimension</span>
degree = <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">6</span>;
f = ones(size(x(:,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>)));  
for i = <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>:degree  
    for j = <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">0</span>:i  
        f(:, end+<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>) = (x(:,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>).^(i-j)).*(x(:,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>).^j);
    end  
end
end

function g=sigmoid(z)
g = <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1.0</span> ./ (<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1.0</span>+exp(-z));
end

function [J,grad] = cost_func(theta, X, y, lambda)
<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% Computer Likelihood Function and Gradient</span>
m = length(y); <span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% training examples</span>
hx = sigmoid(X*theta);
J = (<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>./m)*sum(-y.*log(hx)-(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1.0</span>-y).*log(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1.0</span>-hx)) + (lambda./(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>*m)*norm(theta(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>:end))^<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>);
regularize = (lambda/m).*theta;
regularize(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>) = <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">0</span>;
grad = (<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>./m) .* X' * (y-hx) - regularize;
end

function plotDecisionBoundary(theta, X, y)
<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">%PLOTDECISIONBOUNDARY Plots the data points X and y into a new figure with</span>
<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">%the decision boundary defined by theta</span>
<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">%   PLOTDECISIONBOUNDARY(theta, X,y) plots the data points with + for the </span>
<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">%   positive examples and o for the negative examples. X is assumed to be </span>
<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">%   a either </span>
<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">%   1) Mx3 matrix, where the first column is an all-ones column for the </span>
<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">%      intercept.</span>
<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">%   2) MxN, N>3 matrix, where the first column is all-ones</span>

<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% Plot Data</span>
<span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% plotData(X(:,2:3), y);</span>
hold on

if size(X, <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>) <= <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">3</span>
    <span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% Only need 2 points to define a line, so choose two endpoints</span>
    plot_x = [min(X(:,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>))-<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>,  max(X(:,<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>))+<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>];

    <span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% Calculate the decision boundary line</span>
    plot_y = (-<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>./theta(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">3</span>)).*(theta(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>).*plot_x + theta(<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>));

    <span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% Plot, and adjust axes for better viewing</span>
    plot(plot_x, plot_y)
    
    <span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% Legend, specific for the exercise</span>
    legend(<span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'Admitted'</span>, <span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'Not admitted'</span>, <span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'Decision Boundary'</span>)
    axis([<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">30</span>, <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">100</span>, <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">30</span>, <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">100</span>])
else
    <span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% Here is the grid range</span>
    u = linspace(-<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>, <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1.5</span>, <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">50</span>);
    v = linspace(-<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>, <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1.5</span>, <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">50</span>);

    z = zeros(length(u), length(v));
    <span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% Evaluate z = theta*x over the grid</span>
    for i = <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>:length(u)
        for j = <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">1</span>:length(v)
            z(i,j) = mapFeature([u(i), v(j)])*theta;
        end
    end
    z = z'; <span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% important to transpose z before calling contour</span>

    <span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% Plot z = 0</span>
    <span class="co" style="margin: 0px; padding: 0px; color: rgb(96, 160, 176); font-style: italic;">% Notice you need to specify the range [0, 0]</span>
    contour(u, v, z, [<span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">0</span>, <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">0</span>], <span class="st" style="margin: 0px; padding: 0px; color: rgb(64, 112, 160);">'LineWidth'</span>, <span class="fl" style="float: left; margin: 0px; padding: 0px; color: rgb(64, 160, 112);">2</span>)
end
end</code>

我们再回过头来看Logistic问题:对于非线性的问题,只不过使用了一个叫Sigmoid的非线性映射成一个线性问题。那么,除了Sigmoid函数,还有其它的函数可用吗?Andrew Ng老师还讲了指数函数族。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值