您的位置:首页 > 编程语言 > MATLAB

逻辑回归的Matlab实现

2017-09-17 18:33 471 查看

Logistic回归(Logistic Regression)

方法一、利用matlab自带的函数glmfit() :

function theta=logisticRegression()
% logistic regression的参数theta,可以用matlab自带函数glmfit求出
x = [0.0 0.1 0.7 1.0 1.1 1.3 1.4 1.7 2.1 2.2]';
y = [0 0 1 0 0 0 1 1 1 1]';
theta = glmfit(x, [y ones(10,1)], 'binomial', 'link', 'logit')
end


方法二:使用梯度下降法迭代

function theta =logisticReg()
%   梯度下降法寻找最合适的theta,使得代价函数J最小
options=optimset('GradObj','on','MaxIter',100);
inittheta=[0 0]';
theta=fminunc(@costFunc,inittheta,options);
end

%%
function [J,gradient] = costFunc(theta)
x = [0.0 0.1 0.7 1.0 1.1 1.3 1.4 1.7 2.1 2.2]';
y = [0 0 1 0 0 0 1 1 1 1]';
m=size(x,1);
tmp=theta(1)+theta(2)*x;        %theta'x
hypothesis=1./(1+exp(-tmp));  %logistic function
delta=log(hypothesis+0.01).*y+(1-y).*log(1-hypothesis+0.01);       %加上0.01是为了防止x为0
J=-sum(delta)/m;
gradient(1)=sum(hypothesis-y)/m;  %x0=1;
gradient(2)=sum((hypothesis-y).*x)/m;
%theta=theta-a*gradient;  gradient=-J'(theta)
end


两种方法都使用数据:

x = [0.0 0.1 0.7 1.0 1.1 1.3 1.4 1.7 2.1 2.2]’;

y = [0 0 1 0 0 0 1 1 1 1]’;

注意,Y的值只能取0和1两种。

得到结果:

theta =

-3.4932
2.9402


即可以学习到函数:

Y=1/(1+exp(3.4932-2.9402*x));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: