逻辑回归成本的向量化 [英] Vectorization of logistic regression cost

查看:123
本文介绍了逻辑回归成本的向量化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在matlab中,我有以下代码用于逻辑回归:

I have this code for the cost in logistic regression, in 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的.但是要向量化,我是空白.有什么帮助吗?谢谢.

And I need to vectorize it, but I do not know how do it do it and why? I'm a programmer so I like the for's. But to vectorize it, I'm blank. Any help? Thanks.

推荐答案

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

这篇关于逻辑回归成本的向量化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