Error in logistic regression code

13 views (last 30 days)
Tahira Mahar
Tahira Mahar on 24 Jul 2018
Commented: OCDER on 30 Jul 2018
Dear all,
I have X as 18 input and y as 1 output. When i ran the code than extra colmn occure in X? In X there should be 18 inputs but there occure 19 inputs why 1 extra colmn occure?
This is my main code. error in plotdecisionboundry(theta,X,Y)
data=xlsread('MyData');
X = data(:, [1:18]); y = data(:, 19)
fprintf(['Plotting data with + indicating (y = 1) examples and o ' ...
'indicating (y = 0) examples.\n']);
plotData(X, y);
hold on;
xlabel('Cough')
ylabel('Sputum')
legend('Positive', 'Negative')
hold off;
fprintf('\nProgram paused. Press enter to continue.\n
[m, n] = size(X);
X_test
X = [ones(m, 1) X];
initial_theta = zeros(n + 1, 1);
[cost, grad] = costFunction(initial_theta, X, y);
fprintf('Cost at initial theta (zeros): %f\n', cost);
fprintf('Gradient at initial theta (zeros): \n');
fprintf(' %f \n', grad);
fprintf('\nProgram paused. Press
options = optimset('GradObj', 'on', 'MaxIter', 400);
[theta, cost] = ...
fminunc(@(t)(costFunction(t, X, y)), initial_theta, options)
fprintf('Cost at theta found by fminunc: %f\n', cost);
fprintf('theta: \n');
fprintf(' %f \n', theta);
plotDecisionBoundary(theta, X, y);
hold on;
xlabel('Cough')
ylabel('Sputum')
legend('yes', 'no')
hold off;
fprintf('\nProgram paused. Press enter to continue.\n');
pause;
prob = sigmoid([1 1 1] * theta);
fprintf(['For a student with scores 45 and 85, we predict an admission ' ...
'probability of %f\n\n'], prob);
p = predict(theta, X);
fprintf('Train Accuracy: %f\n', mean(double(p == y)) * 100);
fprintf('\nProgram paused. Press e
This is the plot decision boundry code error in this line
Error. z(i,j) = mapFeature(u(i), v(j))*theta
Plot decision boundry code here
Plotdecisionboundry(theta,X,Y)
plotData(X(:,2:3), y);
hold on
if size(X, 2) <= 3
plot_x = [min(X(:,2))-2, max(X(:,2))+2];
plot_y = (-1./theta(3)).*(theta(2).*plot_x + theta(1));
plot(plot_x, plot_y)
legend('Admitted', 'Not admitted', 'Decision Boundary')
axis([30, 100, 30, 100])
else
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'; %
the range [0, 0]
contour(u, v, z, [0, 0], 'LineWidth', 2)
end
hold off
end

Accepted Answer

OCDER
OCDER on 24 Jul 2018
Your code does grow X by 1 column of 1's. See below
data=xlsread('MyData');
X = data(:, [1:18]);
y = data(:, 19)
plotData(X, y);
hold on;
xlabel('Cough')
ylabel('Sputum')
legend('Positive', 'Negative')
hold off;
[m, n] = size(X);
X_test
X = [ones(m, 1) X]; %There is your grow X by 1-column line!!!!!!!!!! Now X has 19 columns
  11 Comments
Walter Roberson
Walter Roberson on 26 Jul 2018
To post code, paste it in to the window here. Then select it with your mouse, and then click the '{} Code' button.
OCDER
OCDER on 26 Jul 2018
You could also use the Paperclip icon to attach files. It's better to use the forum because you get the help of many experts, and if the problem is stated clearly, you'll get an answer faster.
If I were you, I'd start a new question explaining the detail of what the new error is. This Q&A is "complete" in that the question of "why 1 extra column occur in X?" is solved and you "Accepted" the answer.
In the new forum Question, provide the .m files, FULL ERROR MESSAGE, and explain BRIEFLY what you are trying to do.
------------------------------------------------------------------
EX:
"How to solve "Error: ....(the error you get)"?
I'm trying to plot the ...., but I get an error. I recently removed column 1 from X, and now this error occurs. < https://www.mathworks.com/matlabcentral/answers/411826-error-in-logistic-regression-code >
Here is the full Error Message:
Error: the full error message
error on line XXX on plotdecisionBoundary
Here are the codes needed to do this (.zip or .m files, AND MyData.xlsx)
Here is what I did to generate the error:
data=xlsread('MyData');
X = data(:, [1:18]); y = data(:, 19)
% (REMOVE extra codes, like fprintf, that are not needed.
% Provide only the minimal set of codes required to create error!
Plotdecisionboundry(theta,X,Y) %ERROR HERE, LINE 123
plotData(X(:,2:3), y); %ERROR HERE, LINE 32
Here are the error lines
%Plotdecisionboundary
Line 123: plOt(x, y) %Error: unrecognized function plOt
%plotData
Line 23: a{1) = 1; Error: Unbalanced or unexpected parenthesis or bracket.
---------------------------------------------------------
Essentially, someone in this forum should just be able to download your stuff, run the script, and generate the error. BEFORE posting, format everything nicely.

Sign in to comment.

More Answers (3)

Tahira Mahar
Tahira Mahar on 28 Jul 2018
Dear OCDER, Here are some functions of my code kindly check and get error
  1 Comment
Tahira Mahar
Tahira Mahar on 28 Jul 2018
Edited: Tahira Mahar on 28 Jul 2018
Here are error lines
%ex2.m
plotDecisionBoundary(theta, X, y); % error here
%plotdecisionboundry
z(i,j) =mapFeature(u(i), v(j))*theta; % error here
kindly check and tell me what the actually problem in my code

Sign in to comment.


Tahira Mahar
Tahira Mahar on 28 Jul 2018
Edited: Walter Roberson on 28 Jul 2018
some functions missing above and can't upload because we can upload just 10 files daily so i paste remaining functions here
This is the submit function
function submit()
addpath('./lib');
conf.assignmentSlug = 'support-vector-machines';
conf.itemName = 'Support Vector Machines';
conf.partArrays = { ...
{ ...
'1', ...
{ 'gaussianKernel.m' }, ...
'Gaussian Kernel', ...
}, ...
{ ...
'2', ...
{ 'dataset3Params.m' }, ...
'Parameters (C, sigma) for Dataset 3', ...
}, ...
{ ...
'3', ...
{ 'processEmail.m' }, ...
'Email Preprocessing', ...
}, ...
{ ...
'4', ...
{ 'emailFeatures.m' }, ...
'Email Feature Extraction', ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
function out = output(partId, auxstring)
% Random Test Cases
x1 = sin(1:10)';
x2 = cos(1:10)';
ec = 'the quick brown fox jumped over the lazy dog';
wi = 1 + abs(round(x1 * 1863));
wi = [wi ; wi];
if partId == '1'
sim = gaussianKernel(x1, x2, 2);
out = sprintf('%0.5f ', sim);
elseif partId == '2'
load('ex6data3.mat');
[C, sigma] = dataset3Params(X, y, Xval, yval);
out = sprintf('%0.5f ', C);
out = [out sprintf('%0.5f ', sigma)];
elseif partId == '3'
word_indices = processEmail(ec);
out = sprintf('%d ', word_indices);
elseif partId == '4'
x = emailFeatures(wi);
out = sprintf('%d ', x);
end
end
This is costfunctionreg
function [J, grad] = costFunctionReg(theta, X, y, lambda)
J = COSTFUNCTIONREG(theta, X, y, lambda)
m = length(y); %
J = 0;
grad = zeros(size(theta));
lambda=0.1;
templog(:,1) = log(sigmoid(X*theta));
templog(:,2) = log(1-(sigmoid(X*theta)));
tempy(:,1) = y;
tempy(:,2) = 1-y;
temp = templog.*tempy;
J = (1/m)*(-sum(temp(:,1))-sum(temp(:,2))) +(lambda/(2*m))*sum(theta(2:end,1).^2);
grad(1,1) = (1/m)*sum((sigmoid(X*theta)-y).*X(:,1));
grad(2:end,1)=((1/m)*((sigmoid(X*theta)-y)'*X(:,2:end)))'+(lambda/m)*theta(2:end);
grad = grad(:);
% =============================================================
end
end
This is costfunction
function [J, grad] = costFunction(theta, X, y)
% J = COSTFUNCTION(theta, X, y)
m = length(y)
J = 0;
grad = zeros(size(theta));
hx = sigmoid(X * theta);
m = length(X);
J = sum(-y' * log(hx) - (1 - y')*log(1 - hx)) / m;
grad = X' * (hx - y) / m;
end

Tahira Mahar
Tahira Mahar on 28 Jul 2018
Edited: Tahira Mahar on 28 Jul 2018
Dear OCDER and walter, kindly reply now i clearly and nicely upload my code and explain my error line .error in just two lines which mentioned above.
  1 Comment
OCDER
OCDER on 30 Jul 2018
Okay..... sooo... did you read, understand, and apply ANYTHING on that link? Did you take my advice on 26th? I even gave you a template, which I'm realizing might have been a waste of time...
What are you defending for again? We expect anyone with an academic degree to be able to : ask proper questions, learn quickly, apply knowledge to solve a problem, and communicate effectively.
The fact that you are posting comments on the "ANSWER" section, not starting a new Question on the forum as recommended, not providing a "FULL ERROR MESSAGE", not providing the script to generate the error, and demanding us to answer NOW baffles me...
If you need immediate help, kindly ask a colleage who knows Matlab, and make sure to BUY DINNER(S) for this person! It'll be much faster and you'll get to see the debugging process in person, which helps.

Sign in to comment.

Categories

Find more on Introduction to Installation and Licensing in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!