Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Matlab logistic回归成本的向量化_Matlab_Vectorization_Logistic Regression - Fatal编程技术网

Matlab logistic回归成本的向量化

Matlab logistic回归成本的向量化,matlab,vectorization,logistic-regression,Matlab,Vectorization,Logistic Regression,我在matlab中有逻辑回归中的成本代码: function [J, grad] = costFunction(theta, X, y) m = length(y); % number of training examples thetas = size(theta,1); features = size(X,2); steps = 100; alpha = 0.1; J = 0; grad = zeros(size(theta)); sums = []; result = 0; fo

我在matlab中有逻辑回归中的成本代码:

function [J, grad] = costFunction(theta, X, y)

m = length(y); % number of training examples
thetas = size(theta,1);
features = size(X,2);
steps = 100;
alpha = 0.1;

J = 0;
grad = zeros(size(theta));


sums = [];
result = 0;

for i=1:m

%    sums = [sums; (y(i))*log10(sigmoid(X(i,:)*theta))+(1-y(i))*log10(1-sigmoid(X(i,:)*theta))]

    sums = [sums; -y(i)*log(sigmoid(theta'*X(i,:)'))-(1-y(i))*log(1-sigmoid(theta'*X(i,:)'))];

    %use log simple not log10, mistake
end

result = sum(sums);
J = (1/m)* result;


%gradient one step

tempo = [];
thetas_update = 0;
temp_thetas = [];


grad = temp_thetas;

for i = 1:size(theta)
    for j = 1:m
        tempo(j) = (sigmoid(theta'*X(j,:)')-y(j))*X(j,i);
    end
    temp_thetas(i) = sum(tempo);
    tempo = [];
end

grad = (1/m).*temp_thetas;

% =============================================================

end

我需要矢量化它,但我不知道它是如何做到的,为什么?我是一名程序员,所以我喜欢for的。但要将其矢量化,我是空白的。有什么帮助吗?谢谢。

代码应该是什么

function [J, grad] = costFunction(theta, X, y)
hx = sigmoid(X * theta);
m = length(X);

J = (-y' * log(hx) - (1 - y')*log(1 - hx)) / m;
grad = X' * (hx - y) / m;

end
function[J,grad]=costFunction(θ,X,y)
hx=乙状结肠(X'*θ);
m=长度(X);
J=总和(-y*log(hx)-(1-y)*log(1-hx))/m;
梯度=X'*(hx-y)/m;
结束

这太简单了,想解释一下吗?:)通过使用矩阵乘法,可以去掉i=1:m的
和i=1:size(θ)的
。然后代码变小:)
J=-(1/m)*(log(hX')*y+log(1-hX')*(1-y))@FranckDernoncourt我想出了同样的解决方案。这是令人沮丧的,因为他们经常引用
theta'*X
,但它与他们的向量构造不兼容。@FranckDernoncourt为什么必须求和?J不是1x1向量吗?或者只是将其作为标量而不是向量返回?