import numpy as npDrilling Data Analysis and Estimation of ROP for an EGS Using Machine Learning
1. Project Summary
This is a machine learning workflow for predicting Rate of Penetration (ROP) and analyzing real-time drilling dynamics for enhanced geothermal systems (EGS) using diagnostic drilling data (Pason log files).
Drilling represents the fundamental mechanism for accessing subsurface energy, and it’s the domain where established petroleum engineering mechanics are directly deployed to advance sustainable geothermal systems. While the physics of managing drilling parameters like weight on bit and rotary speed were largely refined in the petroleum sector, these same principles are essential for penetrating the complex, hard rock formations for the development of geothermal platforms. By leveraging data-driven techniques to build robust predictive models for Rate of Penetration (ROP), we can enhance drilling efficiency and improve the economic scalability of geothermal energy extraction.
The primary objectives of this project are to:
- Perform exploratory data analysis to evaluate pairwise interactions, depth-series dynamics, and multi-variable correlations.
- Preprocess the raw diagnostic logs to isolate active drilling intervals, drop duplicate unit channels, and impute missing sensor readings. See Phase 1.
- Engineer physical features (e.g., via interaction terms like hydraulic power proxy and WOB-RPM interactions) and temporal features (via lagged features and rolling averages. See Phase 2.
- Benchmark six distinct machine learning model types (including Support Vector Regression, Random Forest, and Multilayer Perceptron) for Rate of Penetration (ROP) prediction using an 80/20 depth-ordered sequential block split. See Phase 3.
- Tune hyperparameters for a Gradient Boosted Trees model using non-shuffled K-fold cross-validation to preserve spatial sequence and prevent temporal data leakage. See Phase 4.
- Evaluate and visually validate the tuned Gradient Boosted Trees model on the deeper holdout block and extract impurity-based feature importances. Phase 5.
- Implement and evaluate sequence-based deep learning models (Gated Recurrent Units) using overlapping depth-ordered rolling windows, comparing the performance of original sensors against the engineered feature set. Phase 6.
Key Results & Model Performance Summary
| Model | MAE (ft/hr) | RMSE (ft/hr) | Features / evaluation |
|---|---|---|---|
| Random Forest baseline | 4.04 | 5.46 | Phase 2 features including Depth; deeper 20% holdout |
| Gradient Boosted Trees baseline | 4.14 | 5.67 | Phase 2 features including Depth; deeper 20% holdout |
| Tuned Gradient Boosted Trees | 3.95 | 5.29 | Phase 2 features including Depth; deeper 20% holdout |
| GRU, final epoch (80) | 5.13 | 6.37 | Depth > 600 ft; deeper 20% also used as test set |
The tree models and GRU use different depth filtering and sample construction, so these scores are not a like-for-like ranking. The engineered-feature GRU is trained and separately evaluated at epoch 80, with MAE 4.64 ft/hr and RMSE 6.15 ft/hr; its subsequent plots show that model.
Predicted vs Actual ROP using the tuned Gradient Boosted Trees model (MAE of 3.95 ft/hr):

See the section Phase 5: Fine-tuned Model Performance & Visual Validation for more details.
Workflow Implementation Strategy
[ Data Ingestion & Sanitization ]
│
▼
[ Exploratory Pairwise Analysis ]
│ │
▼ ▼
[ Depth-Series Dynamics ] [ Correlation Matrix ]
│ │
└────────┬────────┘
│
▼
[ Feature Engineering & Scaling ]
│
▼
[ Multi-Model Training & Evaluation ]
(SVR, Random Forest, KNN, PolyReg,
Gradient Boosted Trees, MLP Neural Net, GRU)
│
▼
[ Depth Track Overlay & Holdout Evaluation ]
2. Data overview
The dataset contains diagnostic drilling data (Pason log files) for “Well 58-32” provided by the Idaho National Laboratory to the DOE Geothermal Data Repository [1].
Source: https://gdr.openei.org/submissions/1113
- Dataset Source: Well_58-32_processed_pason_log.csv
- Total Identified Numeric Channels: 27 channels across primary operational parameters, mud properties, and gas monitoring.
- Unit Redundancy: Parameters include dual-unit entries (Imperial/Metric), which require feature pruning during pre-processing to eliminate collinearity.
This analysis utilizes the downsampled, depth-based dataset rather than the raw 1 Hz drilling dataset, both of which are available at the DOE Geothermal Data Repository. The original timeseries raw data contains approximately 3.4 million rows recorded between July 31 and September 13, 2017. The provided depth-based alternative condenses this into roughly 7,300 rows at 1-foot intervals, covering the same period of July 31 to September 13. The depth-based dataset does not retain the full temporal resolution of the raw 1 Hz data.
It must be emphasized that the aggressive downsampling caused significant signal loss, which greatly complicates predictive modeling and analysis.
Summary of variables
| Category | Parameters Included |
|---|---|
| Geometry & Penetration | Depth (ft/m), ROP (1 ft / 1 m) |
| Mechanical Drilling | Weight on Bit (k-lbs/kg), Hookload (k-lbs/kg), Rotary Speed (rpm), Surface Torque (psi/kPa) |
| Hydraulics & Mud | Pump Pressure (psi/kPa), Flow In (gal/min & L/min), Flow Out (%), WH Pressure (psi/kPa), Pit Total (bbls/m³) |
| Thermal Dynamics | Temp In (°F/°C), Temp Out (°F/°C) |
| Safety & Environmental | H2S Floor, H2S Cellar, H2S Pits |
- Note that the “Depth” is hole depth, not bit depth.
3. Exploratory Data Analysis
We begin with exploratory data analysis to select optimal features and targets, while determining which machine learning tasks are feasible based on the target variable.
To kick off the analysis, we generate pairwise plots to evaluate the interaction of individual features with each other.
Pairwise Analysis
To examine relationships between the drilling parameters, a pairwise analysis matrix covering 351 unique pairwise combinations of variables was generated. See Drilling_Pairwise_Plots.pdf for the full result (it may load slowly). We highlight key insights below.
- Key Observations: Multi-modal clusters in Weight on Bit (WOB) vs. ROP and Torque vs. RPM suggest different operating regimes, potentially due to distinct lithology transitions downhole.
- Feature Pruning Recommendation: Dual metric/imperial channels (e.g., Depth(ft) vs Depth(m)) must be reduced to single features to avoid perfect multicollinearity (\(r = 1.00\)).
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import os
import IPython.display
def select_feature_columns(dataframe, target_column, *, exclude_depth=False):
"""Select features from the dataframe, excluding the target and optionally Depth."""
return [
column for column in dataframe.columns
if column != target_column
and not (exclude_depth and 'depth' in str(column).casefold())
]project_dir = os.getcwd()file_path = os.path.join(project_dir, r"Well_58-32_processed_pason_log.csv")
df = pd.read_csv(file_path)
# 1. Select only the key interacting drilling features
key_features = [
'Depth(ft)',
'weight on bit (k-lbs)',
'Rotary Speed (rpm)',
'Surface Torque (psi)',
'Pump Press (psi)',
'ROP(1 ft)'
]
# Filter the dataset for available key features (handles variations in column naming)
selected_cols = [col for col in key_features if col in df.columns]
df_subset = df[selected_cols].dropna()
# 2. Configure Seaborn styling for inline report rendering
sns.set_theme(style="ticks", palette="muted")
# 3. Generate focused Pairwise Interaction Plot
g = sns.pairplot(
df_subset,
diag_kind="kde", # Smooth kernel density estimate on the diagonal
plot_kws={'alpha': 0.5, 's': 15, 'edgecolor': 'none'}, # Semi-transparent scatter points
height=2.0, # Compact height per subplot to keep image size manageable
corner=True # Displays only the lower triangle to eliminate duplicate plots
)
g.fig.suptitle("Key Drilling Variables Interaction Matrix", y=1.02, fontsize=14, fontweight='bold')
# 4. Display immediately inline in the notebook
plt.tight_layout()
plt.show()
Pairwise Feature Interactions
- WOB vs. ROP Dynamics: Pairwise plots reveal a nonlinear relationship where moderate increases in WOB initially boost ROP, followed by a dispersed cloud where excessive weight yields diminishing returns.
- WOB vs. Depth: WOB generally increases with depth. As the drill string lengthens and heavier formations are encountered, higher downward force is required to break the rock.
- Operational Clustering: Clusters suggest different operating regimes. But identifying specific connection, off-bottom, or lithological intervals requires additional evidence/data.
Depth-series Plots
We plot the individual channels against depth to examine their variation along the well.
# --- 1. AUTOMATIC DATAFRAME FALLBACK ---
if 'df' not in locals():
possible_dfs = [v for k, v in list(locals().items()) if isinstance(v, pd.DataFrame)]
df = possible_dfs[-1] if possible_dfs else None
# --- 2. FLEXIBLE COLUMN MATCHING ---
# Map common column name variations to clean display labels
channel_mapping = {
'ROP(1 ft)': 'ROP',
'weight on bit (k-lbs)': 'WOB (k-lbs)',
'Rotary Speed (rpm)': 'RPM',
'Surface Torque (psi)': 'Surface Torque',
'Pump Press (psi)': 'Pump Press',
}
# Find matching columns in the DataFrame
found_cols = [col for col in df.columns if col in channel_mapping]
if not found_cols:
# Fallback to numeric columns if named columns aren't matched
found_cols = list(df.select_dtypes(include='number').columns[:4])
# Remove duplicates while keeping mapping
matched_labels = {col: channel_mapping.get(col, col) for col in found_cols}
n_plots = len(matched_labels)
# --- 3. CREATE SUBPLOTS (HANDLES 1 OR MULTIPLE PLOTS) ---
fig, axes = plt.subplots(n_plots, 1, figsize=(10, max(2.5, 2.2 * n_plots)), sharex=True)
# Ensures axes is always iterable (prevents the TypeError when n_plots == 1)
if n_plots == 1:
axes = [axes]
# Determine X-axis (Depth channel or Index)
depth_col = next((col for col in df.columns if 'depth' in col.lower()), None)
x_axis = df[depth_col] if depth_col else df.index
x_label = depth_col if depth_col else 'Sequential Log Index'
# --- 4. PLOT EACH CHANNEL ---
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']
for i, (col, label) in enumerate(matched_labels.items()):
axes[i].plot(x_axis, df[col], color=colors[i % len(colors)], linewidth=1, alpha=0.85)
axes[i].set_ylabel(label, fontsize=10, fontweight='bold')
axes[i].grid(True, linestyle=':', alpha=0.6)
# Restrict Y-axis for ROP to 1000 for better readability
if label == 'ROP':
axes[i].set_ylim(0, 1000)
axes[-1].set_xlabel(x_label, fontsize=11, fontweight='bold')
fig.suptitle("Real-Time Surface Drilling Log Dynamics", y=0.99, fontsize=13, fontweight='bold')
plt.tight_layout()
plt.show()
Depth-Domain Analysis
- Weight on Bit (WOB): The depth-series log shows a clear progressive increase in WOB as the wellbore extends deeper, consistent with changing operating conditions.
- Rate of Penetration (ROP): ROP demonstrates high initial peaks and wide fluctuations near the surface section, which gradually decrease and cluster into lower, more stable values at greater depths, possibly due to increased difficulty of cutting and penetrating the rock by the drill bit.
- Pump Pressure: Pump pressure tracks a steady upward trajectory alongside depth. It flattens in the deeper sections as WOB also flattens and ROP decreases drastically.
- Rotary Speed and Surface Torque: Rotary speed (RPM) maintains consistent operational bands, whereas surface torque exhibits distinct shifts and cyclical patterns that could signify transitions across varying lithological units.
Correlation Matrix & Multi-Variable Relationships
- Overview: A correlation matrix to measure pairwise Pearson correlation coefficients (\(r\)) across select variables in the dataset, including alternate-unit channels.
# 1. Load dataset
file_path = os.path.join(project_dir, r"Well_58-32_processed_pason_log.csv")
df = pd.read_csv(file_path)
# Strip spaces from header names
df.columns = df.columns.astype(str).str.strip()
# Print actual available columns to verify
print("Actual columns found in the Excel file:")
print(df.columns.tolist())
# 2. Explicitly selecting single-unit (imperial) columns to prevent unit duplication
matched_cols = [
"Depth(ft)",
"ROP(1 ft)",
"weight on bit (k-lbs)",
"Temp Out( degF)",
"Temp In(degF)",
"Pit Total (bbls)",
"Pump Press (psi)"
]
matched_cols = [col for col in matched_cols if col in df.columns]
print(f"\nSuccessfully matched {len(matched_cols)} single-unit columns:")
print(matched_cols)
# 3. Clean numeric data
df_subset = df[matched_cols].apply(pd.to_numeric, errors="coerce")
# Drop any column that ended up completely blank
df_subset = df_subset.dropna(how="all", axis=1)
# 4. Calculate Correlation Matrix
corr_matrix = df_subset.corr(method="pearson")
# 5. Plot Heatmap
plt.figure(figsize=(10, 8))
sns.heatmap(
corr_matrix,
annot=True,
fmt=".2f",
cmap="vlag",
vmax=1,
vmin=-1,
linewidths=0.8,
cbar_kws={"label": "Correlation Coefficient"},
)
plt.title(
"Well 58-32 Log - Correlation Matrix (Primary Units)",
fontsize=13,
fontweight="bold",
pad=12,
)
plt.xticks(rotation=45, ha="right", fontsize=9)
plt.yticks(fontsize=9)
plt.tight_layout()
# Save image
output_file = "Well_58-32_Correlation_Matrix_Primary_Units.png"
plt.savefig(output_file, dpi=300)
plt.show()
print(f"\nFull heatmap saved as '{output_file}'.")Actual columns found in the Excel file:
['Depth(ft)', 'Depth(m)', 'ROP(1 ft)', 'ROP(1 m)', 'weight on bit (k-lbs)', 'weight on bit (kg)', 'Temp Out( degF)', 'Temp Out( degC)', 'Temp In(degF)', 'Temp In(degC)', 'Pit Total (bbls)', 'Pit Total (m3)', 'Pump Press (psi)', 'Pump Press (KPa)', 'Hookload (k-lbs)', 'Hookload (kg)', 'Surface Torque (psi)', 'Surface Torque (KPa)', 'Rotary Speed (rpm)', 'Flow In (gal/min)', 'Flow In(liters/min)', 'Flow Out %', 'WH Pressure (psi)', 'WH Pressure (KPa)', 'H2S Floor', 'H2S Cellar', 'H2S Pits']
Successfully matched 7 single-unit columns:
['Depth(ft)', 'ROP(1 ft)', 'weight on bit (k-lbs)', 'Temp Out( degF)', 'Temp In(degF)', 'Pit Total (bbls)', 'Pump Press (psi)']

Full heatmap saved as 'Well_58-32_Correlation_Matrix_Primary_Units.png'.
Correlation Matrix Insights
The correlation matrix quantifies the linear relationship among the selected variables:
- Positive Associations: Depth strongly correlates with both WOB (\(0.76\)) and Pump Pressure (\(0.71\)). Furthermore, WOB and Pump Pressure share a moderate positive correlation (\(0.59\)), showing that these channels tend to increase together, which could be reflecting increased hydraulic energy requirements when heavier drilling loads are applied.
- Inverse Relationships: ROP demonstrates a negative correlation with depth (\(-0.51\)), WOB (\(-0.52\)), and pump pressure (\(-0.49\)), underscoring the drilling challenge of maintaining high penetration rates in deeper, harder intervals.
Order of depth
A monotonically increasing Depth channel (hole depth) would be consistent with chronologically ordered rows. We check for departures from that ordering. The feature engineering conducted below (e.g., rolling means and lagged features) assumes chronologically ordered rows.
# Inspect the depth ordering of the shared Phase 2 dataset.
df = df.copy()
depth_col = "Depth(ft)" if "Depth(ft)" in df.columns else "Depth"
# Plotting row index (serial number) against Depth
plt.figure(figsize=(10, 4))
plt.scatter(df.index, df[depth_col], color="blue", linewidth=1)
plt.title(
"Check Depth Monotonicity: Row Index (Serial Number) vs. Depth",
fontsize=12,
fontweight="bold",
)
plt.xlabel("Row Index / Serial Number", fontsize=10)
plt.ylabel(f"Depth ({depth_col})", fontsize=10)
plt.grid(True, linestyle="--", alpha=0.6)
plt.tight_layout()
plt.show()
# Verify programmatically whether depth increases monotonically
is_increasing = df[depth_col].is_monotonic_increasing
print(
f"Is depth monotonically increasing across rows? -> {is_increasing}"
)
Is depth monotonically increasing across rows? -> False
The Hole Depth channel is not monotonically increasing, although the plot shows that it’s approximately monotonically increasing.
Next, we display neighborhoods around the two detected decreases to inspect the departures from monotonic increase.
# Find and display up to the first 5 neighborhoods of non-monotonicity
if not is_increasing:
# Calculate differences between consecutive rows; fill first row's NaN with a positive value
diffs = df[depth_col].diff().fillna(1)
# Find all integer positions where depth stops strictly increasing (diff <= 0)
faulty_positions = np.where(diffs < 0)[0]
# Limiting to the first few instances to avoid cluttering the output
positions_to_show = faulty_positions[:3]
print(f"\nFound {len(faulty_positions)} non-monotonic instance(s). Displaying the neighborhood of the first {len(positions_to_show)} non-monotonic instance(s):")
for pos in positions_to_show:
# Define a tighter neighborhood window (2 rows before, 2 rows after)
start_pos = max(0, pos - 2)
end_pos = min(len(df), pos + 3)
print(f"\n--- Neighborhood around row position {pos} ---")
# display() renders the DataFrame as a nicely formatted HTML table
display(df.iloc[start_pos:end_pos])
Found 2 non-monotonic instance(s). Displaying the neighborhood of the first 2 non-monotonic instance(s):
--- Neighborhood around row position 5033 ---
| Depth(ft) | Depth(m) | ROP(1 ft) | ROP(1 m) | weight on bit (k-lbs) | weight on bit (kg) | Temp Out( degF) | Temp Out( degC) | Temp In(degF) | Temp In(degC) | ... | Surface Torque (KPa) | Rotary Speed (rpm) | Flow In (gal/min) | Flow In(liters/min) | Flow Out % | WH Pressure (psi) | WH Pressure (KPa) | H2S Floor | H2S Cellar | H2S Pits | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 5031 | 5238.13 | 1596.50 | 8.04 | 2.45 | 18.14 | 8226.76 | 116.59 | 46.99 | 106.27 | 41.26 | ... | 650.96 | 36.04 | 607.53 | 2299.75 | 77.50 | -0.16 | -1.10 | -0.07 | 0.00 | 0.29 |
| 5032 | 5241.16 | 1597.43 | 10.57 | 3.22 | 19.54 | 8861.68 | 116.40 | 46.89 | 106.24 | 41.24 | ... | 388.33 | 36.77 | 614.00 | 2324.24 | 80.94 | -0.54 | -3.72 | -0.06 | 0.00 | 0.33 |
| 5033 | 5240.15 | 1597.12 | 9.47 | 2.89 | 18.22 | 8263.04 | 116.44 | 46.91 | 106.24 | 41.24 | ... | 575.25 | 34.03 | 616.80 | 2334.84 | 76.09 | -0.54 | -3.72 | -0.06 | 0.01 | 0.33 |
| 5034 | 5239.14 | 1596.81 | 8.93 | 2.72 | 19.63 | 8902.49 | 116.51 | 46.95 | 106.24 | 41.24 | ... | 661.71 | 35.98 | 624.99 | 2365.84 | 65.63 | -0.54 | -3.72 | -0.06 | 0.02 | 0.30 |
| 5035 | 5242.17 | 1597.74 | 8.40 | 2.56 | 19.93 | 9038.55 | 116.44 | 46.91 | 106.35 | 41.31 | ... | 62.12 | 36.35 | 606.89 | 2297.33 | 78.11 | -0.54 | -3.72 | -0.07 | 0.01 | 0.33 |
5 rows × 27 columns
--- Neighborhood around row position 5034 ---
| Depth(ft) | Depth(m) | ROP(1 ft) | ROP(1 m) | weight on bit (k-lbs) | weight on bit (kg) | Temp Out( degF) | Temp Out( degC) | Temp In(degF) | Temp In(degC) | ... | Surface Torque (KPa) | Rotary Speed (rpm) | Flow In (gal/min) | Flow In(liters/min) | Flow Out % | WH Pressure (psi) | WH Pressure (KPa) | H2S Floor | H2S Cellar | H2S Pits | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 5032 | 5241.16 | 1597.43 | 10.57 | 3.22 | 19.54 | 8861.68 | 116.40 | 46.89 | 106.24 | 41.24 | ... | 388.33 | 36.77 | 614.00 | 2324.24 | 80.94 | -0.54 | -3.72 | -0.06 | 0.00 | 0.33 |
| 5033 | 5240.15 | 1597.12 | 9.47 | 2.89 | 18.22 | 8263.04 | 116.44 | 46.91 | 106.24 | 41.24 | ... | 575.25 | 34.03 | 616.80 | 2334.84 | 76.09 | -0.54 | -3.72 | -0.06 | 0.01 | 0.33 |
| 5034 | 5239.14 | 1596.81 | 8.93 | 2.72 | 19.63 | 8902.49 | 116.51 | 46.95 | 106.24 | 41.24 | ... | 661.71 | 35.98 | 624.99 | 2365.84 | 65.63 | -0.54 | -3.72 | -0.06 | 0.02 | 0.30 |
| 5035 | 5242.17 | 1597.74 | 8.40 | 2.56 | 19.93 | 9038.55 | 116.44 | 46.91 | 106.35 | 41.31 | ... | 62.12 | 36.35 | 606.89 | 2297.33 | 78.11 | -0.54 | -3.72 | -0.07 | 0.01 | 0.33 |
| 5036 | 5243.18 | 1598.04 | 7.33 | 2.23 | 19.88 | 9015.87 | 116.51 | 46.95 | 106.31 | 41.28 | ... | 883.32 | 34.70 | 601.71 | 2277.72 | 70.91 | -0.16 | -1.10 | -0.06 | 0.00 | 0.32 |
5 rows × 27 columns
The displayed neighborhoods illustrate that Depth is very approximately monotonic and therefore consistent with a chronological ordering.
Descriptive statistics
Descriptive statistics for the whole data and the segment deeper than 600 ft.
# Descriptive statistics of the whole data for all numeric columns
descriptive_stats = df.describe(
percentiles=[0.25, 0.50, 0.75]
).T.rename(columns={
"25%": "Q1 (25%)",
"50%": "Q2 / Median (50%)",
"75%": "Q3 (75%)",
})
display(descriptive_stats)| count | mean | std | min | Q1 (25%) | Q2 / Median (50%) | Q3 (75%) | max | |
|---|---|---|---|---|---|---|---|---|
| Depth(ft) | 7311.0 | 3835.043935 | 2147.503980 | 85.18 | 1970.395 | 3851.85 | 5691.585 | 7536.25 |
| Depth(m) | 7311.0 | 1168.864378 | 654.527243 | 25.96 | 600.545 | 1173.99 | 1734.710 | 2296.94 |
| ROP(1 ft) | 7311.0 | 42.010324 | 75.921118 | 0.00 | 11.400 | 17.99 | 44.295 | 2977.91 |
| ROP(1 m) | 7311.0 | 12.804158 | 23.139621 | 0.00 | 3.470 | 5.48 | 13.500 | 907.62 |
| weight on bit (k-lbs) | 7311.0 | 23.116699 | 9.119495 | 0.00 | 18.310 | 23.83 | 29.680 | 47.05 |
| weight on bit (kg) | 7311.0 | 10483.764002 | 4135.825227 | 0.00 | 8303.850 | 10807.26 | 13460.320 | 21337.87 |
| Temp Out( degF) | 7311.0 | 126.059506 | 12.259879 | 84.07 | 116.130 | 124.86 | 136.490 | 151.70 |
| Temp Out( degC) | 7311.0 | 52.255297 | 6.811023 | 28.93 | 46.740 | 51.59 | 58.050 | 66.50 |
| Temp In(degF) | 7311.0 | 118.315593 | 11.933137 | 85.00 | 108.850 | 117.22 | 126.860 | 146.31 |
| Temp In(degC) | 7311.0 | 47.953090 | 6.629486 | 29.44 | 42.695 | 47.34 | 52.700 | 63.51 |
| Pit Total (bbls) | 7311.0 | 236.929204 | 18.261640 | 170.91 | 224.535 | 238.11 | 249.590 | 279.88 |
| Pit Total (m3) | 7311.0 | 37.668701 | 2.903400 | 27.17 | 35.700 | 37.86 | 39.680 | 44.50 |
| Pump Press (psi) | 7311.0 | 1266.634496 | 490.554609 | 19.94 | 665.590 | 1432.56 | 1669.680 | 2200.43 |
| Pump Press (KPa) | 7311.0 | 8733.444965 | 3382.374016 | 137.49 | 4589.240 | 9877.50 | 11512.440 | 15171.96 |
| Hookload (k-lbs) | 7311.0 | 81.285593 | 26.503832 | 27.27 | 54.720 | 80.14 | 105.630 | 148.93 |
| Hookload (kg) | 7311.0 | 36864.214556 | 12019.878472 | 12367.35 | 24816.330 | 36344.67 | 47904.760 | 67541.95 |
| Surface Torque (psi) | 7311.0 | 130.983649 | 48.706651 | 0.00 | 117.000 | 140.31 | 157.280 | 273.71 |
| Surface Torque (KPa) | 7311.0 | 903.132323 | 335.832421 | 0.00 | 806.715 | 967.44 | 1084.450 | 1887.23 |
| Rotary Speed (rpm) | 7311.0 | 54.947292 | 25.947654 | 0.00 | 38.090 | 50.38 | 75.965 | 271.58 |
| Flow In (gal/min) | 7311.0 | 716.254127 | 141.784179 | 0.00 | 620.260 | 700.21 | 824.610 | 3317.51 |
| Flow In(liters/min) | 7311.0 | 2711.315497 | 536.711275 | 0.00 | 2347.940 | 2650.58 | 3121.485 | 12558.14 |
| Flow Out % | 7311.0 | 79.692834 | 11.909399 | 0.69 | 72.650 | 80.71 | 88.845 | 111.21 |
| WH Pressure (psi) | 7311.0 | -35.760875 | 222.669489 | -1231.83 | 2.920 | 5.94 | 8.260 | 17.41 |
| WH Pressure (KPa) | 7311.0 | -246.571280 | 1535.306539 | -8493.47 | 20.130 | 40.96 | 56.950 | 120.04 |
| H2S Floor | 7311.0 | -0.027372 | 0.042453 | -0.10 | -0.070 | -0.01 | 0.000 | 0.78 |
| H2S Cellar | 7311.0 | 0.004303 | 0.025282 | -0.08 | -0.010 | 0.00 | 0.020 | 0.07 |
| H2S Pits | 7311.0 | 0.148833 | 0.115290 | -0.06 | 0.060 | 0.14 | 0.220 | 0.72 |
# Descriptive statistics of Depth > 600 ft for all numeric columns
descriptive_stats_above_600ft = df.loc[
df["Depth(ft)"] > 600
].describe(
percentiles=[0.25, 0.50, 0.75]
).T.rename(columns={
"25%": "Q1 (25%)",
"50%": "Q2 / Median (50%)",
"75%": "Q3 (75%)",
})
display(descriptive_stats_above_600ft)| count | mean | std | min | Q1 (25%) | Q2 / Median (50%) | Q3 (75%) | max | |
|---|---|---|---|---|---|---|---|---|
| Depth(ft) | 6824.0 | 4084.103886 | 2001.997052 | 600.71 | 2341.3150 | 4097.405 | 5813.8225 | 7536.25 |
| Depth(m) | 6824.0 | 1244.774149 | 610.178888 | 183.09 | 713.6000 | 1248.825 | 1771.9675 | 2296.94 |
| ROP(1 ft) | 6824.0 | 30.700664 | 31.660520 | 0.00 | 11.0275 | 16.765 | 37.5200 | 219.52 |
| ROP(1 m) | 6824.0 | 9.357154 | 9.649709 | 0.00 | 3.3600 | 5.110 | 11.4400 | 66.91 |
| weight on bit (k-lbs) | 6824.0 | 24.301921 | 8.014138 | 0.00 | 19.3875 | 24.380 | 30.0900 | 47.05 |
| weight on bit (kg) | 6824.0 | 11021.279493 | 3634.529760 | 0.00 | 8792.5175 | 11056.690 | 13646.2600 | 21337.87 |
| Temp Out( degF) | 6824.0 | 127.734276 | 10.709836 | 106.60 | 116.8200 | 127.340 | 137.0300 | 151.70 |
| Temp Out( degC) | 6824.0 | 53.185720 | 5.949887 | 41.44 | 47.1200 | 52.970 | 58.3500 | 66.50 |
| Temp In(degF) | 6824.0 | 119.445914 | 11.426046 | 85.00 | 110.8500 | 118.020 | 127.6600 | 146.31 |
| Temp In(degC) | 6824.0 | 48.581030 | 6.347792 | 29.44 | 43.8100 | 47.790 | 53.1400 | 63.51 |
| Pit Total (bbls) | 6824.0 | 236.577229 | 16.425160 | 170.91 | 224.7600 | 237.630 | 248.1025 | 274.88 |
| Pit Total (m3) | 6824.0 | 37.612729 | 2.611428 | 27.17 | 35.7300 | 37.780 | 39.4425 | 43.70 |
| Pump Press (psi) | 6824.0 | 1327.710053 | 449.028785 | 31.27 | 1092.3025 | 1457.760 | 1691.6175 | 2200.43 |
| Pump Press (KPa) | 6824.0 | 9154.560950 | 3096.053421 | 215.61 | 7531.4275 | 10051.255 | 11663.7000 | 15171.96 |
| Hookload (k-lbs) | 6824.0 | 83.312721 | 26.104258 | 39.42 | 55.4500 | 85.140 | 106.4700 | 148.93 |
| Hookload (kg) | 6824.0 | 37783.547131 | 11838.665746 | 17877.55 | 25147.3900 | 38612.240 | 48285.7100 | 67541.95 |
| Surface Torque (psi) | 6824.0 | 139.749056 | 37.188507 | 0.00 | 124.1100 | 142.560 | 158.5700 | 273.71 |
| Surface Torque (KPa) | 6824.0 | 963.569817 | 256.414796 | 0.00 | 855.7400 | 982.950 | 1093.3400 | 1887.23 |
| Rotary Speed (rpm) | 6824.0 | 54.361498 | 23.571771 | 0.00 | 38.2000 | 49.650 | 72.0775 | 178.86 |
| Flow In (gal/min) | 6824.0 | 699.028602 | 127.337905 | 0.00 | 618.3100 | 696.530 | 732.9000 | 3317.51 |
| Flow In(liters/min) | 6824.0 | 2646.109818 | 482.026207 | 0.00 | 2340.5600 | 2636.650 | 2774.3300 | 12558.14 |
| Flow Out % | 6824.0 | 80.091908 | 11.350787 | 0.69 | 73.2600 | 80.990 | 88.7400 | 111.21 |
| WH Pressure (psi) | 6824.0 | 5.721786 | 3.570281 | -4.35 | 3.2800 | 6.130 | 8.2600 | 17.41 |
| WH Pressure (KPa) | 6824.0 | 39.451855 | 24.616646 | -29.99 | 22.6200 | 42.270 | 56.9500 | 120.04 |
| H2S Floor | 6824.0 | -0.029075 | 0.043384 | -0.10 | -0.0700 | -0.010 | 0.0000 | 0.78 |
| H2S Cellar | 6824.0 | 0.005470 | 0.025521 | -0.08 | -0.0100 | 0.000 | 0.0300 | 0.07 |
| H2S Pits | 6824.0 | 0.139543 | 0.112599 | -0.06 | 0.0500 | 0.130 | 0.2000 | 0.72 |
Commentary
Comparing the statistics of the full dataset with the segment deeper than 600 ft corroborates the presence of surface drilling noise, as seen in the Depth-series plot for ROP. The top 600 ft contains highly erratic, extreme values (especially noticeable in ROP), which are typical during the initial spudding and shallow drilling phases. Recognizing this difference is crucial, as filtering out this shallow section can help stabilize the feature distributions and provide a more representative dataset of steady-state downhole drilling conditions for the machine learning models.
4. Phase 1: Data Ingestion & Preprocessing Workflow
Overview & Next Steps
Having completed the exploratory data analysis and correlation matrix evaluation across the full dataset, we now begin the machine learning model development pipeline.
- Objective: Ingest, filter active drilling intervals, deduplicate unit channels, and impute sensor readings in the dataset to construct a clean feature matrix for downstream model training.
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 1000)
print("=" * 70)
print("PHASE 1: DATA LOADING, CLEANING & DRILLING FILTERING")
print("=" * 70)
# LOAD DATA
file_path = os.path.join(project_dir, r"Well_58-32_processed_pason_log.csv")
print("\nLoading Drilling Log File...")
df = pd.read_csv(file_path)
print(f"-> Raw File Loaded: {df.shape[0]} rows across {df.shape[1]} columns.")
# FILTER ACTIVE DRILLING INTERVALS
print("\n" + "-" * 70)
print("Filtering Active Drilling Days/Intervals...")
target_col = 'ROP(1 ft)' if 'ROP(1 ft)' in df.columns else 'ROP'
# Retain only active drilling intervals (ROP>0, WOB>0 and RPM>0)
active_mask = (
(df[target_col] > 0) &
(df['weight on bit (k-lbs)'] > 0) &
(df['Rotary Speed (rpm)'] > 0)
)
active_df = df[active_mask].copy()
print(f"-> Total Raw Log Records: {len(df)}")
print(f"-> Active Drilling Intervals Preserved: {len(active_df)}")
print(f"-> Non-Drilling / Connection / Tripping Noise Filtered: {len(df) - len(active_df)}")
# SELECT KEY OPERATIONAL FEATURES (deduplicating unit pairs)
print("\n" + "-" * 70)
print("Selecting Target & Single-Unit Features...")
candidate_features = [
depth_col,
'weight on bit (k-lbs)',
'Rotary Speed (rpm)',
'Pump Press (psi)',
'Flow In (gal/min)',
'Surface Torque (psi)',
'Hookload (k-lbs)',
'Temp In(degF)',
'Temp Out( degF)',
target_col
]
selected_cols = [c for c in candidate_features if c in active_df.columns]
ml_subset = active_df[selected_cols].copy()
print(f"-> Columns Preserved ({len(selected_cols)} total):\n {selected_cols}")
# SENSOR IMPUTATION
print("\n" + "-" * 70)
print("Imputing Missing Sensor Readings...")
sensor_cols = [c for c in ml_subset.columns if c not in [depth_col, target_col]]
# Count missing values before imputation
missing_counts = ml_subset[sensor_cols].isnull().sum()
total_missing_before = missing_counts.sum()
print(f"-> Total missing values detected across sensors: {total_missing_before}")
if total_missing_before > 0:
print("-> Breakdown of missing values per column:")
for col, count in missing_counts.items():
if count > 0:
print(f" - {col}: {count} missing values")
# Perform imputation
ml_subset[sensor_cols] = ml_subset[sensor_cols].ffill().bfill()
print("-> Successfully forward/backward filled missing operational sensors.")
# EXPORT CLEANED FILE FOR PHASE 2
output_filename = "drilling_phase1_cleaned.csv"
ml_subset.to_csv(output_filename, index=False)
print(f"\n-> Phase 1 Output Saved to '{output_filename}'")
print("\n" + "=" * 70)
print("PHASE 1 COMPLETE: EXTRACTED ACTIVE DRILLING SEGMENTS")
print("=" * 70)======================================================================
PHASE 1: DATA LOADING, CLEANING & DRILLING FILTERING
======================================================================
Loading Drilling Log File...
-> Raw File Loaded: 7311 rows across 27 columns.
----------------------------------------------------------------------
Filtering Active Drilling Days/Intervals...
-> Total Raw Log Records: 7311
-> Active Drilling Intervals Preserved: 6814
-> Non-Drilling / Connection / Tripping Noise Filtered: 497
----------------------------------------------------------------------
Selecting Target & Single-Unit Features...
-> Columns Preserved (10 total):
['Depth(ft)', 'weight on bit (k-lbs)', 'Rotary Speed (rpm)', 'Pump Press (psi)', 'Flow In (gal/min)', 'Surface Torque (psi)', 'Hookload (k-lbs)', 'Temp In(degF)', 'Temp Out( degF)', 'ROP(1 ft)']
----------------------------------------------------------------------
Imputing Missing Sensor Readings...
-> Total missing values detected across sensors: 0
-> Successfully forward/backward filled missing operational sensors.
-> Phase 1 Output Saved to 'drilling_phase1_cleaned.csv'
======================================================================
PHASE 1 COMPLETE: EXTRACTED ACTIVE DRILLING SEGMENTS
======================================================================
Completion Summary
- Saved Dataset: drilling_phase1_cleaned.csv
- Preserved Channels (10 Total): Depth(ft), Weight on Bit (k-lbs), Rotary Speed (rpm), Pump Press (psi), Flow In (gal/min), Surface Torque (psi), Hookload (k-lbs), Temp In (degF), Temp Out (degF), ROP(1 ft)
- Sensor Imputation: Forward/backward filling is applied before export.
- Retained Rows: 6,814 active drilling rows; Phase 2 removes the first two rows and produces 6,812 rows across 45 columns (including ROP).
5. Phase 2: Feature Engineering
Overview
With Phase 1 complete and active drilling segments extracted, we move into feature engineering to prepare the dataset for predictive modeling.
Using the data cleaned and imputed in Phase 1, we generate lagged features and rolling averages of features.
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 1000)
print("=" * 70)
print("PHASE 2: FEATURE ENGINEERING & DRILLING PHYSICS")
print("=" * 70)
# 0. LOAD CLEANED DATA FROM PHASE 1
file_input = "drilling_phase1_cleaned.csv"
df_p2 = pd.read_csv(file_input)
target_col = 'ROP(1 ft)' if 'ROP(1 ft)' in df_p2.columns else 'ROP'
print(f"\nBase Data Loaded: {len(df_p2)} rows across {df_p2.shape[1]} columns.")
# Original operational sensors were imputed in Phase 1.
sensor_cols = select_feature_columns(df_p2, target_col, exclude_depth=True)
# 1. LAGS & ROLLING TRENDS
print("\n" + "-" * 70)
print("Introducing Lagged Features & Calculating Rolling Averages...")
for col in sensor_cols:
df_p2[f'{col}_lag1'] = df_p2[col].shift(1)
df_p2[f'{col}_lag2'] = df_p2[col].shift(2)
df_p2[f'{col}_roll3_mean'] = df_p2[col].shift(1).rolling(window=3, min_periods=1).mean()
df_p2[f'{col}_roll7_mean'] = df_p2[col].shift(1).rolling(window=7, min_periods=1).mean()
# 2. PHYSICAL INTERACTION TERMS
print("\n" + "-" * 70)
print("Engineering Drilling Physics Interactions...")
wob_col = 'weight on bit (k-lbs)'
rpm_col = 'Rotary Speed (rpm)'
flow_col = 'Flow In (gal/min)'
press_col = 'Pump Press (psi)'
if wob_col in df_p2.columns and rpm_col in df_p2.columns:
df_p2['WOB_RPM_INTERACTION'] = df_p2[wob_col] * df_p2[rpm_col]
if flow_col in df_p2.columns and press_col in df_p2.columns:
df_p2['HYDRAULIC_POWER_PROXY'] = df_p2[flow_col] * df_p2[press_col]
if 'Temp Out( degF)' in df_p2.columns and 'Temp In(degF)' in df_p2.columns:
df_p2['DELTA_TEMP'] = df_p2['Temp Out( degF)'] - df_p2['Temp In(degF)']
# 3. REMOVE BOUNDARY LAG ROWS
print("\n" + "-" * 70)
print("Removing Boundary Window NaNs...")
initial_rows = len(df_p2)
# The first two rows lack a complete two-step sensor history.
df_p2_clean = df_p2.iloc[2:].reset_index(drop=True)
dropped_rows = initial_rows - len(df_p2_clean)
print(f"-> Total Rows Before Cleanup: {initial_rows}")
print(f"-> Initial Window Rows Removed: {dropped_rows}")
print(f"-> Final Operational Feature Matrix: {df_p2_clean.shape[0]} rows x {df_p2_clean.shape[1]} columns")
# EXPORT
output_filename_p2 = "drilling_phase2_engineered.csv"
df_p2_clean.to_csv(output_filename_p2, index=False)
print(f"\n-> Phase 2 Output Saved to '{output_filename_p2}'")
print("\n" + "=" * 70)
print("PHASE 2 COMPLETE: READY FOR MODELING")
print("=" * 70)======================================================================
PHASE 2: FEATURE ENGINEERING & DRILLING PHYSICS
======================================================================
Base Data Loaded: 6814 rows across 10 columns.
----------------------------------------------------------------------
Introducing Lagged Features & Calculating Rolling Averages...
----------------------------------------------------------------------
Engineering Drilling Physics Interactions...
----------------------------------------------------------------------
Removing Boundary Window NaNs...
-> Total Rows Before Cleanup: 6814
-> Initial Window Rows Removed: 2
-> Final Operational Feature Matrix: 6812 rows x 45 columns
-> Phase 2 Output Saved to 'drilling_phase2_engineered.csv'
======================================================================
PHASE 2 COMPLETE: READY FOR MODELING
======================================================================
6. Phase 3: Machine Learning (Initial Benchmarking)
Models to be evaluated
Six distinct models were configured to predict ROP values:
- Support Vector Regression (SVR): Kernel-based nonlinear regression.
- Random Forest: Ensemble decision trees capturing non-linear feature interaction with resilience to outliers.
- K-Nearest Neighbors (KNN): Non-parametric spatial distance estimation.
- Polynomial Regression: Multi-variable linear model with polynomial interaction terms.
- Gradient Boosted Trees (GBT): Sequential boosting, targeting residual error minimization.
- Multilayer Perceptron (MLP): Feedforward neural network with two hidden layers (64 and 32 units).
Target & Feature Selection
- Target Variable: Rate of Penetration (ROP)
- Features: All Phase 2 columns except ROP. These are Depth, the retained operational sensors, sensor lags and rolling means, and available physical interaction features. No alternate-unit ROP or ROP-derived features are included.
First, we define useful functions for visualizing Actual vs. Predicted ROP.
from matplotlib.figure import Figure
def plot_rop_fitness(
actual_rop,
predicted_rop,
mae,
*,
model_name="Tuned model",
rop_unit="ft/hr",
figsize=(8, 6),
):
"""Return a fitness-plot figure without displaying it."""
actual = np.asarray(actual_rop, dtype=float).reshape(-1)
predicted = np.asarray(predicted_rop, dtype=float).reshape(-1)
if actual.size == 0 or actual.size != predicted.size:
raise ValueError("Actual and predicted ROP must have equal, nonzero lengths.")
fig = Figure(figsize=figsize)
ax = fig.subplots()
ax.scatter(
actual,
predicted,
alpha=0.6,
color="teal",
edgecolors="k",
linewidths=0.5,
)
min_val = min(actual.min(), predicted.min())
max_val = max(actual.max(), predicted.max())
ax.plot(
[min_val, max_val],
[min_val, max_val],
"r--",
linewidth=2,
label="Perfect Fitness Line",
)
ax.set_title(
f"{model_name}: Actual vs. Predicted ROP (MAE = {mae:.2f} {rop_unit})",
fontsize=14,
)
ax.set_xlabel(f"Actual ROP ({rop_unit})", fontsize=11)
ax.set_ylabel(f"Predicted ROP ({rop_unit})", fontsize=11)
ax.grid(True, alpha=0.3)
ax.set_axisbelow(True)
ax.legend(loc="upper left")
fig.tight_layout()
return fig
def plot_rop_against_depth(
actual_rop,
predicted_rop,
depths,
*,
model_name="Tuned model",
title="ROP Prediction",
rop_unit="ft/hr",
depth_unit="ft",
figsize=(8, 6),
):
"""Return a depth-track figure without displaying it."""
actual = np.asarray(actual_rop, dtype=float).reshape(-1)
predicted = np.asarray(predicted_rop, dtype=float).reshape(-1)
depth = np.asarray(depths, dtype=float).reshape(-1)
if actual.size == 0 or not (
actual.size == predicted.size == depth.size
):
raise ValueError(
"Actual ROP, predicted ROP, and depths must have equal, nonzero lengths."
)
fig = Figure(figsize=figsize)
ax = fig.subplots()
ax.plot(
actual,
depth,
label="Actual ROP",
color="black",
linewidth=1,
)
ax.plot(
predicted,
depth,
label=f"{model_name} Predicted ROP",
color="orangered",
linewidth=1,
alpha=0.8,
)
ax.set_title(title, fontsize=14)
ax.set_xlabel(f"ROP ({rop_unit})", fontsize=11)
ax.set_ylabel(f"Depth ({depth_unit})", fontsize=11)
ax.invert_yaxis()
ax.grid(True, alpha=0.3)
ax.set_axisbelow(True)
ax.legend(loc="lower left")
fig.tight_layout()
return figNext, we set up, train and evaluate the performance of the models.
Shuffling the training data is necessary for MLPRegressor when using a stochastic optimizer. Unlike the other five models that ingest the training data all at once, an MLP (using the Adam optimizer in our case) iteratively processes the data in minibatches; hence, each minibatch should be a representative sample of the training set, and that is achieved by randomly shuffling the whole training data.
We must first split the data into the training and test sets before shuffling. Adjacent drilling data points are highly autocorrelated; therefore, shuffling them before splitting results in information leakage between the training and test sets. That is, there will be data points in the training set that have strong autocorrelation with data points in the test set. Therefore, we must split before shuffling.
from time import perf_counter
cell_started_at = perf_counter()
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.svm import SVR
from sklearn.neighbors import KNeighborsRegressor
from sklearn.neural_network import MLPRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error, mean_absolute_error
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 1000)
print("=" * 70)
print("PHASE 3: MULTI-MODEL ML BENCHMARK (ROP PREDICTION)")
print("=" * 70)
# Load the reusable Phase 2 dataset once for all downstream experiments.
well58_engineered_data = pd.read_csv("drilling_phase2_engineered.csv")
# Phase 1 excludes alternate-unit ROP; Phase 2 creates no ROP-derived predictors.
well58_target_col = 'ROP(1 ft)' if 'ROP(1 ft)' in well58_engineered_data.columns else 'ROP'
df_p3 = well58_engineered_data.copy()
depth_col = 'Depth(ft)' if 'Depth(ft)' in df_p3.columns else 'Depth'
target_col = 'ROP(1 ft)' if 'ROP(1 ft)' in df_p3.columns else 'ROP'
# Select features without ROP-derived columns; retain Depth for this benchmark.
feature_cols = select_feature_columns(df_p3, target_col, exclude_depth=False)
# CLEANING STEP: Handle Inf/NaNs
df_p3[feature_cols] = df_p3[feature_cols].replace([np.inf, -np.inf], np.nan)
df_p3 = df_p3.dropna(subset=feature_cols + [target_col]).reset_index(drop=True)
print(f"\nCleaned Feature Matrix Loaded: {len(df_p3)} active rows.")
print(f"-> Predictor Features: {len(feature_cols)}")
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
# 1. BLOCK SPLIT FOLLOWED BY TRAIN-SET SHUFFLING
print("\n" + "-" * 70)
print("Performing Block Split then Shuffling Train Set...")
# Calculate 80/20 depth cutoff index
split_idx = int(len(df_p3) * 0.80)
# Slice into shallow (train set) and deep (test set) continuous blocks
train_block = df_p3.iloc[:split_idx]
test_block = df_p3.iloc[split_idx:]
# Shuffle ONLY the training block internally
train_block_shuffled = shuffle(train_block, random_state=42).reset_index(drop=True)
# Assign features and target
X_train = train_block_shuffled[feature_cols]
y_train = train_block_shuffled[target_col]
# Test set remains sequential for evaluation
X_test = test_block[feature_cols]
y_test = test_block[target_col]
print(f"-> Training Set: {len(X_train)} samples")
print(f"-> Testing Set: {len(X_test)} samples")
# 2. FEATURE SCALING
scaler = StandardScaler()
X_train_scaled = pd.DataFrame(scaler.fit_transform(X_train), columns=feature_cols)
X_test_scaled = pd.DataFrame(scaler.transform(X_test), columns=feature_cols)
# 3. BENCHMARK ALL 6 ML MODELS
print("\n" + "-" * 70)
print("Training Benchmark Machine Learning Models...")
random_state = 42
models = {
"Random Forest": (RandomForestRegressor(n_estimators=100, random_state=random_state), False),
"Gradient Boosted Trees": (GradientBoostingRegressor(n_estimators=200, learning_rate=0.05, random_state=random_state, subsample=0.5), False),
"Support Vector Machine (SVR)": (SVR(kernel='rbf', C=100, epsilon=0.1), True),
"Nearest Neighbors (k-NN)": (KNeighborsRegressor(n_neighbors=5), True),
"Polynomial Ridge Regression": (make_pipeline(PolynomialFeatures(degree=2, interaction_only=True, include_bias=False), Ridge(alpha=100.0)), True),
"Multilayer Perceptron (Neural Net)": (
MLPRegressor(
hidden_layer_sizes=(64, 32),
activation='relu',
solver='adam',
max_iter=1000,
early_stopping=True,
random_state=random_state
),
True
)
}
results = []
for name, (model, requires_scaling) in models.items():
X_tr = X_train_scaled if requires_scaling else X_train
X_te = X_test_scaled if requires_scaling else X_test
print(f"-> Fitting model: {name}...")
model.fit(X_tr, y_train)
y_pred = model.predict(X_te)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
mae = mean_absolute_error(y_test, y_pred)
results.append({
"Model": name,
"RMSE": round(rmse, 2),
"MAE": round(mae, 2)
})
# 4. SUMMARY EVALUATION TABLE (Sorted by MAE ascending)
print("\n" + "-" * 70)
print("MODEL PERFORMANCE COMPARISON SUMMARY")
print("-" * 70)
summary_df = pd.DataFrame(results).sort_values(by="MAE", ascending=True).reset_index(drop=True)
print(summary_df.to_string(index=False))
# 5. FEATURE IMPORTANCES
print("\n" + "-" * 70)
print("Top 10 Feature Importances (Random Forest)")
print("-" * 70)
rf_model = models["Random Forest"][0]
importances = pd.DataFrame({
'Feature': feature_cols,
'Importance': rf_model.feature_importances_
}).sort_values(by='Importance', ascending=False).reset_index(drop=True)
print(importances.head(10).to_string(index=False))
print("\n" + "=" * 70)
print("PHASE 3 COMPLETE: MULTI-MODEL BENCHMARK FINISHED")
print("=" * 70)
print(f"Phase 3 benchmark cell duration: {perf_counter() - cell_started_at:.2f} seconds")======================================================================
PHASE 3: MULTI-MODEL ML BENCHMARK (ROP PREDICTION)
======================================================================
Cleaned Feature Matrix Loaded: 6812 active rows.
-> Predictor Features: 44
----------------------------------------------------------------------
Performing Block Split then Shuffling Train Set...
-> Training Set: 5449 samples
-> Testing Set: 1363 samples
----------------------------------------------------------------------
Training Benchmark Machine Learning Models...
-> Fitting model: Random Forest...
-> Fitting model: Gradient Boosted Trees...
-> Fitting model: Support Vector Machine (SVR)...
-> Fitting model: Nearest Neighbors (k-NN)...
-> Fitting model: Polynomial Ridge Regression...
-> Fitting model: Multilayer Perceptron (Neural Net)...
----------------------------------------------------------------------
MODEL PERFORMANCE COMPARISON SUMMARY
----------------------------------------------------------------------
Model RMSE MAE
Random Forest 5.46 4.04
Gradient Boosted Trees 5.67 4.14
Multilayer Perceptron (Neural Net) 5.82 4.33
Nearest Neighbors (k-NN) 6.50 5.01
Support Vector Machine (SVR) 7.79 5.38
Polynomial Ridge Regression 33.50 15.26
----------------------------------------------------------------------
Top 10 Feature Importances (Random Forest)
----------------------------------------------------------------------
Feature Importance
Depth(ft) 0.723249
Flow In (gal/min) 0.090661
Rotary Speed (rpm)_roll3_mean 0.037156
Flow In (gal/min)_lag2 0.014066
Hookload (k-lbs)_roll3_mean 0.009879
Flow In (gal/min)_roll3_mean 0.008982
weight on bit (k-lbs)_roll3_mean 0.008324
Hookload (k-lbs) 0.007009
Rotary Speed (rpm)_roll7_mean 0.006969
Surface Torque (psi)_roll7_mean 0.005807
======================================================================
PHASE 3 COMPLETE: MULTI-MODEL BENCHMARK FINISHED
======================================================================
Phase 3 benchmark cell duration: 45.48 seconds
test_depths = df_p3.iloc[split_idx:][depth_col]
gbt_model = models["Gradient Boosted Trees"][0]
requires_scaling = models["Gradient Boosted Trees"][1]
X_te = X_test_scaled if requires_scaling else X_test
y_pred = gbt_model.predict(X_te)
parity_fig = plot_rop_fitness(
actual_rop=y_test,
predicted_rop=y_pred,
mae=mean_absolute_error(y_test, y_pred),
model_name="Trained GBT Model"
)
depth_fig = plot_rop_against_depth(
actual_rop=y_test,
predicted_rop=y_pred,
depths=test_depths,
model_name="Trained GBT Model"
)
IPython.display.display(parity_fig)
IPython.display.display(depth_fig)

