You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Matlab中用ANN实现预测?WTI原油价格预测项目后续步骤咨询

Next Steps for Your ANN WTI Crude Oil Price Prediction

Hey there! Let’s walk through the complete workflow from where you are (train/test split done) to building, training, and evaluating your ANN for WTI price prediction. I’ve tackled similar time series forecasting tasks, so this should cover all the critical steps.

1. Data Preprocessing (Critical for ANN Performance)

ANNs are highly sensitive to data scale, so this step can’t be skipped:

  • Normalize your data: Scale both training and test features/targets to a consistent range (e.g., [0,1] or [-1,1]). Use the training set’s normalization parameters to transform the test set—never re-normalize the test set independently (this introduces data leakage).
  • Structure your time series inputs: Since you’re predicting future prices, you need to frame the problem as "use the past N days of prices to predict the next day’s price". This means creating a sliding window of historical data as your input features, with the next day’s price as the target. For example, a window size of 5 means each input sample is 5 consecutive days of WTI prices, and the target is the 6th day’s price.

2. Build Your ANN Architecture

For time series forecasting like this, a simple feedforward ANN is usually a good starting point:

  • Input layer: Size equals your sliding window size (e.g., 5 neurons if using 5 days of history).
  • Hidden layers: Start with 1 hidden layer (you can test 2 later if needed) with 10-20 neurons. The number of neurons is a hyperparameter to tune—start small and adjust if the model underfits/overfits.
  • Output layer: 1 neuron (since you’re predicting a single value: next day’s price).
  • Activation functions: Use tansig (hyperbolic tangent) or relu for hidden layers; use purelin (linear) for the output layer (since price is a continuous value).

3. Train the Model

  • Choose a training algorithm: For small-to-medium datasets, the Levenberg-Marquardt algorithm (trainlm) is fast and effective. If you run into overfitting, try Bayesian regularization (trainbr) which inherently prevents overfitting.
  • Monitor training: Keep an eye on the training error and validation error (if you split your training set into train/validation subsets). If validation error starts increasing while training error decreases, you’re overfitting—stop training early or adjust your model.

4. Test & Evaluate the Model

Once trained, use your held-out test set to assess performance:

  • Generate predictions: Run the test set through the trained ANN.
  • Reverse normalization: Convert predicted values back to the original price scale using the inverse of your normalization function.
  • Calculate metrics: Use standard regression metrics to evaluate performance:
    • RMSE (Root Mean Squared Error): Measures average prediction error magnitude.
    • MAE (Mean Absolute Error): Measures average absolute error.
    • R² Score: Indicates how much variance in the test data is explained by the model.

5. Optimize & Iterate

Don’t stop at the first model:

  • Tune hyperparameters: Test different window sizes, hidden layer counts/neuron numbers, activation functions, and training algorithms.
  • Prevent overfitting: If your model performs great on training data but poorly on test data, try reducing neurons, adding dropout (Matlab supports this via dropoutLayer in newer versions), or using regularization.

MATLAB Implementation Guide

Here’s a step-by-step code example tailored to your WTI prediction task:

Step 1: Prepare Your Time Series Data

Assume you have a vector price_data containing your raw WTI price history. First, create the sliding window dataset:

window_size = 5; % Adjust this based on your experimentation
X = [];
Y = [];

% Generate input-output pairs
for i = 1:length(price_data) - window_size
    X = [X; price_data(i:i+window_size-1)];
    Y = [Y; price_data(i+window_size)];
end

% Your existing train/test split (70-30)
train_size = floor(0.7 * length(Y));
X_train = X(1:train_size, :);
Y_train = Y(1:train_size);
X_test = X(train_size+1:end, :);
Y_test = Y(train_size+1:end);

Step 2: Normalize the Data

% Normalize inputs to [0,1] using training set stats
[X_train_norm, ps_X] = mapminmax(X_train', 0, 1);
X_train_norm = X_train_norm'; % Convert back to sample-row format

% Normalize targets
[Y_train_norm, ps_Y] = mapminmax(Y_train', 0, 1);
Y_train_norm = Y_train_norm';

Step 3: Build & Configure the ANN

% Create a feedforward network with 1 hidden layer (10 neurons)
net = feedforwardnet(10);

% Set training algorithm to Levenberg-Marquardt (fast for small datasets)
net.trainFcn = 'trainlm';

% Disable automatic train/validation split (since you already split your data)
net.divideFcn = '';

% Set training parameters
net.trainParam.epochs = 1000; % Max training iterations
net.trainParam.goal = 1e-5; % Target error

Step 4: Train the Model

% MATLAB expects inputs as column vectors, so transpose the normalized data
net = train(net, X_train_norm', Y_train_norm');

Step 5: Test the Model & Generate Predictions

% Normalize test inputs using training set's parameters
X_test_norm = mapminmax('apply', X_test', ps_X);
X_test_norm = X_test_norm';

% Generate predictions
Y_pred_norm = sim(net, X_test_norm');
Y_pred_norm = Y_pred_norm';

% Reverse normalization to get actual price values
Y_pred = mapminmax('reverse', Y_pred_norm', ps_Y);
Y_pred = Y_pred';

Step 6: Evaluate Performance

% Calculate key metrics
rmse = sqrt(mean((Y_pred - Y_test).^2));
mae = mean(abs(Y_pred - Y_test));
ss_res = sum((Y_test - Y_pred).^2);
ss_tot = sum((Y_test - mean(Y_test)).^2);
r2 = 1 - (ss_res / ss_tot);

% Print results
fprintf('Model Performance on Test Set:\n');
fprintf('RMSE: %.4f\n', rmse);
fprintf('MAE: %.4f\n', mae);
fprintf('R² Score: %.4f\n', r2);

% Plot actual vs predicted prices
figure;
plot(Y_test, 'b', 'DisplayName', 'Actual Price');
hold on;
plot(Y_pred, 'r--', 'DisplayName', 'Predicted Price');
xlabel('Test Sample Index');
ylabel('WTI Crude Oil Price');
title('Actual vs Predicted WTI Prices');
legend;
grid on;

Key Tips for MATLAB Users

  • If you’re using a newer MATLAB version (R2020b+), you can use the Neural Network Toolbox’s trainNetwork function with a layer graph for more flexibility (e.g., adding dropout layers).
  • To tune hyperparameters, use bayesopt to automate the search for optimal window size, neuron count, etc.
  • Always visualize your predictions vs actual values—plots often reveal patterns that metrics alone don’t.

内容的提问来源于stack exchange,提问作者gdphy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:31:23