MATLAB手工仿照BP神经网络功能,数据预测建模、没有使用第三方库

% 功能:手工仿照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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杨铮...

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值