test_depths = df_p3.iloc[split_idx:][depth_col]
rf_model = models["Random Forest"][0]
requires_scaling = models["Random Forest"][1]
X_te = X_test_scaled if requires_scaling else X_test
y_pred = rf_model.predict(X_te)
parity_fig = plot_rop_fitness(
actual_rop=y_test,
predicted_rop=y_pred,
mae=mean_absolute_error(y_test, y_pred),
model_name="Trained RF Model"
)
depth_fig = plot_rop_against_depth(
actual_rop=y_test,
predicted_rop=y_pred,
depths=test_depths,
model_name="Trained RF Model"
)
IPython.display.display(parity_fig)
IPython.display.display(depth_fig)

Commentary and Key Takeaways
The benchmark trains on the shallower 80% of depth-ordered rows and evaluates on the deeper 20%. This tests transfer to a deeper interval of the same well; it does not establish generalization to new wells or independently identified formations.
The Random Forest model has the lowest benchmark MAE (4.04 ft/hr; RMSE 5.46 ft/hr). Gradient Boosted Trees achieves MAE 4.14 ft/hr and RMSE 5.67 ft/hr.
7. Phase 4: K-Fold Cross-Validation (Without Shuffle) on Gradient Boosted Trees
Strategy & Methodological Intent
The Gradient Boosted Trees model is faster to train/evaluate compared to the Random Forest model, and since both have close learning scores, we chose to tune the Gradient Boosted Trees. We tune the GBT using three-fold cross-validation within the shallower 80% training block. The deeper 20% is reserved for holdout evaluation.
- Mitigating Temporal Autocorrelation across subsets: Standard k-fold cross-validation, which involves pre-shuffling, mixes neighboring data points across training and validation sets. Because drilling data exhibit high autocorrelation (neighboring measurements share near-identical lithological and mechanical signatures), this creates artificial data leakage. Randomly shuffling rows before splitting into folds allows models to “cheat” by training on samples immediately adjacent to the validation data, yielding overly optimistic evaluation metrics that do not reflect true field performance.
- Preserving Sequential Order: By setting
shuffle=Falsein the KFold configuration, we split the dataset into contiguous sequential folds, respecting the natural downhole continuity of the logging measurements. This evaluates the model’s ability to estimate the target variable across varying formation zones while maintaining rigorous local independence between training and validation folds. - Hyperparameter Search: The grid evaluates 36 combinations of tree count, learning rate, maximum depth, and subsampling fraction, with three fits per combination. The best estimator is refitted on the full training block before holdout evaluation.
Evaluation & Loss Function: Mean Squared Error (MSE)
Cross-validation selects hyperparameters using negative MSE (equivalent to minimizing MSE). The regressor uses loss='squared_error', which penalizes larger residuals quadratically. MAE and RMSE are subsequently reported on the deeper holdout block.
cell_started_at = perf_counter()
from sklearn.model_selection import KFold, GridSearchCV
print("=" * 70)
print("PHASE 5: K-FOLD CROSS-VALIDATION (WITHOUT SHUFFLE) & HYPERPARAMETER TUNING")
print("=" * 70)
# 0. REUSE AND PREPARE DATASET (EXCLUDING DEPTH AND ROP-DERIVED FEATURES)
df_p4 = well58_engineered_data.copy()
depth_col = 'Depth(ft)' if 'Depth(ft)' in df_p4.columns else 'Depth'
target_col = 'ROP(1 ft)' if 'ROP(1 ft)' in df_p4.columns else 'ROP'
# Ensure the dataset is sorted by depth
df_p4 = df_p4.sort_values(depth_col).reset_index(drop=True)
# Exclude ROP-derived columns from features.
feature_cols = select_feature_columns(df_p4, target_col, exclude_depth=False)
# Clean Inf/NaNs
df_p4[feature_cols] = df_p4[feature_cols].replace([np.inf, -np.inf], np.nan)
df_p4 = df_p4.dropna(subset=feature_cols + [target_col]).reset_index(drop=True)
# 1. SEQUENTIAL BLOCK SPLIT (80% Train Block / 20% Holdout Test Block)
split_idx = int(len(df_p4) * 0.80)
train_block = df_p4.iloc[:split_idx]
test_block = df_p4.iloc[split_idx:]
X_train_seq = train_block[feature_cols]
y_train_seq = train_block[target_col]
X_test = test_block[feature_cols]
y_test = test_block[target_col]
print(f"\nData Prepared: {len(X_train_seq)} training rows, {len(X_test)} holdout test rows.")
# 2. STREAMLINED GRID SEARCH USING NON-SHUFFLED K-FOLD (3 Folds)
kf = KFold(n_splits=3, shuffle=False)
param_grid = {
'n_estimators': [100, 200, 400],
'learning_rate': [0.03, 0.05],
'max_depth': [3, 7, 10],
'subsample': [0.2, 0.5]
}
gbm_base = GradientBoostingRegressor(loss='squared_error', random_state=42)
print("\nRunning GridSearchCV with Non-Shuffled K-Fold...")
grid_search = GridSearchCV(
estimator=gbm_base,
param_grid=param_grid,
cv=kf,
scoring='neg_mean_squared_error',
n_jobs=1, # Prevents multi-threading CPU locks
verbose=3 # Prints continuous step-by-step progress
)
grid_search.fit(X_train_seq, y_train_seq)
best_gbm = grid_search.best_estimator_
print("\n" + "=" * 70)
print("OPTIMAL HYPERPARAMETERS FOUND BY CROSS-VALIDATION")
print("=" * 70)
for k, v in grid_search.best_params_.items():
print(f" - {k}: {v}")
# 3. EVALUATE TUNED MODEL ON UNSEEN DEEP HOLDOUT TEST SET
y_pred_tuned = best_gbm.predict(X_test)
rmse_tuned = np.sqrt(mean_squared_error(y_test, y_pred_tuned))
mae_tuned = mean_absolute_error(y_test, y_pred_tuned)
print("\n" + "=" * 70)
print("FINAL PERFORMANCE: TUNED GRADIENT BOOSTING (HOLDOUT TEST BLOCK)")
print("=" * 70)
print(f"MAE : {mae_tuned:.2f} ft/hr")
print(f"RMSE : {rmse_tuned:.2f} ft/hr")
print("=" * 70)
print(f"Phase 5 tuning cell duration: {perf_counter() - cell_started_at:.2f} seconds")======================================================================
PHASE 5: K-FOLD CROSS-VALIDATION (WITHOUT SHUFFLE) & HYPERPARAMETER TUNING
======================================================================
Data Prepared: 5449 training rows, 1363 holdout test rows.
Running GridSearchCV with Non-Shuffled K-Fold...
Fitting 3 folds for each of 36 candidates, totalling 108 fits
[CV 1/3] END learning_rate=0.03, max_depth=3, n_estimators=100, subsample=0.2;, score=-4892.953 total time= 0.9s
[CV 2/3] END learning_rate=0.03, max_depth=3, n_estimators=100, subsample=0.2;, score=-297.801 total time= 0.9s
[CV 3/3] END learning_rate=0.03, max_depth=3, n_estimators=100, subsample=0.2;, score=-2228.629 total time= 0.9s
[CV 1/3] END learning_rate=0.03, max_depth=3, n_estimators=100, subsample=0.5;, score=-5330.441 total time= 2.2s
[CV 2/3] END learning_rate=0.03, max_depth=3, n_estimators=100, subsample=0.5;, score=-307.224 total time= 2.3s
[CV 3/3] END learning_rate=0.03, max_depth=3, n_estimators=100, subsample=0.5;, score=-296.197 total time= 2.2s
[CV 1/3] END learning_rate=0.03, max_depth=3, n_estimators=200, subsample=0.2;, score=-4715.983 total time= 1.8s
[CV 2/3] END learning_rate=0.03, max_depth=3, n_estimators=200, subsample=0.2;, score=-318.829 total time= 1.8s
[CV 3/3] END learning_rate=0.03, max_depth=3, n_estimators=200, subsample=0.2;, score=-1535.609 total time= 1.9s
[CV 1/3] END learning_rate=0.03, max_depth=3, n_estimators=200, subsample=0.5;, score=-5022.706 total time= 4.6s
[CV 2/3] END learning_rate=0.03, max_depth=3, n_estimators=200, subsample=0.5;, score=-311.613 total time= 4.5s
[CV 3/3] END learning_rate=0.03, max_depth=3, n_estimators=200, subsample=0.5;, score=-315.048 total time= 4.6s
[CV 1/3] END learning_rate=0.03, max_depth=3, n_estimators=400, subsample=0.2;, score=-4926.978 total time= 3.7s
[CV 2/3] END learning_rate=0.03, max_depth=3, n_estimators=400, subsample=0.2;, score=-321.728 total time= 4.0s
[CV 3/3] END learning_rate=0.03, max_depth=3, n_estimators=400, subsample=0.2;, score=-1696.247 total time= 3.8s
[CV 1/3] END learning_rate=0.03, max_depth=3, n_estimators=400, subsample=0.5;, score=-5282.894 total time= 9.2s
[CV 2/3] END learning_rate=0.03, max_depth=3, n_estimators=400, subsample=0.5;, score=-302.457 total time= 9.2s
[CV 3/3] END learning_rate=0.03, max_depth=3, n_estimators=400, subsample=0.5;, score=-255.135 total time= 9.2s
[CV 1/3] END learning_rate=0.03, max_depth=7, n_estimators=100, subsample=0.2;, score=-4565.251 total time= 1.9s
[CV 2/3] END learning_rate=0.03, max_depth=7, n_estimators=100, subsample=0.2;, score=-211.176 total time= 2.0s
[CV 3/3] END learning_rate=0.03, max_depth=7, n_estimators=100, subsample=0.2;, score=-1948.776 total time= 2.0s
[CV 1/3] END learning_rate=0.03, max_depth=7, n_estimators=100, subsample=0.5;, score=-5955.497 total time= 5.1s
[CV 2/3] END learning_rate=0.03, max_depth=7, n_estimators=100, subsample=0.5;, score=-202.276 total time= 5.3s
[CV 3/3] END learning_rate=0.03, max_depth=7, n_estimators=100, subsample=0.5;, score=-536.872 total time= 5.3s
[CV 1/3] END learning_rate=0.03, max_depth=7, n_estimators=200, subsample=0.2;, score=-4422.823 total time= 4.5s
[CV 2/3] END learning_rate=0.03, max_depth=7, n_estimators=200, subsample=0.2;, score=-212.770 total time= 4.3s
[CV 3/3] END learning_rate=0.03, max_depth=7, n_estimators=200, subsample=0.2;, score=-1468.304 total time= 4.3s
[CV 1/3] END learning_rate=0.03, max_depth=7, n_estimators=200, subsample=0.5;, score=-6169.434 total time= 10.1s
[CV 2/3] END learning_rate=0.03, max_depth=7, n_estimators=200, subsample=0.5;, score=-208.232 total time= 10.3s
[CV 3/3] END learning_rate=0.03, max_depth=7, n_estimators=200, subsample=0.5;, score=-265.165 total time= 10.7s
[CV 1/3] END learning_rate=0.03, max_depth=7, n_estimators=400, subsample=0.2;, score=-4290.702 total time= 8.6s
[CV 2/3] END learning_rate=0.03, max_depth=7, n_estimators=400, subsample=0.2;, score=-209.814 total time= 8.5s
[CV 3/3] END learning_rate=0.03, max_depth=7, n_estimators=400, subsample=0.2;, score=-1300.633 total time= 8.4s
[CV 1/3] END learning_rate=0.03, max_depth=7, n_estimators=400, subsample=0.5;, score=-6176.723 total time= 20.2s
[CV 2/3] END learning_rate=0.03, max_depth=7, n_estimators=400, subsample=0.5;, score=-202.138 total time= 20.6s
[CV 3/3] END learning_rate=0.03, max_depth=7, n_estimators=400, subsample=0.5;, score=-208.428 total time= 21.2s
[CV 1/3] END learning_rate=0.03, max_depth=10, n_estimators=100, subsample=0.2;, score=-5182.396 total time= 2.9s
[CV 2/3] END learning_rate=0.03, max_depth=10, n_estimators=100, subsample=0.2;, score=-240.666 total time= 2.9s
[CV 3/3] END learning_rate=0.03, max_depth=10, n_estimators=100, subsample=0.2;, score=-2179.559 total time= 2.8s
[CV 1/3] END learning_rate=0.03, max_depth=10, n_estimators=100, subsample=0.5;, score=-5529.578 total time= 7.3s
[CV 2/3] END learning_rate=0.03, max_depth=10, n_estimators=100, subsample=0.5;, score=-249.807 total time= 7.4s
[CV 3/3] END learning_rate=0.03, max_depth=10, n_estimators=100, subsample=0.5;, score=-703.606 total time= 7.2s
[CV 1/3] END learning_rate=0.03, max_depth=10, n_estimators=200, subsample=0.2;, score=-4854.178 total time= 6.0s
[CV 2/3] END learning_rate=0.03, max_depth=10, n_estimators=200, subsample=0.2;, score=-241.100 total time= 6.0s
[CV 3/3] END learning_rate=0.03, max_depth=10, n_estimators=200, subsample=0.2;, score=-1517.280 total time= 6.0s
[CV 1/3] END learning_rate=0.03, max_depth=10, n_estimators=200, subsample=0.5;, score=-5269.233 total time= 14.5s
[CV 2/3] END learning_rate=0.03, max_depth=10, n_estimators=200, subsample=0.5;, score=-245.995 total time= 14.9s
[CV 3/3] END learning_rate=0.03, max_depth=10, n_estimators=200, subsample=0.5;, score=-437.672 total time= 14.6s
[CV 1/3] END learning_rate=0.03, max_depth=10, n_estimators=400, subsample=0.2;, score=-4605.806 total time= 11.8s
[CV 2/3] END learning_rate=0.03, max_depth=10, n_estimators=400, subsample=0.2;, score=-241.610 total time= 12.3s
[CV 3/3] END learning_rate=0.03, max_depth=10, n_estimators=400, subsample=0.2;, score=-1310.571 total time= 12.3s
[CV 1/3] END learning_rate=0.03, max_depth=10, n_estimators=400, subsample=0.5;, score=-5288.350 total time= 30.2s
[CV 2/3] END learning_rate=0.03, max_depth=10, n_estimators=400, subsample=0.5;, score=-250.826 total time= 30.8s
[CV 3/3] END learning_rate=0.03, max_depth=10, n_estimators=400, subsample=0.5;, score=-516.140 total time= 30.6s
[CV 1/3] END learning_rate=0.05, max_depth=3, n_estimators=100, subsample=0.2;, score=-4855.774 total time= 0.9s
[CV 2/3] END learning_rate=0.05, max_depth=3, n_estimators=100, subsample=0.2;, score=-283.243 total time= 1.0s
[CV 3/3] END learning_rate=0.05, max_depth=3, n_estimators=100, subsample=0.2;, score=-762.047 total time= 0.9s
[CV 1/3] END learning_rate=0.05, max_depth=3, n_estimators=100, subsample=0.5;, score=-5397.619 total time= 2.3s
[CV 2/3] END learning_rate=0.05, max_depth=3, n_estimators=100, subsample=0.5;, score=-306.133 total time= 2.4s
[CV 3/3] END learning_rate=0.05, max_depth=3, n_estimators=100, subsample=0.5;, score=-289.421 total time= 2.3s
[CV 1/3] END learning_rate=0.05, max_depth=3, n_estimators=200, subsample=0.2;, score=-5522.169 total time= 2.1s
[CV 2/3] END learning_rate=0.05, max_depth=3, n_estimators=200, subsample=0.2;, score=-291.509 total time= 2.0s
[CV 3/3] END learning_rate=0.05, max_depth=3, n_estimators=200, subsample=0.2;, score=-669.481 total time= 2.0s
[CV 1/3] END learning_rate=0.05, max_depth=3, n_estimators=200, subsample=0.5;, score=-5806.755 total time= 4.8s
[CV 2/3] END learning_rate=0.05, max_depth=3, n_estimators=200, subsample=0.5;, score=-316.173 total time= 4.8s
[CV 3/3] END learning_rate=0.05, max_depth=3, n_estimators=200, subsample=0.5;, score=-413.543 total time= 4.9s
[CV 1/3] END learning_rate=0.05, max_depth=3, n_estimators=400, subsample=0.2;, score=-6028.069 total time= 4.0s
[CV 2/3] END learning_rate=0.05, max_depth=3, n_estimators=400, subsample=0.2;, score=-273.397 total time= 4.1s
[CV 3/3] END learning_rate=0.05, max_depth=3, n_estimators=400, subsample=0.2;, score=-795.199 total time= 4.2s
[CV 1/3] END learning_rate=0.05, max_depth=3, n_estimators=400, subsample=0.5;, score=-5947.229 total time= 9.7s
[CV 2/3] END learning_rate=0.05, max_depth=3, n_estimators=400, subsample=0.5;, score=-304.467 total time= 9.8s
[CV 3/3] END learning_rate=0.05, max_depth=3, n_estimators=400, subsample=0.5;, score=-352.126 total time= 9.6s
[CV 1/3] END learning_rate=0.05, max_depth=7, n_estimators=100, subsample=0.2;, score=-4609.650 total time= 2.1s
[CV 2/3] END learning_rate=0.05, max_depth=7, n_estimators=100, subsample=0.2;, score=-247.604 total time= 2.1s
[CV 3/3] END learning_rate=0.05, max_depth=7, n_estimators=100, subsample=0.2;, score=-565.709 total time= 2.2s
[CV 1/3] END learning_rate=0.05, max_depth=7, n_estimators=100, subsample=0.5;, score=-5991.659 total time= 5.3s
[CV 2/3] END learning_rate=0.05, max_depth=7, n_estimators=100, subsample=0.5;, score=-189.421 total time= 5.1s
[CV 3/3] END learning_rate=0.05, max_depth=7, n_estimators=100, subsample=0.5;, score=-614.245 total time= 5.1s
[CV 1/3] END learning_rate=0.05, max_depth=7, n_estimators=200, subsample=0.2;, score=-4609.212 total time= 4.3s
[CV 2/3] END learning_rate=0.05, max_depth=7, n_estimators=200, subsample=0.2;, score=-252.040 total time= 4.4s
[CV 3/3] END learning_rate=0.05, max_depth=7, n_estimators=200, subsample=0.2;, score=-367.238 total time= 4.5s
[CV 1/3] END learning_rate=0.05, max_depth=7, n_estimators=200, subsample=0.5;, score=-5962.673 total time= 10.6s
[CV 2/3] END learning_rate=0.05, max_depth=7, n_estimators=200, subsample=0.5;, score=-196.217 total time= 10.7s
[CV 3/3] END learning_rate=0.05, max_depth=7, n_estimators=200, subsample=0.5;, score=-734.312 total time= 10.5s
[CV 1/3] END learning_rate=0.05, max_depth=7, n_estimators=400, subsample=0.2;, score=-4483.403 total time= 9.1s
[CV 2/3] END learning_rate=0.05, max_depth=7, n_estimators=400, subsample=0.2;, score=-290.257 total time= 8.9s
[CV 3/3] END learning_rate=0.05, max_depth=7, n_estimators=400, subsample=0.2;, score=-388.167 total time= 9.0s
[CV 1/3] END learning_rate=0.05, max_depth=7, n_estimators=400, subsample=0.5;, score=-5929.196 total time= 21.5s
[CV 2/3] END learning_rate=0.05, max_depth=7, n_estimators=400, subsample=0.5;, score=-192.464 total time= 21.3s
[CV 3/3] END learning_rate=0.05, max_depth=7, n_estimators=400, subsample=0.5;, score=-931.100 total time= 21.8s
[CV 1/3] END learning_rate=0.05, max_depth=10, n_estimators=100, subsample=0.2;, score=-4382.203 total time= 3.0s
[CV 2/3] END learning_rate=0.05, max_depth=10, n_estimators=100, subsample=0.2;, score=-239.280 total time= 3.1s
[CV 3/3] END learning_rate=0.05, max_depth=10, n_estimators=100, subsample=0.2;, score=-2822.668 total time= 3.0s
[CV 1/3] END learning_rate=0.05, max_depth=10, n_estimators=100, subsample=0.5;, score=-5551.101 total time= 7.0s
[CV 2/3] END learning_rate=0.05, max_depth=10, n_estimators=100, subsample=0.5;, score=-239.808 total time= 7.1s
[CV 3/3] END learning_rate=0.05, max_depth=10, n_estimators=100, subsample=0.5;, score=-769.381 total time= 7.1s
[CV 1/3] END learning_rate=0.05, max_depth=10, n_estimators=200, subsample=0.2;, score=-4204.653 total time= 5.8s
[CV 2/3] END learning_rate=0.05, max_depth=10, n_estimators=200, subsample=0.2;, score=-248.904 total time= 6.2s
[CV 3/3] END learning_rate=0.05, max_depth=10, n_estimators=200, subsample=0.2;, score=-2563.336 total time= 6.5s
[CV 1/3] END learning_rate=0.05, max_depth=10, n_estimators=200, subsample=0.5;, score=-5426.850 total time= 14.3s
[CV 2/3] END learning_rate=0.05, max_depth=10, n_estimators=200, subsample=0.5;, score=-239.563 total time= 14.5s
[CV 3/3] END learning_rate=0.05, max_depth=10, n_estimators=200, subsample=0.5;, score=-869.375 total time= 14.4s
[CV 1/3] END learning_rate=0.05, max_depth=10, n_estimators=400, subsample=0.2;, score=-4156.984 total time= 11.6s
[CV 2/3] END learning_rate=0.05, max_depth=10, n_estimators=400, subsample=0.2;, score=-260.151 total time= 11.8s
[CV 3/3] END learning_rate=0.05, max_depth=10, n_estimators=400, subsample=0.2;, score=-2135.854 total time= 11.8s
[CV 1/3] END learning_rate=0.05, max_depth=10, n_estimators=400, subsample=0.5;, score=-5393.682 total time= 29.0s
[CV 2/3] END learning_rate=0.05, max_depth=10, n_estimators=400, subsample=0.5;, score=-241.734 total time= 30.4s
[CV 3/3] END learning_rate=0.05, max_depth=10, n_estimators=400, subsample=0.5;, score=-947.507 total time= 29.4s
======================================================================
OPTIMAL HYPERPARAMETERS FOUND BY CROSS-VALIDATION
======================================================================
- learning_rate: 0.05
- max_depth: 7
- n_estimators: 400
- subsample: 0.2
======================================================================
FINAL PERFORMANCE: TUNED GRADIENT BOOSTING (HOLDOUT TEST BLOCK)
======================================================================
MAE : 3.95 ft/hr
RMSE : 5.29 ft/hr
======================================================================
Phase 5 tuning cell duration: 912.34 seconds
8. Phase 5: Fine-tuned Model Performance & Visual Validation
Performance Benchmarks (Tuned Gradient Boosted Trees)
The tuning goal was to select Gradient Boosted Trees hyperparameters via cross-validation, using squared-error as the training score.
Performance on the deeper holdout test block:
- Root Mean Squared Error (RMSE): \(5.29\text{ ft/hr}\)
- Mean Absolute Error (MAE): \(3.95\text{ ft/hr}\)
The selected hyperparameters were learning_rate=0.05, max_depth=7, n_estimators=400, and subsample=0.2. This run has smaller holdout errors than the depth-included Gradient Boosted Trees benchmark (MAE 4.14 ft/hr; RMSE 5.67 ft/hr), showing improved holdout scores after tuning.
Visual Validation
To verify model performance, we implemented two key visualizations:
- Actual vs. Predicted Evaluation (Scatter Plot): Validates residual spread and assesses fit and bias alongside performance metrics (MAE, RMSE).
- Actual vs. Predicted Against Depth: Displays continuous actual measured ROP (Black) vs. model-predicted ROP (Orange).
test_depths = df_p4.iloc[split_idx:][depth_col]
parity_fig = plot_rop_fitness(
actual_rop=y_test,
predicted_rop=y_pred_tuned,
mae=mae_tuned,
model_name="Tuned GBM"
)
depth_fig = plot_rop_against_depth(
actual_rop=y_test,
predicted_rop=y_pred_tuned,
depths=test_depths,
model_name="Tuned GBM",
title="ROP Prediction Tracking Holdout (Test) Block"
)
IPython.display.display(parity_fig)
IPython.display.display(depth_fig)

