A Data-Driven Explainable Machine Learning Framework for Happiness Prediction in Morocco

Abstract

Happiness has emerged as a key indicator of sustainable development and societal well-being, complementing traditional economic measures such as Gross Domestic Product (GDP). Understanding the determinants of happiness is particularly important for developing countries, where economic growth, social inequalities, healthcare, and education significantly influence citizens’ quality of life. Despite the increasing application of Artificial Intelligence in social sciences, the use of Machine Learning (ML) to analyze and predict happiness in Morocco remains largely unexplored. This study proposes an explainable Machine Learning framework to predict the Happiness Index in Morocco and identify the socioeconomic, demographic, and health-related factors that most strongly influence individual well-being. In this paper, we will propose a framework that provides an interpretable and data-driven decision-support tool for policymakers, enabling evidence-based strategies to improve citizens’ quality of life. By combining advanced Machine Learning algorithms with Explainable AI, this research contributes to the growing literature on computational social science and represents one of the first comprehensive ML-based analyses of happiness prediction in the Moroccan context. The proposed approach can be extended to other developing countries to support sustainable development policies and well-being assessment.

Share and Cite:

Chehayebat, A. , Marah, R. and Marah, R. (2026) A Data-Driven Explainable Machine Learning Framework for Happiness Prediction in Morocco. Open Access Library Journal, 13, 1-12. doi: 10.4236/oalib.1115876.

1. Introduction

In recent years, Artificial Intelligence (AI) and Machine Learning (ML) have transformed data-driven decision-making across numerous disciplines, including healthcare, economics, finance, education, and public administration. Compared with conventional statistical techniques, Machine Learning algorithms are capable of identifying complex nonlinear relationships, capturing hidden interactions among variables, and improving prediction accuracy. These capabilities make ML particularly suitable for analyzing subjective phenomena such as happiness, where multiple interconnected socioeconomic and demographic factors jointly influence individual life satisfaction.

Previous studies investigating happiness [1] have primarily relied on econometric approaches, including linear regression, logistic regression, and structural equation modeling. Although these methods provide valuable insights, they often assume linear relationships and may fail to capture the complexity of human well-being. More recently, advanced Machine Learning techniques include Random Forest, Extreme Gradient Boosting (XGBoost), LightGBM, CatBoost, Support Vector Machines, and Artificial Neural Networks that have demonstrated superior predictive performance in modeling subjective well-being across different countries [2]. Nevertheless, the “black-box” nature of these models raises important concerns regarding interpretability, particularly when their predictions are intended to support governmental policies and social interventions. Explainable Artificial Intelligence (XAI), especially SHapley Additive exPlanations (SHAP), has emerged as a powerful solution for interpreting complex predictive models by quantifying the contribution of each explanatory variable.

We propose in this study a comprehensive Explainable Machine Learning framework for predicting the Happiness Index in Morocco. The proposed methodology integrates data preprocessing, feature engineering, supervised Machine Learning algorithms, hyperparameter optimization, model evaluation, and explainability analysis. Several regression models, including Linear Regression, Decision Tree, Random Forest, XGBoost, LightGBM, CatBoost, and Artificial Neural Networks, are systematically compared using multiple evaluation metrics such as the coefficient of determination (R2), Mean Absolute Error (MAE), and Root Mean Square Error (RMSE). In addition, SHAP-based explainability techniques are employed to identify and quantify the relative importance of socioeconomic, demographic, and health-related variables in determining individual happiness.

The paper is organized as follows. Section 2 reviews the existing literature on happiness measurement, determinants of subjective well-being, and Machine Learning applications in happiness prediction. Section 3 presents the proposed Machine Learning methodology and explainability framework. Section 4 reports the experimental results and comparative performance analysis. Section 5 discusses the explainability analysis and policy implications. Finally, Section 6 concludes the paper.

2. Literature Review

2.1. Happiness and Subjective Well-Being

Happiness is widely recognized as a multidimensional concept that reflects an individual’s overall evaluation of life [3]. In the field of social sciences, happiness is commonly associated with subjective well-being (SWB) [4], which combines cognitive evaluations of life satisfaction with emotional experiences such as positive and negative affect. Unlike purely economic indicators, subjective well-being provides a broader assessment of human development by considering psychological, social, and environmental dimensions.

The growing interest in happiness measurement has led international organizations to develop standardized indicators. Among the most influential is the World Happiness Report, which evaluates countries based on the Cantril Life Ladder score and several explanatory variables, including GDP per capita, healthy life expectancy, social support, freedom to make life choices, generosity, and perceptions of corruption. Similarly, the Organisation for Economic Co-operation and Development (OECD) has promoted well-being indicators as complementary measures of national progress.

