Full text
University of Minho School of Engineering Maria José Borges Pires Overstock prediction using machine learning january 2024
University of Minho School of Engineering Maria José Borges Pires Overstock prediction using machine learning Master’s Dissertation in Informatics Engineering Dissertation supervised by Professor Doutor João Miguel Lobo Fernandes january 2024
Copyright and Terms of Use for Third Party Work This dissertation reports on academic work that can be used by third parties as long as the internationally accepted standards and good practices are respected concerning copyright and related rights. This work can thereafter be used under the terms established in the license below. Readers needing authorization conditions not provided for in the indicated licensing should contact the author through the RepositóriUM of the University of Minho. License granted to users of this work: CC BY-NC https://creativecommons.org/licenses/by-nc/4.0/ i
Acknowledgements I would like to thank Professor Doutor João Miguel Lobo Fernandes for his guidance. To Bosch Car Multimedia Portugal and to my colleagues from ME/LOG-Brg for encouraging me to complete this chapter and for all their support and guidance. To TrueDevops for being the best group of friends I could ask for, for all the support throughout this journey, for all the adventures and weekly ”sprints reviews” that kept me sane the past two years. To all the friends I made throughout the intense academic journey that was MiEI. Finalmente, à minha famila, à qual sou profundamente grata por todo o apoio e sacrifícios que me permitiram chegar aqui. ii
Statement of Integrity I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Code of Ethical Conduct of the University of Minho. University of Minho, Braga, january 2024 Maria José Borges Pires iii
Abstract Inventory level trends refers to the changes in inventory levels of specific items or groups of items over a defined period of time. By analysing these trends, it is possible to identify patterns that indicate possible issues or opportunities related to inventory management, such as excessive stock levels. This project carried out within the Bosch Car Multimedia Portugal S.A. environment aims to leverage historical data and machine learning algorithms in order to develop a predictive model that analyses inventory level trends and identifies patterns indicating overstock scenarios within a future timeframe allowing end-users to manage and optimise inventory levels with efficiency. To tackle this issue, this document proposes two approaches: classification and regression, using the LightGBM model, a high-performance gradient boosting framework, following the Cross-Industry Standard Processes for Data Mining (CRISP-DM) methodology. The classification approach involves categorising data into discrete classes to enable the model to distinguish between overstock scenarios and normal inventory conditions. In contrast, regression focuses on predicting numerical values, enabling the model to estimate and quantify inventory fluctuations. This study integrates time series analysis into the classification and regression approaches, enriching the predictive capabilities of the LightGBM model and optimizing inventory trend pattern recognition. The use of temporal analysis improves the model’s ability to identify changing trends and fluctuations in inventory levels over time, resulting in a more precise understanding of overstock situations. The proposed solution reveals a binary classification model with highly accurate predictive capabilities for overstock scenarios and offers valuable insights for enhancing inventory management procedures in organisational settings. Keywords Inventory Trend, Overstock, Supply Chain, Machine Learning, Time Series iv
Resumo Inventory level trends refere-se às alterações nos níveis de inventário de artigos específicos ou grupos de artigos durante um determinado período de tempo. Ao analisar estas tendências, é possível identificar padrões que indicam possíveis problemas ou oportunidades relacionadas com a gestão de inventário, tais como níveis de stock excessivos, isto é, overstock . Este projeto, realizado no âmbito do Bosch Car Multimedia Portugal S.A. , pretende tomar partido de dados históricos e algoritmos de aprendizagem automática para desenvolver um modelo preditivo que analise as tendências dos níveis de inventário e identifique padrões que indiquem cenários de excesso de stock num horizonte futuro, permitindo aos utilizadores finais gerir e otimizar os níveis de inventário com eficiência. Para resolver este problema, este documento propõe duas abordagens: classificação e a regressão, utilizando o model de machine learrning LightGBM , um modelo de gradient boosting de alto desempenho, seguindo a metodologia CRISP-DM (Cross-Industry Standard Processes for Data Mining) . A abordagem de classificação envolve a categorização dos dados em classes discretas para permitir ao modelo distinguir entre cenários de excesso de stock e condições normais de inventário. Em contrapartida, a regressão centra-se na previsão de valores numéricos, permitindo ao modelo estimar e quantificar as flutuações do inventário. Este estudo integra a análise de séries temporais nas abordagens de classificação e regressão, reforçando as capacidades de previsão do modelo LightGBM e optimizando o reconhecimento de padrões nas flutuações de inventário. A utilização de séries temporais melhora a capacidade do modelo para identificar padrões e flutuações nos níveis de inventário ao longo do tempo, resultando numa identificação com maior precisão de situações de overstock . A solução proposta revela um modelo de classificação binária com capacidades reditivas de alta precisão para cenários de excesso de stock e oferece informações valiosas para melhorar os procedimentos de gestão de inventário em ambientes organizacionais. Palavras-chave Inventory Trend , Excedentes de Stock , Cadeia de Abastecimento, Machine Learning , Séries Temporais v
Contents I Introductory material 1 1 Introduction 2 1.1 Contextandmotivation ................................ 2 1.2 Objectives ...................................... 3 1.3 ResearchMethodology ................................ 4 1.4 Dissertationstructure................................. 5 2 State of the art 7 2.1 MaterialCollection .................................. 7 2.2 TheoreticalConcepts ................................. 8 2.2.1 Rule-basedsystems ............................. 8 2.2.2 Artificial Intelligence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 2.2.3 MachineLearning .............................. 9 2.2.4 Machine learning algorithms and models . . . . . . . . . . . . . . . . . . . 10 2.2.5 Time-Series forecasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.2.6 Error Metrics and Error Estimation . . . . . . . . . . . . . . . . . . . . . . 19 2.3 Machine Learning and Overstock Prediction . . . . . . . . . . . . . . . . . . . . . . 22 2.4 Machine learning tools and libraries . . . . . . . . . . . . . . . . . . . . . . . . . . 23 2.4.1 Machine learning tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 2.4.2 Machine learning libraries . . . . . . . . . . . . . . . . . . . . . . . . . . 24 II Core of the Dissertation 26 3 Implementation 27 vi
Chapter 1 Introduction This chapter provides a brief overview of the topics covered in this dissertation, followed by a brief description of the of the problem, the objectives and the research methodology. It concludes by presenting the structure of the document. 1.1 Context and motivation In today’s global environment, organisations face unprecedented challenges due to the interconnectedness of economies, advances in technology, and unexpected events such as a global pandemic. These challenges highlight the volatility, uncertainty, complexity, and ambiguity of the supply chains. Supply chains are complex systems, with many interconnected components, such as suppliers, distributors, and various stages of production. Fluctuations in demand and supply chain dynamics can occur suddenly due to various factors such as customer preferences, economic conditions, and unforeseen events such as natural disasters. Therefore, it is crucial to remain flexible and adaptable. The volatility of these factors creates uncertainty, making it difficult to predict future outcomes. The complexity of forecasting demand and supply increases as more factors and variables are involved, due to their intricate and interconnected nature [49]. Managing these inter-dependencies is crucial to optimise inventory management within a company. It can be challenging and ambiguous to decipher the meaning of data, understand customer preferences and market signals, and evaluate the impact of external factors. Inventory trend refers to the patterns in which inventory levels of specific items change over time. By monitoring these trends, a company can make informed decisions about sourcing, production and distribution to ensure the right balance between supply and demand. The success of a manufacturing company like Bosch Car Multimedia Portugal, S.A depends largely on the efficiency of its supply chain. Data Intelligence & Analytics for Business Operations (DIABO) 2
is a project developed by Bosch that focuses on supply chain risk management and optimisation [49]. DIABO uses Artificial Inteligence (AI) techniques such as Machine Learning (ML) and optimisation algorithms to analyse data and provide insights for decision-making in supply chain operations. It aims to optimise inventory levels, anticipate supplier risk dynamics and improve overall supply chain performance. Predicting an increase or decrease in demand for a product is not an easy task, but it is even more complicated to determine the exact or optimal number of products to order or produce in order to avoid situations of excess stock. Accurately forecasting demand, and in particular anticipating these overstock situations, is critical to efficient inventory management. Overstocking means holding excess inventory, which ties up capital and adds warehousing costs. Leveraging historical data is a fundamental aspect of predicting inventory trends in order to accurately predict overstock scenarios and take proactive measures such as adjusting production schedules, and optimising reorder points, among others. Through training, algorithms learn from past trends and patterns to recognise and understand the complex interplay of variables that affect inventory levels. As new data becomes available, models can be refined to ensure that their predictions and recommendations remain accurate and relevant over time. The effectiveness of inventory management strategies is continually improved through this iterative learning process. Essentially, training algorithms using past inventory data is a fundamental aspect of making data-driven decisions in inventory management. 1.2 Objectives The main aim of this dissertation is to create a predictive model capable of detecting patterns indicating overstock scenarios by analysing inventory trends in the supply chain to help to manage and optimise inventory effectively inside the Bosch Car Multimedia Portugal, S.A environment. To achieve this goal, the following research questions (RQ) were proposed to be answered: •RQ1 - What methods have been explored concerning the detection of inventory trends and identification of overstock? •RQ2 - How to design and implement a robust system capable of leveraging historical data, employing machine learning algorithms and large amounts of data to predict overstock situations? 3
1.3 Research Methodology Given the nature of this research, the Cross-Industry Standard Processes for Data Mining (CRISPDM) proposed in [14] provides a structured and widely accepted framework that provides a systematic and comprehensive approach for the development of the contents presented in subsequent chapters. The CRISP-DM methodology, as shown in figure 1, comprises of six phases, each with its own set of tasks and interdependent relationships. Figure 1: CRISP-DM model (adapted from [14]). This process is highly flexible and facilitates the movement between phases as required. The next phase is determined based on the outcome of each phase. The six major phases of this methodology [14][48], described in table 1, serve as the basis to solve the research questions proposed in 1.2. Description Business Understanding Factors such as success criteria, business and data mining objectives, requirements, business terminologies and technical terms are defined in this initial phase. 4
Data Understanding In this phase, data is collected, subjected to a quality check and explored in order to gain insights and hypothesize about hidden information. Data Preparation All activities required to create the dataset that will feed the models are included in this phase. These activities include data selection, preparation, transformation and cleansing. Modelling At this stage, different modelling techniques are applied, different algorithms can be used and different parameters can be set to search and identify patterns. A number of different approaches can be used to tackle the same problem. Evaluation The results of the previous phase are thoroughly reviewed to ensure that the previously defined business objectives are being met. Deployment In the deployment phase, the gained knowledge is organised and presented so that it can be applied by the end user. Table 1: Summary of CRISP-DM phases 1.4 Dissertation structure This dissertation is divided into five chapters are described below. The present chapter, chapter 1 provides a general overview of the main objectives and the context of the project as well as the research methodology. Chapter 2 - State of the art, provides a literature review and theoretical background to the research presented in subsequent chapters, identifies existing relevant research in machine learning and overstock forecasting, and details the technological tools used in the development of the project. Chapter 3 - Implementation, presents the implementation process, covering all the key steps to obtain a predictive model capable of achieving the objective of this thesis, which is to detect patterns indicative of overstock scenarios. Chapter 4 - Results, displays and discusses the main results obtained throughout the conducted research. 5
Chapter 5 - Conclusions and future work, exposes the main conclusions drawn from the results and prospects for future work that may lead to further improvements. 6
Chapter 2 State of the art This chapter presents a systematic literature review (SLR) [53] and its primary objective is to address the first research question (RQ1) outlined in section 1.2. It begins with an explanation of the literature review process (section 2.1), then presents an overview of the essential theoretical background information that underpins the work carried out throughout this document (section 2.2), then aims to identify relevant research in the area of machine learning and overstock and demand forecasting (section 2.3). Finally, it describes the technological tools employed in the project’s development (section 2.4). 2.1 Material Collection The main source of information used for the literature review was the Scopus database. Scopus is regarded as a comprehensive research database and it is also recommended as a trusted source of peer-reviewed articles in the supply chain literature [16] [53]. A query was created to capture all published models and methods for overstock detection. To achieve this, a wide range of search terms were used, as shown in Table 2. The query structure consists of two levels, the first representing the search context and the second the technological context. This search resulted in an initial set of 35 publications. A brief analysis of each paper, by reading the corresponding abstracts, identified those most relevant to the aim of this dissertation. In addition, only publications published in peer-reviewed journals were included. As a result, the number of publications was reduced to 9. Section 2.3 provides details on the exploration of these studies. To supplement the research and support the background presented throughout this chapter, scientific articles and books were also retrieved from Google Scholar and Science Direct . The materials were screened for relevance to aid in understanding and developing the project. Additionally, the year of publication was considered to ensure the information remains current and reflects the actuality of the context. 7
Research Query (Overstock OR “Excessive Stock” OR Surplus) AND (”Supply Chain Management” OR “Inventory Management” OR “Inventory Optimization”) AND (“Demand Forecast” OR “Machine Learning” OR “ Predictive Model” OR “Prediction” OR “Time Series” OR “Time Series Forecasting”) Results in Scopus 35 Table 2: Resarch query applied in Scopus 2.2 Theoretical Concepts This section introduces fundamental concepts in machine learning and provides an overview of the key theoretical background that underpins the work carried out throughout this document. 2.2.1 Rule-based systems Rule-based systems operate on explicitly defined rules, meaning that knowledge in the system is explicitly encoded as rules. These rules often take the form of conditional statements, where certain conditions trigger predefined actions. Rule-based systems are generally easy to interpret because the decision-making process is based on explicitly stated rules that can be understood and modified by human experts [24]. According to [28], due to the current availability of programming frameworks, abundant data, and widespread computing power, ML techniques are now predominantly used rather than traditional rulebased approaches to develop intelligent systems more efficiently. 2.2.2 Artificial Intelligence The creation of computer systems that can carry out tasks that conventionally need human intelligence is referred to as artificial intelligence. This covers acquiring knowledge, resolving issues, and comprehending spoken language [56]. By using methods like machine learning and deep learning, artificial intelligence systems seek to mimic human cognitive functions. 8
2.2.3 Machine Learning Machine learning is a branch of artificial intelligence in which systems are able to automatically learn from observations or data in order to look for patterns make accurate decisions and improve from experience without being explicitly programmed [39]. The effectiveness of a machine learning model depends on several factors, such as the quantity and quality of the training data, the chosen algorithm, and the finetuning of the model’s parameters. As stated by [7] there are four primary categories in machine learning: supervised learning, unsupervised learning, semi-supervised learning, and reinforcement learning. Supervised learning reflects the ability of an algorithm to generalise knowledge and learn hidden patterns within labelled or categorised data and subsequently classify data or predict outcomes accurately [4]. Supervised learning can be separated into two categories: •Classification maps the input to output labels (discrete). •Regression maps the input to a continuous output. Unsupervised learning models can autonomously identify the underlying structure of unlabelled data. However, human intervention is often necessary to validate the results [3]. These models are computationally complex because they require a large training set to produce the intended outcomes. Unsupervised learning can be separated into two man types: •Clustering which consists of grouping unlabelled data based on similarities or differences. •Dimensionality reduction is a technique used when the number of features (or dimensions) in a given dataset is too high. It reduces the number of data inputs to a manageable size while preserving the data integrity. As the name suggests, semi-supervised learning is a combination of supervised and unsupervised learning methods [35]. In this approach, a dataset including both labelled and unlabelled instances is used to train the model. Reinforcement learning refers to a category of problems in which an agent interacts with an environment and learns to operate through feedback [50]. The goal is to map situations to actions that maximise a numerical reward signal. The agent is not instructed on which actions to take, but must determine which actions result in the highest reward by experimenting with them. 9
Deep Learning Deep Learning (DL) is a type of machine learning that aims to mimic the way the human brain works by using data inputs, weights and biases, and is more effective at dealing with large amounts of data than traditional ML [28]. DL is capable of processing unstructured data, such as text and images, and can automatically extract features. Figure 2: Relationship between artificial inteligence, machine learning and deep learning, adapted from [23] 2.2.4 Machine learning algorithms and models This section provides details of a variety of supervised learning algorithms relevant to this dissertation. It considers algorithms used in the development of the project, but also provides an understanding of models that have been studied and applied in the context of overstock prediction, as shown in section 2.3. Linear Regression Linear regression (LR) is one of the most common and comprehensive statistical and machine learning algorithms [36]. In the linear regression algorithm a linear combination of input variables is used to calculate the output. Linear regression can be divided into two types: simple regression, when there is only one input variable, and Multiple Linear Regression (MLR), when there is more than one input variable. 10
Decision Trees Decision Tree (DT) is a supervised learning algorithm that can be applied to both regression and classification problems. A decision tree comprises nodes that represent decisions, branches that represent possible outcomes of those decisions, and leaves that represent the final predicted outcomes or target values. Each node in the tree corresponds to a feature or attribute. The branches from each node represent the possible values or ranges of that feature. The tree structure is created by recursively partitioning the data. This is done until a stopping condition is met. At the leaf nodes, the decision tree provides the final predictions or classifications for the given input [9]. When target variables are continuous, it is known as a regression tree, whereas the target variables are discrete these trees are called classification trees. Bagging Bagging, short for Bootstrap Aggregating was firstly proposed in [10] is an ensemble learning technique1 that aims to improve the predictive performance and stability of machine learning models. This is achieved by creating multiple instances of the same learning algorithm, each trained on a different subset of the training data. The subsets are obtained through bootstrapped sampling, which involves randomly selecting data points with replacement. Bagging is a technique that reduces overfitting and variance by introducing diversity in the training data. The Random Forest (RF) algorithm is an example of bagging, in which decision trees are trained independently of each other on different sets of bootstrap samples. The final prediction is determined by aggregating the predictions of the individual trees, either by averaging (for regression) or by majority voting (for classification) [5]. Boosting Boosting is an ensemble method that combines multiple weak learners to create a strong learner. Boosting aims to improve the predictive accuracy of models by addressing their weaknesses in a sequential manner. The key idea is to iteratively build a series of weak models, each addressing the shortcomings of the ensemble, by assigning weights to instances in the training process and emphasising misclassified ones in subsequent iterations. This leads to a robust and accurate final model [21]. Unlike bagging, boosting trains models sequentially, with each model assigning higher weights to instances that were misclassified 1Ensemble learning is a machine learning technique that combines the predictions of multiple models to create a more accurate and robust model. Bagging and Boosting are the two main forms of ensemble learning. 11
time series data. The size of the window can vary depending on the task at hand. This approach can be applied to various stages in the machine learning pipeline, including feature engineering, model training, and performance evaluation. During the training process, a model can be iteratively updated as the window progresses through the dataset. This allows it to highlight local patterns and adapt to the evolving patterns in the data. Figure 8: Rolling window technique Growing Window Technique The growing window technique is a cross-temporal validation technique that involves gradually expanding the time window to incorporate more recent observations. This technique aims to simulate a model’s performance in a real-world scenario, where it must adapt to new data as it becomes available. This technique assists in evaluating the model’s ability to generalise to new data over time. Similar to the rolling window technique, this approach can be applied to various stages in the machine learning pipeline. 18
Figure 9: Growing window technique 2.2.6 Error Metrics and Error Estimation Monitoring and evaluating a model’s performance is crucial to its success. Error metrics and error estimation are the tools used to accomplish this [41]. By providing insight into different aspects of a model’s behaviour, these metrics aid in selecting and tuning models, while also ensuring that the model can generalise to unseen data. Ultimately, these tools are essential in guiding the development and optimisation of machine learning models. Classification Classification methods are used to divide data into different classes of data. There are two main types of classification: binary3and multi-class4. The performance of binary classification models is often represented in a confusion matrix, where each column of the matrix represents predicted instances and each row represents actual instances, as shown in table 10. True Positive (TP) represent instances that have been correctly identified as belonging to the positive class, while True Negative (TN) are instances that have been correctly identified as not belonging to the positive class. False Positive (FP) are instances that have been incorrectly predicted as positive, and False Negative (FN) are instances that have been incorrectly predicted as negative. 3Binary classes are those with two labels (i.e. positive and negative etc.) 4Multi-classes are those having more than two labels (i.e. a degree e.g. low, medium, high etc.) 19
Figure 10: Confusion Matrix The following metrics apply exclusively to binary classification. • Recall - Measures the proportion of actual positives that are correctly identified as positives. Recall =True Positive True Positive +False Negative • Precision - Measures the proportions of positive observations that are true positives. Precision =True Positive True Positive +False Positive • F1-score - Harmonic mean 5of the precision and recall. This metric focuses on one class only. F1 = 2×Precision ×Recall Precision +Recall As per [41], the following metrics are the most commonly applied to binary and multi-class classifiers. • Accuracy - Measures the ratio of correct predictions to the total number of samples. Accuracy =True Positive +True Negative Total Instances • AUC-ROC - Receiver Operating Characteristic (ROC) is a graphical representation summarising the trade-off between the ratio of correctly predicted positive observations and the ratio of incorrectly predicted positive observations across varying threshold levels. Area under the ROC 5The harmonic mean is a type of average that balances values in a series by calculating the reciprocal of each number, averaging them, and then taking the reciprocal of the result. 20
Curve (AUC) measures the two-dimensional area underneath the entire ROC curve. AUROC =Z1 0 True Positive Rate d(False Positive Rate), where True Positive Rate: True Positive True Positive+False Negative , False Positive Rate: False Positive False Positive+True Negative . Regression Regression machine learning methods involve the prediction of a target value by means of independent variables. The most commonly used metrics in the literature are based on methods that calculate the distance between points primarily using subtraction or division operations, and can be supplemented with absolute or squared values. According to [41], below are the most common regression metrics. •Error (E) - Measures the amount by which an observation differs from its actual value. This metric is very intuitive and easy to apply. E=yi−ˆyi, where yiis the actual value for observation iand ˆyiis the predicted value for observation i. •Mean Error (ME) - Measures the mean of all errors in a set. ME =1 n n X i=1 (yi−ˆyi), where nis the number of observations, yiis the actual value for observation i,ˆyiis the predicted value for observation i. •Mean Absolute Error (MAE) - Measures the mean of the absolute values of the errors. MAE =1 n n X i=1 |yi−ˆyi|, where nis the number of observations, yithe actual value for observation i,ˆyiis the predicted value for observation i. •Mean Squared Error (MSE) - Measures the mean of the squares of the errors. This metric is scale dependent and highly dependent on the fraction of data used. MSE =1 n n X i=1 (yi−ˆyi)2, where nis the number of observations, yiis the actual value for observation i,ˆyiis the predicted value for observation i. 21
•Root Mean Squared Error (RMSE) - Measures the root square of mean squared error. This metric is scale dependent and sensitive to outliers. RMSE =v u u t 1 n n X i=1 (yi−ˆyi)2, where nis the number of observations, yiis the actual value for observation i,ˆyiis the predicted value for observation i. •Mean Absolute Percentage Error (MAPE) - Measures the average percentage difference between predicted and actual values. MAP E =1 n n X i=1 yi−ˆyi yi ×100, where nis the number of observations, yiis the actual value for observation i,ˆyiis the predicted value for observation i. 2.3 Machine Learning and Overstock Prediction The findings on the use of machine learning models and traditional mathematical techniques to forecast demand and overstock are summarised in table 3. Statistical models Machine learning and Deep Learning models Model Type Sliding window technique Best performance Metrics References ARIMA ANN, LSTM, XGBoost Regression No XGBoost MSE, MAE [2] - XGBoost Regression No XGBoost RMSE [6] -Linear Regression, XGBoost, Random Forest Regression Yes XGBoost RMSE, MSE, MAE [45] ARIMA, SARIMA Prophet model, LSTM, ANN Regression Yes LSTM RMSE, MAPE [19] - Prophet, LightGBM Regression No LighGBM RMSE [29] SARIMA LSTM Regression No LSTM RMSE, MAPE [20] - LSTM, LightGBM Regression Yes LightGBM RMSE, MAE [46] - LSTM, RNN, GRU, LightGBM Regression No LSTM MAPE [34] - LightGBM, LSTM Classification No LSTM Accuracy [52] Table 3: A literature overview of models applied to overstock and demand prediction As the literature review in the table shows, regression models are commonly used for forecasting demand and overstock scenarios and there is a lack of research on the effectiveness of classification 22
models for these predictive tasks. However, there is an opportunity for further research to investigate and assess the applicability of classification models in the context of overstock prediction scenarios. It’s worth noting that three models, XGBoost,LSTM, and LightGBM, have been identified as effective and frequently used in various studies. This highlights their ability to handle the complexities of inventory management and demand prediction. Studies often use the sliding window to iteratively train models on historical data since it helps to continuously refine the model’s ability to accurately classify instances over time. The evaluated models commonly use RMSE,MSE, and MAE as performance metrics for regression tasks. For classification, commonly used metrics include accuracy and precision. Lastly, it is noted a lack of studies regarding the application of semi-supervised or unsupervised learning techniques to solve the problem of detecting overstock scenarios. 2.4 Machine learning tools and libraries Machine learning tools and libraries are crucial elements that offer a range of algorithms, frameworks, and utilities to simplify the entire machine learning pipeline. Whether dealing with classification, regression, clustering, or complex neural network architectures, these tools provide a range of functions to extract patterns, make predictions, and derive insights from large sets of data. This section provides an overview of the state of the art of the tools that allowed the development of this project, limited by the Data Intelligence & Analytics for Business Operations (DIABO) environment. 2.4.1 Machine learning tools Hadoop is a distributed storage and processing framework that provides the Hadoop Distributed File System (HDFS)6and MapReduce7for batch processing [18]. Apache Spark [55] is an open-source distributed computing system designed for large-scale data processing with in-memory processing, fault tolerance, and versatile APIs, making it ideal for machine learning tasks. Apache Spark can be integrated with the Hadoop ecosystem, providing a powerful combination for distributed data storage and processing. This integration enables the direct reading and writing of data to HDFS, the usage of Hadoop YARN for resource management, among others. Spark can replace Hadoop 6HDFS is a distributed file system designed to store and manage large volumes of data across a cluster of computers within the Hadoop framework 7MapReduce is a distributed data processing paradigm that divides tasks into map and reduce phases, enabling efficient parallel processing across a cluster of computers. 23
MapReduce for batch processing, providing faster and more expressive data processing. The shared cluster model enables Spark and Hadoop to run on the same cluster, leveraging the strengths of both frameworks. PySpark is the Python Application Programming Interface (API) for Apache Spark. PySpark enables the interaction of Python with Spark’s functionalities. It provides a simplified and user-friendly interface, supporting major Spark libraries such as MLlib [38]. Apache Spark, Hadoop, and PySpark are powerful tools to compute, store, and process big data, making them ideal for building machine learning pipelines. 2.4.2 Machine learning libraries Python is the most developer-friendly language for machine learning due to the abundance of open-source libraries available. These libraries help to increase productivity and improve code quality. Listed below are the most commonly used machine learning libraries. •Pandas, a data analysis Python library that is used primarily for data manipulation and analysis [42]. Pandas is an important tool for preparing datasets before training. They offer a range of features, including reshaping and pivoting datasets, merging and joining datasets, handling missing data and data alignment, and various indexing options such as hierarchical axis indexing. Pandas make use of DataFrames, which are a two-dimensional representation of the data. •NumPy is a Python library that concentrates on handling extensive multi-dimensional data. It offers comprehensive mathematical functions, random number generators, linear algebra routines, Fourier transforms, and plenty other useful tools for fundamental scientific computations in Machine Learning. NumPy is fast and versatile. Its vectorization, indexing, and broadcasting concepts are the standards of array computing nowadays [25]. •SciPy is a Python library that provides algorithms for optimisation, integration, interpolation, eigenvalue problems, algebraic equations, differential equations, statistics and many other classes of problems [54]. SciPy is a great tool for image manipulation as well. This library wraps highly optimised implementations written in low level languages. •Scikit-learn is a Python library focused on data modelling. It is built on top of two other libraries, NumPy and SciPy. Scikit-learn supports most of the supervised and unsupervised learning algorithms [13]. This library supports several algorithms such as classification, regression, clustering, dimensionality reduction, among others. 24
• Apache Spark’s MLlib provides a comprehensive set of tools and algorithms for machine learning tasks, it supports several languages, including Python, and provides a high-level API that leverages Spark’s rich ecosystem to simplify the development of end-to-end machine learning pipelines [38]. 25
Part II Core of the Dissertation 26
Chapter 3 Implementation This chapter provides a detailed overview of the implementation process, covering all the key steps required to achieve the solution to RQ2 as posed in section 1.2, following the CRISP-DM methodology. Firstly, the definition of overstock is presented, followed by the process of data collection and dataset creation. Next, the mechanism of input monitoring, which ensures the quality of the dataset, is explained. The following section explains the process of model development in depth, covering hyperparameter tuning, implementation of a growing window for cross-temporal validation, and performance evaluation of the model. The prediction process is then explained, with emphasis on the differences between the predictions of the classification and regression models. Subsequently, the deployment section explains how the enduser is able to take advantage of the developed work. Finally, this section presents the measures taken during the implementation process to optimise computational resources and address the challenge of resource management. 3.1 Overstock definition The definition of Overstock was developed collectively by various stakeholders within the project. The mathematical definition is as follows: overstock = 1,if coverage >max(avg(cdd),avg(pdd)×multiplier +grpt +buffer 0,otherwise where: • coverage is the amount of time the stock will last in days; • cdd is the component delivery deviation1in days; 1Delivery deviation is the difference between planned and actual delivery date of each schedule line. 27
3.5 Prediction To predict whether a material will be in overstock within a given timeframe, the previously trained models are fed a dataset that contains the same features as those referred to in section 3.2, but only for the current day. Classification The prediction of the probability of overstock given the inputs of a certain day in a binary classification task returns: • Prediction - 1 (overstock) or 0 (no overstock) • Probability of prediction - [0,1] After prediction, this model offers a clear classification of whether or not a material will be in an overstock situation within a specified timeframe. Regression In a regression task, where the model’s label is a real value for the coverage of a material on a certain day, the prediction returns a real value. To understand what that value means and determine whether or not a material will be in overstock in a given timeframe, it is necessary to apply the formula present in section 3.1 to the predicted coverage values. Output Monitoring Since the goal of the model is to predict a future value within a given timeframe, it is only possible to calculate the true value of overstock when that amount of time has passed. Once this has occurred, the true value is calculated and compared to the predicted value. This output monitoring module is scheduled to run once a week in order to calculate the metrics associated with the predictions and the actual value observed. The metrics used to monitor and evaluate the performance of the model are the same as those shown in the table 4, which were chosen to evaluate the training process. 34
3.6 Deployment This section introduces the DIABO interface [49] and the mechanisms that allow the end-user to interact and take advantage of the multiple components developed in this work. The pipeline described in previous sections of this chapter is deployed on the interface of DIABO, where it is possible to schedule the run of the model with any frequency. The model is trained on a monthly basis to capture fluctuations in inventory trends efficiently while also ensuring the efficient use of computational resources. The goal is to avoid overwhelming the cluster as the model training process is resource-intensive and time-consuming. However, the user can run the model at any time in case of need. Figure 16 shows the feature that enables scheduling of the model in the interface. Once a month, a new dataframe containing 360 days of data is generated as described in 3.2 and then monitored using the process described in 3.2.2. Input monitoring focuses on predefined thresholds for each metric type to activate alerts, enabling efficient detection of potential data issues. Figure 15 exhibits the input monitoring carried out on the data for a particular plant during a short period of time. For each metric, the dashboard facilitates the identification of potential issues. Figure 15: Input Monitoring Dashboard After the monitoring process, the input data is then prepared to be fed into a model that automatically selects the best combination of hyperparameters, trains in a growing window manner and calculates the average of the training metrics of those windows. 35
The complete flow of data generation, input monitoring and train of the model is shown in figure 17, where the end-user is able to run each part according to their needs. Every day, predictions are calculated using the most recently trained model and fed into DIABO’s alert system. This system, which is beyond the scope of this dissertation, uses the predicted value to generate alerts so that users know which materials will be in overstock in the future.DIABO also provides a lists of the materials that will be in overstock, shown in figure 18, and allows users to plan the needs of the plant and manage inventory according to it. Figure 16: Schedule of a model in the DIABO interface Figure 17: Model train flow in the DIABO interface 36
Figure 18: List of materials in overstock in the DIABO interface It is worth noting that the interfaces shown in Figures 16, 17, 18 were developed by the DIABO development team to display and provide the user with a way to interact with the content developed in this dissertation. 3.7 Computational resources Efficient resource management is crucial when training machine learning models with large datasets to optimise the use of computational resources. It is important to avoid overwhelming system resources. The model training presented a challenge due to running times taking up to 48 hours. Although Apache Spark facilitates parallel processing across multiple machines, mitigating the burden on individual nodes, memory and processing power were a struggle due to limited resources. To address this issue, caching mechanisms were implemented to store frequently accessed data, reducing the need for repeated loading and minimising idle times during the training process. Additionally, due to the tree-based structure of LightGBM, the learning rate and number of trees in the ensemble can result in resource-intensive computations, which may overwhelm the system. Therefore, these hyperparameters were carefully selected to optimise predictive power while preventing computational overload in the hyperparameter tuning phase. The analysis of the code execution was crucial in identifying opportunities for optimisation. Hadoop’s functionality for monitoring runtime behaviour enabled the identification of bottlenecks and areas of inefficiency, which allowed the code to be optimised accordingly. 37
Chapter 4 Results This chapter provides an in-depth analysis of the results obtained in the training and prediction of both classification and regression models, the implementation of which was described in the previous chapter. Furthermore, a comparative analysis of the metrics for these models is carried out, along with a comparison to a rule-based system that was in place at the company before the implementation of these two models. 4.1 Classification 4.1.1 Training Table 5 shows the optimal combination of hyperparameters for the training of the classification model. It should be noted that the learning rate remains constant across all timeframes. Furthermore, the optimal hyperparameters for both the 30-day and 60-day timeframes are identical. However, the 90-day timeframe has a different boosting type and an increased number of leaves. The adjustment to the 90-day timeframe may be due to the fact that longer timeframes can exhibit more complex patterns compared to shorter ones. The model may benefit from a different type of boosting and an increased number of leaves when dealing with longer timeframes. This may be due to the need for a more robust strategy to handle a wider range of patterns. Timeframe learning_rate boosting_type num_leaves 30 days 0.1 gdbt 10 60 days 0.1 gdbt 10 90 days 0.1 dart 50 Table 5: Optimal configuration of hyperparameters in the classification model Table 6 describes the train error metrics for the classification model. The label presented in 3.1 is 38
a very inclusive label for the identification of overstock, the value of the accuracy alongside the precision and recall indicates that there are a lot of overstock cases happening and being correctly predicted, this is also supported by the increasing pattern seen in f1-score and the AUC-ROC. It is expected that all cases of overstock identified in the first timeframe will also be included in the second, and those identified in the second timeframe will be included in the third. Therefore, the 90-day timeframe has the best metrics, as expected. It should be noted that the increase in metrics over a 90- day timeframe is not significantly different from that of the 30-day and 60-day timeframes. This suggests that most cases occur within the first timeframes, which is expected behaviour as it is easier to predict occurrences in a shorter timeframe than many days into the future. Overall it is noted that there’s few cases of false identification of overstock (false positives) since the recall is generally high. Over a 90-day timeframe, there was a decrease in recall compared to the 60-day timeframe which indicates an increase in false negatives however the increase in precision indicates that there was also an increase in overstock cases that were properly identified (true positives). The class distribution may change over timeframes, leading to a higher number of false negatives in the 90-day dataset. Timeframe Accuracy Precision Recall F1-Score AUC-ROC 30 days 0.8298 0.8635 0.8141 0.8381 0.7597 60 days 0.8555 0.9038 0.8939 0.8988 0.8259 90 days 0.8670 0.9691 0.8849 0.9251 0.8321 Table 6: Classification model train performance metrics 4.1.2 Prediction The prediction metrics on table 7 show an expected upward trend. In contrast to the training phase, they are closer to each other, indicating an accurate and robust model was obtained in the training phase. The binary classification model shows strong predictive capabilities for identifying overstock cases across different timeframes (30, 60, and 90 days). The accuracy, precision, and AUC-ROC all increase as the prediction horizon expands, indicating improvement in the model performance over longer timeframes. The precision metric reflects considerable success in identifying overstock. However, there is still room for improvement in identifying non-overstock cases, which suggests that the model may be overfitted. As time passes and the timeframe increases, precision and recall are approaching the ideal scenario of correctly identifying cases with success and reducing the number of false positives. Values above 95% are 39
considered very good in the literature. The accuracy and precision metrics have both improved from the values seen in the training phase, indicating the presence of many true positives. The label accurately predicts instances of overstock, and the precision values suggest that it may be slightly overfitting. Despite efforts to balance the model, overfitting appears to be present during periods with many cases of overstock. This area could be improved. Timeframe Accuracy Precision Recall F1-Score AUC-ROC 30 days 0.9028 0.9286 0.9531 0.9407 0.8210 60 days 0.9113 0.9406 0.9514 0.9459 0.8428 90 days 0.9231 0.9582 0.9493 0.9537 0.8700 Table 7: Classification model prediction performance metrics 4.2 Regression 4.2.1 Training Table 8 shows the optimal combination of hyperparameters for the training of the regression model. In this model, the learning rate and boosting type remain constant across all timeframes. Furthermore, it is worth noting that the optimal number of leaves remains the same for both the 60-day and 90-day timeframes, and is slightly higher than the 30-day timeframe. The fact that the learning rate and boosting are consistent over the three time periods may indicate stability in the patterns and behaviour of the data over the different prediction horizons. Timeframe learning_rate boosting_type num_leaves 30 days 0.1 gdbt 50 60 days 0.1 gdbt 75 90 days 0.1 gdbt 75 Table 8: Optimal configuration of hyperparameters in the regression model Table 9 contains the train error metrics for the regression model. It is important to note that the values for MAE,MSE and RMSE in this table have all been multiplied by a factor in order to provide anonymity to the data. 40
The interpretation of the MAE,MSE and RMSE metrics is not straightforward. Therefore, the main focus is on the MAPE, which provides a percentage representation of the average magnitude of error in the predictions. According to [33], MAPE values ranging from 20-25 indicate reasonable forecasting, however, there is still room for improvement. An unexpected increase is noted in values from the 30-day timeframe to the 60-day timeframe, followed by a decrease in the 90-day timeframe. As MAPE is generally more sensitive to outliers than MAE, this could imply that outliers are present in the 60-day timeframe. This timeframe may exhibit temporal patterns or events that are more prone to outliers compared to the 90-day timeframe. It is possible that shorter-term fluctuations, not present in the 90-day data, lead to outliers affecting the 60-day predictions. The sensitivity of the model to time horizons introduces an interesting dynamic in the context of outlier impact. The model is more sensitive to outliers in shorter timeframes, which can be attributed to the challenges in capturing and generalizing patterns over brief periods. This aligns with observations in the 60-day predictions. In contrast, the 90-day timeframe benefits from a larger data volume, which enhances stability and robustness in predictions. The importance of data scale in model resilience is underscored by the increased sample size, which mitigates outlier influence. Additionally, the selected features and overall model intricacy are more amenable to the 90-day data. Tailored feature engineering or model refinement may be necessary to effectively accommodate short-term variations for the 60-day predictions. The relationship between model sensitivity, data volume, and feature considerations demonstrates the complex nature of prediction dynamics over varying time periods. Timeframe MAE MSE RMSE MAPE 30 days 0.8321 9718.0164 0.9858 23.0482% 60 days 0.9018 17569.5025 1.3255 23.1537% 90 days 0.8145 9269.8384 0.9628 22.8485% Table 9: Regression model train performance metrics 4.2.2 Prediction Table 10 contains the prediction error metrics of the regression model. It is important to note that the values for MAE,MSE and RMSE in this table have all been multiplied by a factor in order to provide anonymity to the data. The error metrics show a clear downward trend, indicating improved accuracy over time. The 90 41
timeframe model has the lowest error metrics, suggesting it can detect longer time patterns as seen previously. The MAPE values for the prediction reflect the expected behavior, and as the timeframe increases, so does the number of cases detected, leading to a reduction in the MAPE. According to [33], a forecasting error value below 20%, as seen in the the 90-day timeframe, is considered good. It is worth noting that this value only differs minimally from the error values of the two other timeframes. The MAPE values may indicate overfitting in the training data, but not necessarily in the prediction phase, as the values have decreased from those seen in the training phase. Therefore, the model is not overfitting and is performing well on the new data. Timeframe MAE MSE RMSE MAPE 30 days 0.7941 8996.5225 0.9485 21.7482% 60 days 0.7853 8650.8601 0.9301 21.0156% 90 days 0.7476 8270.0836 0.9094 19.3916% Table 10: Regression model prediction performance metrics 4.3 Conclusion Table 11 presents a comparative analysis of the accuracy of three different approaches. The first column shows the accuracy of the rule-based approach, which was in place at the company before the implementation of a machine learning model. The second column displays the accuracy values obtained from the prediction of the classification model. The accuracy after applying the overstock formula to the predicted coverage values in the regression model are provided in the third column. Timeframe Rule-based Classification Model Regression Model 30 days 0.7099 0.9028 0.7841 60 days 0.7554 0.9113 0.8099 90 days 0.7620 0.9231 0.8228 Table 11: Comparison of accuracy between different approaches The Rule-based Model consistently exhibits the lowest accuracy across all timeframes, indicating potential limitations in capturing the complexity of the data compared to the other models. 42
The table values demonstrate a significant improvement over a rule-based system, justifying the adoption of a machine learning approach. This is because even the lowest value registered by a machine learning model is still higher than the highest value registered for the rule-based approach. This improvement was expected since a rule-based system lacks the ability to learn patterns and adapt over time to better fit the data. The rule-based approach shows a significant improvement in accuracy between the 30-day and 60-day timeframes, which is not evident in the machine learning approach. This suggests greater stability in the machine learning models. The overstock label was created for a classification system and performs better in classification tasks, as expected. The regression model requires prediction values to be converted to determine if there will be overstock in the selected timeframe. Surprisingly, there is a significant gap in accuracy between the classification and regression models as the metrics indicate that the regression model performs closer to the rule-based model. While the classification model is not optimal and has room for improvement in every timeframe, it is effective at classifying overstock and is a better choice compared to the other two approaches. The classification model demonstrates an ability to fulfill the project’s goal of detecting overstock cases, which is essential for inventory management. Accurate predictions have a direct impact on inventory levels, financial outcomes, and risk mitigation. 43
[44] Kedar Potdar, Taher S Pardawala, and Chinmay D Pai. A comparative study of categorical variable encoding techniques for neural network classifiers. International journal of computer applications , 175(4):7–9, 2017. [45] Puneet, Sugandha Sharma, Deepika Deepika, and Gunwant Singh. Intelligent warehouse stocking using machine learning. In 2021 IEEE International Conference on Mobile Networks and Wireless Communications (ICMNWC) , pages 1–6, 2021. [46] Priyam Saha, Nitesh Gudheniya, Rony Mitra, Dyutimoy Das, Sushmita Narayana, and Manoj K. Tiwari. Demand forecasting of a multinational retail company using deep learning frameworks. IFAC- PapersOnLine , 55(10):395–399, 2022. [47] Tim Schröder and Michael Schulz. Monitoring machine learning models: a categorization of challenges and methods. Data Science and Management , 5(3):105–116, 2022. [48] Umair Shafique and Haseeb Qaiser. A comparative study of data mining process models (kdd, crisp-dm and semma). International Journal of Innovation and Scientific Research , 12:2351–8014, 2014. [49] Pedro M. Silva, João N.C. Gonçalves, Tiago M. Martins, Luís C. Marques, Miguel Oliveira, Marcelo I. Reis, Luís Araújo, Daniela Correia, José Telhada, Lino Costa, and João M. Fernandes. A hybrid bi-objective optimization approach for joint determination of safety stock and safety time buffers in multi-item single-stage industrial supply chains. Computers and Industrial Engineering , 168:108095, 2022. [50] Richard S. Sutton and Andrew G. Barto. Reinforcement learning - an introduction . Adaptive computation and machine learning. MIT Press, 1998. [51] Sean J. Taylor and Benjamin Letham. Forecasting at scale. In Proceedings of the 31st International Conference on Neural Information Processing Systems (NeurIPS) , 2017. [52] Olga Tcheremenskaia, Romualdo Benigni, Ivelina Nikolova, Nina Jeliazkova, Sylvia E Escher, Monika Batke, Thomas Baier, Vladimir Poroikov, Alexey Lagunin, Micha Rautenberg, and Barry Hardy. Opentox predictive toxicology framework: toxicological ontology and semantic media wiki-based opentoxipedia. Journal of Biomedical Semantics , 3(Suppl 1):S7, 2012. 50
[53] David Tranfield, David Denyer, and Palminder Smart. Towards a methodology for developing evidenceinformed management knowledge by means of systematic review. British Journal of Management , 14(3):207–222, 2003. [54] Pauli Virtanen, Ralf Gommers, Travis E. Oliphant, Matt Haberland, Tyler Reddy, Evgeni Cournapeau, David an Burovski, Pearu Peterson, Jonathan Weckesser, Warren an Bright, Stéfan J. van der Walt, Matthew Brett, Joshua Wilson, K. Jarrod Millman, Nikolay Mayorov, Andrew R. J. Nelson, Eric Jones, Robert Kern, Eric Larson, C J Carey, İlhan Polat, Yu Feng, Eric W. Moore, Jake VanderPlas, Denis Laxalde, Josef Perktold, Robert Cimrman, Ian Henriksen, E. A. Quintero, Charles R. Harris, Anne M. Archibald, Antônio H. Ribeiro, Fabian Pedregosa, Paul van Mulbregt, and SciPy 1.0 Contributors. SciPy 1.0: Fundamental Algorithms for Scientific Computing in Python. Nature Methods , 17:261– 272, 2020. [55] Matei Zaharia, Reynold S. Xin, Patrick Wendell, Tathagata Das, Michael Armbrust, Ankur Dave, Xiangrui Meng, Josh Rosen, Shivaram Venkataraman, Michael J. Franklin, Ali Ghodsi, Joseph Gonzalez, Scott Shenker, and Ion Stoica. Apache spark: A unified engine for big data processing. Commun. ACM , 59(11):56–65, 2016. [56] Caiming Zhang and Yang Lu. Study on artificial intelligence: The state of the art and future prospects. Journal of Industrial Information Integration , 23:100224, 2021. [57] Eric Zivot, Jiahui Wang, Eric Zivot, and Jiahui Wang. Rolling analysis of time series. Modeling financial time series with S-Plus® , pages 299–346, 2003. [58] Jinming Zou, Yi Han, and Sung-Sau So. Overview of artificial neural networks. Artificial neural networks: methods and applications , pages 14–22, 2009.
This work is supported by: European Structural and Investment Funds in the FEDER component, through the Operational Competitiveness and Internationalization Programme (COMPETE 2020)[Project nº 179826; Funding Reference: SIFN-01-9999-FN-179826].