欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

回歸預測! 手把手實現(xiàn)MATLAB的CNN 卷積神經(jīng)網(wǎng)絡回歸

  發(fā)布時間:2025-01-13 11:15:38   作者:佚名   我要評論
MATLAB自帶一個回歸教程,但是很多朋友不會跟著學,今天我們就來分享MATLAB實現(xiàn)CNN的技巧

基于MATLAB的深度學習工具箱(推薦2018b以上),實現(xiàn)CNN回歸。網(wǎng)上的例子比較少,這里簡單的說一下傳統(tǒng)的多輸入單輸出怎么做。手把手的教(PS:MATLAB自帶一個回歸教程,竟然還是有學生不知道對照著寫)

1、首先加載數(shù)據(jù)與數(shù)據(jù)集劃分

clc;clear;close all
load data
n=700;
train_x=input(:,1:n);
train_y=output(:,1:n);
test_x=input(:,n+1:end);
test_y=output(:,n+1:end);

我的輸入數(shù)據(jù)是m*n形式的,m代表有多少個輸入特征(如下訓練集集數(shù)據(jù)特征是209個),n是有多少個樣本(如下訓練集數(shù)據(jù)樣本是700個),輸出數(shù)據(jù)是1*n,1代表輸出是單輸出。劃分后如下

2、數(shù)據(jù)歸一化(或者標準化,看哪個效果好)

method=@mapminmax;
% method=@mapstd;
[train_x,train_ps]=method(train_x);
test_x=method('apply',test_x,train_ps);
[train_y,output_ps]=method(train_y);
test_y=method('apply',test_y,output_ps);

程序里用的是mapminmax,就是極大極小值歸一化,

3、數(shù)據(jù)的一個轉換,轉換成MATLAB的CNN的輸入數(shù)據(jù)形式,是4-D形式的,最后一維就是樣本數(shù)

trainD=reshape(train_x,[209,1,1,700]);%訓練集輸入
testD=reshape(test_x,[209,1,1,311]);%測試集輸入
targetD = train_y;%訓練集輸出
targetD_test  = test_y;%測試集輸出

轉換后訓練集輸入的size是209*1*1*700,輸出的size是1*700

4、CNN模型建立

layers = [
    imageInputLayer([209 1 1]) %輸入層參數(shù)設置
    convolution2dLayer([3,1],16,'Padding','same')%卷積層的核大小[3 1],因為我們的輸入是[209 1],是一維的數(shù)據(jù),所以卷積核第二個參數(shù)為1就行了,這樣就是1d卷積
%、數(shù)量,填充方式
    reluLayer%relu激活函數(shù)
    maxPooling2dLayer([2 1],'Stride',2)% 2x1 kernel stride=2
    fullyConnectedLayer(384) % 384 全連接層神經(jīng)元
    reluLayer%relu激活函數(shù)
    fullyConnectedLayer(384) % 384 全連接層神經(jīng)元
    fullyConnectedLayer(1) % 輸出層神經(jīng)元
    regressionLayer];%添加回歸層,用于計算損失值
 

5、模型訓練與測試

% 設置迭代次數(shù) batchsize 學習率啥的
options = trainingOptions('adam', ...
    'MaxEpochs',20, ...
    'MiniBatchSize',16, ...
    'InitialLearnRate',0.005, ...
    'GradientThreshold',1, ...
    'Verbose',false,...
    'Plots','training-progress',...
    'ValidationData',{testD,targetD_test'});
%這里要吐槽一下,輸入數(shù)據(jù)都是最后一維為樣本數(shù),偏偏輸出要第一維為樣本數(shù),所以targetD和targetD_test都取了轉置
% 訓練
net = trainNetwork(trainD,targetD',layers,options);
% 預測
YPred = predict(net,testD);
% 結果
YPred=double(YPred');%輸出是n*1的single型數(shù)據(jù),要轉換為1*n的double是數(shù)據(jù)形式
% 反歸一化
predict_value=method('reverse',YPred,output_ps);predict_value=double(predict_value);
true_value=method('reverse',targetD_test,output_ps);true_value=double(true_value);

如果options里面沒有ValidationData那一句,就看不到驗證集(比較懶,沒有換分驗證集,用的測試集代替)的loss變化,就不方便判斷模型有沒有過擬合。

6、最后是模型評價

 
figure
plot(true_value,'-*','linewidth',3)
hold on
plot(predict_value,'-s','linewidth',3)
legend('實際值','預測值')
grid on
rmse=sqrt(mean((true_value-predict_value).^2));
disp(['根均方差(RMSE):',num2str(rmse)])
mae=mean(abs(true_value-predict_value));
disp(['平均絕對誤差(MAE):',num2str(mae)])
mape=mean(abs((true_value-predict_value)./true_value));
disp(['平均相對百分誤差(MAPE):',num2str(mape*100),'%'])

根均方差(RMSE):9.3368e-05
平均絕對誤差(MAE):6.9173e-05
平均相對百分誤差(MAPE):0.0069244%

相關文章

最新評論