运行环境:ubuntu16.10+MATLAB2016a
数据集:
该数据集来自2010年1月11日的UCI机器学习数据库,该数据最早由加拿大安大略省圭尔夫大学计算机系Mary McLeish和Matt Cecile收集。
每一行为一个样本,最后一列为标签。
可自行百度“从疝气病症预测病马的死亡率的数据集”
基于MATLAB的代码:
%%机器学习-logistic回归-使用随机梯度上升算法预测病马死亡率
%%machine learning-logistic regression-predict mortality using stochastic gradient ascent algorithm
clear;
trainSet = importdata('horseColicTraining.txt');
[m,n] = size(trainSet);
trainVectors = zeros(m,n);
trainVectors(:,1) = ones(m,1);
trainVectors(:,2:end) = trainSet(:,1:end-1);
trainLabels = trainSet(:,end);
maxCycles = 500; %最大迭代次数
weights = ones(1,n); %回归系数
rightRate = zeros(1,10);
for k = 1:10
for i = 1:maxCycles
for j = 1:m
alpha = 4.0 / (1.0+i+j) + 0.01; %步长是可变的
randIndex = fix(1+(m-1)*rand);
h = 1.0./(1 + exp(-trainVectors(randIndex,:) * weights'));
error = trainLabels(randIndex) - h;
weights = weights + alpha * error *trainVectors(randIndex,:);
end
end
%%测试
testSet = importdata('horseColicTest.txt');
[m,n] = size(testSet);
testVectors = zeros(m,n);
testVectors(:,1) = ones(m,1);
testVectors(:,2:end) = testSet(:,1:end-1);
testLabels = testSet(:,end);
prob = 1.0./(1 + exp(-testVectors * weights'));
predictLabels = prob>0.5;
rightRate(k) = sum(predictLabels == testLabels) / m;
end
bar(1:10,rightRate);
xlabel('实验次数');
ylabel('正确率');
实验结果:
这是进行了10次实验统计出来的识别正确率,使用MATLAB的mean函数计算十次正确率的平均值,一般在0.65左右。