Machine Learning(三)(逻辑回归Logistical Regression)

来源:互联网 发布:谷歌关键词优化 编辑:程序博客网 时间:2024/04/30 10:23

如果说线性回归的问题是解决连续性问题的话,那么逻辑回归是要解决0-1的分类问题。


对于逻辑回归,可以采用一和二讲里面使用到的梯度下降方法来求得theta的最优值。但是这里我们有一个更好的方法,就是使用Advanced optimization算法。具体的算法可以为


而且它的使用步骤,在Matlab里可以简化为以下两个步骤。一是在costFunction函数里面实现消耗函数的计算

还有对theta的梯度的计算;而是调用fminunc函数。最终可以求出最优的theta值。


作业题:这里给出的训练样本的特征为80个学生的两门功课的分数,样本值为对应的同学是否允许被上大学,如果是允许的话则用’1’表示,否则不允许就用’0’表示,这是一个典型的二分类问题。在此问题中,给出的80个样本中正负样本各占40个。而这节采用的是logistic regression来求解,该求解后的结果其实是一个概率值,当然通过与0.5比较就可以变成一个二分类问题了。

data = load('ex2data1.txt');X=data(:,1:2);y=data(:,3);[m, n] = size(X);X = [ones(m, 1) X];initial_theta = zeros(n + 1, 1);[cost, grad] = costFunction(initial_theta, X, y);options = optimset('GradObj', 'on', 'MaxIter', 400);[theta, cost] = ...fminunc(@(t)(costFunction(t, X, y)), initial_theta, options);prob = sigmoid([1 45 85] * theta);fprintf(['For a student with scores 45 and 85, we predict an admission ' ...         'probability of %f\n\n'], prob);% Compute accuracy on our training setp = predict(theta, X);fprintf('Train Accuracy: %f\n', mean(double(p == y)) * 100);

下面贴出啦调用的两个子函数

sigmoid和costFunction和预测函数predict

function [J, grad] = costFunction(theta, X, y)m = length(y);J = 0;grad = zeros(size(theta));J=(y'*log(sigmoid(X*theta))+(1-y)'*log(1-sigmoid(X*theta)))/(-m);grad=X'*(sigmoid(X*theta)-y)/m;end
function g = sigmoid(z)g = zeros(size(z));g=(1+exp(-z)).^(-1);endfunction p = predict(theta, X)m = size(X, 1); % Number of training examplesp = zeros(m, 1);for i=1:m    if X(i,:)*theta>0        p(i)=1;end实验结果theta:  -24.932941  0.204407  0.199618 For a student with scores 45 and 85, we predict an admission probability of 0.774323Train Accuracy: 89.000000