Commentary: Model Visualizations
The depth-track plot compares predicted ROP (orange) with measured ROP (black) in the deeper holdout block. Agreement and departures show where the model tracks or misses ROP variation.
Feature Importance & Predictive Associations
The following plot ranks the top 15 features by impurity-based importance in the tuned Gradient Boosted Trees model. ROP-derived features are excluded from this model. Importance describes their contribution to the fitted model, not a causal physical effect. Correlated sensors, lags, and rolling means can share or redistribute importance.
# Extract feature importances from the tuned Gradient Boosted Tree model
importances = best_gbm.feature_importances_
# Sort top 15 features
feature_imp_df = pd.DataFrame({
'Feature': feature_cols,
'Importance': importances
}).sort_values(by='Importance', ascending=False).head(15)
# Plot Feature Importances
plt.figure(figsize=(10, 5))
sns.set_theme(style="whitegrid")
ax = sns.barplot(
data=feature_imp_df,
x='Importance',
y='Feature',
palette='Blues_r',
hue='Feature',
legend=False
)
plt.title('Top 15 Most Important Features in Tuned ROP Model', fontsize=12, fontweight='bold')
plt.xlabel('Relative Feature Importance (Gini/Gain)', fontsize=11)
plt.ylabel('Feature Name', fontsize=11)
# Annotate exact values on each bar
for p in ax.patches:
width = p.get_width()
ax.annotate(f'{width:.3f}',
(width + 0.002, p.get_y() + p.get_height() / 2.),
ha='left', va='center', fontsize=9, color='black', xytext=(5, 0),
textcoords='offset points')
plt.tight_layout()
plt.show()
9. Phase 6: Deep Learning Using a Recurrent Neural Network
This section details the implementation of a sequence-based deep learning workflow for predicting Rate of Penetration (ROP). To capture the sequential nature of drilling operations, the model employs a Gated Recurrent Unit (GRU), which is a type of recurrent neural network (RNN).
RNNs process ordered sequences by updating a hidden state at each step, allowing information from earlier rows to influence the output. Here, sequences follow depth order rather than equally spaced time intervals.
A GRU builds upon the basic RNN by using gates to increase the preservation of temporal information over greater sequence lengths and reduce the problem of vanishing gradients.
The two experiments use a 2-layer unidirectional GRU: one uses cleaned operational sensors without Depth, and the other uses the Phase 2 engineered features with Depth included. Both exclude ROP-derived features.
Model and Training Configuration
| Component | Configuration in the current code |
|---|---|
| Inputs | Original-sensor experiment: Phase 1 sensors, excluding Depth and ROP. Engineered experiment: all Phase 2 features, including Depth and excluding ROP. |
| Filtering and order | Active drilling rows from Phase 1; sorted by Depth; both GRU calls retain only Depth > 600 ft. Nonfinite features become missing, and rows missing a feature or target are dropped. |
| Split and scaling | Shallower 80% of eligible rows for training, deeper 20% for evaluation. StandardScaler is fitted on training features only; the target (ROP) is unscaled. |
| Sequences and target | Overlapping windows of 7 depth-ordered rows, stride 1, ending at row \(t\) and estimating ROP at \(t\). Adjacent windows share 6 rows. Windows are built separately within each split, so the first 6 rows of each split have no prediction. Rows are not equally spaced timesteps, and filtering can introduce depth gaps. |
| Recurrent model | Two unidirectional GRU layers, 64 hidden units per layer, batch_first=True; the last sequence output feeds the regression head. Hidden state is initialized afresh for each sequence. |
| Regression head | Linear (64 → 32), ReLU, Linear (32 → 1), with an unrestricted scalar ROP output. |
| Optimizer | Adam, selected learning rate, \(\beta_1=0.9\), \(\beta_2=0.999\), \(\epsilon=10^{-8}\), weight decay = 0. |
| Training loss | nn.MSELoss() on unscaled ROP. Training and evaluation losses printed during training are MSE; RMSE is computed afterward as the square root of evaluation MSE. |
| Regularization | Dropout = 0.1 between GRU layers. No head dropout, weight-decay penalty, gradient clipping, learning-rate scheduler, or early stopping is configured. |
| Learning-rate search | One candidate, 0.0005, is evaluated in each current experiment. Each candidate starts a new model and trains for 10 epochs; the candidate with lowest evaluation-block MSE is selected. |
| Main training | A new model trains for 80 epochs at the selected learning rate; batch size 32. Training windows are shuffled, preserving row order within each window; evaluation windows are not shuffled. |
| Checkpoints and evaluation | Both the final model and an independent copy of the epoch with lowest evaluation-block MSE are returned. evaluate_gru_experiment separately evaluates either checkpoint, reporting epoch, MSE, RMSE, and MAE. The current evaluation calls request the final model. |
| Runtime and seeds | CPU; Python, NumPy, and PyTorch seeds set to 42 at the start of each experiment. |
Current evaluation reference: The original-sensor evaluation passes gru_result, and the engineered-feature evaluation passes gru_engineered_result. Consequently, the metrics, parameter counts, and subsequent plots show the respective final models at epoch 80.
# Shared implementation for the three Phase 7 GRU experiments.
import random
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
from copy import deepcopy
def create_sequences(feature_array, target_array, seq_length=7):
"""Return windows ending at t and the corresponding ROP target at t."""
X_seq, y_seq = [], []
for i in range(seq_length - 1, len(feature_array)):
X_seq.append(feature_array[i - seq_length + 1 : i + 1])
y_seq.append(target_array[i])
return np.asarray(X_seq, dtype=np.float32), np.asarray(
y_seq, dtype=np.float32
).reshape(-1, 1)
class DrillingSequenceDataset(Dataset):
def __init__(self, X, y):
self.X = torch.tensor(X, dtype=torch.float32)
self.y = torch.tensor(y, dtype=torch.float32)
def __len__(self):
return len(self.X)
def __getitem__(self, idx):
return self.X[idx], self.y[idx]
class GRUROPRegressor(nn.Module):
def __init__(self, input_dim, hidden_dim=64, num_layers=2, dropout=0.1):
super().__init__()
self.gru = nn.GRU(
input_size=input_dim, hidden_size=hidden_dim,
num_layers=num_layers, batch_first=True, bidirectional=False,
dropout=dropout if num_layers > 1 else 0.0,
)
self.fc = nn.Sequential(
nn.Linear(hidden_dim, 32), nn.ReLU(), nn.Linear(32, 1)
)
def forward(self, x):
gru_out, _ = self.gru(x)
return self.fc(gru_out[:, -1, :])
def train_gru_experiment(dataframe, feature_columns, *, model_name,
seq_length=7, batch_size=32, num_epochs=60,
tuning_epochs=10, train_ratio=0.80,
filter_surface=True,
lr_candidates=(0.0001, 0.0005, 0.001, 0.003, 0.005, 0.01, 0.02)):
"""Tune the learning rate and train the final and best-epoch GRU models."""
device = torch.device("cpu")
print(f"Running PyTorch on Device: {device} | {model_name}\n")
torch.manual_seed(42)
np.random.seed(42)
random.seed(42)
torch.use_deterministic_algorithms(True)
data = dataframe.copy()
depth_column = "Depth(ft)" if "Depth(ft)" in data.columns else "Depth"
target_column = "ROP(1 ft)" if "ROP(1 ft)" in data.columns else "ROP"
feature_columns = list(feature_columns)
if not feature_columns or target_column in feature_columns:
raise ValueError("GRU predictors must be nonempty and exclude the target column.")
if not 1 <= len(lr_candidates) <= 7:
raise ValueError("The learning-rate search must contain 1 to 7 candidates.")
data = data.sort_values(depth_column).reset_index(drop=True)
# Conditionally remove surface noise (0 to 600 ft) based on filter_surface
if filter_surface and depth_column in data.columns:
initial_rows = len(data)
data = data[data[depth_column] > 600].reset_index(drop=True)
print(f"Filtered out surface interval (0–600 ft): Removed {initial_rows - len(data)} rows.")
else:
print("Retaining full depth interval (0–7000 ft without surface filtering).")
data[feature_columns] = data[feature_columns].replace([np.inf, -np.inf], np.nan)
data = data.dropna(subset=feature_columns + [target_column]).reset_index(drop=True)
# Split using the specified ratio (e.g., 0.80 for 80-20)
split_index = int(len(data) * train_ratio)
train_data = data.iloc[:split_index].copy()
test_data = data.iloc[split_index:].copy()
if min(len(train_data), len(test_data)) < seq_length:
raise ValueError("Each GRU split must contain at least one complete sequence.")
scaler = StandardScaler()
train_features = scaler.fit_transform(train_data[feature_columns])
test_features = scaler.transform(test_data[feature_columns])
X_train_gru, y_train_gru = create_sequences(
train_features, train_data[target_column].to_numpy(), seq_length
)
X_test_gru, y_test_gru = create_sequences(
test_features, test_data[target_column].to_numpy(), seq_length
)
# Each test prediction corresponds to the last row of its sequence.
test_depths_gru = test_data[depth_column].iloc[seq_length - 1:].to_numpy()
print(f" -> Training Tensor Shape (N, T, F): {X_train_gru.shape}\n")
print(f" -> Testing Tensor Shape (N, T, F): {X_test_gru.shape}\n")
print(f" -> Predictor Features:\n{feature_columns}")
train_dataset = DrillingSequenceDataset(X_train_gru, y_train_gru)
test_dataset = DrillingSequenceDataset(X_test_gru, y_test_gru)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
criterion = nn.MSELoss()
input_dim = X_train_gru.shape[2]
best_lr, best_val_loss = None, float("inf")
tuning_results = []
print(f"\nPHASE 7A: FINE-TUNING LEARNING RATE (MAX {len(lr_candidates)} ITERATIONS)")
for iteration, lr in enumerate(lr_candidates, start=1):
model = GRUROPRegressor(input_dim=input_dim).to(device)
optimizer = torch.optim.Adam(
model.parameters(), lr=lr, betas=(0.9, 0.999),
eps=1e-08, weight_decay=0,
)
model.train()
for epoch in range(tuning_epochs):
for bx, by in train_loader:
bx, by = bx.to(device), by.to(device)
optimizer.zero_grad()
loss = criterion(model(bx), by)
loss.backward()
optimizer.step()
model.eval()
val_loss = 0.0
with torch.no_grad():
for bx, by in test_loader:
bx, by = bx.to(device), by.to(device)
val_loss += criterion(model(bx), by).item() * len(by)
val_mse = val_loss / len(test_dataset)
tuning_results.append((lr, val_mse))
print(f"Iteration {iteration}/{len(lr_candidates)} | Candidate LR: {lr:<7} -> Val MSE: {val_mse:.4f}")
if val_mse < best_val_loss:
best_val_loss, best_lr = val_mse, lr
print(f"Optimal Learning Rate Found: {best_lr} (MSE Loss: {best_val_loss:.4f})")
print(f"\nPHASE 7B: TRAINING FINAL GRU MODEL (LR = {best_lr})")
if num_epochs < 1:
raise ValueError("num_epochs must be at least 1.")
print(f"\nPHASE 7B: TRAINING GRU MODEL (LR = {best_lr})")
final_model = GRUROPRegressor(input_dim=input_dim).to(device)
optimizer = torch.optim.Adam(
final_model.parameters(), lr=best_lr, betas=(0.9, 0.999),
eps=1e-08, weight_decay=0,
)
best_model = None
best_test_mse = float("inf")
best_epoch = None
for epoch in range(1, num_epochs + 1):
final_model.train()
train_loss = 0.0
for bx, by in train_loader:
bx, by = bx.to(device), by.to(device)
optimizer.zero_grad()
loss = criterion(final_model(bx), by)
loss.backward()
optimizer.step()
train_loss += loss.item() * len(by)
train_mse = train_loss / len(train_dataset)
final_model.eval()
test_loss = 0.0
with torch.no_grad():
for bx, by in test_loader:
bx, by = bx.to(device), by.to(device)
test_loss += criterion(final_model(bx), by).item() * len(by)
test_mse = test_loss / len(test_dataset)
# Preserve an independent copy of the best epoch's model.
# Later training updates affect only final_model.
if np.isfinite(test_mse) and test_mse < best_test_mse:
best_test_mse = test_mse
best_epoch = epoch
best_model = deepcopy(final_model)
if epoch % 10 == 0 or epoch == 1:
print(
f"Epoch {epoch:02d}/{num_epochs} | "
f"Train MSE: {train_mse:.4f} | "
f"Test MSE: {test_mse:.4f}"
)
if best_model is None:
raise RuntimeError(
"No epoch produced a finite test MSE. "
"Check the data and training settings."
)
# Generate all reported predictions and metrics using the best model.
# Return the trained models and everything needed for separate evaluation.
return {
"best_model": best_model,
"final_model": final_model,
"scaler": scaler,
"features": feature_columns,
"X_test_gru": X_test_gru,
"actual_rop": y_test_gru,
"depths": test_depths_gru,
"batch_size": batch_size,
"seq_length": seq_length,
"num_epochs": num_epochs,
"best_epoch": best_epoch,
"best_test_mse": best_test_mse,
"best_lr": best_lr,
"tuning_results": tuning_results,
"model_name": model_name,
}
def evaluate_gru_experiment(training_result, *, model_type="best"):
"""
Evaluate the best or final model without retraining.
Return predictions and metrics in the format expected by plot_gru_results.
The training_result dictionary is not modified.
"""
if model_type not in ("best", "final"):
raise ValueError("model_type must be 'best' or 'final'.")
model = training_result[f"{model_type}_model"]
device = next(model.parameters()).device
test_dataset = DrillingSequenceDataset(
training_result["X_test_gru"],
training_result["actual_rop"],
)
test_loader = DataLoader(
test_dataset,
batch_size=training_result["batch_size"],
shuffle=False,
)
model.eval()
predictions = []
with torch.no_grad():
for bx, _ in test_loader:
predictions.append(model(bx.to(device)).cpu().numpy())
y_pred = np.vstack(predictions)
y_actual = training_result["actual_rop"]
mse = mean_squared_error(y_actual, y_pred)
rmse = np.sqrt(mse)
mae = mean_absolute_error(y_actual, y_pred)
epoch_number = (
training_result["best_epoch"]
if model_type == "best"
else training_result["num_epochs"]
)
print(
f"\n{model_type.upper()}-MODEL PERFORMANCE: "
f"{training_result['model_name']} (DEEP TEST BLOCK)"
)
print("Model Architecture : 2-Layer Unidirectional GRU")
print(f"Sequence Window : {training_result['seq_length']} Timesteps")
print(f"Optimal Learning Rate: {training_result['best_lr']}")
print(f"Epoch : {epoch_number}/{training_result['num_epochs']}")
print(f"Test MSE : {mse:.4f}")
print(f"RMSE : {rmse:.2f} ft/hr")
print(f"MAE : {mae:.2f} ft/hr")
return {
**training_result,
"model": model,
"model_type": model_type,
"evaluated_epoch": epoch_number,
# Distinguish the best and final models in plot titles.
"model_name": (
f"{training_result['model_name']} "
f"— {model_type.capitalize()} Model (Epoch {epoch_number})"
),
"predicted_rop": y_pred,
"mse": mse,
"rmse": rmse,
"mae": mae,
}
def plot_gru_results(result):
"""Display the existing parity and depth-track plots for a GRU result."""
IPython.display.display(plot_rop_fitness(
actual_rop=result["actual_rop"], predicted_rop=result["predicted_rop"],
mae=result["mae"], model_name=result["model_name"],
))
IPython.display.display(plot_rop_against_depth(
actual_rop=result["actual_rop"], predicted_rop=result["predicted_rop"],
depths=result["depths"], model_name=result["model_name"],
title=f"{result['model_name']}: ROP Prediction",
))# GRU with original sensors (Depth > 600 ft, 80-20 Split)
cell_started_at = perf_counter()
gru_original_data = pd.read_csv("drilling_phase1_cleaned.csv")
gru_original_target = "ROP(1 ft)" if "ROP(1 ft)" in gru_original_data.columns else "ROP"
gru_original_features = select_feature_columns(
gru_original_data, gru_original_target, exclude_depth=True
)
gru_result = train_gru_experiment(
gru_original_data,
gru_original_features,
model_name="GRU — Original Sensors (>600ft, 80-20 Split)",
train_ratio=0.80,
filter_surface=True,
num_epochs=80,
lr_candidates=(0.0005,),
)
print(f"Original-feature GRU cell duration: {perf_counter() - cell_started_at:.2f} seconds")Running PyTorch on Device: cpu | GRU — Original Sensors (>600ft, 80-20 Split)
Filtered out surface interval (0–600 ft): Removed 240 rows.
-> Training Tensor Shape (N, T, F): (5253, 7, 8)
-> Testing Tensor Shape (N, T, F): (1309, 7, 8)
-> Predictor Features:
['weight on bit (k-lbs)', 'Rotary Speed (rpm)', 'Pump Press (psi)', 'Flow In (gal/min)', 'Surface Torque (psi)', 'Hookload (k-lbs)', 'Temp In(degF)', 'Temp Out( degF)']
PHASE 7A: FINE-TUNING LEARNING RATE (MAX 1 ITERATIONS)
Iteration 1/1 | Candidate LR: 0.0005 -> Val MSE: 22.2293
Optimal Learning Rate Found: 0.0005 (MSE Loss: 22.2293)
PHASE 7B: TRAINING FINAL GRU MODEL (LR = 0.0005)
PHASE 7B: TRAINING GRU MODEL (LR = 0.0005)
Epoch 01/80 | Train MSE: 1896.8006 | Test MSE: 143.0575
Epoch 10/80 | Train MSE: 133.6948 | Test MSE: 33.2412
Epoch 20/80 | Train MSE: 125.0692 | Test MSE: 34.0654
Epoch 30/80 | Train MSE: 115.7428 | Test MSE: 32.1912
Epoch 40/80 | Train MSE: 106.9157 | Test MSE: 32.8553
Epoch 50/80 | Train MSE: 99.4001 | Test MSE: 37.7890
Epoch 60/80 | Train MSE: 95.7799 | Test MSE: 37.8972
Epoch 70/80 | Train MSE: 88.7289 | Test MSE: 37.4651
Epoch 80/80 | Train MSE: 83.4174 | Test MSE: 40.5987
Original-feature GRU cell duration: 146.94 seconds
gru_eval_result = evaluate_gru_experiment(gru_result, model_type="final")
# Total number of model parameters.
total_params = sum(p.numel() for p in gru_eval_result["model"].parameters())
print("\nTotal number of model parameters:", total_params)
FINAL-MODEL PERFORMANCE: GRU — Original Sensors (>600ft, 80-20 Split) (DEEP TEST BLOCK)
Model Architecture : 2-Layer Unidirectional GRU
Sequence Window : 7 Timesteps
Optimal Learning Rate: 0.0005
Epoch : 80/80
Test MSE : 40.5987
RMSE : 6.37 ft/hr
MAE : 5.13 ft/hr
Total number of model parameters: 41281
plot_gru_results(gru_eval_result)

