机器学习深入篇(三)——逻辑回归
代码实现
1、sigmod函数
function g = sigmoid(z)
g = 1./(1+exp(1).^(-z));
end
2、代价函数
function [J, grad] = costFunctionReg(theta, X, y, lambda)
m = length(y); % number of training examples
n = length(theta);
h = sigmoid(X * theta);
J = 1/m * (-y' * log(h) - (1-y)' * log(1 - h)) + lambda/(2*m) * sum(theta(2:n).^2);
grad = (1/m * (h - y)' * X)' + [0; lambda/m * theta(2:n)];
end
3、决策边界
function plotDecisionBoundary(theta, X, y)
plotData(X(:,2:3), y);
hold on
if size(X, 2) <= 3
% Only need 2 points to define a line, so choose two endpoints
plot_x = [min(X(:,2))-2, max(X(:,2))+2];
% Calculate the decision boundary line
plot_y = (-1./theta(3)).*(theta(2).*plot_x + theta(1));
% Plot, and adjust axes for better viewing
plot(plot_x, plot_y)
% Legend, specific for the exercise
legend('Admitted', 'Not admitted', 'Decision Boundary')
axis([30, 100, 30, 100])
else
% Here is the grid range
u = linspace(-1, 1.5, 50);
v = linspace(-1, 1.5, 50);
z = zeros(length(u), length(v));
% Evaluate z = theta*x over the grid
for i = 1:length(u)
for j = 1:length(v)
z(i,j) = mapFeature(u(i), v(j))*theta;
end
end
z = z'; % important to transpose z before calling contour
% Plot z = 0
% Notice you need to specify the range [0, 0]
contour(u, v, z, [0, 0], 'LineWidth', 2)
end
hold off
end
4、数据绘制
function plotData(X, y)
pos=find(y==1);
neg=find(y==0);
% Plot Examples
plot(X(pos,1),X(pos,2),'k+','LineWidth',2,...
'MarkerSize',7);
plot(X(neg,1),X(neg,2),'ko','MarkerFaceColor','y',...
'MarkerSize',7);
hold off;
end
5、特征绘制
function out = mapFeature(X1, X2)
degree = 6;
out = ones(size(X1(:,1)));
for i = 1:degree
for j = 0:i
out(:, end+1) = (X1.^(i-j)).*(X2.^j);
end
end
end
6、预测(分类)
function p = predict(theta, X)
m = size(X, 1); % Number of training examples
% You need to return the following variables correctly
p = zeros(m, 1);
h = sigmoid(X * theta);
pos = h>=0.5;
neg = h<0.5;
p(pos) = 1;
p(neg) = 0;
end
告一段落