在逻辑回归中绘制决策边界

时间:2020-05-15 06:51:27

标签: machine-learning octave logistic-regression gradient-descent

我正在对如下所示的小型数据集进行逻辑回归:

enter image description here

在实现梯度下降和成本函数之后,我在预测阶段获得了89%的准确性,但是我想确保一切都井井有条,因此我试图绘制将两个数据集分开的决策边界线

下面,我展示了显示成本函数和theta参数的图。可以看出,当前我正在错误地打印决策边界线。

enter image description here

当我缩小决策边界图时,可以看到以下内容: enter image description here

我的决策边界被绘制在数据集下方。 需要注意的一件事是我使用了功能缩放。

下面是我使用的代码:

主程序

%% Initialization
clear ; close all; clc

%% Load Data
%  The first two columns contains the exam scores and the third column
%  contains the label.

data = load('ex2data1.txt');
X = data(:, [1, 2]); y = data(:, 3);

%% ==================== Part 1: Plotting ====================
%  We start the exercise by first plotting the data to understand the 
%  the problem we are working with.

fprintf(['Plotting data with + indicating (y = 1) examples and o ' ...
         'indicating (y = 0) examples.\n']);

plotData(X, y);

% Put some labels 
hold on;
% Labels and Legend
xlabel('Exam 1 score')
ylabel('Exam 2 score')

% Specified in plot order
legend('Admitted', 'Not admitted')
hold off;

fprintf('\nProgram paused. Press enter to continue.\n');
pause;


%% ============ Part 2: Compute Cost and Gradient ============
%  In this part of the exercise, you will implement the cost and gradient
%  for logistic regression. You neeed to complete the code in 
%  costFunction.m

%  Setup the data matrix appropriately, and add ones for the intercept term
[m, n] = size(X);

%Normalize Feature
[X_norm mu sigma] = featureNormalize(X);

% Add intercept term to x and X_test
X = [ones(m, 1) X];
X_norm = [ones(m, 1) X_norm];

% Initialize fitting parameters
initial_theta = zeros(n + 1, 1);

% Compute and display initial cost and gradient
J = computeCostgrad(X_norm, y, initial_theta);

fprintf('Cost at initial theta (zeros): %f\n', J);
fprintf('Expected cost (approx): 0.693\n');


fprintf('\nProgram paused. Press enter to continue.\n');
pause;

%% ============= Part 2a: Gradient Descent =====================
alpha=0.1;
iter=1000;
[theta, J_hist]=gradientDescent(initial_theta, X_norm, y, alpha, iter);
fprintf('Theta found by gradient descent:\n');
fprintf('%f\n', theta);

% Plot the convergence graph
figure;
plot(1:numel(J_hist), J_hist, '-b', 'LineWidth', 2);
xlabel('Nnumelumber of iterations');
ylabel('Cost J');



% Plot Boundary
plotDecisionBoundary(theta, X, y);

% Put some labels 
hold on;
% Labels and Legend
xlabel('Exam 1 score')
ylabel('Exam 2 score')

% Specified in plot order
legend('Admitted', 'Not admitted')
hold off;

fprintf('\nProgram paused. Press enter to continue.\n');
pause;

%% ============== Part 4: Predict and Accuracies ==============
%  After learning the parameters, you'll like to use it to predict the outcomes
%  on unseen data. In this part, you will use the logistic regression model
%  to predict the probability that a student with score 45 on exam 1 and 
%  score 85 on exam 2 will be admitted.
%
%  Furthermore, you will compute the training and test set accuracies of 
%  our model.
%
%  Your task is to complete the code in predict.m

%  Predict probability for a student with score 45 on exam 1 
%  and score 85 on exam 2 

%prob = sigmoid([1 45 85] * theta);
pred_admit=[45 85];
norm_pred_admit=[1,(pred_admit-mu)./sigma];
prob = norm_pred_admit*theta;
fprintf(['For a student with scores 45 and 85, we predict an admission ' ...
         'probability of %f\n'], prob);
fprintf('Expected value: 0.775 +/- 0.002\n\n');

% Compute accuracy on our training set
p = predict(theta, X_norm);

fprintf('Train Accuracy: %f\n', mean(double(p == y)) * 100);
fprintf('Expected accuracy (approx): 89.0\n');
fprintf('\n');

computeCostgrad

function [J] = computeCostgrad(X, y, theta)
  % Initialize some useful values
m = length(y); % number of training examples

% You need to return the following variables correctly 
J = 0;


prediction=sigmoid(X*theta);
prob1=-y'*log(prediction);
prob0=(1-y')*log(1-prediction);
J=1/m*(prob1-prob0);
endfunction

gradientDescent

function [theta, J_hist] = gradientDescent(theta, X, y, alpha, iter)

   m=length(y);
   J_hist=zeros(iter, 1);
  for (i=1:iter)
  prediction=sigmoid(X*theta);
  err=prediction-y;
  newDecrement = (alpha * (1/m) * err' * X); 
  theta=theta-newDecrement';
  J_hist(i)=computeCostgrad(X,y,theta);
  end

endfunction

plotDecisionBoundary

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

功能正常化

function [X_norm, mu, sigma] = featureNormalize(X)

X_norm = X;
mu = zeros(1, size(X, 2));
sigma = zeros(1, size(X, 2));


mu=mean(X);
sigma=std(X);
X_norm1=(X(:,1)-mu(1))/sigma(1);
X_norm2=(X(:,2)-mu(2))/sigma(2);
X_norm=[X_norm1,X_norm2];

有人可以帮助我正确绘制决策边界吗?我认为在绘制决策边界图时,intercept的计算存在一些错误。

1 个答案:

答案 0 :(得分:0)

由于使用了要素缩放,因此权重与原始数据不匹配。

您需要将X_norm传递给plotDecisionBoundary函数,而不是原始数据X,如下所示:

plotDecisionBoundary(theta, X_norm, y);

同样,当您要预测一个新示例时,首先需要使用与计算所得的值相同的值对其进行缩放,以对训练示例进行标准化。

此外,在plotDecisionBoundary中,行axis([30, 100, 30, 100])适合X而不适合X_norm。因此,您需要对其进行更改以适应X_norm的范围(这只是为了舒适起见,您始终可以通过更改缩放比例来更改它,直到找到该行为止)。