利用逻辑回归分类模型,针对鸢尾花属性中的花瓣长和花瓣宽,实现鸢尾花数据集中山鸢尾和变色鸢尾的分类,使用matlab进行编程
时间: 2024-05-30 22:14:00 浏览: 95
基于MATLAB的鸢尾花数据集分类
5星 · 资源好评率100%
% 加载数据集
load fisheriris
X = [meas(:,3), meas(:,4)];
Y = strcmp(species,'versicolor');
% 划分数据集,70%训练集,30%测试集
idx = randperm(size(X,1));
train_idx = idx(1:round(0.7*size(X,1)));
test_idx = idx(round(0.7*size(X,1))+1:end);
X_train = X(train_idx,:);
Y_train = Y(train_idx,:);
X_test = X(test_idx,:);
Y_test = Y(test_idx,:);
% 训练逻辑回归模型
[B,dev,stats] = glmfit(X_train,Y_train,'binomial','link','logit');
% 预测测试集结果
Y_pred = glmval(B,X_test,'logit');
Y_pred = round(Y_pred);
% 计算准确率
accuracy = sum(Y_pred == Y_test)/length(Y_test)
% 绘制决策边界
x1 = linspace(min(X(:,1)),max(X(:,1)),100);
x2 = linspace(min(X(:,2)),max(X(:,2)),100);
[X1,X2] = meshgrid(x1,x2);
Y_pred = glmval(B,[X1(:),X2(:)],'logit');
Y_pred = round(Y_pred);
Z = reshape(Y_pred,size(X1));
figure;
gscatter(X(:,1),X(:,2),Y,'rb','.');
hold on
contour(X1,X2,Z,[0.5,0.5],'k','LineWidth',2);
xlabel('花瓣长度');
ylabel('花瓣宽度');
title('鸢尾花分类决策边界');
legend('变色鸢尾','山鸢尾','决策边界');
阅读全文