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i:i+lag-1)';
end
targets=x(lag+1:end);
%创建网络
hiddenLayerSize = 10; %隐藏层神经元个数
net = fitnet(hiddenLayerSize);
% 避免过拟合,划分训练,测试和验证数据的比例
net.divideParam.trainRatio = 70/100;
net.divideParam.valRatio = 15/100;
net.divideParam.testRatio = 15/100;
%训练网络
[net,tr] = train(net,inputs,targets);
%% 根据图表判断拟合好坏
yn=net(inputs);
errors=targets-yn;
figure, ploterrcorr(errors) %绘制误差的自相关情况(20lags)
figure, parcorr(errors) %绘制偏相关情况
%[h,pValue,stat,cValue]= lbqtest(errors) %Ljung-Box Q检验(20lags)
figure,plotresponse(con2seq(targets),con2seq(yn)) %看预测的趋势与原趋势
%figure, ploterrhist(errors) %误差直方图
%figure, plotperform(tr) %误差下降线
%% 下面预测往后预测几个时间段
fn=5; %比如预测步数为fn.
f_in=iinput(n-lag+1:end)';
f_out=zeros(1,fn); %预测输出
% 多步预测时,用下面的循环将网络输出重新输入
for i=1:fn
f_out(i)=net(f_in);
f_in=[f_in(2:end);f_out(i)];
end
% 画出预测图
figure,plot(1:n,iinput,'b',n:n+fn,[iinput(end),f_out],'r')
效果不是很好,但未来5个点风速应该是增大的.