Preprint
Article

This version is not peer-reviewed.

Mid-Season Wheat Yield Estimation and Decision Support: Bridging Regularized Machine Learning and Full-Stack Geospatial Web Architecture

Submitted:

05 October 2026

Posted:

09 October 2026

You are already at the latest version

Abstract
Background: Wheat (Triticum aestivum) is a cornerstone of national food security in Pakistan, par-ticularly in Punjab province. However, climate variability, rising temperatures, and unpredictable precipitation patterns increasingly threaten yields. Traditional crop-yield forecasting relies heavily on manual, post-harvest reporting that leaves government authorities and farming communities without operational visibility during the growing season. Objective: This study evaluates whether regularized regression can accurately forecast season-level wheat yields using multispectral satellite and climate data restricted to the first 50% of the growing season (mid-February cutoff), thereby providing a critical eight-week lead time before harvest. Furthermore, it presents the engineering and deployment of an operational full-stack web application that translates this predictive model into a real-time decision-support system. Methods: We analyzed a six-season dataset (2019–2020 to 2024–2025) across experimental fields at the University of Agriculture Faisalabad (UAF) PARS Campus. High-resolution Sentinel-2 Normalized Difference Vegetation Index (NDVI) observations, CHIRPS daily precipitation estimates, and ERA5-Land temperature reanalysis records were integrated to derive 25 agroclimatic and phenological features. Six regression algorithms—ElasticNet, Ridge, Partial Least Squares (PLS), Principal Component Regression (PCR), Support Vector Regression with a Radial Basis Function (SVR-RBF), and Gaussian Process Regression (GPR)—were evaluated under a strict Leave-One-Season-Out Cross-Validation (LOOCV) framework. Feature selection was conducted strictly in-fold to prevent data leakage. Results: The optimized ElasticNet model achieved the highest predictive stability and accuracy at the 50% season-elapsed window, yielding an out-of-fold R2 of 0.868, a Root Mean Squared Error (RMSE) of 64.72 kg, a Mean Absolute Error (MAE) of 59.14 kg, and a Mean Absolute Percentage Error (MAPE) of 3.36%. Comparative analyses showed that ElasticNet significantly outperformed high-complexity, non-regularized models, which suffered severe overfitting due to the high-dimensional, small-sample (n = 6) nature of season-level crop datasets. Growing De-gree Days (GDD) and GDD–NDVI interaction terms were identified as the primary predictors of final productivity. Conclusions: To operationalize these findings, a production-grade web application was developed utilizing a FastAPI (ASGI) backend and a React.js frontend. By integrating the Google Earth Engine (GEE) REST API, the platform enables real-time, cloud-based data extraction and prediction for custom user-drawn field polygons, with predictions stored in a MongoDB NoSQL database with GeoJSON spatial indexing. The application is actively deployed and utilized by agricultural extension officers, researchers, and regional policymakers.
Keywords: 
;  ;  ;  ;  ;  ;  ;  

1. Introduction

1.1. Food Security and the Pakistani Wheat Economy

Wheat is the world’s most widely cultivated cereal crop and plays an indispensable role in maintaining global food security [1]. In Pakistan, agriculture is a vital driver of the national economy, contributing approximately 21% to the Gross Domestic Product (GDP) and supporting the livelihoods of a large proportion of the rural population [2,10]. Within the agrarian sector, wheat stands as the primary staple crop, occupying a central position in the nutritional and economic fabric of the country. Punjab province, known historically as the breadbasket of the Indus Basin, accounts for the vast majority of the national wheat acreage and total production [2,10].
However, the agricultural landscape of Punjab is increasingly vulnerable to environmental and climate-induced stressors. Spatiotemporal fluctuations in temperature, heat waves during the grain-filling phase, water scarcity, and highly erratic monsoon and winter precipitation patterns pose severe threats to crop yields [21]. Rising temperatures, in particular, have been shown to accelerate crop development, shorten the grain-filling period, and lead to premature senescence, ultimately depressing final grain yields [21]. The devastating floods in 2010, 2011, and 2012, combined with subsequent droughts, highlight the urgent need for robust, technology-driven tools to monitor, predict, and mitigate climate-related agricultural shortfalls [21].

1.2. Limitations of Traditional Forecasting and the Remote Sensing Alternative

To formulate effective food policies, manage trade balances, and stabilize domestic grain markets, governmental agencies require precise, timely, and spatially explicit crop yield forecasts before harvest. Traditional wheat yield assessment methods in Pakistan, however, rely heavily on manual field surveys, crop-cutting experiments, and post-harvest government reporting. While these methods provide ground-truth verification, they are labor-intensive, expensive, logistically challenging to scale, and inherently delayed—often yielding official estimates only after the harvest has concluded in May. This “information vacuum” prevents the state from anticipating deficits, leaving policymakers unable to negotiate favorable import prices or secure emergency food reserves until domestic price volatility and supply chain shocks have already occurred.
Satellite remote sensing and climate reanalysis datasets offer a scalable, non-destructive, and highly cost-effective alternative [2,9,18]. The launch of high-resolution satellite constellations, such as the European Space Agency’s Sentinel-2, has revolutionized crop monitoring by providing multispectral imagery at 10-meter spatial resolution with a frequent 5-day revisit cycle. From these spectral observations, vegetation indices like the Normalized Difference Vegetation Index (NDVI) can be continuously calculated to monitor canopy greenness, leaf area dynamics, and seasonal vegetation vigor [2]. When paired with daily gridded meteorological products—such as CHIRPS precipitation estimates and ERA5-Land temperature reanalysis records—remote sensing enables comprehensive, real-time monitoring of crop growth and environmental stress across diverse spatial scales [2,18].

1.3. Machine Learning and the Need for Mid-Season Actionability

In recent years, the integration of big Earth Observation (EO) data with machine learning (ML) has emerged as a dominant paradigm in digital agriculture [4,7,20]. A variety of machine learning and deep learning architectures have been developed to model the complex, non-linear relationships between environmental covariates and crop productivity. For instance, studies have successfully utilized Support Vector Regression (SVR) to map wheat yields across the Australian wheat belt [15], Random Forest (RF) ensembles to predict European cultivar yields [16], and deep hybrid networks such as CNN-GRUs [20] or SSA-LSTM-transformers [11] to model winter wheat yields in China.
Despite these methodological advances, two persistent gaps remain in the current literature. First, most crop yield modeling efforts focus primarily on late-season or post-harvest yield estimation, using predictors aggregated across the entire crop growth cycle to maximize statistical accuracy. While scientifically informative, such models offer minimal operational utility; by the time the full-season data is collected, the harvest is already complete, rendering the forecast useless for proactive market interventions or regional resource reallocation. To be truly actionable, a forecasting framework must be truncated mid-season, utilizing only the environmental variables available during the first half of the growing season to provide a significant early-warning window (e.g., eight weeks prior to harvest) when management adjustments and trade policy negotiations are still viable.

1.4. Overcoming the Small-Sample Overfitting Bottleneck

The second critical challenge lies in the mathematical suitability of machine learning models for small-sample, high-dimensional agricultural datasets. While deep neural networks (e.g., LSTMs, Transformers, and custom CNNs) excel at extracting features from massive spatial arrays, they are highly prone to severe overfitting when trained on small, season-level historical datasets [2,3]. In many developing regions, verified historical ground-truth crop yield records are only available for a small number of growing seasons (e.g., n < 10 ). Under these conditions, the number of engineered temporal and climate features (frequently exceeding 100) vastly exceeds the number of observations ( p ≫ n ).
In such data-scarce and high-dimensional regimes, flexible nonlinear “black-box” models often fail to generalize, whereas regularized linear models can maintain exceptional predictive stability [2,3]. ElasticNet regression—which combines the L 1 penalty of Lasso for sparse feature selection and the L 2 penalty of Ridge for group collinearity management [13]—presents a highly suitable mathematical framework. However, the potential of ElasticNet to operate as a robust, mid-season forecasting model under strict, leakage-free cross-validation in the semi-arid, irrigated conditions of Punjab, Pakistan, remains largely unexplored.

