您的位置:首页 > 其它

深度学习(逻辑回归)

2016-08-21 13:29 218 查看
今天练习了Logistic Regression,具体的损失函数和计算方法在该链接中都有。

问题描述

根据已知的Exam1和Exam2两个科目的成绩以及是否被学校录取成功(0或1)的数据集,训练出一个分类器。

代码实现

clear;
clc;
x=load('ex4x.dat');
y=load('ex4y.dat');
[m,n]=size(x);                 %数据的维数
x=[ones(m,1),x];               %在x前面插入一列1
%画出数据点分布
figure;
hold on;
yes=find(y==1);
plot(x(yes,2),x(yes,3),'bo');
no=find(y==0);
plot(x(no,2),x(no,3),'b+');
xlabel('Exam1 score');
ylabel('Exam2 score');
%初始化theta参数
theta=zeros(size(x,2),1);
%定义sigmoid内联函数
g=inline('1./(1+exp(-z))');
%牛顿法解逼近损失方程的解
Max_Inter=10;                  %迭代次数
J=zeros(Max_Inter,1);          %定义损失函数
for i=1:Max_Inter
z=x*theta;
h=g(z);
J(i)=1/m*sum((-y.*log(h)-(1-y).*(log(1-h))));
grad = (1/m).*x' * (h-y);  %
H = (1/m).*x' * diag(h) * diag(1-h) * x; %计算heissan矩阵
theta=theta-H\grad;
end
%画出分界面
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);
legend('Accepted','Not Accepted','Decision Boundary');
title('Logistic Regression');
hold off;
%画出损失函数变化情况
figure;
plot(1:Max_Inter,J,'s--','MarkerFaceColor','r','MarkerSize',8);
xlabel('iterations');
ylabel('loss value');
title('Loss Value');
%对一个两门成绩分别为20,80的同学预测
possb=g([1,20,80]*theta);
fprintf('Exam1=20分,Exam2=80分的同学被录取的概率为%f\n',possb);


结果显示





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: