回忆
----------------------------------------------------------------------------------------------------------------------
训练集合
其中有n个特征,只有一个,那么假如有如下关系:
则:
-----------------------------------------------------------------------------------------------------------------------
Logistic函数(Sigmoid函数):
让则:
cost function:
其中:
计算,
处理步骤:
其中:
现在来证明logistic函数和线性回归函数的梯度表达是一样的:
线性回归的梯度:
logistic的梯度:
又因为:
那么:
其中z就是式中的h,所以和线性回归一样的梯度函数:
实验:
%逻辑回归 %初始数据 x=[-3; -2; -1; 0; 1; 2; 3]; y=[0.01; 0.1; 0.3; 0.45; 0.8; 0.8; 0.99]; plot(x,y,'ro'); hold on %拟合 m = length(y); theta = [0 0]; a=0.005; loss = 1; iters = 1; eps = 0.0001; while loss >eps && iters <100 loss = 0; for i = 1:length(y) h = 1./(1+exp(-(theta(1)+theta(2)*x(i)))); theta(1)=theta(1)+a*(y(i)-h); theta(2)=theta(2)+a*(y(i)-h)*x(i,1); err = theta(1)+theta(2)*x(i,1)-y(i); loss = loss+err*err/m; end iters = iters+1; end iters theta %画图对比 for x = -3:0.01:3 h = 1./(1+exp(-(theta(1)+theta(2)*x))); plot(x,h); end hold off
时间: 2024-10-13 10:00:33