【发布时间】:2015-04-06 21:04:09
【问题描述】:
我试图在不调用任何 matlab 支持的函数的情况下实现逻辑回归算法,然后我调用 matlab 函数进行逻辑回归mnrfit,因此我可以交叉确认我的算法运行良好。
我正在实施的过程如下。我首先制作一个包含输入数据的向量 x 和一个向量 y [0,1],其中每个数据 x 都有相应的类。我使用梯度下降对这些数据实现线性回归,一旦我提取系数,我就通过 sigmoid 函数传递线。稍后我对 x=10 进行预测,以找到该输入的第 1 类的可能性。就这么简单。。
之后我调用 matlab 函数 mnrfit 并提取逻辑回归的系数。为了做出同样的预测,我用参数 10 调用函数mnrval,因为我想像以前一样预测输入 x=10。我的结果不同,我不知道为什么..
最后显示了提取的 2 个图,显示每个案例的概率密度函数。
我还附上了实现的代码。
% x is the continues input and y is the category of every output [1 or 0]
x = (1:100)'; % independent variables x(s)
y(1:10) = 0; % Dependent variables y(s) -- class 0
y(11:100) = 1; % Dependent variables y(s) -- class 1
y=y';
y = y(randperm(length(y))); % Random order of y array
x=[ones(length(x),1) x]; % This is done for vectorized code
%% Initialize Linear regression parameters
m = length(y); % number of training examples
% initialize fitting parameters - all zeros
Alpha = 0; % gradient
Beta = 0; % offset
% Some gradient descent settings
% iterations must be a big number because we are taking very small steps .
iterations = 100000;
% Learning step must be small because the line must fit the data between
% [0 and 1]
Learning_step_a = 0.0005; % step parameter
%% Run Gradient descent
fprintf('Running Gradient Descent ...\n')
for iter = 1:iterations
% In every iteration calculate objective function
h= Alpha.*x(:,2)+ Beta.*x(:,1);
% Update line variables
Alpha=Alpha - Learning_step_a * (1/m)* sum((h-y).* x(:,2));
Beta=Beta - Learning_step_a * (1/m) * sum((h-y).*x(:,1));
end
% This is my linear Model
LinearModel=Alpha.*x(:,2)+ Beta.*x(:,1);
% I pass it through a sigmoid !
LogisticRegressionPDF = 1 ./ (1 + exp(-LinearModel));
% Make a prediction for p(y==1|x==10)
Prediction1=LogisticRegressionPDF(10);
%% Confirmation with matlab function mnrfit
B=mnrfit(x(:,2),y+1); % Find Logistic Regression Coefficients
mnrvalPDF = mnrval(B,x(:,2));
% Make a prediction .. p(y==1|x==10)
Prediction2=mnrvalPDF(10,2);
%% Plotting Results
% Plot Logistic Regression Results ...
figure;
plot(x(:,2),y,'g*');
hold on
plot(x(:,2),LogisticRegressionPDF,'k--');
hold off
title('My Logistic Regression PDF')
xlabel('continues input');
ylabel('propability density function');
% Plot Logistic Regression Results (mnrfit) ...
figure,plot(x(:,2),y,'g*');
hold on
plot(x(:,2),mnrvalPDF(:,2),'--k')
hold off
title('mnrval Logistic Regression PDF')
xlabel('continues input');
ylabel('propability density function')
为什么我的情节(只要预测)每个案例都不一样??
- 您可能提取的输出在每次执行时都会有所不同,因为 y 向量中 1 和 0 的顺序是随机的。
【问题讨论】:
-
有什么建议吗?
-
您的评论没有通知任何人。您可以对我的回答发表评论,让我知道您编辑了问题;照原样,直到现在我才知道编辑。你问为什么情节不同。但逻辑回归与由 sigmoid 组成的线性回归不同。从数学上讲,没有理由期望这两个过程会产生相同的结果。
-
是的,我看到我的评论没有通知任何人,我很惊讶,因为这是一个简单的问题。如果我的问题有误,那么有人必须再次告诉我,我在问一些无法理解的问题。无论如何,你能向我解释为什么它不一样(Logistic Regression vs Linear through sigmoid)吗?从互联网上的例子中我可以理解。如何通过非矢量化 matlab 代码正确实现逻辑回归?
标签: matlab logistic-regression