clear all;
xlsfile='sex.xls';
[data,label]=getdata(xlsfile);
[traind,trainl,testd,testl]=divide(data,label);
% 设置参数
rng('default')
rng(0)
nTrainNum=60;%60个训练样本
nSampDim=2;%样本是二维的
% 构造网络
net.nIn=2;
net.nHidden=3;%3个隐含节点
net.nOut=1;
w1=2*(rand(net.nHidden,net.nIn)-1/2);
b1=2*(rand(net.nHidden,1)-1/2);
net.w1=[w1,b1];
W=2*(rand(net.nOut,net.nHidden)-1/2);
B=2*(rand(net.nOut,1)-1/2);
net.w2=[W,B];
% 训练数据归一化
mm=mean(traind);
% 均值平移
for i=1:2
traind_s(:,i)=traind(:,i)-mm(i);
end
% 方差标准化
ml(1)=std(traind_s(:,1));
ml(2)=std(traind_s(:,2));
for i=1:2
traind_s(:,i)=traind(:,i)/ml(1);
end
% 训练
SampInEx=[traind_s';ones(1,nTrainNum)];
expectedOut=trainl;
eb=0.01;
eta=0.6;
mc=0.8;
maxiter=2000;
iteration=0;
errRec=zeros(1,maxiter);
outRec=zeros(nTrainNum,maxiter);
NET=[];
% 开始迭代
for i=1:maxiter
hid_input=net.w1*SampInEx;
hid_out=logsig(hid_input);
ou_input1=[hid_out;ones(1,nTrainNum)];
ou_input2=net.w2*ou_input1;
out_out=logsig(ou_input2);
outRec(:,i)=out_out';%记录每次迭代输出
err=expectedOut-out_out;%误差
sse=sumsqr(err);
errRec(i)=sse;
fprintf('第%d次迭代 误差: %f\n',i,sse);
iteration=iteration+1;
%判断是否收敛
if sse<=eb
break;
end
%误差反向传播
%隐含层与输出层之间的局部梯度
delta2=err.*dlogsig(ou_input2,out_out);
%输入层与隐含层之间的局部梯度
delta1=net.w2(:,1:end-1)'*delta2.*dlogsig(hid_input,hid_out);
%权值修改量
dwex2=delta2*ou_input1';
dwex1=delta1*SampInEx';
%修改权值,如果不是第一次修改,则使用动量因子
if i == 1
net.w2=net.w2+eta*dwex2;
net.w1=net.w1+eta*dwex1;
else
net.w2=net.w2+(1-mc)*eta*dwex2+mc*dwexold2;
net.w1=net.w1+(1-mc)*eta*dwex1;+mc*dwexold1;
end
% 记录上一次的权值修改量
dwexold2=dwex2;
dwexold1=dwex1;
end
% 测试数据归一化
for i=1:2
testd_s(:,i)=testd(:,i)-mm(i);
end
for i=1:2
testd_s(:,i)=testd(:,i)/mm(i);
end
% 计算测试输出
InEx=[testd_s';ones(1,360-nTrainNum)];
hid_input=net.w1*InEx;
hid_out=logsig(hid_input);
ou_input1=[hid_out;ones(1,360-nTrainNum)];
ou_input2=net.w2*ou_input1;
out_out=logsig(ou_input2);
out_out1=out_out;
%取整
out_out(out_out<0.5)=0;
out_out(out_out>=0.5)=1;
%正确率
rate=sum(out_out==testl)/length(out_out);
% 显示训练样本
train_m=traind(trainl==1,:);
train_m=train_m';
train_f=traind(trainl==0,:);
train_f=train_f';
figure(1)
plot(train_m(1,:),train_m(2,:),'bo');
hold on;
plot(train_f(1,:),train_f(2,:),'r*');