本文接着上一篇《Logistic回归分类----梯度上升法》,升级为随机梯度上升法。同理,《机器学习实战》一书改编而来,测试数据依然保存在网盘上,https://pan.baidu.com/s/1qY9jFsg。相比梯度上升算法,随机梯度上升算法的优势在于大大减少了循环次数,提高分类的效率。
以下为改编的Matlab的程序:
clc;
clear;
%加载测试数据文件,前两列为坐标值,后两列为类标号
fileID = fopen('D:\matlabFile\Logistic\Logistic.txt');
DS=textscan(fileID,'%f %f %f');
fclose(fileID);
%将数据转为矩阵形式
DataMat=cat(2,DS{1},DS{2});
%在dataMat第一列之前再增加都为1的列
[Row,Column]=size(DataMat);
DataMat=cat(2,ones(Row,1),DataMat);
LabelMat=DS{3};
%重新获得行列数
[Row,Column]=size(DataMat);
%%%===利用梯度上升法寻找最佳参数
%设定迭代次数
numIter=150;
%初始化系数矩阵为1
Weight=ones(Column,1);
%循环中止条件
flag=1;
while flag<numIter+1
%生成随机序号数组
dataIndex=unidrnd(Row,1,Row);
%计算所有样本的梯度
for i=1:Row
%设定Alpha值
Alpha=4/(1+i+flag)+0.001;
%随机选取更新的项的序号
randIndex=unidrnd(length(dataIndex));
%计算每一个样本的梯度
h=sigmf(DataMat(dataIndex(randIndex),:)*Weight,[1,0]);
%计算误差
Error=LabelMat(dataIndex(randIndex))-h;
%更新系数矩阵
Weight=Weight+Alpha*DataMat(dataIndex(randIndex),:)'*Error;
%将上述序号从序号数组中删除
dataIndex(randIndex)=[];
end
flag=flag+1;
end
%画出原始点集
scatter(DataMat(:,2),DataMat(:,3),'filled');
hold on
%画出最佳拟合曲线
%定义X的取值范围
x=-3:0.1:3;
%计算Y的值域范围
y=(-Weight(1)-Weight(2)*x')/Weight(3);
plot(x,y,'r');
以下为仿真结果: