Chapter 4
Chapter 4
4.1.1 Background
Natural Gas Liquids (NGL) recovery is a critical unit operation in the oil and gas in-
dustry, responsible for extracting valuable hydrocarbon components—predomi-
nantly ethane, propane, butane, and heavier fractions—from raw natural gas
streams. The turbo-expander process is the most widely employed technology for
this purpose, leveraging cryogenic temperatures generated through isentropic ex-
pansion of the feed gas to achieve high recovery efficiencies. In a typical turbo-ex-
pander based NGL recovery plant, the feed gas is cooled and partially condensed
before entering the expander, where rapid pressure reduction produces the low
temperatures needed for fractionation. The liquid product is then separated and
further processed through de-ethanizer and de-butanizer distillation columns to
meet product specifications.
56
ear equations describing phase equilibria, energy balances, and mass transfer
across multiple unit operations. A single steady-state simulation can take several
minutes to converge, and systematic exploration of the operating envelope—vary-
ing six input parameters across their operable ranges—requires hundreds or thou-
sands of individual simulation runs. This computational cost makes HYSYS im-
practical for:
57
with configurable architectures and regularization, K-Fold cross-validation, predic-
tion (both single-point and batch), and process optimization into a unified interac-
tive web application.
58
4.2 System Architecture and Overview
The ML-ROM system is built upon a carefully selected set of open-source tech-
nologies, each serving a specific role in the pipeline:
— Python 3.8+: The core programming language, chosen for its extensive
ecosystem in scientific computing and machine learning.
— fpdf2 and Kaleido: Enable PDF report generation with embedded plots and
metrics.
59
4.2.2 Modular Architecture
The project follows a modular design pattern that separates concerns across dis-
tinct modules, facilitating maintainability, testability, and reuse:
NGLRecoveryModel/
├── [Link] # Streamlit web application (4 tabs)
├── dnn_rom_model.py # Standalone CLI training script
├── [Link] # Python dependencies
├── ngl_data.csv # Primary training dataset
├── model/ # Core ML modules
│ ├── __init__.py
│ ├── [Link] # Preprocessing, scaling, model management
│ ├── [Link] # Training, K-Fold CV, architecture
presets
│ ├── [Link] # Single/batch prediction functions
│ └── [Link] # PDF report generation
├── saved_models/ # Trained model artifacts
│ ├── ngl_dnn_model.keras # Keras saved model
│ ├── x_scaler.pkl # Fitted input scaler
│ ├── y_scaler.pkl # Fitted output scaler
│ ├── training_history.pkl # Loss curves over epochs
│ ├── model_metadata.pkl # Architecture & regularization config
│ └── input_ranges.pkl # Training data min/max ranges
└── assets/
└── [Link] # Shadcn-inspired UI stylesheet
The model/ package encapsulates all machine learning logic. The [Link] mod-
ule handles data loading, validation, splitting, scaling, and persistence of trained
artifacts. The [Link] module provides functions for model creation, training (in-
cluding K-Fold cross-validation), and evaluation. The [Link] module exposes
clean interfaces for single-point and batch prediction with automatic scaling and in-
verse transformation. The [Link] module generates downloadable PDF re-
ports summarizing training results, K-Fold metrics, and prediction analysis.
The [Link] file orchestrates the entire user experience through a Streamlit-based
web interface, while dnn_rom_model.py provides a command-line alternative for
training and evaluation without the web interface.
60
4.2.3 Data Flow Pipeline
6. Optimization: The trained model serves as the objective function for SciPy's
differential evolution optimizer, searching for input conditions that minimize the
target output.
61
4.3 Process Variables and Data Description
The ML-ROM accepts six input variables that characterize the operating conditions
of the NGL recovery process. These variables were selected based on their direct
influence on both product quality and energy consumption, as determined by
process engineering knowledge and parametric studies in HYSYS.
Typical
Variable Symbol Unit Physical Description
Range
Feed Molar Flow x₃ kmol/h Volumetric rate of the incoming natural 1,000 to
gas stream 5,000
The feed conditions (x₁, x₂, x₃) define the thermodynamic state and composition of
the inlet gas. The expander outlet pressure (x₄) directly determines the expansion
ratio and thus the refrigeration duty available for condensation. The column re-
boiler temperatures (x₅, x₆) control the separation sharpness in the de-ethanizer
62
and debutanizer, respectively, fundamentally affecting the product composition and
energy requirements.
Specific Energy y₂ kWh/ton Total energy consumed per unit mass of NGL
Consumption produced. This encompasses compressor work,
reboiler duty, and pump power. Lower SEC indicates
more energy-efficient operation.
The ethane percentage (y₁) quantifies product purity, while the SEC (y₂) quantifies
energy efficiency. In practice, these two objectives often conflict—reducing ethane
content typically requires more energy—making simultaneous optimization of both
a non-trivial engineering challenge. The LPG product specification for ethane con-
tent is critical because excessive ethane degrades product quality and may violate
contractual or regulatory limits, while high SEC values indicate poor energy effi-
ciency and increased operating costs.
63
trol setpoints (Expander Pressure, De-ethanizer Reboiler Temperature, and
Debutanizer Reboiler Temperature). Below, we justify the selection of each variable
and analyze their impact on the process performance using parametric study
graphs generated from the HYSYS simulation dataset.
— Justification: The inlet feed gas temperature determines the initial enthalpy
and the fraction of liquids that will condense in the upstream gas-gas exchang-
ers and chiller before reaching the expander.
— Justification: The feed pressure sets the high-pressure boundary for the ex-
Pfeed
pansion process. It directly determines the pressure ratio ( Pexpander ) available to
64
— Ethane Percentage vs. Feed Pressure: Higher feed pressure increases
the pressure drop across the expander, leading to lower expander outlet
temperatures due to isentropic expansion. This causes more ethane and
heavier components to condense, thereby increasing the ethane
percentage in the condensed liquid phase that feeds the de-ethanizer, as
demonstrated in the graph.
— SEC vs. Feed Pressure: Although higher feed pressure requires more
compressor work upstream, it also provides more expansion energy
(recovered by the expander-compressor link) and lower cryogenic
temperatures without additional external cooling, which can lead to a net
reduction in the specific energy consumption (SEC) per ton of NGL
recovered within certain operating limits.
Figure 4.3.3: Ethane Fraction vs. Feed Pressure Figure 4.3.4: SEC vs. Feed Pressure
— Justification: The gas flow rate dictates the plant throughput and directly af-
fects velocities, pressure drops, and heat transfer efficiency throughout the
heat exchangers and distillation columns.
— Ethane Percentage vs. Feed Molar Flow: The graph shows how changes
in throughput alter the residence time and heat load on the separation
columns, affecting the separation efficiency and resulting in mild variations
in the final product ethane content.
— SEC vs. Feed Molar Flow: Higher throughput can improve specific energy
efficiency by spreading fixed thermal and mechanical losses over a larger
mass of product, reducing the specific energy consumption (SEC) up to a
65
point before equipment constraints (like compressor capacity or column
flooding) begin to dominate.
Figure 4.3.5: Ethane Fraction vs. Feed Molar Figure 4.3.6: SEC vs. Feed Molar Flow
Flow
66
Figure 4.3.8: SEC vs. Expander Pressure
Figure 4.3.7: Ethane Fraction vs. Expander
Pressure
Figure 4.3.9: Ethane Fraction vs. De-ethanizer Figure 4.3.10: SEC vs. De-ethanizer
Temperature Temperature
67
[Link] Debutanizer Temperature (x6 )
of the LPG stream. Properly predicting and optimizing this temperature ensures
that downstream specification changes are captured by the ROM.
The raw HYSYS export column names are automatically mapped to standardized
internal names:
An important preprocessing detail is the handling of the ethane output: HYSYS ex-
ports this value as a mole fraction in the range [0, 1] (e.g., 0.0285 for 2.85%).
Because the SEC values range in the tens (e.g., 52.8 kWh/ton), leaving ethane in
its native scale would cause the loss function to be dominated by the SEC target,
68
severely biasing the model. The system therefore automatically detects values be-
low 2.0 and multiplies by 100 to convert to percentages, balancing both targets in
the loss function.
69
4.4 Data Preprocessing Pipeline
2. NaN column removal: Columns consisting entirely of NaN values are dropped
using [Link](axis=1, how='all') . This handles a common HYSYS export
artifact: when the Case Study Manager exports data, it may insert an empty
separator column between the input and output columns. The raw CSV file
ngl_data.csv demonstrates this issue—it contains an unnamed empty column
between the Debutanizer Temperature and Ethane columns, which would cor-
rupt the column indexing if not removed. After dropping NaN columns, the col-
umn names are re-stripped to handle any shifted indices.
4. Column mapping: The first six columns are assigned as inputs (X) and, if
present, columns seven and eight are assigned as outputs (Y). This positional
70
approach means the column order must be consistent: inputs first, then out-
puts. The function returns the column names alongside the arrays so the user
interface can display proper labels.
5. Mole fraction conversion: The first output column (Y[:, 0], representing
Ethane content) is checked: if the maximum value is below 2.0, all values in
that column are assumed to be mole fractions and multiplied by 100. This auto-
matic detection handles both scenarios—HYSYS exports mole fractions in the
range [0, 1] (e.g., 0.0285 for 2.85%), while some users may manually enter
percentage values. The threshold of 2.0 (rather than 1.0) accounts for the pos-
sibility of ethane values slightly above 1% in certain operating conditions, en-
suring that legitimate small percentage values are not accidentally multiplied by
100.
Why this matters: Without these cleaning steps, the model would receive incon-
sistent, noisy, or mis-scaled data, leading to poor convergence during training, bi-
ased predictions toward over-represented input combinations, and an imbalanced
loss function that prioritizes one target over the other. The cleaning pipeline en-
sures data quality and consistent scaling before the model ever sees the data.
The dataset is split into training and test subsets using scikit-learn's
train_test_split with a configurable ratio (default 20% test split). The random
state is fixed at 42 to ensure reproducibility:
D = Dtrain ∪ Dtest ,
∣Dtest ∣/∣D∣ = 0.20
When K-Fold cross-validation is active, this split is bypassed in favor of the fold-
based partitioning described in Section 4.8.
71
SEC around 50 kWh/ton), unscaled features would cause gradient descent to con-
verge slowly and unevenly. Without scaling, the optimizer would take large steps in
the direction of high-magnitude features (Feed Pressure) and tiny steps along low-
magnitude features (Feed Temperature), resulting in slow convergence, unstable
training, and suboptimal solutions. After scaling, all features occupy comparable
numerical ranges, the gradient contributions from each feature are balanced, and
the optimizer navigates the loss landscape efficiently.
The system supports three scaling strategies, each with distinct mathematical for-
mulations and practical trade-offs:
The Standard Scaler transforms each feature to have zero mean and unit variance:
x−μ
z= σ
where μ is the sample mean and σ is the sample standard deviation. After transfor-
mation, each feature has a mean of approximately 0 and a standard deviation of
approximately 1. Outliers remain present in the data but their influence is reduced
because they are expressed in terms of standard deviations from the mean rather
than in raw units.
When to use: This is the default and most commonly used scaler, suitable when
features follow approximately Gaussian (normal) distributions. It works well with
neural networks because the resulting values are centered around zero, which
aligns with the initial random weight distributions (typically initialized from
N (0, 0.05) or Glorot uniform). For the NGL dataset, Feed Pressure and Feed Flow
have relatively symmetric distributions, making Standard Scaler a good fit.
Practical impact: For the NGL dataset with Standard Scaler, the model typically
converges within 50–100 epochs and achieves R² > 0.97. The scaler parameters
(mean and standard deviation for each of the 6 input features and 2 output targets)
are stored as part of the model artifacts.
The MinMax Scaler maps each feature to a fixed range [0, 1]:
72
x−xmin
z= xmax −xmin
After transformation, all values fall between 0 and 1, with the minimum value map-
ping to 0 and the maximum value mapping to 1. The transformed distribution pre-
serves the original shape but compresses it into the unit interval.
Practical impact: For clean NGL data without significant outliers, MinMax Scaler
performs similarly to Standard Scaler. However, if outliers are present, the model
may take longer to converge because the compressed input range leads to smaller
gradient magnitudes for the majority of samples.
The Robust Scaler uses the median and interquartile range (IQR) to reduce the in-
fluence of outliers:
x−median(x) x−median(x)
z= IQR(x)
= Q3 (x)−Q1 (x)
where Q1 and Q3 are the 25th and 75th percentiles, respectively. Unlike Standard
Scaler (which uses mean and standard deviation) and MinMax Scaler (which uses
min and max), the Robust Scaler relies on statistics that are inherently resistant to
outliers. The median is unaffected by extreme values, and the IQR only reflects the
spread of the central 50% of the data.
When to use: This scaler is recommended when the dataset contains significant
outliers that would distort the mean, standard deviation, or min/max values. In
HYSYS-generated datasets, outliers can arise from simulations that converge at
extreme operating conditions (e.g., very low temperatures or pressures near ther-
73
modynamic boundaries). If these data points are not removed during cleaning,
Robust Scaler ensures they do not distort the feature representation.
Practical impact: When outliers are present, Robust Scaler prevents the com-
pressed-range problem that plagues MinMax and the skewed-centre problem that
affects Standard Scaler. For clean NGL data, the practical difference between
Standard and Robust Scaler is minimal (typically <0.01 R² difference). For data
with outliers, Robust Scaler can improve R² by 0.02–0.05 compared to Standard
Scaler.
Standard Mean & Std Dev Yes Clean, normally Fast, stable
distributed data
MinMax Min & Max Very sensitive Bounded data, no Fast, may be slow
outliers with outliers
Robust Median & IQR No Data with outliers Stable under all
conditions
A critical design consideration is that the scalers must be fitted on the training data
only and then applied (without refitting) to the test data and any future prediction in-
puts. The system enforces this by calling fit_transform() on the training set and
transform() on the test and prediction sets. The fitted scaler parameters (means,
standard deviations, min/max values, or medians/IQRs) are serialized to disk using
joblib as x_scaler.pkl and y_scaler.pkl , ensuring that the exact same trans-
formation is applied during inference.
are produced in the scaled domain and must be transformed back to the original
units using y_scaler.inverse_transform() before being reported to the user or
compared against ground truth values.
74
4.5 Deep Neural Network Architecture
Hidden Total
Preset Output Best For
Layer Sizes Parameters
The naming convention follows the pattern: first hidden layer receives the 6-dimen-
sional input, subsequent layers progressively reduce dimensionality in a funnel pat-
tern, and the final output layer produces the 2-dimensional prediction. This "en-
coder-like" funnel structure encourages the network to learn increasingly com-
pressed and abstract representations of the input-output mapping.
For a network with hidden layer sizes {n1 , n2 , … , nL } and input dimension d = 6,
where:
75
— W(l) ∈ Rnl ×nl−1 is the weight matrix for layer l
flinear (z) = z
Since the targets (Ethane % and SEC) are continuous unbounded values, a linear
output layer allows the network to produce predictions across the full real number
domain without artificially constraining the output range.
For the Standard architecture (32 → 16 → 8 → 2) with 6 inputs and 2 outputs, the
total parameter count is:
76
Layer Weights Biases Total
Output (8 → 2) 8 × 2 = 16 2 18
Total 906
The model uses Mean Squared Error (MSE) as the loss function:
1 N 2 2
LMSE =
N
∑i=1 ∑j=1 (yi,j − y^i,j )
where N is the number of samples in the batch, yi,j is the true value, and y^i,j is the
predicted value for output j (ethane or SEC) of sample i. The MSE penalizes large
errors quadratically, making it sensitive to outliers but driving the model toward ac-
curate predictions across both targets. Since both outputs have been scaled to
comparable ranges (via the output scaler), the loss function balances learning be-
tween the two targets naturally.
The Adaptive Moment Estimation (Adam) optimizer is used for gradient-based pa-
rameter updates. Adam maintains per-parameter adaptive learning rates using first
and second moment estimates:
mt = β1 ⋅ mt−1 + (1 − β1 ) ⋅ gt
77
vt = β2 ⋅ vt−1 + (1 − β2 ) ⋅ gt2
Bias-corrected estimates:
mt vt
^t =
m
1−β1t
,
v^t =
1−β2t
Parameter update:
θt+1 = θt −
α
v^t +ϵ
⋅m
^t
where α is the learning rate (default 0.001), β1 = 0.9, β2 = 0.999, and ϵ = 10−7 .
The default learning rate can be adjusted by the user through the dashboard inter-
face (selectable from {0.0001, 0.0005, 0.001, 0.005, 0.01}).
78
4.6 Regularization Techniques
4.6.1 Dropout
Training phase: For each neuron in a Dropout layer, a binary mask is sampled:
~ (l) rj
(l)
(l)
hj = ⋅ hj
1−p
(l)
where rj ∼ Bernoulli(1 − p) is a binary mask sampled independently for each
neuron, and p is the dropout rate. The (1 − p) scaling factor (inverted dropout) en-
sures that the expected activation magnitude remains consistent between training
and inference, eliminating the need for weight scaling at test time.
What difference does it make? Dropout has several observable effects on train-
ing and model quality:
— Slower training convergence: Because each training step uses only a subset
of neurons, the gradient signal is noisier and the model requires more epochs
79
to converge. With a dropout rate of 0.2, training typically takes 20–40% more
epochs to reach the same validation loss compared to training without dropout.
— Reduced overfitting gap: The most important effect. Without dropout, the
model may achieve very low training loss while validation loss plateaus or
increases—this is the hallmark of overfitting. With dropout, the gap between
training and validation loss narrows significantly. For the NGL dataset, the
training-validation loss gap typically decreases from ~30% to <5% with dropout
enabled.
Training phase:
1 m (l)
μB = ∑i=1
B
hi
mB
2
i=1 (hi − μB )
1 (l)
σB2 = ∑m B
mB
(l)
^ (l) =
h
hi −μB
i
2 +ϵ
σB
i
80
2
where μB and σB
are the batch mean and variance, mB is the batch size, ϵ is a
small constant (default ϵ = 10−3 ) for numerical stability, and γ (l) and β (l) are learn-
able scale and shift parameters that allow the layer to recover the original repre-
sentation if needed.
Inference phase: During prediction, the running mean and running variance (com-
puted as exponential moving averages during training) are used instead of batch
statistics:
h−μrunning
BN(h) = γ ⋅ +β
2
σrunning +ϵ
— Mild regularization effect: Because the batch statistics (mean and variance)
are computed from a mini-batch rather than the full dataset, they introduce a
small amount of noise into the training process. This noise has a regularizing
effect similar to (but weaker than) Dropout. In practice, this means a model with
81
BatchNorm alone may achieve slightly better generalization than a model
without any regularization.
— Interaction with Dropout: When BatchNorm and Dropout are used together
(the default configuration), they complement each other well. BatchNorm
stabilizes the activation magnitudes, which prevents Dropout from producing
extremely large or small activations when neurons are dropped. Without
BatchNorm, combining Dropout with a high learning rate can cause numerical
instability.
(l)
where ∥W(l) ∥2F = ∑i,j (Wij )2 is the Frobenius norm squared of the weight matrix
∂
∂Wij
(λ∥W∥2F ) = 2λWij
weights toward zero at each update step. At each gradient descent iteration, the
weight update becomes:
= Wij − α ( ∂L
∂Wij + 2λWij ) = (1 − 2αλ)Wij − α ∂Wij
(t+1) (t) MSE ∂LMSE (t) (t)
Wij
82
rate λ is configurable from {0.0001, 0.0005, 0.001, 0.005, 0.01}, defaulting to 0.001.
Note that L2 regularization is applied only to the hidden layer weight matrices, not
to biases or the output layer.
83
4.6.4 Combined Regularization Strategy
— BatchNorm reduces internal covariate shift, allowing higher learning rates and
acting as a mild regularizer through the noise injected by batch statistics. It also
produces smoother optimization landscapes that make gradient descent more
stable.
84
Typical Typical
Configuration Training Validation Gap Overfitting? Recommendation
R² R²
How to read the table: The "Gap" column shows the difference between training
and validation R². A large gap (>0.05) indicates overfitting—the model is memoriz-
ing training patterns rather than learning the underlying function. A negative gap
(validation R² > training R²) indicates underfitting—the model doesn't have enough
capacity or is too heavily regularized. The ideal configuration produces a small gap
(<0.02) with high validation R² (>0.95).
85
86
4.7 Training Callbacks and Strategies
Early Stopping monitors the validation loss and halts training when it ceases to im-
prove, preventing overfitting and saving computation time:
Stop if: Lval (epoch) > Lval (best) for p consecutive epochs
where p is the patience parameter. The system uses the Keras EarlyStopping
callback with the following configuration:
The patience mechanism provides a grace period to account for temporary fluctua-
tions in validation loss that may occur during training (e.g., when the optimizer tra-
verses a flat region of the loss landscape). Setting patience too low (e.g., 5–10
epochs) may cause premature termination before the model has fully converged,
especially with noisy loss landscapes. Setting it too high (e.g., 100 epochs) re-
duces the early stopping benefit—the model may waste significant computation
time in regions where no improvement is occurring.
What difference does it make? Early Stopping is the single most impactful call-
back for preventing overfitting:
— Without Early Stopping: A model trained for 300 epochs on the NGL dataset
may achieve a training R² of 0.999+ but a validation R² of only 0.88–0.92. After
approximately epoch 50–100, the validation loss begins to increase while the
training loss continues to decrease—this is the classic overfitting signature.
Early Stopping detects this divergence and halts training at the optimal point.
87
are restored to the epoch with the best validation loss, ensuring the saved
model is the best-performing one rather than the last-trained one. For the
Standard architecture on the NGL dataset, this typically results in training
stopping at epoch 70–150, saving 50–80% of the planned computation.
— The restore_best_weights parameter: This is critical. Without it, the model at
the time of stopping would be the model after 30 epochs of no improvement—
which is worse than the model at the epoch with the minimum validation loss.
The restore_best_weights=True setting ensures the final model corresponds
to the best epoch, not the last epoch.
The ReduceLROnPlateau callback dynamically reduces the learning rate when the
validation loss stops improving, allowing the optimizer to take finer steps in the loss
landscape:
— Monitor: val_loss
The learning rate schedule typically proceeds as: 0.001 → 0.0005 → 0.00025 → ...
until convergence or until the minimum learning rate is reached. This adaptive
schedule ensures that the optimizer makes large steps during early training (when
the loss landscape is roughly convex) and progressively smaller steps as it ap-
proaches a local minimum.
What difference does it make? The LR scheduler has a subtle but important ef-
fect on training:
88
around the minimum in later epochs without converging—the step size is too
large for the narrow valley at the bottom of the loss landscape. The training
loss may bounce between two values without reaching a stable minimum.
The ModelCheckpoint callback saves the model weights to disk whenever the vali-
dation loss improves. This ensures that the best model state is preserved even if
training continues and the model subsequently overfits. The checkpointed model is
saved to saved_models/ngl_dnn_model.keras .
The system supports continuing training on an existing saved model, allowing in-
cremental learning when new data becomes available. The continue_training
function in model/[Link] loads the saved .keras model and resumes the train-
ing loop with the same or modified callbacks. This is useful for:
89
class StreamlitCB([Link]):
def on_epoch_end(self, epoch, logs=None):
progress = (epoch + 1) / total_epochs
progress_bar.progress(progress)
status = f"Epoch {epoch+1}/{total} — Loss: {logs['loss']:.6f}"
if 'val_loss' in logs:
status += f" — Val Loss: {logs['val_loss']:.6f}"
status_text.text(status)
After training completes, the system displays the training convergence plot show-
ing both training and validation loss curves on a logarithmic scale, along with true-
vs-predicted scatter plots for both output targets.
90
Effect on
Setting Effect on
Effect on Training Convergence Recommendation
Changed Validation R²
Speed
Lower Smaller, more Slightly higher 2–3× slower Use with Early
learning precise updates final R² Stopping if model
rate oscillates
(0.0001)
91
4.7.7 Empirical Training Results and Data Ranges
The deep neural network model was trained on a dataset generated from targeted
process variable ranges in HYSYS to capture localized thermodynamic behavior.
The model was compiled with a Standard architecture and Standard scaler, utiliz-
ing the Adam optimizer (LR = 0.001). The complete model configuration, metrics,
and hyperparameter logs are detailed in the Model Training Report (PDF).
92
Model Performance Analysis
The model achieved high accuracy on both output targets, reaching an Overall
Average R2 Score of 0.9842. The individual target metrics are:
The training process and generalization behavior are visualized in the plots below:
— Accuracy Analysis (Figure 4.7.4): The parity plots illustrate the predicted
values versus the actual simulation values. The points cluster tightly along the
45-degree line for both targets, confirming that the surrogate model is highly
accurate and free of systematic bias.
Figure 4.7.4: Parity Plot (Predicted vs. Actual for Ethane % and SEC)
93
NGL Recovery ML-ROM Report
1. Model Configuration
Architecture: Standard
Scaler Type: Standard
Learning Rate: 0.001
Epochs Completed: 125
2. Performance Metrics
Ethane % 0.9873
SEC 0.9812
94
Page 1/2
NGL Recovery ML-ROM Report
3. Visualizations
Training History
Accuracy Analysis
95
Page 2/2
4.8 K-Fold Cross Validation
4.8.1 Motivation
4.8.2 Algorithm
3. For k = 1, 2, … , K :
(k)
— Training set: Dtrain = D ∖ Fk
(k)
— Validation set: Dval = Fk
(k)
— Fit feature scaler on Dtrain and transform both sets
(k) (k)
— Train model on Dtrain , validating on Dval
96
4. Compute average metrics: ˉ2 =
R 1
∑K 2
σR 2 =
K
k=1 R(k)
2
1
∑k=1 (R(k) ˉ2)
K 2
K−1
−R
2
5. Select the fold with the highest Roverall as the best model and save it.
— Each fold independently fits its own scalers on the training portion, preventing
data leakage from the validation fold.
— The number of folds K is configurable from 3 to 10, with 5 being the default.
— The best-performing fold model (highest overall R²) is persisted as the final
production model.
Metric Description
2 (k)
Rethane R² score for Ethane Percentage prediction on fold k
(k)
2
RSEC R² score for SEC prediction on fold k
2 (k)
Roverall
Average R² across both outputs on fold k
Epochs run Number of epochs completed (may be less than max if Early Stopping triggered)
K
k=1 Rethane
, σRethane
2
K
∑K
k=1 RSEC
, σRSEC
2
A low standard deviation (σ < 0.02) indicates that the model's performance is con-
sistent across different training data partitions, suggesting a robust model. High
variability (σ > 0.05) suggests that the model may be sensitive to specific training
examples or that more data is needed.
97
98
4.9 Prediction System
^ = Scaler−1
4. Inverse scaling: Recover the original domain prediction: y Y (y
^ scaled )
For example, if the model was trained on Feed Temperatures from 25°C to 38°C, a
prediction at 50°C would trigger: " ⚠️ Feed Temp (°C) = 50.0 is outside training
range [25.0, 38.0]". This serves as a practical guardrail reminding users that pre-
dictions outside the training domain are unreliable.
99
4.9.3 Batch Prediction with Comparison
1. Prediction-only mode (6-column CSV): The user provides only input values.
The system returns a CSV with two additional columns: Pred_Ethane_Pct and
Pred_SEC .
2. Comparison mode (8-column CSV): The user provides both inputs and
known outputs. The system computes prediction accuracy metrics:
∑N ^i )2
i=1 (yi −y
R2 = 1 −
1
MSE = N
∑N ^i )2
i=1 (yi − y
RMSE = MSE
1
MAE = N
∑N ^i ∣
i=1 ∣yi − y
These metrics are computed separately for each output (Ethane % and SEC) and
presented in the dashboard along with true-vs-predicted scatter plots and residual
distributions.
100
4.10 Process Optimization
The Optimization tab (Tab 4) leverages the trained ML-ROM as a fast surrogate
objective function, enabling rapid identification of optimal operating conditions.
Rather than optimizing a single objective (SEC or Ethane % individually), the sys-
tem employs a multi-objective Best Combination approach that simultaneously
minimizes both the ethane percentage in the LPG product and the specific energy
consumption.
where:
— yˉ1 and yˉ2 are the normalized Ethane % and SEC predictions, scaled to [0, 1]
using the min–max values estimated from a 500-point random sample within
the feasible bounds
The bounds are configurable through the dashboard interface using range sliders,
with sensible defaults based on the training data range.
101
the search space broadly.
(xr2 − xr3 ) where r1, r2, r3 are distinct random indices and F ∈ [0.5, 1.0] is
3. Crossover: Create a trial vector by mixing the target and mutant vectors:
ui,j = {
vi,j if rj ≤ CR or j = jrand
where CR is the crossover probability
otherwise
xi,j
x(t) otherwise
i
— Optimal input parameters: The six input values that jointly minimize the
combined objective.
— Predicted outputs: The resulting Ethane % and SEC at the optimal point.
102
Table 4.10.1: Default Optimization Bounds
The following results were obtained by running the Best Combination optimizer on
the trained model with bounds set to the full training data range:
These results represent the best trade-off point where both ethane contamination
in the LPG product and energy consumption are simultaneously minimized under
the equal-weight (w = 0.5) objective.
103
4.11 Web Application and User Interface
The dashboard employs a Shadcn-inspired light theme with the following design
principles:
— Metric cards: Key performance indicators (R² scores, sample counts) are
displayed in bordered cards with large numeric values and unit labels,
providing instant visual feedback.
— Status badges: The sidebar displays the model training status ("TRAINED" in
green or "NOT TRAINED" in gray) with the last training timestamp and
architecture information.
— Consistent color palette: Primary blue (#0369a1) for training curves and
primary data, secondary green (#10b981) for validation data and positive
indicators, amber (#f59e0b) for secondary outputs, and slate (#64748b) for
reference lines.
104
4.11.3 Four-Tab Architecture
The application is organized into four tabs, each serving a distinct function:
Tab 1: Train Model — Provides complete control over model training, including ar-
chitecture selection (Simple/Standard/Advanced), scaler choice
(Standard/MinMax/Robust), regularization configuration (Dropout, BatchNorm, L2),
training callbacks (Early Stopping, LR Scheduler), and K-Fold Cross Validation.
Includes real-time progress bars and a standardized data preview panel.
Tab 2: Batch Prediction — Accepts CSV uploads with 6 or 8 columns, runs pre-
dictions on the entire dataset, and presents accuracy metrics (R², MSE, RMSE,
MAE), scatter plots, and residual distributions. Supports downloading predictions
as CSV and generating PDF reports.
Tab 3: Manual Prediction — Provides individual input fields with sensible defaults
for single-point predictions. Includes range warnings when inputs exceed training
bounds.
Tab 4: Optimization — Allows the user to define constraints via range sliders and
runs a multi-objective Best Combination optimization that simultaneously mini-
mizes both Ethane % and SEC. Uses differential evolution to find the optimal
trade-off point and visualizes the response surface in 3D.
105
prediction analysis plots.
All reports use a consistent visual style with teal (#0D9488) headers, formatted ta-
bles with alternating row colors, and embedded Plotly charts rendered as PNG im-
ages via Kaleido.
python dnn_rom_model.py
1. Data Loading: Reads ngl_data.csv from the project root directory, validating
the column structure and converting mole fractions to percentages.
2. Preprocessing: Splits the data 80/20 into training and test sets using a fixed
random seed (42) for reproducibility, then applies StandardScaler
normalization.
4. Training: Trains for 300 epochs with a 20% validation split, outputting epoch-
by-epoch progress to the console.
7. Persistence: Saves the trained model, scalers, training history, and metadata
to the saved_models/ directory.
The standalone script uses the same underlying model/ package modules, ensur-
ing consistency between the CLI and web interface workflows.
106
4.12 Conclusion
K-Fold Cross Validation: Rather than relying on a single train-test split, the sys-
tem supports K-Fold CV with independent scaler fitting per fold, producing statisti-
cally reliable performance estimates with mean and standard deviation metrics
across folds.
107
Process Optimization: The multi-objective Best Combination optimizer leverages
the ML-ROM's speed to evaluate thousands of candidate operating conditions per
second, enabling practical real-time optimization of NGL recovery processes by si-
multaneously minimizing both ethane contamination and energy consumption.
The demonstrated acceleration factor of 104 to 105 over full HYSYS simulations
opens new possibilities for integrating process simulation insights into operational
workflows. Engineers can now explore the entire operating envelope in seconds
rather than hours, conduct previously infeasible optimization studies, and embed
surrogate models into control systems requiring sub-second response times.
108
References
109