1.5. Gaps in Operational Deployment and Software Engineering

Finally, there is a profound translational gap between academic machine learning research and practical agricultural deployment. The vast majority of published yield forecasting literature remains restricted to static, offline computational environments (e.g., local Jupyter notebooks or scripts). These research codebases are inaccessible to non-technical end-users, such as smallholder farmers, local agricultural extension officers, and public sector grain procurement authorities.
To bridge this gap, an empirical forecasting model must be embedded within an operational, production-grade software architecture. Such a system must address complex software engineering challenges, including:
1.
Automated, real-time ingestion of high-resolution satellite and climate reanalysis data across custom spatial boundaries.
2.
The elimination of expensive local compute clusters by offloading heavy, planetary-scale image processing to cloud-based serverless APIs (such as Google Earth Engine) [9].
3.
The orchestration of asynchronous, non-blocking API tasks to handle long-running satellite queries without triggering frontend gateway timeouts.
4.
The implementation of secure data persistence and user-management schemas that map user activity to spatial historical records.

1.6. Research Objectives and Key Contributions

To address these scientific and translational gaps, this study presents the development, validation, and full-stack operational deployment of an end-to-end, mid-season wheat-yield forecasting platform centered on a six-season pilot study in Faisalabad, Punjab, Pakistan.
Specifically, this research makes the following core contributions:
1.
A Leakage-Free Mid-Season Predictive Framework: We demonstrate that regularized ElasticNet regression, operating on environmental covariates restricted to the first 50% of the growing season (mid-February cutoff), can forecast final wheat yield with high accuracy ( R 2 = 0.868 , RMSE = 64.72 kg ) and a 60-day early-warning lead time.
2.
High-Dimensional, Small-Sample Validation: We present a rigorous, comparative machine learning evaluation under Leave-One-Season-Out Cross-Validation (LOOCV) and in-fold feature selection, proving that regularized linear models outperform PCR, PLS, Ridge, SVR, and GPR under extreme data-scarcity constraints.
3.
Agronomic Driver Identification: We analyze model coefficients and correlation structures to establish that early-season thermal accumulation (Growing Degree Days) and cumulative precipitation are the primary environmental drivers of final wheat yields in Faisalabad.
4.
Full-Stack Operationalization: We document the system engineering and deployment of a live, full-stack React.js, FastAPI, MongoDB, and Google Earth Engine web application (accessible at https://wheatyieldapp.vercel.app/), which actively serves as an interactive spatial decision-support system for local farmers and regional policymakers.

2. Materials and Methods

To establish a scalable and robust early-warning wheat yield forecasting framework, this study integrates multi-source earth observation data with in-situ crop yield records. This section describes the geographical area under investigation, the multi-source data ingestion pipeline, feature engineering and selection methods, the predictive machine learning architectures, and the validation protocols designed to prevent data leakage.

2.1. Study Area and Experimental Design

The study was conducted at the experimental farm of the University of Agriculture, Faisalabad (UAF), Post Graduate Agricultural Research Station (PARS) Campus, situated in the Faisalabad District, Punjab Province, Pakistan. Faisalabad is characterized by a semi-arid climate with hot summers and mild winters, making wheat (Triticum aestivum) the dominant staple crop grown during the winter (Rabi) season. The cropping cycle spans approximately seven months, with sowing typically taking place between October and November, and harvesting occurring in late April or early May.
Figure 1. Geographical study area map showing regional context in Punjab, Pakistan (a) and detailed field boundaries of UAF PARS Campus in Faisalabad (b).
Figure 1. Geographical study area map showing regional context in Punjab, Pakistan (a) and detailed field boundaries of UAF PARS Campus in Faisalabad (b).
Preprints 236716 g001
Figure 2. Sentinel-2 derived NDVI pixel coverage map of the UAF PARS Campus pilot fields, illustrating the spatial extent of the ∼222 active Sentinel-2 pixels used for spatial aggregation across the four operational field units.
Figure 2. Sentinel-2 derived NDVI pixel coverage map of the UAF PARS Campus pilot fields, illustrating the spatial extent of the ∼222 active Sentinel-2 pixels used for spatial aggregation across the four operational field units.
Preprints 236716 g002
The primary pilot field covers approximately 2.23 hectares (equivalent to ∼222 Sentinel-2 pixels at a 10 m spatial resolution). To validate the system’s predictive accuracy and support multi-field mapping, the study area was divided into four distinct operational units:
1.
North Field (1.30 ha, 3.20 acres): Centered at coordinates 31 . 3905 ∘ N , 73 . 0143 ∘ E with 8 boundary nodes defined for polygon extraction.
2.
South Field (0.90 ha): Utilized for independent spatial yield mapping.
3.
Combined Fields (2.23 ha): Representing the entire contiguous experimental block.
4.
CHIRPS Pixel Region (131.40 ha): Representing the surrounding meteorological grid footprint used to align spatial climate estimates.
The compiled dataset spans six consecutive agricultural seasons (from 2019–2020 through 2024–2025), capturing substantial inter-annual weather variability. High-resolution ground-truth crop yields were recorded at the field scale upon harvest for each of the six seasons, providing the target variable (y) for regression modeling. In total, the integrated database contains more than 10,000 spatial records and 32,370 individual crop-growth observations.
Figure 3. End-to-end operational data acquisition, preprocessing, 50% early-season truncation, feature engineering, and cross-validation workflow.
Figure 3. End-to-end operational data acquisition, preprocessing, 50% early-season truncation, feature engineering, and cross-validation workflow.
Preprints 236716 g003

2.2. Automated Multi-Source Data Ingestion and Preprocessing

An automated pipeline was developed in Python to query and retrieve three distinct satellite-derived data streams via the Google Earth Engine (GEE) REST API, using secure service account credentials [9]:
1.
Sentinel-2 Multispectral Surface Reflectance (Level-2A): Acquired at a spatial resolution of 10 meters with a nominal 5-day revisit frequency [9]. The Normalized Difference Vegetation Index (NDVI) was calculated using the Red (Band 4) and Near-Infrared (Band 8) surface reflectance values:
NDVI = B 8 − B 4 B 8 + B 4
2.
CHIRPS Precipitation Estimates: Daily rainfall records gridded at a 0 . 05 ∘ (∼5 km) spatial resolution.
3.
ERA5-Land Climate Reanalysis Data: Daily 2-meter air temperature estimates gridded at a 0 . 1 ∘ (∼9 km) spatial resolution.

2.2.1. Spatial and Temporal Quality Filtering

To minimize noise from edge effects, atmospheric interference, and off-season agricultural practices, a four-tier preprocessing filter was enforced:
  • Cloud and Shadow Masking: Sentinel-2 granules were filtered using the Quality Assessment (QA60) band to identify and mask opaque and cirrus clouds. Any tile exceeding a 30% total cloud cover threshold was excluded from the collection.
  • Inward Spatial Buffer: A negative spatial buffer of −10 meters was applied to the study area boundary polygons prior to GEE extraction. This buffer eliminated “mixed pixels” along field boundaries, ensuring that canopy reflectance estimates were strictly representative of the internal wheat crop and free from adjacent road or bare soil contamination.
  • Off-Season Filtering: To isolate the active crop vegetative and reproductive cycles, all daily observations falling between June 1st and September 30th were discarded. The active temporal window was strictly defined from October 1st to May 31st of the following year.
  • Non-Vegetated Soil Filtering: Low-vegetation and bare soil signals were eliminated by applying an NDVI threshold filter of > 0.17 . NDVI observations below this threshold were treated as bare soil or land preparation noise and omitted.
Following quality filtering, missing values caused by persistent cloud cover were reconstructed using linear temporal interpolation. The resulting smoothed time series were then synchronized and merged by calendar date, latitude, longitude, and pixel ID into a unified spatial-temporal dataframe.
Figure 4. Seasonal NDVI time-series profile for the UAF PARS Campus pilot field across the six growing seasons (2019–2020 to 2024–2025), illustrating inter-annual variability in canopy greenness dynamics following cloud masking, off-season filtering, and linear gap-filling.
Figure 4. Seasonal NDVI time-series profile for the UAF PARS Campus pilot field across the six growing seasons (2019–2020 to 2024–2025), illustrating inter-annual variability in canopy greenness dynamics following cloud masking, off-season filtering, and linear gap-filling.
Preprints 236716 g004

2.3. Early-Season Truncation (Lead Time Modeling)

A key limitation of existing crop yield models is their dependence on full-season datasets, which restricts their utility to post-harvest evaluations. To establish a true “early-warning” capability, this study implements an early-season truncation protocol.
The growing season was dynamically sliced based on the percentage of elapsed season length. To evaluate mid-season forecasting viability, all observations recorded after 50% of the growing season had elapsed (approximately mid-February, which occurs during the jointing/booting stage) were truncated and discarded. This restriction ensures that all engineered features represent environmental and canopy conditions available at least eight weeks prior to the harvest, providing policymakers and farmers with a critical window for crop management, resource allocation, and macroeconomic supply-chain planning.

2.4. Agroclimatic Feature Engineering and Spatial Aggregation

Using the truncated daily pixel-level datasets, we engineered 25 candidate agroclimatic variables for each individual Sentinel-2 pixel within the field:

2.4.1. Phenological Canopy Metrics

  • Peak NDVI: The maximum greenness value reached during the truncated season window.
  • Peak Position: The temporal day of the year (DOY) at which the maximum NDVI is recorded.
  • Greenup Rate: The positive slope of the NDVI curve during the early vegetative phase (representing canopy establishment speed).
  • Senescence Slope: The rate of greenness decline during the crop senescence phase.
Figure 5. Pearson correlation heatmap between the top 15 engineered agroclimatic features and observed wheat yield at 50% season progress.
Figure 5. Pearson correlation heatmap between the top 15 engineered agroclimatic features and observed wheat yield at 50% season progress.
Preprints 236716 g005
Figure 6. Ranked bar chart of Pearson correlation coefficients ( | r | > 0.50 ) between the 18 selected agroclimatic features and observed season-level wheat yield, illustrating the dominant predictive role of GDD–NDVI interaction terms and thermal accumulation metrics across the in-fold feature selection step.
Figure 6. Ranked bar chart of Pearson correlation coefficients ( | r | > 0.50 ) between the 18 selected agroclimatic features and observed season-level wheat yield, illustrating the dominant predictive role of GDD–NDVI interaction terms and thermal accumulation metrics across the in-fold feature selection step.
Preprints 236716 g006
Figure 7. Scatter plots of the top agroclimatic feature predictors against observed season-level wheat yield, demonstrating the linear relationships exploited by the ElasticNet regularization framework. Points represent individual growing seasons (2019–2020 to 2024–2025).
Figure 7. Scatter plots of the top agroclimatic feature predictors against observed season-level wheat yield, demonstrating the linear relationships exploited by the ElasticNet regularization framework. Points represent individual growing seasons (2019–2020 to 2024–2025).
Preprints 236716 g007

2.4.2. Thermal Time and Climatic Stress Metrics

  • Growing Degree Days (GDD): Accumulated thermal time computed using daily mean temperatures ( T mean ) relative to a base developmental threshold ( T base = 5 ∘ C ):
    GDD = ∑ max T mean − T base , 0
    GDD provides a biologically consistent timeline of crop phenological progress that outperforms standard calendar days under varying climate conditions.
  • Chilling Hours: Total cumulative hours where temperatures fell below 7 . 2 ∘ C , necessary for satisfying the vernalization requirements of winter wheat.
  • Cumulative Precipitation: Integrated sum of daily CHIRPS rainfall records over the truncated window.
  • Drought Fraction: The proportion of the season characterized by extreme rainfall deficits or high atmospheric saturation deficits.
  • Temperature Percentiles: The 25th and 75th percentiles of daily maximum and minimum temperatures.

2.4.3. Fused Interaction Terms

To capture the joint effects of thermal energy and canopy transpiration, multi-source interaction variables were created:
  • GDD–NDVI Interaction (gdd_ndvi_smean): The mathematical product of cumulative thermal time and mean greenness, representing the thermal efficiency of canopy development.
  • Temperature–NDVI Covariance (temp_ndvi_smean): The daily covariance between T mean and NDVI, capturing canopy heat stress levels.

2.4.4. Spatial Aggregation

To scale these localized canopy measurements to field-level predictors, the pixel-level variables were spatially aggregated across the pilot field’s ∼222 pixels. For each of the 25 variables, we calculated five spatial statistics: the mean, standard deviation, 25th percentile, 50th percentile (median), and 75th percentile. This spatial reduction flattened the high-resolution pixel matrices into a single season-level observation vector containing 125 candidate predictors per growing season.

2.5. Leakage-Free Feature Selection and Cross-Validation

The primary methodological challenge in modeling with a limited number of growing seasons ( n = 6 ) is the extreme risk of overfitting and data leakage, which leads to overly optimistic performance estimates. To address this risk, we enforced a strict, leakage-free cross-validation and feature-reduction workflow.

2.5.1. Leave-One-Season-Out Cross-Validation (LOOCV)

Model evaluation was executed using a strict Leave-One-Season-Out (LOSO) cross-validation loop. In each of the six outer validation folds, one entire growing season was completely removed from the dataset to act as the independent test set. The remaining five seasons were utilized for feature selection, hyperparameter tuning, and model training. This setup guarantees that no information from the evaluated season can influence model development.

2.5.2. In-Fold Feature Selection

Within each training fold, a correlation-guided feature selection step was performed:
1.
Pearson correlation coefficients (r) were calculated between each of the 125 candidate features and the historical yields of the five training seasons.
2.
A strict threshold of | Pearson r | > 0.50 was applied. Only features exceeding this threshold were retained.
3.
Because feature correlation was calculated only on the five active training seasons, the feature subset varied slightly across folds, successfully preventing target leakage.
4.
This threshold reduced the predictor space from 125 candidate features to 18 highly predictive, non-redundant variables. Among the top-ranked variables retained across all folds were the interaction terms gdd_ndvi_smean and temp_ndvi_smean.

2.6. Machine Learning Regression Framework

The selected 18-feature datasets were evaluated across six distinct machine learning regression architectures, chosen for their varying capacities to handle high-dimensional, small-sample data:
1.
ElasticNet Regression (Primary Model): A regularized linear model that combines L1 (Lasso) and L2 (Ridge) a priori constraints to manage multicollinearity while performing automated feature selection [13].
2.
Ridge Regression: Utilizes an L2 penalty to shrink coefficients of highly correlated variables, stabilizing parameter estimates under multicollinearity.
3.
Partial Least Squares (PLS): Decomposes the predictor matrix into latent components that maximize the covariance with the response variable, handling high-dimensional feature spaces effectively.
4.
Principal Component Regression (PCR): Projects the predictor matrix onto its principal components before regression, reducing dimensionality without supervision.
5.
Support Vector Regression with RBF Kernel (SVR-RBF): A kernel-based method that maps inputs into a high-dimensional feature space, capable of capturing non-linear relationships [15].
6.
Gaussian Process Regression (GPR): A non-parametric Bayesian approach that models the predictive distribution with uncertainty quantification, previously applied in crop monitoring [4].
Figure 8. Out-of-fold Leave-One-Season-Out Cross-Validation (LOOCV) model performance benchmarks across RMSE, MAE, R 2 , and MAPE metrics for all six evaluated regression architectures at the 50% season-elapsed window.
Figure 8. Out-of-fold Leave-One-Season-Out Cross-Validation (LOOCV) model performance benchmarks across RMSE, MAE, R 2 , and MAPE metrics for all six evaluated regression architectures at the 50% season-elapsed window.
Preprints 236716 g008
Figure 9. Cross-model performance heatmap summarizing the five evaluation metrics ( R 2 , RMSE, MAE, MAPE, and Pearson r) across all six regression architectures under LOOCV, enabling direct visual comparison of regularized versus non-regularized approaches.
Figure 9. Cross-model performance heatmap summarizing the five evaluation metrics ( R 2 , RMSE, MAE, MAPE, and Pearson r) across all six regression architectures under LOOCV, enabling direct visual comparison of regularized versus non-regularized approaches.
Preprints 236716 g009
Figure 10. Partial Least Squares (PLS) component analysis showing the variance explained by the first latent component and the PLS loading vectors for the top agroclimatic predictors, illustrating the latent covariance structure between environmental features and wheat yield.
Figure 10. Partial Least Squares (PLS) component analysis showing the variance explained by the first latent component and the PLS loading vectors for the top agroclimatic predictors, illustrating the latent covariance structure between environmental features and wheat yield.
Preprints 236716 g010
Figure 11. Gaussian Process Regression (GPR) uncertainty bands across the six-season LOOCV evaluation, illustrating the severe overconfidence and prediction collapse that occurs when a high-flexibility non-parametric model is trained on a small-sample ( n = 5 ) dataset.
Figure 11. Gaussian Process Regression (GPR) uncertainty bands across the six-season LOOCV evaluation, illustrating the severe overconfidence and prediction collapse that occurs when a high-flexibility non-parametric model is trained on a small-sample ( n = 5 ) dataset.
Preprints 236716 g011

2.6.1. ElasticNet Mathematical Formulation and Grid Search

The ElasticNet model was selected as the optimal architecture due to its unique ability to balance sparsity and stability [13]. It minimizes the following loss function:
L ElasticNet ( β ) = 1 2 n ∑ i = 1 n y i − x i β 2 + α λ ∑ j = 1 p | β j | + 1 − λ 2 ∑ j = 1 p β j 2
where:
  • α represents the overall regularization magnitude.
  • λ ∈ [ 0 , 1 ] is the l1_ratio, controlling the balance between L1 (Lasso) and L2 (Ridge) penalties. When λ = 1 , the model simplifies to pure Lasso; when λ = 0 , it simplifies to pure Ridge.
  • The L1 term ( ∑ | β j | ) drives uninformative coefficients to exactly zero, performing implicit feature selection.
  • The L2 term ( ∑ β j 2 ) ensures coefficient stability when group collinearity exists among multiple correlated temperature and vegetation indices.
To find the optimal regularization balance, an in-fold hyperparameter grid search was conducted using the training seasons:
  • Alpha search space: α ∈ { 0.1 , 1.0 , 5.0 , 10.0 , 50.0 }
  • L1-Ratio search space: λ ∈ { 0.1 , 0.5 , 0.9 }
Under cross-validation, the grid search selected α = 10.0 and λ = 0.5 as the optimal hyperparameter combination, establishing a balanced model that leverages both sparsity and coefficient smoothing.

2.7. Evaluation Metrics

Figure 12. Parity scatter plots comparing observed wheat yield against out-of-fold ElasticNet predictions across six growing seasons. (a) Direct LOOCV predictions. (b) Bootstrap-validated predictions with 90% confidence interval bounds, confirming prediction stability.
Figure 12. Parity scatter plots comparing observed wheat yield against out-of-fold ElasticNet predictions across six growing seasons. (a) Direct LOOCV predictions. (b) Bootstrap-validated predictions with 90% confidence interval bounds, confirming prediction stability.
Preprints 236716 g012
To rigorously assess performance across the held-out test seasons, the out-of-fold predictions from the LOOCV loop were evaluated using five standard statistical metrics:
1.
Coefficient of Determination ( R 2 ):
R 2 = 1 − ∑ i = 1 n ( y i − y ^ i ) 2 ∑ i = 1 n ( y i − y ¯ ) 2
2.
Root Mean Squared Error (RMSE):
RMSE = 1 n ∑ i = 1 n ( y i − y ^ i ) 2
3.
Mean Absolute Error (MAE):
MAE = 1 n ∑ i = 1 n | y i − y ^ i |
4.
Mean Absolute Percentage Error (MAPE):
MAPE = 100 % n ∑ i = 1 n y i − y ^ i y i
5.
Pearson Correlation Coefficient (r): Measures the linear association and temporal trend alignment between the predicted and actual yield series across the six historical seasons.
These five metrics collectively assess absolute error, relative error, variance explanation, and overall directional consistency, ensuring a comprehensive validation of the early-warning forecasting engine.

3. Web Application Architecture and System Engineering

To bridge the gap between empirical predictive modeling and real-world agricultural decision support, the validated machine learning pipeline was operationalized into a production-grade, secure, and highly interactive full-stack web application. Prior agricultural literature frequently stops at offline model training on static regional datasets, leaving farmers and policymakers without a mechanism to query arbitrary boundaries or receive real-time, in-season forecasts. This section details the operational architecture, asynchronous processing workflows, cloud-serverless integration, frontend interface design, and database schemas that enable real-time, pixel-level wheat yield forecasting in the Faisalabad region of Pakistan.
Figure 13. Full-stack web application system architecture detailing the presentation layer (React.js SPA), FastAPI ASGI backend, asynchronous background job orchestration, and cloud/database infrastructure (Google Earth Engine, MongoDB).
Figure 13. Full-stack web application system architecture detailing the presentation layer (React.js SPA), FastAPI ASGI backend, asynchronous background job orchestration, and cloud/database infrastructure (Google Earth Engine, MongoDB).
Preprints 236716 g013

3.1. Platform Design Principles and Operational Workflow

The system is designed around a cloud-serverless hybrid architecture. This approach minimizes capital expenditure and server maintenance costs by offloading massive, planetary-scale geospatial calculations to Google Earth Engine’s (GEE) distributed cloud infrastructure [9]. The end-to-end operational workflow of the platform proceeds through five sequential phases:
1.
Polygon Definition and User Query: An authenticated user logs into the dashboard and utilizes an interactive drawing tool to outline a custom field boundary or selects a predefined research plot.
2.
Asynchronous Request Dispatch: The frontend dispatches an HTTP POST query with JSON-encoded GeoJSON coordinates and target season parameters to the backend REST API. The backend spawns an asynchronous process to manage the satellite data extraction and returns a unique job_id to the client in under 200 milliseconds to avoid frontend timeout errors.
3.
Cloud-Serverless Spatial Ingestion and Filtering: The backend authenticates with GEE using secure service account credentials. GEE accesses Level-2A Sentinel-2 multispectral imagery, CHIRPS precipitation, and ERA5-Land temperature grids on the cloud. The serverless pipeline applies a 30% cloud mask, clips the images to the queried polygon, applies an inward spatial buffer of − 10 m to eliminate edge artifacts, and aggregates pixel values over the growing season.
4.
Temporal Preprocessing and Inference Execution: The retrieved raw time series is processed by the predictive engine. Missing dates are resolved via linear interpolation, and 25 phenological and climate features are engineered across five spatial statistics (mean, standard deviation, and the 25th, 50th, and 75th percentiles) to build a 125-dimensional feature vector. If a past season is queried, the engine truncates observations to the 50% season-elapsed window (mid-season) to test predictive capability. For an active current season, all available data up to the current date is utilized. The aligned feature vector is standardized and fed into the pre-trained, cross-validated ElasticNet model to yield the predicted harvest value in kilograms.
5.
State Persistence and Client Rendering: The job state transitions to done, and the prediction is cached. The prediction metadata and GeoJSON spatial coordinates are stored as an embedded activity document within the user’s secure database schema. The React frontend, which has been polling the status endpoint, receives the finalized predictions, renders the spatial boundaries on a map, and displays NDVI time-series trends alongside bootstrap uncertainty quantification.

3.2. Asynchronous Backend Architecture (FastAPI)

The backend is built using FastAPI (Python), a high-performance, modern framework designed for low-latency asynchronous operations. FastAPI leverages ASGI (Asynchronous Server Gateway Interface) via Uvicorn to support non-blocking concurrent requests. This is essential for handling multiple simultaneous GEE cloud-processing queries from government officials and agricultural researchers.

3.2.1. Asynchronous Background Job System

A primary software engineering challenge in remote sensing web platforms is the varying latency of external API connections. Programmatically querying Sentinel-2, CHIRPS, and ERA5-Land collections over large spatial areas via Google Earth Engine can take anywhere from 30 to 120 seconds to complete. Under a standard synchronous HTTP model, such long-running operations would block the server’s thread pool, causing client-side gateway timeouts and degrading user experience.
To mitigate this, the backend utilizes FastAPI’s native BackgroundTasks system. The endpoint handlers act as non-blocking dispatchers, as shown in Listing 1:
Listing 1. FastAPI asynchronous polygon prediction endpoint with background task dispatch.
Listing 1. FastAPI asynchronous polygon prediction endpoint with background task dispatch.
Preprints 236716 i001
Upon receiving a POST request, FastAPI instantiates a unique job ID, registers a queued state in the global thread-safe dictionary _jobs, schedules run_polygon_predict_in_background to run asynchronously, and immediately returns a 200 OK or 202 Accepted response to the client. The frontend then polls the status endpoint (GET /api/polygon/predict/status/{job_id}) every 2 to 3 seconds, updating the user interface with detailed progress strings until the state transitions to done.

3.2.2. Backend Endpoint Classification

The FastAPI backend exposes a comprehensive REST API grouped into four functional namespaces:
1.
Core Endpoints (/api/fields/): Handles the retrieval of geospatial and historical datasets, including field boundary metadata, time-series queries, yearly statistics, and CSV export.
2.
Machine Learning Endpoints (/api/ml/): Interacts with the core prediction engine, including LOOCV pipeline execution, comparative metrics retrieval, bootstrap confidence interval computation, ElasticNet coefficient export, and Random Forest feature importance rankings.
3.
Geospatial Processing Endpoints (/api/gee/and/api/polygon/): Powers real-time, interactive geospatial queries, accepting user-drawn polygon coordinates to trigger the end-to-end data fetching and ElasticNet prediction pipeline.
4.
Data Export Endpoints (/api/export/): Facilitates scholarly output and GIS data interoperability, including Google Drive export and publication-quality research image serving.

3.3. Interactive Geospatial Frontend (React.js)

The user interface is engineered as a responsive Single-Page Application (SPA) using React.js. Styling is implemented via Tailwind CSS, a utility-first framework that ensures consistent layout behavior across tablet and desktop resolutions (minimum width ≥ 1024 px ). The frontend UI is organized into a cohesive five-tab structure:
1.
Overview Tab (Default Landing): Displays the primary model’s operational performance (ElasticNet, R 2 = 0.868 , RMSE = 65 kg ) alongside seasonal statistics cards for NDVI, precipitation, and temperature.
2.
Field Map Tab (GIS Exploration): Provides a geospatial view centered on the Faisalabad research area with toggleable predefined field boundaries and a pixel-querying module to fetch and plot per-pixel NDVI time series.
3.
Predict Yield Tab (Custom Query): Contains the custom boundary forecasting tool with an interactive Leaflet polygon drawing tool. Displays real-time progress bars and loading spinners during active data fetches, concluding with a detailed prediction report.
4.
ML Analysis Tab (Model Diagnostics): Features a “Run ML Pipeline” button that starts the backend LOOCV grid search and dynamically renders the comparison metrics table, bootstrap uncertainty limits, and interactive bar charts.
5.
Research Tab (Scholarly Exports): Serves as a scientific gallery listing eight publication-ready analytical plots with download buttons and a CSV data export utility.

3.3.1. Geospatial Engine (Leaflet and React-Leaflet)

Interactive mapping is implemented using Leaflet and React-Leaflet, integrating OpenStreetMap raster tiles with vector overlays. Custom boundaries are defined using the leaflet-geoman library, allowing users to draw freeform polygons.
To ensure high-contrast visual accessibility, geospatial layers (such as NDVI pixel grids) are rendered using the standard RdYlGn (Red-Yellow-Green) color ramp. NDVI values approaching 1.0 (dense canopy during the heading stage) map to green, while lower NDVI values ( < 0.2 ) map to red, highlighting areas of poor crop development. All vector components are drawn with a spatial reference system set to standard WGS-84 coordinate arrays to align with GEE.

3.4. Cloud-Serverless Hybrid Data Integration (Google Earth Engine API)

To enable real-time calculations on custom boundaries without requiring high-performance local servers, the platform offloads heavy geospatial queries to Google Earth Engine (GEE) [9]. The backend connects to GEE via its Python API using secure service account credentials stored as environment variables (EE_SERVICE_ACCOUNT and EE_KEY_FILE) to prevent hardcoding sensitive credentials.
When a background prediction task is triggered, GEE processes the query through five main steps:
1.
Geometry Initialization: The raw coordinate arrays are parsed and instantiated as a spatial polygon object via aoi = ee.Geometry.Polygon(coordinates).
2.
Dataset Filtering and Cloud Masking: Sentinel-2 Level-2A surface reflectance collections are filtered by the active growing season dates and clipped to the polygon boundary. Images with cloud cover exceeding 30% are filtered out using the QA60 band.
3.
Inward Spatial Buffering: To eliminate edge noise from neighboring non-agricultural lands or roads, an inward spatial buffer of − 10 m is applied to the boundary coordinates. This buffering is critical for maintaining model accuracy on smaller fields, such as the 1.30-hectare North Field and the 0.90-hectare South Field.
4.
Temporal and Spatial Reduction: GEE reduces the daily spatial arrays within the buffered polygon to a single statistic (mean, standard deviation, and percentiles) for each date in the time series. This spatial reduction converts multi-gigabyte satellite imagery into lightweight daily time-series data, which is returned as a JSON payload.
5.
Meteorological Data Alignment: GEE simultaneously queries daily CHIRPS precipitation (5 km resolution) and ERA5-Land 2 m air temperature records (9 km resolution), aggregating them using the centroid of the polygon. These records are joined with the Sentinel-2 vegetation indices on the server.
By utilizing this serverless hybrid model, the web server only needs to process lightweight numeric arrays, avoiding the computational overhead of storing and manipulating raw, terabyte-scale GeoTIFF files.

3.5. Database Model and Schemas (MongoDB)

To maintain secure, user-driven data access, the platform utilizes MongoDB (NoSQL), which is well-suited for storing dynamic spatial coordinates and user activity logs. The database schema is structured around a One-to-Many relationship, where a primary User document embeds an array of nested Estimation-Record sub-documents. This document structure simplifies querying by keeping each user’s history co-located within a single database document.

3.5.1. User Document Schema

The User collection manages authentication profile details:
  • name (String, Required): User’s full name.
  • email (String, Required, Unique): Email used for dashboard authentication.
  • authProvider (Enum: credentials, google, Required): Defines the authentication provider.
  • role (Enum: farmer, agronomist, admin, Default: farmer): Determines frontend tab permissions. Agricultural extension officers and researchers are assigned agronomist or admin roles to access model training capabilities and advanced ML diagnostics.
  • createdAt & updatedAt (Date, Defaults to now): Temporal tracking of user account lifetimes.

3.5.2. Embedded Estimation-Record Schema

Whenever an authenticated user executes a yield prediction query for a custom polygon, the spatial parameters and returned predictions are saved to their profile as a nested document. This schema includes:
  • location (GeoJSON Point, Required): A GeoJSON Point mapping the centroid of the queried polygon. A MongoDB 2dsphere index is applied to this field, enabling spatial proximity queries on historical results.
  • predictedYield (Embedded Document, Required): Contains the numeric forecast value (e.g., 1847.3 ) and the unit string (default: kg).
  • meanNdviValue (Number, Required): The average NDVI value calculated within the polygon at the truncation window.
  • ndviMapUrl (String, Required): A signed temporal URL referencing the GEE-rendered raster overlay for Leaflet map display.
  • checkedAt (Date, Default: now): Logs the exact time the query was executed.

3.6. System Constraints, Edge Cases, and Mitigations

Deploying an operational machine learning model into a live application exposes it to real-world edge cases that are typically not encountered during offline model training.

3.6.1. The Crop Classification Bottleneck

A primary operational challenge is that satellite data streams do not automatically identify crop types or differentiate between agricultural croplands and urban development. If a user draws a polygon over an urban area or a non-wheat field, GEE will still fetch NDVI values and the predictive engine will still run, but the resulting wheat yield prediction would be highly inaccurate.
Mitigation: The application provides pre-defined field boundary polygons for the validated wheat fields at UAF PARS Campus as default selections. For custom polygon queries, the frontend displays clear user instructions explaining that non-wheat field boundaries will produce invalid results. Future updates plan to integrate a GEE land-use classification mask to automatically reject custom polygon queries that do not overlap with classified agricultural wheat land.

3.6.2. GEE Latency and Rate Limiting

Under high concurrent usage, frequent GEE REST requests can lead to API rate limiting, increasing response times or causing temporary connection drops.
Mitigation: The backend utilizes a caching layer. For historical growing seasons (2019 to 2025), the preprocessed feature datasets are stored in a local CSV database. When a user queries a historical season, the system reads from this local cache, returning the results in under 2 seconds without making external GEE API calls. For the current active season, the backend caches retrieved satellite records in an in-memory database, which is invalidated and refreshed only once every 24 hours.

3.6.3. Satellite Sensor Limitations and Quality Control

During periods of persistent cloud cover, Sentinel-2 optical imagery can be obscured, leading to missing observations or inaccurate NDVI values during critical crop growth stages. Furthermore, ERA5-Land temperature grids are subject to a standard 5-day reporting delay.
Mitigation: The GEE collector incorporates a robust quality control pipeline. Sentinel-2 scenes with cloud cover exceeding 30% are filtered out. Pixels with NDVI values below 0.17 are removed to filter non-vegetated soil and water noise. Linear interpolation is applied to gap-fill missing observations, ensuring a continuous temporal profile for feature engineering. To address the 5-day ERA5-Land temperature lag, the system dynamically calculates the active season length using yesterday’s date as the effective endpoint, preventing pipeline failures due to missing current-day weather records.

4. Results and Discussion

4.1. Model Performance and Baseline Comparisons

The predictive performance of the machine learning pipeline was evaluated across six consecutive growing seasons (2019–2020 to 2024–2025) at the UAF PARS Campus in Faisalabad using a rigorous Leave-One-Season-Out Cross-Validation (LOOCV) framework. Evaluating the models under LOOCV ensures that each season is entirely excluded from the training and feature selection folds, preventing optimistic performance estimation and data leakage. Six regression architectures were compared at the 50% season-elapsed window (mid-February, corresponding to approximately 60 days before harvest).
The statistical metrics evaluated on the held-out validation folds are summarized in Table 1 and visualized in Figure 8 and Figure 9.

4.1.1. Analysis of Local Baseline Results

The cross-validated results reveal a stark contrast between regularized linear algorithms and flexible, non-linear/kernel-based estimators. ElasticNet achieved the superior predictive performance across all five metrics, explaining 86.8% of the out-of-fold yield variance with a remarkably low MAPE of 3.36% and an out-of-fold Pearson correlation coefficient of r = 0.945 ( p = 0.004 ). This performance confirms our core hypothesis: under small-sample, high-dimensional conditions ( n = 6 growing seasons with dozens of spatial-temporal variables), highly parameterized or non-parametric models suffer from catastrophic overfitting.
The physical and mathematical reasons for this behavior are distinct:
1.
ElasticNet and Regularization Mechanics: ElasticNet minimizes a loss function that incorporates both L 1 (Lasso) and L 2 (Ridge) regularizers. The L 1 penalty enforces sparsity by driving irrelevant coefficients to zero (feature selection), while the L 2 penalty forces coefficients of highly correlated variables to shrink together, managing the strong multicollinearity among temperature and GDD metrics. In-fold optimization selected α = 10.0 and λ = 0.5 , balancing feature exclusion with coefficient stabilization. The resulting parity plot (Figure 12) confirms strong alignment between predicted and observed values, with bootstrap uncertainty bounds (Figure 12) further validating prediction stability.
2.
PLS and PCR Performance: PLS ( R 2 = 0.808 , RMSE = 78.0 kg) and PCR ( R 2 = 0.693 , RMSE = 98.7 kg) project high-dimensional predictors into a low-dimensional subspace of latent components. Because they constrain the model to a single component ( n c = 1 ), they effectively capture the major direction of variance (primarily driven by temperature–NDVI covariance), showing strong baseline stability. The PLS loading structure is detailed in Figure 10.
3.
Overfitting in SVR and GPR: SVR-RBF and GPR performed poorly, yielding negative out-of-fold R 2 values ( R 2 = − 0.417 and − 97.0 , respectively). While these algorithms can fit non-linear training boundaries, their high flexibility causes them to interpret year-to-year noise in the 5-season training folds as true structural features. Consequently, when applied to an unseen test season, their predictions deviate severely, performing worse than a naïve baseline that predicts the historic mean. This collapse is directly visible in the GPR uncertainty analysis (Figure 11).

4.2. Comparative Analysis with Regional and International Studies

To evaluate the academic and operational significance of our early-warning platform, we compare our findings with peer-reviewed studies utilizing remote sensing and machine learning for cereal yield forecasting.

4.2.1. Comparison with Faisalabad Regional Benchmarks (MS-YieldStackNet)

In a recent study localized to the Faisalabad region, Waqas Ali et al. [19] developed MS-YieldStackNet, a stacked ensemble neural network integrating multispectral satellite indices (NDVI, DVI), lab-tested soil physicochemical attributes, and meteorological records. MS-YieldStackNet achieved an R 2 of 0.81, an RMSE of 78.19 kg/ha, and a MAPE of 3.55%. While their system achieves high accuracy, our ElasticNet model at the 50% season-elapsed window achieved a higher R 2 (0.868) and a lower MAPE (3.36%). Critically, MS-YieldStackNet depends on laboratory soil sampling and full-season meteorological averages, whereas our system relies exclusively on open-access satellite and reanalysis parameters requiring no field soil testing. Furthermore, our pipeline truncates data at the 50% mark (mid-February), delivering a genuine eight-week early warning before harvest.

4.2.2. Comparison with Regional Statistical Regularization (Odesa, Ukraine)

Kulyk et al. [17] evaluated regularized regression methods (Ridge, Lasso, ElasticNet) to model cereal and legume yields under severe multicollinearity in the Odesa region. Their study proved that regularized linear estimators significantly outperform classical Ordinary Least Squares (OLS) regression, improving R 2 from 0.257 for OLS to 0.606 for Ridge. This aligns with our finding that regularization is critical in small-sample agricultural datasets. Our ElasticNet model achieved a substantially higher R 2 of 0.868, highlighting the advantage of our pixel-level (10 m) Sentinel-2 feature extraction and localized crop boundary masking over county-level, aggregated regional statistical reporting.

4.2.3. Comparison with Continental-Scale Wheat SVR Models (Australia)

Kamir et al. [15] mapped wheat yields across the Australian wheat belt using Support Vector Regression (SVR-RBF) integrated with MODIS time series (250 m) and climate reanalysis, achieving an R 2 of 0.77. SVR-RBF was the optimal model in Australia because their dataset contained 125 fields and over 2,000 spatial-temporal calibration pixels, which saturated the SVR learning curve without overfitting. Conversely, in our data-scarce pilot field with only 6 season-level records, SVR-RBF overfitted severely ( R 2 = − 0.417 ). This comparison demonstrates that model complexity must be scaled directly to sample volume, and highlights regularized linear models as the appropriate choice for data-scarce developing regions.

4.2.4. Comparison with High-Resolution In-Season Swiss Models (GPR/RF)

Amin et al. [4] developed a high-resolution (10 m) Sentinel-2 in-season forecasting workflow for Swiss winter cereals, evaluating GPR, KRR, and RF models spaced temporally via Growing Degree Days (GDD). Their best prediction was achieved at the anthesis (flowering) phase (approximately 1,300 GDD, 2 to 2.5 months before harvest), yielding an RMSE of 0.71 t/ha. Our study similarly found that early-season thermal accumulation (GDD and temperature–NDVI covariance) contains the dominant predictive information, and that early predictions converge around mid-season (February in Pakistan, matching anthesis and jointing stages). Our ElasticNet model maintains a high out-of-fold R 2 of 0.868, comparing favorably with the Swiss GPR models which suffered performance drops when evaluated in unseen years ( R 2 = 0.52 , RMSE = 2.61 t/ha in 2020).

4.2.5. Comparison with China’s GEE Deep Learning Models

Several recent papers have applied advanced deep learning models to estimate winter wheat yield in China’s wheat-producing regions. Wang et al. [20] combined 1D CNN feature extraction with a Gated Recurrent Unit (GRU), achieving an R 2 of 0.64 and an RMSE of 462.56 kg/ha with a 20-day forecast lead time. Zhang et al. [12] integrated Solar-Induced Chlorophyll Fluorescence (SIF), EVI, LAI, and ERA5 climate data into a Bayesian-optimized CNN-BiLSTM network, achieving an R 2 of 0.81 with a 25-day forecast lead time. Our regularized ElasticNet pipeline demonstrates several distinct advantages:
1.
Lead-Time Superiority: Our system delivers a robust early warning 60 days (eight weeks) before harvest (February), compared to the 20-day and 25-day lead times of deep learning approaches.
2.
Computational Efficiency: Training deep learning ensembles and transformers requires massive computing resources, whereas our regularized regression executes in milliseconds, enabling live spatial calculations within a web application sandbox.
3.
Data Efficiency: Our regularized framework handles a 6-season historical dataset elegantly, whereas deep learning architectures overfit on small samples or require regional augmentation.

4.3. Software System Validation and Testing Results

To verify that the empirical model operates reliably within the web portal, we executed a comprehensive, multi-layered testing protocol:
1.
Unit Testing: Individual software units, including GEE collection classes, database connection pooling, and JWT authentication modules, were tested in isolation. We verified that the cloud feature extraction logic yields identical metrics compared to the offline Python pipeline.
2.
Integration Testing: We evaluated the communication between the FastAPI REST layer and Google Earth Engine REST API, confirming that asynchronous polygon-based coordinates are translated into valid GEE spatial geometries and filtered cloud-free time series are returned within an acceptable 1.5-second latency.
3.
System Testing: End-to-end flows were validated by simulating a live user scenario: an authenticated user logs in, navigates to the Predict Yield Leaflet map, draws a custom polygon over a post-graduate experimental field, initiates a query, and triggers the asynchronous BackgroundTasks runner. The portal successfully extracts the GEE features, runs the pre-trained ElasticNet model, and writes the prediction to the MongoDB cluster.
4.
Model Validation Testing: The backend’s embedded ML pipeline was re-validated inside the system framework using the strict LOOCV routine, confirming that the frontend ML Analysis dashboard dynamically renders the target out-of-fold metrics ( R 2 = 0.868 , RMSE = 64.7 kg) with accurate bootstrap confidence intervals.

4.4. Policy Implications and Stakeholder Impact

Moving crop yield modeling from offline, localized Python scripts to an operational, web-based platform has profound implications for regional food security:
  • Empowering Low-Resource Farmers: By providing real-time pixel-level querying (10 m spatial resolution) and bootstrap uncertainty bounds via a simple, interactive React map, farmers can visualize spatial yield variability in their fields. This allows them to apply fertilizers, plan localized irrigation, and optimize input costs weeks before harvesting.
  • Informing Proactive Policy Planning: An operational eight-week advance warning (mid-February) of regional crop performance enables the Ministry of Food Security and agricultural officers to accurately estimate the national harvest volume. If early-season climate anomalies indicate a production shortfall, the government can initiate proactive food import contracts, schedule logistical distribution, and adjust national cash reserve pricing early, mitigating potential food crises before they impact markets.
  • Addressing Operational Bottlenecks: The system’s main limitation remains the crop classification bottleneck. Because GEE does not automatically classify crop boundaries dynamically, the web portal requires users to select or pre-define agricultural field boundaries. In future iterations, we plan to incorporate a real-time, random-forest-driven crop classification mask to automatically isolate wheat fields during early growth.

5. Conclusions

This study presents a comprehensive, end-to-end mid-season wheat yield forecasting framework and its operationalization into a production-grade web application. The key findings are as follows:
1.
ElasticNet as an Optimal Small-Sample Forecaster: Under a rigorous, leakage-free Leave-One-Season-Out Cross-Validation (LOOCV) framework, ElasticNet achieved the highest predictive accuracy ( R 2 = 0.868 , RMSE = 64.72 kg, MAE = 59.14 kg, MAPE = 3.36%) at the 50% season-elapsed window—corresponding to a 60-day early-warning lead time—significantly outperforming SVR-RBF, GPR, Ridge, PCR, and PLS, all of which exhibited severe overfitting under the n = 6 season-level data constraint.
2.
Thermal Accumulation as the Primary Yield Driver: Model coefficient analysis and feature correlation structures identified GDD (gdd_smean) and the GDD–NDVI interaction term (gdd_ndvi_smean) as the most consistently predictive features across all LOOCV folds, confirming that early-season thermal accumulation dominates over spectral vegetation signals in capturing yield potential.
3.
Successful Full-Stack Deployment: The platform was successfully deployed as a live, production-grade React.js and FastAPI web application at https://wheatyieldapp.vercel.app/, integrating Google Earth Engine serverless processing and MongoDB spatial indexing to serve real-time yield predictions for custom field polygons.
4.
Demonstrated Superiority Over Regional Benchmarks: Our pipeline compares favorably with seven international peer-reviewed studies, demonstrating advantages in early-warning lead time, computational efficiency, and data efficiency over both deep learning architectures (CNN-GRU, BO-CNN-BiLSTM) and regional stacked ensembles (MS-YieldStackNet).
Future research will focus on: (i) extending the spatial coverage from the UAF PARS Campus pilot fields to district-level and provincial-level mapping across Punjab; (ii) incorporating SAR (Synthetic Aperture Radar) imagery from Sentinel-1 to maintain model robustness during persistent cloud-cover events; and (iii) integrating an automated crop type classification mask to extend the platform to multi-crop forecasting scenarios.

Author Contributions

Conceptualization, M.H.H.; methodology, M.H.H.; software, M.H.H.; validation, M.H.H.; formal analysis, M.H.H.; investigation, M.H.H.; resources, M.H.H.; data curation, M.H.H.; writing—original draft preparation, M.H.H.; writing—review and editing, A.K.; visualization, M.H.H.; project administration, A.K. The authors have read and agreed to the published version of the manuscript.

Funding

This research received no external funding.

Institutional Review Board Statement

Not applicable.

Data Availability Statement

The preprocessed six-season agroclimatic dataset, model training scripts, and FastAPI backend source code supporting the findings of this study are available in the project repository. The live web application is accessible at https://wheatyieldapp.vercel.app/.

Acknowledgments

The authors acknowledge the Department of Computer Science, University of Agriculture Faisalabad (UAF), for providing access to the PARS Campus experimental fields and historical ground-truth yield records. The author also acknowledges the use of Google Earth Engine, Copernicus Sentinel-2, CHIRPS, and ERA5-Land open-access datasets.

Conflicts of Interest

The author declares no conflicts of interest.

Abbreviations

The following abbreviations are used in this manuscript:
NDVI Normalized Difference Vegetation Index
GDD Growing Degree Days
LOOCV Leave-One-Season-Out Cross-Validation
RMSE Root Mean Squared Error
MAE Mean Absolute Error
MAPE Mean Absolute Percentage Error
GEE Google Earth Engine
ASGI Asynchronous Server Gateway Interface
SPA Single-Page Application
PLS Partial Least Squares
PCR Principal Component Regression
SVR Support Vector Regression
GPR Gaussian Process Regression
CHIRPS Climate Hazards Group InfraRed Precipitation with Station data
UAF University of Agriculture Faisalabad
PARS Post Graduate Agricultural Research Station
DOY Day of Year
GIS Geographic Information System
JSON JavaScript Object Notation
REST Representational State Transfer
API Application Programming Interface
JWT JSON Web Token

References

  1. Bentley, A.R.; Donovan, J.; Sonder, K.; Baudron, F.; Lewis, J.M.; Voss, R.; et al. Near- to long-term measures to stabilize global wheat supplies and food security. Nat. Food 2022, 3, 483–486. [Google Scholar] [CrossRef]
  2. Arshad, S.; Kazmi, J.H.; Javed, G.M.; Mohammed, S. Applicability of machine learning techniques in predicting wheat yield based on remote sensing and climate data in Pakistan, South Asia. Eur. J. Agron. 2023, 147, 126837. [Google Scholar] [CrossRef]
  3. Ahmed, N.; Mahmood, S.A.; Haseeb, M.; Tahir, Z.; Batool, S. Enhancing food security: machine learning-based wheat yield prediction using remote sensing and climate data in Pakistan. Theor. Appl. Climatol. 2025, 156. [Google Scholar] [CrossRef]
  4. Amin, E.; Belda, S.; Pipia, L.; Szantoi, Z.; Verrelst, J.; et al. In-season grain yield forecasting at a high spatial resolution of 10 meters using Sentinel-2 satellite time series. Int. J. Appl. Earth Obs. Geoinf. 2024, 126, 103636. [Google Scholar] [CrossRef]
  5. Ashfaq, M.; Khan, I.; Alzahrani, A.; Tariq, M.U.; Khan, H.; Ghani, A. Accurate Wheat Yield Prediction Using Machine Learning and Climate-NDVI Data Fusion. IEEE Access 2024, 12, 40947–40961. [Google Scholar] [CrossRef]
  6. Camenzind, M.P.; Yu, K. Multi-temporal multispectral UAV remote sensing allows for yield assessment across European wheat varieties already before flowering. Front. Plant Sci. 2024, 14, 1214931. [Google Scholar] [CrossRef]
  7. Cheng, E.; Zhang, B.; Peng, D.; Zhong, L.; Yu, L.; Liu, Y.; et al. Wheat yield estimation using remote sensing data based on machine learning approaches. Front. Plant Sci. 2022, 13, 1090970. [Google Scholar] [CrossRef]
  8. Dinh, T.L.A.; Aires, F. Nested leave-two-out cross-validation for the optimal crop yield model selection. Geosci. Model Dev. 2022, 15, 3519–3535. [Google Scholar] [CrossRef]
  9. Gorelick, N.; Hancher, M.; Dixon, M.; Ilyushchenko, S. Google Earth Engine: Planetary-scale geospatial analysis for everyone. Remote Sens. Environ. 2017, 202, 18–27. [Google Scholar] [CrossRef]
  10. Government of Pakistan; Finance Division. Pakistan Economic Survey 2024–25. Finance Division: Islamabad, Pakistan, 2025. Available online: https://www.finance.gov.pk/survey_2025.html.
  11. Guo, F.; Wang, P.; Tansey, K.; Zhang, Y.; Li, M.; Liu, J.; et al. A novel transformer-based neural network under model interpretability for improving wheat yield estimation using remotely sensed multi-variables. Comput. Electron. Agric. 2024, 223, 109111. [Google Scholar] [CrossRef]
  12. Zhang, L.; Li, C.; Wu, X.; Xiang, H.; Jiao, Y.; Chai, H. BO-CNN-BiLSTM deep learning model integrating multisource remote sensing data for improving winter wheat yield estimation. Front. Plant Sci. 2024, 15, 1500499. [Google Scholar] [CrossRef]
  13. Zou, H.; Hastie, T. Regularization and variable selection via the Elastic Net. J. R. Stat. Soc. Ser. B (Stat. Methodol.) 2005, 67, 301–320. [Google Scholar] [CrossRef]
  14. Hochreiter, S.; Schmidhuber, J. Long Short-Term Memory. Neural Comput. 1997, 9, 1735–1780. [Google Scholar] [CrossRef]
  15. Kamir, E.; Waldner, F.; Hochman, Z. Estimating wheat yields in Australia using climate records, satellite image time series and machine learning methods. ISPRS J. Photogramm. Remote Sens. 2020, 160, 124–135. [Google Scholar] [CrossRef]
  16. Keselj, K.; Stamenkovic, Z.; Kostic, M.; Acin, V.; Ivezic, A.; Ivanisevic, M.; Magazin, N. Temporal Dynamics of UAV Multispectral Vegetation Indices for Accurate Machine Learning-Based Wheat Yield Prediction. AgriEngineering 2026, 8, 71. [Google Scholar] [CrossRef]
  17. Kulyk, A.; Fokina-Mezentseva, K.; Piankova, O.; Slokva, M.; Sierova, L. Modelling grain yield under the influence of agrotechnological and climatic factors: a regularised regression analysis. Agric. Resour. Econ. 2026, 12, 125–148. [Google Scholar] [CrossRef]
  18. Okupska, E.; Juostas, A.; Gozdowski, D.; Wojcik-Gront, E. Field-Scale Prediction of Winter Wheat Yield Using Satellite-Derived NDVI. Agronomy 2026, 16, 00670. [Google Scholar] [CrossRef]
  19. Ali, Waqas; Ramzan, Zeeshan; Shahbaz, Muhammad; Ul Zaman Bhutta, Qamar; Talha, Muhammad; AlGhamdi, M.J. MS-YieldStackNet: multi-source data fusion for wheat yield estimation using a stacked ensemble neural network. PeerJ Comput. Sci. 2026, 12, e3434. [Google Scholar] [CrossRef]
  20. Wang, J.; Wang, P.; Tian, H.; Tansey, K.; Liu, J.; Quan, W. A deep learning framework combining CNN and GRU for improving wheat yield estimates using time series remotely sensed multi-variables. Comput. Electron. Agric. 2023, 206, 107705. [Google Scholar] [CrossRef]
  21. Yasin, M.Y.; Khan, M.R.; Amin, M. Impacts of Spatio-Temporal Changes in Rainfall and Temperature on Different Crops in Selected Districts of Punjab, Pakistan. Sarhad J. Agric. 2018, 34, 400–413. [Google Scholar] [CrossRef]
Table 1. Cross-validated performance of six regression models at the 50% season-elapsed window.
Table 1. Cross-validated performance of six regression models at the 50% season-elapsed window.
Regression Model R 2 RMSE (kg) MAE (kg) MAPE (%) Pearson r
ElasticNet 0.868 64.7 59.1 3.36 0.945
PLS ( N comp = 1 ) 0.808 78.0 63.3 3.79 0.938
PCR ( N comp = 1 ) 0.693 98.7 78.1 4.53 0.944
Ridge 0.375 140.8 114.4 6.62 0.700
SVR-RBF −0.417 211.9 190.8 11.12 −0.881
GPR −97.000 1762.3 1753.2 100.00 −1.000
Source: Model validation output on Faisalabad pilot dataset.
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.
Copyright: This open access article is published under a Creative Commons CC BY 4.0 license, which permit the free download, distribution, and reuse, provided that the author and preprint are cited in any reuse.