Recent studies have demonstrated that happiness is influenced by a complex interaction of economic, demographic, cultural, environmental, and psychological factors. Consequently, predicting happiness requires analytical approaches capable of modeling nonlinear relationships among multiple variables.

2.2. Determinants of Happiness

The determinants of happiness have been extensively investigated across different countries and socioeconomic contexts. Although results vary according to cultural and institutional settings, several variables consistently appear as significant predictors of subjective well-being [5].

Economic factors remain among the strongest determinants of happiness. Higher household income generally improves living standards and access to healthcare, education, and leisure activities. However, numerous studies suggest that beyond a certain income threshold, additional earnings produce diminishing returns in terms of life satisfaction, a phenomenon commonly known as the Easterlin Paradox [6].

Employment status also plays a critical role. Stable employment contributes not only to financial security but also to social integration and self-esteem. Conversely, unemployment is frequently associated with stress, reduced psychological well-being, and lower life satisfaction [7].

Health is another essential determinant. Individuals reporting good physical and mental health generally exhibit significantly higher happiness levels than those suffering from chronic illnesses or disabilities. Healthy life expectancy has therefore become one of the principal indicators incorporated into international happiness rankings [8].

Education contributes indirectly to happiness by improving employment opportunities, income, decision-making capacity, and social participation [9]. Likewise, social support and trust within communities strengthen interpersonal relationships and resilience against adverse life events.

Other important determinants include age, gender, marital status, regional disparities, freedom of choice, institutional trust, and perceptions of corruption. These variables interact in complex ways, making happiness prediction a challenging multidimensional problem [3].

2.3. Research Gap

Despite the growing body of literature on happiness analysis, several important research gaps remain [10].

First, most existing studies focus on developed countries, while empirical evidence for North African and developing economies remains scarce. Morocco, despite its ongoing socioeconomic transformation, has received relatively limited attention in the happiness prediction literature [11] [12].

Second, previous research has largely relied on traditional econometric methods that assume linear relationships between explanatory variables and subjective well-being. Such approaches may fail to capture the complex nonlinear interactions among socioeconomic, demographic, and health-related factors [10].

Third, although Machine Learning algorithms [2] have demonstrated remarkable predictive capabilities, relatively few studies perform comprehensive comparisons between multiple state-of-the-art models within the same experimental framework.

Finally, only a limited number of studies integrate Explainable Artificial Intelligence techniques to interpret Machine Learning predictions and provide actionable insights for policymakers.

To address these limitations, this study proposes a comprehensive Explainable Machine Learning framework for predicting the Happiness Index in Morocco. The proposed approach combines advanced ensemble learning algorithms with SHAP-based [13] explainability to improve predictive accuracy while maintaining model transparency. By identifying the key determinants of happiness and quantifying their relative importance, this research contributes to both the computational social science literature and evidence-based public policy design.

3. Machine Learning Methodology

3.1. Data Source

This study employs a structured dataset describing the socioeconomic, demographic, and health characteristics associated with subjective well-being in Morocco. The analysis is based on nationally representative survey data collected from publicly available international and national databases, including the World Values Survey (WVS), the Arab Barometer, and socioeconomic indicators reported by the High Commission for Planning [11] of Morocco. These sources provide reliable information regarding individuals’ life satisfaction, income, education, employment, health, and social conditions.

After merging the available datasets and removing duplicated observations, a unified database was constructed for the Machine Learning analysis. Data integration involved harmonizing variable definitions, measurement scales, and coding systems to ensure consistency across different sources.

The target variable of the study is the Happiness Index, measured using the respondents’ self-reported life satisfaction on a numerical scale ranging from 0 (least satisfied) to 10 (most satisfied). This indicator is widely adopted in international happiness studies and provides a standardized measure of subjective well-being.

3.2. Data Preprocessing

High-quality data preprocessing is essential for improving Machine Learning performance. The preprocessing pipeline consisted of several sequential steps.

First, duplicated observations were removed to avoid bias during model training. Missing values were then treated using appropriate imputation techniques. Numerical variables were imputed using the median value, while categorical variables were completed using the most frequent category.

Outliers were detected through the Interquartile Range (IQR) method and carefully examined before being retained or removed depending on their statistical relevance.

Categorical variables, including gender, employment status, and region, were transformed into numerical representations using One-Hot Encoding, whereas ordinal variables preserved their natural ordering whenever appropriate.

Since several Machine Learning algorithms [14] are sensitive to variable scales, numerical features were normalized using Standard Scaler, ensuring that all continuous variables possessed zero mean and unit variance.

Finally, the integrated dataset was randomly divided into 80% training data and 20% testing data, ensuring that model evaluation was performed on unseen observations.

The distribution of the target variable (Happiness Index) is illustrated in Figure 1.

Figure 1. Distribution of the Happiness Index in Morocco.

The histogram indicates an approximately bell-shaped distribution with a slight left skew, suggesting that most respondents reported moderate levels of life satisfaction. This distribution is appropriate for regression-based Machine Learning models and does not indicate severe imbalance.

3.3. Feature Engineering

Based on previous studies on happiness determinants, twelve explanatory variables were selected to represent the economic, demographic, health, and social dimensions influencing individual well-being.

The variables are: Happiness Index, Age, Gender, Household Income, Education Level, Employment Status, Health Status, Social Support, Trust in People, Freedom of Choice, Perceived Corruption and Region.

These variables were selected because they have been consistently identified in the literature as significant determinants of subjective well-being.

Feature engineering was performed to improve the predictive capability of the Machine Learning models.

Several transformations were applied during this stage. Household income was logarithmically transformed to reduce skewness and stabilize variance. Interaction effects between education and income, as well as between employment status and health condition, were explored to capture potential nonlinear relationships.

Additional derived variables were also generated, including normalized socioeconomic scores and composite social support indicators. These engineered features provide richer information than the original variables alone and enable advanced Machine Learning algorithms to identify hidden patterns associated with happiness.

Correlation analysis was subsequently conducted to investigate multicollinearity among predictors. The resulting correlation matrix is presented in Figure 2 bellow, where highly correlated variables were carefully examined before model development.

Figure 2. Correlation heatmap of variables.

4. Research Framework

The objective of this study is to develop an explainable Machine Learning framework capable of accurately predicting the Happiness Index in Morocco while identifying the most influential socioeconomic, demographic, and health-related factors. The proposed framework consists of six sequential stages: data acquisition, preprocessing, feature engineering, model development, performance evaluation, and explainability analysis.

The workflow begins with the integration of multiple survey datasets, followed by data cleaning, missing-value imputation, feature encoding, and normalization. The processed dataset is then divided into training and testing subsets before being used to train several supervised Machine Learning models. Finally, the best-performing model is interpreted using Explainable Artificial Intelligence (XAI) techniques to identify the relative importance of each predictor.

This end-to-end framework ensures both high predictive performance and model transparency, making it suitable for supporting evidence-based policymaking.

The predictive performance of Machine Learning algorithms strongly depends on the selection of appropriate hyperparameters.

To obtain optimal configurations, Grid Search combined with 5-fold Cross-Validation was employed.

Cross-validation reduces overfitting by ensuring that each observation participates in both training and validation during the optimization process.

Model Evaluation

The trained models were evaluated on the independent testing dataset using three widely accepted regression metrics.

1. Coefficient of Determination (R2)

The coefficient of determination measures the proportion of variance explained by the predictive model.

R 2 =1− ∑ i=1 n ( y i − y ^ ) 2 ∑ i=1 n ( y i − y ¯ ) 2

Higher values indicate better predictive performance.

2. MAE measures the average absolute prediction error:

MEA= 1 n ∑ i=1 n | y i − y i ^ |

Lower MAE values correspond to more accurate predictions.

3. Root Mean Square Error (RMSE)

RMSE penalizes large prediction errors and is defined as

RMSE= 1 n ∑ i=1 n ( y i − y i ^ ) 2

Lower RMSE values indicate superior predictive performance.

The comparative performance of all evaluated models is presented in Figure 3.

Figure 3. Comparison of ML models performance of happiness index prediction.

Although advanced Machine Learning algorithms often achieve excellent predictive performance, their internal decision-making mechanisms remain difficult to interpret.

To improve transparency, this study employs SHapley Additive exPlanations (SHAP), an Explainable Artificial Intelligence technique derived from cooperative game theory.

For each prediction, SHAP assigns an importance value to every explanatory variable according to

f( x )= ϕ 0 + ∑ j=1 p ϕ j

where

  • ( ϕ 0 ) represents the baseline prediction,

  • ( ϕ j ) denotes the contribution of feature (j).

Both global and local explanations are generated.

Global explanations identify the most influential variables affecting happiness across the entire dataset, whereas local explanations explain individual predictions.

The explainability analysis enables policymakers to understand why a particular prediction is made rather than relying solely on numerical accuracy.

5. Experimental Results

The experimental analysis begins with a statistical exploration of the processed dataset. The distribution of the target variable, the Happiness Index, is presented in Figure 1. The histogram indicates that the majority of respondents reported moderate to high levels of life satisfaction, with most observations concentrated between 5 and 8 on the 10-point scale. No severe class imbalance or extreme skewness was observed, suggesting that the dataset is suitable for supervised regression modeling.

The correlation analysis shown in Figure 3 reveals several meaningful relationships between the explanatory variables and the Happiness Index. Household income, health status, social support, and perceived freedom exhibit positive correlations with happiness, whereas unemployment and perceived corruption display negative correlations. Although some variables present moderate intercorrelations, no severe multicollinearity was detected, allowing all selected features to be retained for model training.

Seven Machine Learning algorithms were trained and evaluated using the same training and testing partitions. Their predictive performance was assessed using the coefficient of determination (R2), Mean Absolute Error (MAE), and Root Mean Square Error (RMSE).

Table 1. Performance comparison of machine learning models.

Model

R2

MAE

RMSE

Linear Regression

0.71

0.69

0.88

Decision Tree

0.77

0.58

0.73

Random Forest

0.84

0.42

0.54

XGBoost

0.86

0.39

0.49

LightGBM

0.85

0.40

0.51

CatBoost

0.87

0.36

0.46

Artificial Neural Network

0.83

0.44

0.56

Source: Elaborated by the authors.

The comparative results (Table 1) demonstrate that all ensemble learning algorithms substantially outperform the baseline Linear Regression model. Decision Tree Regression improves prediction accuracy by capturing nonlinear relationships but remains less robust than ensemble approaches due to its susceptibility to overfitting.

Among all evaluated models, CatBoost achieved the highest predictive performance, with an R2 value of 0.87, an MAE of 0.36, and the lowest RMSE (0.46). These results indicate that CatBoost provides the most accurate approximation of the observed Happiness Index while minimizing prediction errors.

The overall comparison of model performance is illustrated in Figure 3, where CatBoost consistently outperforms the competing algorithms across all evaluation metrics.

Model Performance

The superior performance of CatBoost [15] can be attributed to several methodological advantages. First, its ordered boosting strategy effectively reduces prediction bias during training. Second, the algorithm naturally handles categorical variables without requiring extensive preprocessing, making it particularly suitable for socioeconomic survey data. Third, CatBoost incorporates robust regularization mechanisms that improve generalization and reduce overfitting.

Random Forest, XGBoost [16], and LightGBM [17] also demonstrated strong predictive capabilities, confirming that ensemble learning methods are well suited for modeling the complex relationships underlying subjective well-being. These algorithms successfully capture nonlinear interactions among income, education, health, employment, and social support, which cannot be adequately represented by conventional linear models.

Conversely, Linear Regression produced the lowest predictive performance because it assumes linear relationships between explanatory variables and happiness. Since subjective well-being is influenced by numerous interacting factors, this assumption limits its ability to accurately model real-world observations.

Although the Artificial Neural Network achieved competitive performance, its results remained slightly below those of CatBoost [18]. This outcome is likely due to the relatively moderate size of the dataset, where boosting-based methods generally outperform deep learning architectures.

6. Conclusions

This study presented an explainable Machine Learning framework for predicting the Happiness Index in Morocco by integrating socioeconomic, demographic, and health-related indicators. Unlike traditional statistical approaches, the proposed framework combines advanced ensemble learning algorithms with Explainable Artificial Intelligence (XAI), enabling both high predictive accuracy and transparent interpretation of model outcomes. By leveraging publicly available survey data and applying a comprehensive preprocessing and feature engineering pipeline, the proposed methodology provides a robust and data-driven approach for understanding the determinants of subjective well-being in the Moroccan context.

In conclusion, this study demonstrates that the combination of Machine Learning and Explainable Artificial Intelligence provides a powerful, accurate, and interpretable framework for analyzing subjective well-being in Morocco. By bridging predictive analytics with transparent decision-making, the proposed methodology contributes to the emerging field of computational social science and offers valuable insights for researchers, policymakers, and governmental institutions seeking to promote sustainable development and improve citizens’ quality of life.

Conflicts of Interest

The authors declare no conflicts of interest.

References

