bp神经网络的数据分类matlab源代码
%%%清除空间clcclear all ; close all ;%%%训练数据预测数据提取以及归一化%%%下载四类数据load data1 c1load data2 c2load data3 c3load data4 c4%%%%四个特征信号矩阵合成一个矩阵data ( 1:500 , : ) = data1 ( 1:500 , :) ;data ( 501:1000 , : ) = data2 ( 1:500 , : ) ;data ( 1001:1500 , : ) = data3 ( 1:500 , : ) ;data ( 1501:2000 , : ) = data4 ( 1:500 , : ) ;%%%%%%从 1 到 2000 间的随机排序k = rand ( 1 , 2000 ) ;[ m , n ] = sort ( k ) ; %%m 为数值, n 为标号%%%%%%%%%%%输入输出数据 = data ( : , 2:25 ) ;output1 = data ( : , 1) ;%%%%%%把输出从 1 维变到 4 维for i = 1 : 1 :2000switch output1( i ) case 1output( i , :) = [ 1 0 0 0 ] ;case 2 output( i , :) = [ 0 1 0 0 ] ;case 3output( i , :) = [ 0 0 1 0 ] ;case 4output( i , :) = [ 0 0 0 1 ] ;end end%%%%随机抽取 1500 个样本作为训练样本,500 个样本作为预测样本_train = ( n( 1:1500 , : ) )’ ;output_train = output ( n( 1:1500 , : ) )’ ; _test = ( n( 1501:2000 , : ) )’ ; output_test = output ( n( 1501:2000 , : ) )’ ;%%%%输入输出数据归一化[ n , ps ] = mapminmax ( _train ) ;%%%网络结构初始化innum = 24 ; %输入层midnum = 25 ; %隐含层outnum = 4 ; %输出层%权值初始化w1 = rands ( midnum , innum ) ; b1 = rands ( midnum , 1 ) ; w2 = rands ( midnum , outnum ) ;b2 = rands ( outnum , 1) ;w2_1 = w2 ; w2_2 = w2_1 ;w1_1 = w1 ; w1_2 = w1_1 ;b1_1 = b1 ; b1_2 = b1_1 ;b2_1 = b2 ; b2_2 = b2_1 ;%%%学习速率xite = 0.1 ;alfa = 0.01 ;%%%%%网络训练for ii = 1:10E( ii ) = 0 ;for i = 1:1:1500 ;%%网络预测输出x = n ( : , j ) ;%%%隐含层输出for j = 1:1:midnuml (j) = n ( : , i )’*w1( j , : )’ + b1 (j) ;lout (j) = 1/( 1 +exp( -1(j) ) ) ;end%%%%输出层输出yn = w2’ * lout’ + b2 ;%%%权值阈值修正%计算权值变化率dw2 = e * lout ;db2 = e’ ;for j = 1:1:midnum S= 1/(1 + exp ( -l(j) ) ) ;Fl (j) = S * ( 1- S) ;endfor k = 1:1:innumfor j = 1:1:midnumdw1( k, j ) = Fl (j) * x (k) *( e(1)*w2( j,1) + e(2)*w2( j,2) + e(3)*w2( j,3) + e(4)*w2( j,4) ) ;db1( j ) = Fl (j) * *( e(1)*w2( j,1) + e(2)*w2( j,2) + e(3)*w2( j,3) + e(4)*w2( j,4) ) ;end endw1=w1_1+xite*dw1 ;b1=b1_1+xite*db1 ;w2=w2_1+xite*dw2 ;b2=b2_1+xite*db2 ; w1_2=w1_1;w1_1=w1;w2_2=w2_1;w2_1=w2;b1_2=b1_1;b1_1=b1;b2_2=b2_1;b2_1=b2;endend %%%%语音特征信号分类_test = mapminmax ( ‘apply’ , _test , ps );for ii = 1:1for i = 1:500%隐含层输出for j = 1:1:midnuml (j) = _test ( : , i )’ * w1( j , : )’ + b1(j) ; lout ( j ) = 1/ ( 1 + exp( -l(j) ) ) ;endfore( :,i ) = w2’ * lout’ + b2 ;endend%%%结果分析%%%%根据网络输出找出数据属于哪类for i = 1:500output_fore (i) = find ( fore (:,i) = =max (fore(:,i) ) ) ;end%%%%%BP 网络预测输出error = output_fore - output1 ( n( 1501:2000) )’ ;%%画出分类图figure (1)plot ( output_fore , ‘r’ ) hold onplot (output1( n (1501:2000))’ , ‘b’ ) ;legend ( ‘预测语音类别 ’ , ‘实际语音类别 ’ )%%%画出误差图figure (2)plot (error)title ( ‘BP 网络分类误差’ , ‘fontsize’ , 12 )xlabel ( ‘语音信号’ , ‘fontsize’ , ‘12’ )ylabel ( ‘分类误差’ , ‘fontsize’ , 12 )%%%%%找出属于哪种类型for i = 1:500if error (i) ~= 0[ b,c ] = max (output_test( :,i ) );switch ccase 1k(1) = k(1) + 1 ;case 2k(2) = k(2) + 1 ;case 3k(3) = k(3) + 1 ;case 4k(4) = k(4) + 1 ;endendend%%%%找出每一类的个体总和kk = zeros ( 1,4 )for i = 1:500[ b,c ] = max ( output_test( :,i) ) ;switch ccase 1kk(1) = kk(1) + 1 ;case 2kk(2) = kk