# GRU with all eligible engineered predictors.
cell_started_at = perf_counter()
gru_engineered_features = select_feature_columns(
well58_engineered_data, well58_target_col, exclude_depth=False
)
gru_engineered_result = train_gru_experiment(
well58_engineered_data, gru_engineered_features,
model_name="GRU — Engineered Features", lr_candidates=(0.0005,),
num_epochs=80
)
print(f"Engineered-feature GRU cell duration: {perf_counter() - cell_started_at:.2f} seconds")Running PyTorch on Device: cpu | GRU — Engineered Features
Filtered out surface interval (0–600 ft): Removed 238 rows.
-> Training Tensor Shape (N, T, F): (5253, 7, 44)
-> Testing Tensor Shape (N, T, F): (1309, 7, 44)
-> Predictor Features:
['Depth(ft)', 'weight on bit (k-lbs)', 'Rotary Speed (rpm)', 'Pump Press (psi)', 'Flow In (gal/min)', 'Surface Torque (psi)', 'Hookload (k-lbs)', 'Temp In(degF)', 'Temp Out( degF)', 'weight on bit (k-lbs)_lag1', 'weight on bit (k-lbs)_lag2', 'weight on bit (k-lbs)_roll3_mean', 'weight on bit (k-lbs)_roll7_mean', 'Rotary Speed (rpm)_lag1', 'Rotary Speed (rpm)_lag2', 'Rotary Speed (rpm)_roll3_mean', 'Rotary Speed (rpm)_roll7_mean', 'Pump Press (psi)_lag1', 'Pump Press (psi)_lag2', 'Pump Press (psi)_roll3_mean', 'Pump Press (psi)_roll7_mean', 'Flow In (gal/min)_lag1', 'Flow In (gal/min)_lag2', 'Flow In (gal/min)_roll3_mean', 'Flow In (gal/min)_roll7_mean', 'Surface Torque (psi)_lag1', 'Surface Torque (psi)_lag2', 'Surface Torque (psi)_roll3_mean', 'Surface Torque (psi)_roll7_mean', 'Hookload (k-lbs)_lag1', 'Hookload (k-lbs)_lag2', 'Hookload (k-lbs)_roll3_mean', 'Hookload (k-lbs)_roll7_mean', 'Temp In(degF)_lag1', 'Temp In(degF)_lag2', 'Temp In(degF)_roll3_mean', 'Temp In(degF)_roll7_mean', 'Temp Out( degF)_lag1', 'Temp Out( degF)_lag2', 'Temp Out( degF)_roll3_mean', 'Temp Out( degF)_roll7_mean', 'WOB_RPM_INTERACTION', 'HYDRAULIC_POWER_PROXY', 'DELTA_TEMP']
PHASE 7A: FINE-TUNING LEARNING RATE (MAX 1 ITERATIONS)
Iteration 1/1 | Candidate LR: 0.0005 -> Val MSE: 28.7443
Optimal Learning Rate Found: 0.0005 (MSE Loss: 28.7443)
PHASE 7B: TRAINING FINAL GRU MODEL (LR = 0.0005)
PHASE 7B: TRAINING GRU MODEL (LR = 0.0005)
Epoch 01/80 | Train MSE: 1999.7297 | Test MSE: 137.9835
Epoch 10/80 | Train MSE: 122.0581 | Test MSE: 28.3493
Epoch 20/80 | Train MSE: 105.2684 | Test MSE: 26.7160
Epoch 30/80 | Train MSE: 95.6050 | Test MSE: 33.0924
Epoch 40/80 | Train MSE: 89.2234 | Test MSE: 31.9015
Epoch 50/80 | Train MSE: 84.0293 | Test MSE: 31.6916
Epoch 60/80 | Train MSE: 78.1946 | Test MSE: 35.0210
Epoch 70/80 | Train MSE: 72.2857 | Test MSE: 40.6254
Epoch 80/80 | Train MSE: 66.8775 | Test MSE: 37.8269
Engineered-feature GRU cell duration: 147.63 seconds
gru_eng_eval_result = evaluate_gru_experiment(gru_engineered_result, model_type="final")
# Total number of model parameters.
total_params = sum(p.numel() for p in gru_eng_eval_result["model"].parameters())
print("\nTotal number of model parameters:", total_params)
FINAL-MODEL PERFORMANCE: GRU — Engineered Features (DEEP TEST BLOCK)
Model Architecture : 2-Layer Unidirectional GRU
Sequence Window : 7 Timesteps
Optimal Learning Rate: 0.0005
Epoch : 80/80
Test MSE : 37.8269
RMSE : 6.15 ft/hr
MAE : 4.64 ft/hr
Total number of model parameters: 48193
plot_gru_results(gru_eng_eval_result)

Summary
- Tensor Dimensions & Sliding Window: Both experiments use 7-row overlapping windows and produce 5,253 training sequences and 1,309 evaluation sequences. Original-sensor tensors have shapes
(5253, 7, 8)and(1309, 7, 8); engineered-feature tensors have shapes(5253, 7, 44)and(1309, 7, 44). - Learning Rate Tuning: The selected rate is 0.0005 for both experiments, with one candidate evaluated per experiment. The 10-epoch candidate evaluation MSE is 22.2293 for original sensors and 28.7443 for engineered features.
- Training Trajectory: Original-sensor training MSE declines from 1896.8006 at epoch 1 to 83.4174 at epoch 80, with epoch-80 evaluation MSE 40.5987. Engineered-feature training MSE declines from 1999.7297 to 66.8775, but evaluation MSE fluctuates considerably and ends at 37.8269.
- Reported Evaluation Performance: The separately evaluated original-sensor final model (epoch 80) has 41,281 parameters, RMSE 6.37 ft/hr, and MAE 5.13 ft/hr. The separately evaluated engineered-feature final model (epoch 80) has 48,193 parameters, RMSE 6.15 ft/hr, and MAE 4.64 ft/hr.
Commentary on the Outcome
The original-sensor model shows declining training loss at the printed checkpoints, while evaluation loss drops initially and then fluctuates, ending above its epoch-10 value. The engineered-feature model has lower final training MSE and lower final evaluation MSE, RMSE, and MAE than the original-sensor model, so the current final-epoch scores improve with the engineered feature set. That set also includes Depth, whereas the original-sensor experiment excludes it.
These are same-row ROP estimates from windows ending at the current row, rather than forecasts of a future ROP value. Both final checkpoints are now separately evaluated; the current output does not establish robust convergence or adaptation to formation changes.
10. Other Works
Several studies have used the drilling data from “Well 58-32” at the DOE Geothermal Data Repository [1] to investigate machine learning applications. One is briefly discussed below and compared with this project.
Applying Machine Learning to Predict the Rate of Penetration for Geothermal Drilling Located in the Utah FORGE Site [2]
Ben Aoun and Madarász (2022) [2] predict ROP for “Well 58-32” (the downsampled version) using Random Forest and an MLP (with three hidden layers of 12 neurons each, and using ReLU activation). Their optimized Random Forest achieves R² = 0.84 and MAE = 2.46 m/hr (equivalent to 3.28 ft/hr), outperforming the neural network (R² = 0.73; MAE = 3.98 m/hr). The paper uses a 70-30 training-test split (randomly shuffled).
Both this project and the study estimate ROP from the drilling data, but this project explicitly represents neighboring observations through engineered histories. This project uses an 80-20 split and compares six regression models and two GRU configurations. The paper reports the MAE in m/hr, whereas we report in ft/hr. Differences in preprocessing and evaluation block (the last 20% vs 30%) prevent a direct model ranking.
11. References
[1] R. Podgorney, J. McLennan, and J. Moore, Utah FORGE: Drilling Data for Student Competition, Idaho National Laboratory, Geothermal Data Repository, 2018, doi: 10.15121/1495411. Dataset page.
[2] M. A. Ben Aoun and T. Madarász, “Applying Machine Learning to Predict the Rate of Penetration for Geothermal Drilling Located in the Utah FORGE Site,” Energies, vol. 15, no. 12, Art. no. 4288, 2022, doi: 10.3390/en15124288. Accompanying source code: GitHub repository.