data=xlsread('data_load'); % 按时间排序 load_data = sortrows(data, 1); % 生成训练集和测试集 train_ratio = 0.8; train_size = floor(train_ratio * size(load_data, 1)); train_data = load_data(1:train_size, 2:end); test_data = load_data(train_size+1:end, 2:end); % 数据归一化 train_data_norm = normalize(train_data); test_data_norm = normalize(test_data); % 准备训练数据 X_train = []; Y_train = []; n_steps = 3; % 每个时间步长包含的数据点数 for i = n_steps:size(train_data_norm, 1) X_train = [X_train; train_data_norm(i-n_steps+1:i, :)]; Y_train = [Y_train; train_data_norm(i, :)]; end % 调整训练数据的形状 X_train = permute(reshape(X_train', [], n_steps, size(X_train,1)), [3, 2, 1]); Y_train = permute(reshape(Y_train', [], n_steps, size(Y_train,1)), [3, 2, 1]); % 构建LSTM模型 input_size = size(train_data,2)-1; output_size = size(train_data,2)-1; num_hidden_units = 64; layers = [ ... sequenceInputLayer(input_size) lstmLayer(num_hidden_units,'OutputMode','last') fullyConnectedLayer(output_size) regressionLayer]; % 训练模型 opts = trainingOptions('adam', ... 'MaxEpochs',50, ... 'GradientThreshold',1, ... 'InitialLearnRate',0.01, ... 'LearnRateSchedule','piecewise', ... 'LearnRateDropFactor',0.1, ... 'LearnRateDropPeriod',30, ... 'Verbose',0, ... 'Plots','training-progress'); trained_net = trainNetwork(X_train, Y_train, layers, opts); % 准备测试数据 X_test = []; Y_test = []; for i = n_steps:size(test_data_norm, 1) X_test = [X_test; test_data_norm(i-n_steps+1:i, :)]; Y_test = [Y_test; test_data_norm(i, :)]; end % 调整测试数据的形状 X_test = reshape(X_test, [size(X_test,1), n_steps, size(test_data,2)-1]); Y_test = reshape(Y_test, [size(Y_test,1), size(test_data,2)-1]); % 进行预测 Y_pred = predict(trained_net, X_test); % 反归一化预测结果 Y_pred = Y_pred .* max(train_data) + min(train_data); Y_test = Y_test .* max(train_data) + min(train_data); % 绘制预测结果 figure plot(Y_test(:,1), 'b') hold on plot(Y_pred(:,1), 'r') legend('真实值', '预测值') title('负荷预测结果') xlabel('时间步长') ylabel('负荷值')
时间: 2023-12-24 21:11:22 浏览: 78
PSD.rar_matlab psd函数_power spectrum_psd_psd代码 matlab_psd功率谱代码
5星 · 资源好评率100%
根据您提供的代码,出错的原因是您的输入数据的特征维度为 51,但是您的模型的输入层需要的特征维度为 2。这是因为您在将数据转换为训练数据时,使用了所有特征。您需要仅选择前两个特征作为输入,即时间和负荷值。您可以在以下代码中对 `train_data_norm` 进行修改,以仅选择前两个特征作为输入:
```
% 准备训练数据
X_train = [];
Y_train = [];
n_steps = 3; % 每个时间步长包含的数据点数
for i = n_steps:size(train_data_norm, 1)
X_train = [X_train; train_data_norm(i-n_steps+1:i, 1:2)]; % 只选择前两个特征作为输入
Y_train = [Y_train; train_data_norm(i, 1:2)];
end
```
这样可以确保您的输入数据的特征维度为 2,与您的模型的输入层所需的特征维度相匹配。
阅读全文