天天看點

BP神經網絡預測(人口)程式(matlab)

自己測試人口預測的matlab實作:

x=[54167    
55196    
56300    
57482    
58796    
60266    
61465    
62828    
64653    
65994    
67207    
66207    
65859    
67295    
69172    
70499    
72538    
74542    
76368    
78534    
80671    
82992    
85229    
87177    
89211    
 90859    
 92420    
 93717    
 94974    
 96259    
 97542    
 98705    
100072    
101654    
103008    
104357    
105851    
107507    
109300    
111026    
112704    
114333    
115823    
117171    
118517    
119850    
121121    
122389    
123626    
124761    
125786    
126743    
127627    
128453    
129227    
129988    
130756    
131448    
132129    
132802    
134480    
135030    
135770    
136460    
137510]';
% 該腳本用來做NAR神經網絡預測
lag=3;    % 自回歸階數
iinput=x;    % x為原始序列(行向量)
n=length(iinput);

%準備輸入和輸出資料
inputs=zeros(lag,n-lag);
for i=1:n-lag
    inputs(:,i)=iinput(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=7;  %預測步數為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(1949:2013,iinput,'b',2013:2020,[iinput(end),f_out],'r')
           

用2014a版matlab運作後結果如下:

     網絡結構和各參數顯示如下:

BP神經網絡預測(人口)程式(matlab)
BP神經網絡預測(人口)程式(matlab)
BP神經網絡預測(人口)程式(matlab)
BP神經網絡預測(人口)程式(matlab)

                                                                       誤差直方圖

BP神經網絡預測(人口)程式(matlab)
BP神經網絡預測(人口)程式(matlab)
BP神經網絡預測(人口)程式(matlab)
BP神經網絡預測(人口)程式(matlab)

圖1  自相關    圖2 誤差

BP神經網絡預測(人口)程式(matlab)

 圖3 預測

BP神經網絡預測(人口)程式(matlab)

      注意在對結果好壞的判斷中,僅僅看誤差圖是不夠的,如果是一個好的預測,那麼自相關性圖中除了0階自相關外,其他的自相關系數系數都不應該超過上下置信區間。還有其他的統計量和圖表都都寫在”%“後面了,如果需要,去掉就可用。最後的預測值為f_out,我的預測值為

138701.065269972    139467.632609654    140207.209707364    141210.109373609    141981.285378849    142461.332139592    143056.073139776

繼續閱讀