% 功能:手工仿照BP神经网络功能,数据预测建模、没有使用第三方库
clear;close all; clc;
% 网络架构:401-10-1
% 50个样本,每个样本402个变量、输入变量401个、输出变量1个
% y=f(x1,x2,x3,...,x401)
%
%第一步 读取数据
[data,text] = xlsread('yangzheng', '数据', 'B2:OM51');
input=data(:,2:402)'; %载入输入数据
output=data(:,1)'; %载入输出数据
%归一化需要保证每一列是一个样本、因此需要对原始数据进行转置
[inputn,inputps]=mapminmax(input,-1,1);
[outputn,outputps]=mapminmax(output,-1,1);
inputn = inputn';
outputn = outputn';
nnI = 401;% 输入401个
nnM = 10;% 隐含层10个
nnO = 1;% 输出1个
W1=2*rand(nnM,nnI)-1;
W2=2*rand(nnO,nnM)-1;
lr = 0.01;% 学习率为0.01
epochs = 1000;% 训练1000次
for i=1:epochs
[W1,W2]=TrainNET(W1,W2,inputn,outputn,lr);
end
% 单点预测
xtest_=input(:,1);
xtest=mapminmax('apply',xtest_,inputps); % 对样本数据进行归一化
v1test=W1*xtest;
y1test=Sigmond(v1test);
vtest=W2*y1test;
ytest_=Sigmond(vtest);
ytest=mapminmax('reverse',ytest_,outputps);
formatSpec = 'The ytest is %f';
resutstr = sprintf(formatSpec,ytest)
% 多点预测
N=size(inputn,1);
y_ = zeros(1,50);
for i=1:N
x=inputn(i,:)';%401*1
v1=W1*x;%10*401*401*1=10*1
y1=Sigmond(v1);
v2=W2*y1;
y_(i)=Sigmond(v2);
end
y=mapminmax('reverse',y_,outputps);
figure(1)
subplot(121);
plot(y);
xlabel(' ','Fontsize',18);
ylabel(' ','Fontsize',18);
title('预测');
subplot(122);
plot(output);
xlabel(' ','Fontsize',18);
ylabel(' ','Fontsize',18);
title('实测');
figure(2)
plot(y);
hold on
plot(output);
xlabel(' ','Fontsize',18);
ylabel(' ','Fontsize',18);
legend('预测','实测')
function y=Sigmond(x)
y=1./(1+exp(-x));
end
function [W1,W2]=TrainNET(W1,W2,X,D,lr)
a=lr;
N=size(X,1);
for k=1:N
x=X(k,:)';
d=D(k);
v1=W1*x;
y1=Sigmond(v1);
v=W2*y1;
y=Sigmond(v);
e=d-y;
delta=y.*(1-y).*e;
e1=W2'*delta;
delta1=y1.*(1-y1).*e1;
dW2=a*delta*y1';
dW1=a*delta1*x';
W1=W1+dW1;
W2=W2+dW2;
end
end
将训练好的权值保存下来便于后期使用,这样一来移植到C++上仅需将权值矩阵移植即可,不用C++与Matlab混合编译,拖慢计算和控制速度。
数据见:https://download.csdn.net/download/weixin_37928884/86544101