簡體   English   中英

在邏輯回歸中繪制決策邊界

[英]Plotting decision boundary in logistic regression

我在一個看起來像這樣的小數據集上運行邏輯回歸:

在此處輸入圖像描述

在實施梯度下降和成本 function 之后,我在預測階段獲得了 89% 的准確率,但是我想確保一切正常,所以我試圖 plot 分隔兩個數據集的決策邊界線。

下面我展示了顯示成本 function 和 theta 參數的圖表。 可以看出,目前我正在錯誤地打印決策邊界線。

在此處輸入圖像描述

當我縮小決策邊界圖時,我可以看到以下內容: 在此處輸入圖像描述

我的決策邊界繪制在數據集下方。 需要注意的一件事是我使用了特征縮放。

以下是我使用的代碼:

主程序

%% 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');

計算成本梯度

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

梯度下降

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

繪圖決策邊界

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];

任何人都可以幫助我正確繪制決策邊界。 我認為在繪制決策邊界時計算 yintercept 存在一些錯誤。

因為您使用了特征縮放,所以您的權重與原始數據不匹配。

您需要將X_norm傳遞給您的plotDecisionBoundary function,而不是原始數據X ,如下所示:

plotDecisionBoundary(theta, X_norm, y);

同樣,當您想要預測一個新示例時,您首先需要使用您計算的相同值對其進行縮放以標准化您的訓練示例。

此外,在plotDecisionBoundary中, axis([30, 100, 30, 100])適合X而不是X_norm 因此,您需要更改它以適應X_norm的范圍(這只是為了舒適,您始終可以通過更改縮放來更改它,直到找到線)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM