三层神经网络实现分类器

一、简介

神经网络模型是一种模仿生物大脑的神经元连接,提出的一种计算模型。目前已在人工智能领域取得了广泛的应用。

下图为一个神经元的抽象模型,一个神经元接收来自其他神经元的信号,对信号进行加和后作一个激励,然后输出。

三层神经网络实现分类器_第1张图片   三层神经网络实现分类器_第2张图片

二、实现

原始数据共有30个,分为3类,每类10个:
samples1=[
1.58 2.32 -5.8;
0.67 1.58 -4.78;
1.04 1.01 -3.63;
-1.49 2.18 -3.39;
-0.41 1.21 -4.73;
1.39 3.16 2.87;
1.20 1.40 -1.89;
-0.92 1.44 -3.22;
0.45 1.33 -4.38;
-0.76 0.84 -1.96;
];
samples2=[
0.21 0.03 -2.21;
0.37 0.28 -1.8;
0.18 1.22 0.16;
-0.24 0.93 -1.01;
-1.18 0.39 -0.39;
0.74 0.96 -1.16;
-0.38 1.94 -0.48;
0.02 0.72 -0.17;
0.44 1.31 -0.14;
0.46 1.49 0.68;
];
samples3=[
-1.54 1.17 0.64;
5.41 3.45 -1.33;
1.55 0.99 2.69;
1.86 3.19 1.51;
1.68 1.79 -0.87;
3.51 -0.22 -1.39;
1.40 -0.44 -0.92;
0.44 0.83 1.97;
0.25 0.68 -0.99;
0.66 -0.45 0.08;
];
samples=[samples1;samples2;samples3];
labels=zeros(size(samples));
labels(1:10,1)=1;
labels(11:20,2)=1;
labels(21:30,3)=1;
save -v7 'data.mat' samples labels;

除了原始数据,还要构造one-hot vector指示向量。因为一共有3类,所以网络的输出层的节点数为3,对于每个数据,用一个三维向量来指示数据具体属于哪一类,one-hot vector为对应位上为1,其余位为0,这就是网络训练的目标值。这样通过对输入数据的训练,我们的网络能对将输入数据输出为一个one-hot vector即完成了对数据的分类。

为了实现对上述数据的分类,采用包含一个隐含层的三层前馈神经网络,结构如下图。并且采用梯度下降算法对网络参数进行优化。
三层神经网络实现分类器_第3张图片

matlab/octave 代码:

clear;
load data.mat
samples=[samples ones(size(samples,1),1)];
nn=size(samples,1); %number of samples
ni=size(samples,2); %number of input layer nodes
nh=8;   %number of hidden layer nodes
nj=3;   %number of output layer nodes
eta=0.5;    %learning rate
theta=0.0001;   %criterion threshold
Jw=[0]; %errors of traning
wih=rand(ni,nh)-0.5;
whj=rand(nh,nj)-0.5;
for r=0:1000
  for k=1:nn
    rk=randi(nn);
    xi=samples(rk,:);  %kth sample
    tj=labels(rk,:);   %expected output
    neth=xi*wih;  %hidden layer net
    yh=tanh(neth);  %hidden layer out and activation function is tanh
    netj=yh*whj;  %output lay net
    zj=sigmoid(netj); %output layer out and activation function is sigmoid
    delta_j=(sigmoid(netj).*(1-sigmoid(netj))).*(tj-zj);
    delta_h=(1-tanh(neth).^2).*(delta_j*whj');
    delta_whj=eta*yh'*delta_j;
    delta_wih=eta*xi'*delta_h;
    whj=whj+delta_whj;
    wih=wih+delta_wih;
  end 
  result=sigmoid(tanh(samples*wih)*whj);
  Jw=[Jw sum(sum((labels-result).^2))];
  delta_Jw=abs(Jw(end)-Jw(end-1));
  if delta_Jw


你可能感兴趣的:(matlab,人工智能,神经网络)