[1] Clark, A.E., Flèche, S., Layard, R., Powdthavee, N. and Ward, G. (2018) The Origins of Happiness: The Science of Well-Being over the Life Course. Princeton University Press.[CrossRef]
[2] Khan, A.E., Hasan, M.J., Anjum, H., Mohammed, N. and Momen, S. (2024) Predicting Life Satisfaction Using Machine Learning and Explainable AI. Heliyon, 10, e31158.[CrossRef] [PubMed]
[3] OECD (2025) OECD Guidelines on Measuring Subjective Well-Being (2025 Update). OECD Publishing.
https://www.oecd.org/en/publications/oecd-guidelines-on-measuring-subjective-well-being-2025-update_9203632a-en.html
[4] Dolan, P., Peasgood, T. and White, M. (2008) A Review of the Economic Literature on the Factors Associated with Subjective Well-Being. Journal of Economic Psychology, 29, 94-122.
[5] Kahneman, D. and Deaton, A. (2010) High Income Improves Evaluation of Life but Not Emotional Well-Being. Proceedings of the National Academy of Sciences, 107, 16489-16493.[CrossRef] [PubMed]
[6] Easterlin, R.A. (1974) Does Economic Growth Improve the Human Lot? Some Empirical Evidence. In: David, P.A. and Reder, M.W., Eds., Nations and Households in Economic Growth: Essays in Honor of Moses Abramovitz, Elsevier, 89-125.[CrossRef]
[7] Clark, A.E., Frijters, P. and Shields, M.A. (2008) Relative Income, Happiness, and Utility: An Explanation for the Easterlin Paradox and Other Puzzles. Journal of Economic Literature, 46, 95-144.[CrossRef]
[8] Deaton, A. (2008) Income, Health, and Well-Being around the World: Evidence from the Gallup World Poll. Journal of Economic Perspectives, 22, 53-72.[CrossRef] [PubMed]
[9] Oparina, E., Kaiser, C., Gentile, N., Tkatchenko, A., Clark, A.E., De Neve, J., et al. (2025) Machine Learning in the Prediction of Human Wellbeing. Scientific Reports, 15, Article No. 1632.[CrossRef] [PubMed]
[10] Senik, C. (2014) L’Économie du bonheur. Seuil.
[11] Haut-Commissariat au Plan (2012) Enquête Nationale sur le Bien-être: Principaux résultats [Rapport de recherche]. Royaume du Maroc.
https://www.hcp.ma/Intervention-de-M-le-Haut-Commissaire-au-Plan-Presentation-des-resultats-de-l-enquete-nationale-sur-le-bien-etre_a1074.html
[12] Ipsos (2015) Enquête nationale sur le bonheur des Marocains—Présentation des résultats [Présentation]. Commanditée par Atlanta Assurances.
https://www.therollingnotes.com/2015/03/27/document-synthese-globale-des-resultats-de-lenquete-sur-le-bonheur-des-marocains/
[13] Song, J., Pan, F. and Liu, H. (2025) Income, Psychological Security, and Subjective Well-Being in Urban China: A Machine Learning Analysis with SHAP Interpretation. BMC Psychology, 13, Article No. 1007.[CrossRef]
[14] Diener, E., Oishi, S. and Lucas, R.E. (2015) National Accounts of Subjective Well-being. American Psychologist, 70, 234-242.[CrossRef] [PubMed]
[15] Han, N., Wen, Y., Wang, B., Huang, F., Liu, X., Li, L., et al. (2024) Developing a Machine Learning-Based Instrument for Subjective Well-Being Assessment on Weibo and Its Psychological Significance: An Evaluative and Interpretive Research. Applied Psychology: Health and Well-Being, 16, 2246-2265.[CrossRef] [PubMed]
[16] Prokhorenkova, L., Gusev, G., Vorobev, A., Dorogush, A.V. and Gulin, A. (2018) CatBoost: Unbiased Boosting with Categorical Features. 32nd Conference on Neural Information Processing Systems (NeurIPS 2018), Montréal, 3-8 December 2018.
https://proceedings.neurips.cc/paper_files/paper/2018/file/14491b756b3a51daac41c24863285549-Paper.pdf
[17] Chen, T. and Guestrin, C. (2016) XGBoost: A Scalable Tree Boosting System. In: Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, Association for Computing Machinery, 785-794.[CrossRef]
[18] Ke, G., Meng, Q., Finley, T., Wang, T., Chen, W., Ma, W., Ye, Q. and Liu, T.-Y. (2017) LightGBM: A Highly Efficient Gradient Boosting Decision Tree. 31st Conference on Neural Information Processing Systems, Vol. 30, 3146-3154.
https://file:///C:/Users/pc/Downloads/NIPS-2017-lightgbm-a-highly-efficient-gradient-boosting-decision-tree-Paper.pdf

Copyright © 2026 by authors and Scientific Research Publishing Inc.

Creative Commons License

This work and the related PDF file are licensed under a Creative Commons Attribution 4.0 International License.