⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 toolboxsam.m

📁 matlab写的神经网络的几个演示程序
💻 M
字号:
clc
close all
clear all

InDim=2;%样本输入维数
OutDim=3;% 样本输出维数
figure
title('训练样本');echo off
axis([-2,2,-2,2]);axis on;grid
xlabel('SamIn x');
ylabel('SamIn y');
line([-1 1],[1 1])
line([1 -1],[1 0])
line([-1 -1],[0 1])
line([-1 1],[-0.5 -0.5])
line([-1 1],[-1.5 -1.5])
line([1 1],[-0.5 -1.5])
line([-1 -1],[-0.5 -1.5])
hold on
SamNum=200;%训练样本数
%     rand('state',sum(100*clock))
SamIn=(rand(2,SamNum)-0.5)*4;% 随机产生200个[-2,2]区间样本输入
SamOut=[];
for i=1:SamNum
    Sam=SamIn(:,i);
    x=Sam(1,1);
    y=Sam(2,1);
    if((x>-1)&(x<1))==1
        if ((y>x/2+1/2)&(y<1))==1
            plot(x,y,'r+')
            class=[0 1 0]';
        elseif((y<-0.5)&(y>-1.5))==1
            plot(x,y,'rs')
            class=[0 0 1]';
        else
            plot(x,y,'ro')
            class=[1 0 0]';
        end
    else
        plot(x,y,'ro')
        class=[1 0 0]';
    end
    SamOut=[SamOut class];                  %得到样本对应的类别属性
end
HiddenUnitNum=10;%隐节点数
MaxEpochs=10000;%最大训练次数
lr=0.1;%学习率
E0=0.01;%目标误差

net=newff([-2 2;-2 2],[HiddenUnitNum OutDim],{'logsig','logsig'},'trainbr');%此处采用贝叶斯正则化法。
net=init(net);
net.trainParam.epochs=MaxEpochs;
net.trainParam.goal=E0;
net.trainParam.lr=lr;
[net,tr,NetOut,NetError]=train(net,SamIn,SamOut);

% [net,tr]=newrb(SamIn,SamOut,0.01,1.0,20,1);

% net=newlvq([-2 2;-2 2],8,[13/16 1/16 1/8],0.01);
% net=init(net);
% net.trainParam.show=1;
% net.trainParam.epochs=20;
% net=train(net,SamIn,SamOut);

% net=newelm([-2 2;-2 2],[8 3]);
% net=init(net);
% net.trainParam.show=100;
% net.trainParam.epochs=1000;
% net=train(net,SamIn,SamOut);

% net=newpnn(SamIn,SamOut,0.1);

TestSamNum=500;% 测试样本数
TestSamIn=(rand(2,TestSamNum)-0.5)*4;
% TestSamNum=SamNum;% 测试样本数
% TestSamIn=SamIn;
TestNNOut = sim(net,TestSamIn);
[val nnclass]=max(TestNNOut);

figure
title('测试结果');echo off
axis([-2,2,-2,2]);axis on
grid
xlabel('TestSamIn x');
ylabel('TestSamIn y');
line([-1 1],[1 1]);
line([1 -1],[1 0]);
line([-1 -1],[0 1]);
line([-1 1],[-0.5 -0.5]);
line([-1 1],[-1.5 -1.5]);
line([1 1],[-0.5 -1.5]);
line([-1 -1],[-0.5 -1.5]);
hold on

TestSamOut = [];
for i = 1:TestSamNum
    x = TestSamIn(1,i);
    y = TestSamIn(2,i);
    if nnclass(i)==1
        plot(x,y,'ro');
    elseif nnclass(i)==2
        plot(x,y,'r+');
    else
        plot(x,y,'rs');
    end
    if((x>-1)&(x<1))==1
        if ((y>x/2+1/2)&(y<1))==1
            class = 2;
        elseif((y<-0.5)&(y>-1.5))==1
            class = 3;
        else
            class = 1;
        end
    else
        class = 1;
    end
    TestSamOut = [TestSamOut class];
end

Result = ~abs(nnclass-TestSamOut);     % 正确分类显示为1
Percent = sum(Result)/length(Result)   % 正确分类率

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -