gpt4 book ai didi

matlab - matlab中的正则逻辑回归代码

转载 作者:太空宇宙 更新时间:2023-11-03 19:15:40 25 4
gpt4 key购买 nike

我正在尝试正则化 LR,使用 matlab 中的这个公式很简单:

代价函数:

J(theta) = 1/m*sum((-y_i)*log(h(x_i)-(1-y_i)*log(1-h(x_i))))+(lambda/2*m)*sum(theta_j)

渐变:

∂J(theta)/∂theta_0 = [(1/m)*(sum((h(x_i)-y_i)*x_j)] if j=0

∂j(theta)/∂theta_n = [(1/m)*(sum((h(x_i)-y_i)*x_j)]+(lambda/m)*(theta_j) if j>1

这不是matlab代码,只是公式。

到目前为止,我已经这样做了:

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

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

temp_theta = [];

%cost function

%get the regularization term

for jj = 2:length(theta)

temp_theta(jj) = theta(jj)^2;
end

theta_reg = lambda/(2*m)*sum(temp_theta);

temp_sum =[];

%for the sum in the cost function

for ii =1:m

temp_sum(ii) = -y(ii)*log(sigmoid(theta'*X(ii,:)'))-(1-y(ii))*log(1-sigmoid(theta'*X(ii,:)'));

end

tempo = sum(temp_sum);

J = (1/m)*tempo+theta_reg;

%regulatization
%theta 0

reg_theta0 = 0;

for jj=1:m
reg_theta0(jj) = (sigmoid(theta'*X(m,:)') -y(jj))*X(jj,1)
end

reg_theta0 = (1/m)*sum(reg_theta0)

grad_temp(1) = reg_theta0

%for the rest of thetas

reg_theta = [];
thetas_sum = 0;

for ii=2:size(theta)
for kk =1:m
reg_theta(kk) = (sigmoid(theta'*X(m,:)') - y(kk))*X(kk,ii)
end
thetas_sum(ii) = (1/m)*sum(reg_theta)+(lambda/m)*theta(ii)
reg_theta = []
end

for i=1:size(theta)

if i == 1
grad(i) = grad_temp(i)
else
grad(i) = thetas_sum(i)
end
end
end

并且成本函数给出了正确的结果,但我不知道为什么梯度(一步)不正确,成本给出的 J = 0.6931 是正确的,而梯度 grad = 0.3603 -0.1476 0.0320 不是,成本从 2 开始,因为参数 theta(1) 不必正则化,有帮助吗?我猜代码有问题,但 4 天后我看不到它。谢谢

最佳答案

矢量化:

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

hx = sigmoid(X * theta);
m = length(X);

J = (sum(-y' * log(hx) - (1 - y')*log(1 - hx)) / m) + lambda * sum(theta(2:end).^2) / (2*m);
grad =((hx - y)' * X / m)' + lambda .* theta .* [0; ones(length(theta)-1, 1)] ./ m ;

end

关于matlab - matlab中的正则逻辑回归代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19824293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com