写一个适用于一下代码的能运行出matlab图的代码% 加载数据 load fisheriris.mat X = meas'; Y = zeros(3,length(species)); for i = 1:length(species) if strcmp(species{i},'setosa') Y(1,i) = 1; elseif strcmp(species{i},'versicolor') Y(2,i) = 1; elseif strcmp(species{i},'virginica') Y(3,i) = 1; end end % 将数据集分为训练集和测试集 [trainInd,testInd] = dividerand(length(species),0.7,0.3); X_train = X(:,trainInd); Y_train = Y(:,trainInd); X_test = X(:,testInd); Y_test = Y(:,testInd); % 设置神经网络参数 inputSize = size(X_train,1); hiddenSize = 10; outputSize = size(Y_train,1); net = feedforwardnet(hiddenSize); % 训练神经网络 net.trainFcn = 'trainlm'; net.trainParam.epochs = 100; net.trainParam.goal = 0.01; net = train(net,X_train,Y_train); % 测试神经网络 Y_pred = net(X_test); [~,Y_pred] = max(Y_pred); [~,Y_test] = max(Y_test); % 计算准确率 accuracy = sum(Y_pred == Y_test)/length(Y_test); disp(['Accuracy: ',num2str(accuracy*100),'%']);
时间: 2024-02-21 12:57:25 浏览: 59
Gabor滤波matlab代码,有测试图,可运行
以下是适用于上述代码的 MATLAB 代码,可以生成分类结果的可视化图表:
```
% 加载数据
load fisheriris.mat
X = meas';
Y = zeros(3,length(species));
for i = 1:length(species)
if strcmp(species{i},'setosa')
Y(1,i) = 1;
elseif strcmp(species{i},'versicolor')
Y(2,i) = 1;
elseif strcmp(species{i},'virginica')
Y(3,i) = 1;
end
end
% 将数据集分为训练集和测试集
[trainInd,testInd] = dividerand(length(species),0.7,0.3);
X_train = X(:,trainInd);
Y_train = Y(:,trainInd);
X_test = X(:,testInd);
Y_test = Y(:,testInd);
% 设置神经网络参数
inputSize = size(X_train,1);
hiddenSize = 10;
outputSize = size(Y_train,1);
net = feedforwardnet(hiddenSize);
% 训练神经网络
net.trainFcn = 'trainlm';
net.trainParam.epochs = 100;
net.trainParam.goal = 0.01;
net = train(net,X_train,Y_train);
% 测试神经网络
Y_pred = net(X_test);
[~,Y_pred] = max(Y_pred);
[~,Y_test] = max(Y_test);
% 计算准确率
accuracy = sum(Y_pred == Y_test)/length(Y_test);
disp(['Accuracy: ',num2str(accuracy*100),'%']);
% 绘制分类结果图表
figure;
gscatter(X_test(1,:),X_test(2,:),Y_pred);
hold on;
gscatter(X_test(1,:),X_test(2,:),Y_test,'k','o',8);
xlabel('Sepal length');
ylabel('Sepal width');
legend('Predicted Setosa','Predicted Versicolor','Predicted Virginica','Actual Setosa','Actual Versicolor','Actual Virginica','Location','best');
```
这段代码会生成一个散点图,其中预测的分类结果用不同颜色的点表示,实际分类结果用黑色圆圈表示。图表的横坐标和纵坐标分别表示花萼长度和花萼宽度。图表还包括一个图例,显示了预测的三个分类和实际的三个分类。
阅读全文