matlab - 逻辑回归代价的向量化

标签 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;

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

关于matlab - 逻辑回归代价的向量化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19938565/

相关文章:

matlab - 测试周围的非零元素

matlab - 你如何对函数句柄进行符号微分?

python - 3d 数组的 Numpy 元素乘积

pyspark - 如何将从逻辑回归模型获得的系数映射到pyspark中的特征名称

machine-learning - 为什么逻辑回归称为回归?

linux - 如何为当前工作目录起别名

matlab,我如何写一个语句,从 y=0.3 开始在 xaxis 上给我时间

python - numpy数组操作方法

python - 随机矩阵所有行的快速随机加权选择

python - 从逻辑回归(Python)中获取摘要