scieee AI-readable full text Open interactive document viewer

Porting of vision and image recognition applications to TIDL environments

Ribeiro, Carlos Xavier Fernandes

Abstract

No mundo da Inteligência Artificial (IA), o desenvolvimento de aplicações relacionadas ao machine learning está a tornar-se cada vez mais relevante. Estas aplicações têm a capacidade de resolver problemas que, até então, eram exclusivamente atribuídos aos seres humanos. Ao confiar essas tarefas a aplicações treinadas e autónomas, é possível aliviar os encargos humanos. No entanto, estas aplicações enfrentam desafios significativos devido à complexidade dos cálculos matemáticos e processamento de imagem necessários. Dado o alto nível computacional exigido por estas aplicações, minimizar o uso de recursos torna-se uma prioridade crucial. Isso implica fazer escolhas cuidadosas em relação ao modelo de machine learning, incluindo considerações sobre o número de camadas e a precisão do modelo. Optar por modelos menos precisos, que consomem menos recursos computacionais, torna-se uma estratégia essencial para otimizar o desempenho em sistemas com recursos limitados. Nesse contexto, esta dissertação tem como objetivo principal elaborar uma aplicação de visão por computador para um sistema embebido. Para alcançar esse objetivo, é fundamental selecionar ferramentas e bibliotecas que abordem os desafios contemporâneos das aplicações de visão. Além disso, é necessário desenvolver um modelo de machine learning que atenda a todos os requisitos essenciais, garantindo que ele possa ser implementado numa placa com recursos limitados. Após a realização destas etapas, será crucial avaliar os recursos disponíveis para melhorar a precisão do modelo e aumentar a taxa de acertos. Esta pesquisa não apenas contribuirá significativamente para o avanço científico, mas também auxiliará na superação dos desafios atuais, capacitando a inferência de uma aplicação de visão utilizando o TIDL. Isso será alcançado por meio de um bloco de camadas que pode ser repetido quantas vezes necessário para adequar o modelo às exigências do kit de desenvolvimento da Texas.

Full text

Carlos Xavier Fernandes Ribeiro Instantiation of vision and image recognition applications in embedded systems Dissertação de Mestrado Mestrado Integrado em Engenharia Eletrónica Industrial e Computadores Work performed under the supervision of: Prof. Paulo Cardoso Janeiro 2022 Carlos Xavier Fernandes Ribeiro Porting of vision and image recognition applications to TIDL environments Portabilidade de aplicações de reconhecimento de imagem e visão para ambientes TIDL. Dissertação de Mestrado Mestrado Integrado em Engenharia Eletrónica Industrial e Computadores Trabalho efetuado sob orientação do Professor Doutor Paulo Cardoso Outubro 2023 DIREITOS DE AUTOR E CONDIÇÕES DE UTILIZAÇÃO DO TRABALHO POR TERCEIROS Este é um trabalho académico que pode ser utilizado por terceiros desde que respeitadas as regras e boas práticas internacionalmente aceites, no que concerne aos direitos de autor e direitos conexos. Assim, o presente trabalho pode ser utilizado nos termos previstos na licença abaixo indicada. Caso o utilizador necessite de permissão para poder fazer um uso do trabalho em condições não previstas no licenciamento indicado, deverá contactar o autor, através do RepositóriUM da Universidade do Minho. Licença concedida aos utilizadores deste trabalho Atribuição-NãoComercial-SemDerivações CC BY-NC-ND h tt p s:/ / crea t ive common s .o rg / licen s es / by - nc - n d/ 4.0/ Universidade do Minho, 31-10-20223 Assinatura: i ACKNOWLEDGMENTS I extend my heartfelt gratitude to several individuals who have been instrumental in my journey to completing this master’s dissertation: First and foremost, I am profoundly thankful to my supervisor, Paulo Cardoso, for his unwavering support and invaluable insights that proved indispensable in this project’s completion. To my parents and siblings, mere words cannot encompass my gratitude. Thank you for standing by me during the moments of despair, carrying the burdens, and being my unwavering support system. My deepest appreciation goes to my girlfriend, Cátia Carneiro. Your comforting presence, unwavering support, and encouragement sustained me through the challenges, and for that, I am truly thankful. I am also indebted to my friends, whose kind words and motivation guided me through the toughest times. Special mention to my friend João Borlido, who shared ideas and discussed the best way forward during this long journey. I am grateful for the camaraderie and wisdom shared by Rodrigo Pereira, Inês Pires, Gabriela Viana, Diogo Cerqueira, Eduardo Fernandes, Rui Lima, Simão Leite, Dinis Fernandes, Jorge Pinto, Paulo Pereira, José Gomes, Beatriz Machado, João Faria, Marcelo Amaral, and Daniel Cunha, who have been my companions for these six years. To all of you, your unwavering support, encouragement, and love have made my academic journey and the completion of this dissertation possible. My gratitude knows no bounds. Thank you from the depths of my heart. ii Despacho RT - 31 /2019 - Anexo 4 DECLARAÇÃO DE INTEGRIDADE Declaro ter atuado com integridade na elaboração do presente trabalho académico e confirmo que não recorri à prática de plágio nem a qualquer forma de utilização indevida ou falsificação de informações ou resultados em nenhuma das etapas conducente à sua elaboração. Mais declaro que conheço e que respeitei o Código de Conduta Ética da Universidade do Minho. Universidade do Minho, 31-10-2023 Assinatura: iii Acronyms AI Artificial Intelligence. i, ix, 3, 4, 5, 20, 26, 27, 28 ANN Artificial Neural Networks. i, 11, 13 CNN Convolutional Neural Networks. i, 14, 16, 23, 42, 57 CPU Central Processing Unit. i, 22, 26, 27 CUDA Compute Unified Device Architecture. i, 24, 25 DL Deep Learning. i DSP Digital Signal Processing. i, 26, 27, 28, 31, 34 EVE Embedded Vision Engines. i, 27 GPU Graphics Processing Unit. i, 22, 24, 25, 26, 27 ML Machine Learning. i, vii, 5, 8, 30, 33, 35, 38, 43, 44, 55, 57, 70 ONNX Open Neural Network Exchange. i PCA Principal Component Analysis. i PRU Programmable Real-time Units. i ReLU Rectified Linear Unit. i RL Reinforcement Learning. i SDK Software Development Kit. i SNN Simulated Neural Networks. i SVM Support Vector Machines. i TF TensorFlow. i, xiii, 37, 48, 49, 68 TI Texas Instruments. i, 26, 28, 41 TIDL Texas Instruments Deep Learning. i, vii, x, 26, 31, 32, 33, 34, 37, 40, 41, 42, 43, 45, 46, 49, 54, 55, 56, 58, 59, 65, 70 iv Resumo No mundo da Inteligência Artificial (IA), o desenvolvimento de aplicações relacionadas ao machine learning está a tornar-se cada vez mais relevante. Estas aplicações têm a capacidade de resolver problemas que, até então, eram exclusivamente atribuídos aos seres humanos. Ao confiar essas tarefas a aplicações treinadas e autónomas, é possível aliviar os encargos humanos. No entanto, estas aplicações enfrentam desafios significativos devido à complexidade dos cálculos matemáticos e processamento de imagem necessários. Dado o alto nível computacional exigido por estas aplicações, minimizar o uso de recursos torna-se uma prioridade crucial. Isso implica fazer escolhas cuidadosas em relação ao modelo de machine learning , incluindo considerações sobre o número de camadas e a precisão do modelo. Optar por modelos menos precisos, que consomem menos recursos computacionais, torna-se uma estratégia essencial para otimizar o desempenho em sistemas com recursos limitados. Nesse contexto, esta dissertação tem como objetivo principal elaborar uma aplicação de visão por computador para um sistema embebido. Para alcançar esse objetivo, é fundamental selecionar ferramentas e bibliotecas que abordem os desafios contemporâneos das aplicações de visão. Além disso, é necessário desenvolver um modelo de machine learning que atenda a todos os requisitos essenciais, garantindo que ele possa ser implementado numa placa com recursos limitados. Após a realização destas etapas, será crucial avaliar os recursos disponíveis para melhorar a precisão do modelo e aumentar a taxa de acertos. Esta pesquisa não apenas contribuirá significativamente para o avanço científico, mas também auxiliará na superação dos desafios atuais, capacitando a inferência de uma aplicação de visão utilizando o TIDL. Isso será alcançado por meio de um bloco de camadas que pode ser repetido quantas vezes necessário para adequar o modelo às exigências do kit de desenvolvimento da Texas. v Abstract In the realm of Artificial Intelligence (AI), the development of machine learning applications is becoming increasingly relevant. These applications have the ability to solve problems that were traditionally handled exclusively by humans. By entrusting these tasks to trained and autonomous applications, we can alleviate human burdens. However, these applications face significant challenges due to the complexity of the required mathematical computations and image processing. Given the high computational demands of these applications, minimizing resource usage becomes a crucial priority. This entails making careful choices regarding the machine learning model, including considerations about the number of layers and model accuracy. Opting for less accurate models that consume fewer computational resources becomes an essential strategy to optimize performance in systems with limited resources. In this context, this dissertation aims to develop a computer vision application for an embedded system. To achieve this goal, it is essential to select tools and libraries that address contemporary challenges in vision applications. Furthermore, it is necessary to develop a machine learning model that meets all essential requirements, ensuring it can be deployed on a board with limited resources. After completing these steps, it will be crucial to assess the available resources to enhance the model’s accuracy and increase the success rate. This research will not only significantly contribute to scientific advancement but also help address current challenges by empowering embedded systems with the ability to efficiently and autonomously perform complex computer vision tasks. vi Contents 1 Introduction 1 1.1 Context............................................. 1 1.2 Motivation ........................................... 1 1.3 Objectives ........................................... 2 1.4 Dissertationorganization .................................... 2 2 Literature Review 3 2.1 ArtificialIntelligence....................................... 3 2.2 MachineLearning........................................ 6 2.2.1 SupervisedLearning .................................. 6 2.2.2 UnsupervisedLearning................................. 8 2.2.3 Reinforcement Learning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 2.3 NeuralNetworks ........................................ 11 2.4 DeepLearningNetworks .................................... 13 2.4.1 Convolutional Neural Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.5 ComputerVision ........................................ 20 2.6 Machine Learning Frameworks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 2.6.1 TensorFlow ...................................... 22 2.6.2 TensorFlowLite .................................... 23 2.6.3 PyTorch ........................................ 24 2.6.4 Scikit-learn....................................... 24 2.6.5 Keras ......................................... 24 2.6.6 MXNet......................................... 24 2.6.7 Caffe.......................................... 25 2.7 InstantiationAPI ........................................ 25 2.7.1 NVIDIAJetpack..................................... 25 2.7.2 TIDL.......................................... 26 2.8 HardwareDescription...................................... 26 2.9 Netron ............................................. 28 3 System Design 30 3.1 ProblemDefinition ....................................... 30 3.2 Selection of Tool for ML Training and Inference . . . . . . . . . . . . . . . . . . . . . . . . . 30 3.2.1 Selection Machine Learning Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 vii 1. Introduction This chapter is a gateway to understanding the project’s context within the overarching problem. It provides crucial insights into where the project fits in the larger scheme. The initial section offers vital information, enhancing the reader’s comprehension of the product’s utility and significance. The chapter then explores diverse application areas where the project can make a meaningful impact. It also delves into the motivations that influenced the selection of this specific project, shedding light on the driving factors behind its inception. Crucially, the successful completion of the project is contingent upon achieving all proposed objectives. The subsequent section will outline these objectives, each representing a pivotal step towards the project’s fulfillment. Lastly, the chapter concludes with a detailed presentation of the project and an overview of how this dissertation is organized. This structure provides a clear roadmap, guiding readers through the intricacies of the project and the subsequent sections of this document. 1.1 Context The automotive industry’s range of functionalities within vehicles is constantly expanding. Modern features, such as computer vision, are utilized for image processing and recognition, particularly in applications like Advanced Driver-Assistance Systems (ADAS), Driver Monitoring Systems (DMS), and Occupant Monitoring Systems (OMS). Machine learning algorithms responsible for image recognition form the core of these computer vision applications. These applications operate on embedded platforms specifically designed for the automotive environment. Increasingly, these embedded platforms must keep up with the growing array of new functionalities, leading to an augmentation of resources on the embedded platform. Consequently, transitioning platforms typically requires an effort to adapt the applications. 1.2 Motivation A computer vision inference system is typically based on machine learning (ML) models. These models are generally developed in unrestricted computational environments, requiring adaptation for deployment on embedded hardware solutions. Migrating these models alone poses challenges due to the resource-constrained environment where they will be executed, as the model cannot be directly transposed to the new computational unit. Ideally, creating a tool that allows the adaptation of models to different hardware solutions within a delimited set would be relevant. This dissertation is an initial step towards creating such a tool in the context of embedded platforms for automotive environments. The migration of machine learning models to embedded systems requires careful consideration of resource 1 limitations. Developing a versatile tool for model adaptation is crucial for ensuring optimal performance across varied hardware configurations. This research addresses this need within the specific domain of embedded platforms for automotive applications, laying the foundation for a more flexible and efficient deployment of computer vision models in these environments. 1.3 Objectives Since models are created in environments without resource restrictions, not all layers are directly transposed to an equivalent model running on an embedded system. Additionally, frameworks aimed at model creation have characteristics that can influence the model’s composition. Furthermore, even the layers’ parameters can impact the model’s structure. Thus, in adapting a model for the embedded system, all these issues must be addressed to tailor the model to the hardware. This dissertation aims to study how different layers can be adapted to an embedded environment when their implementation is not partially or fully accepted by the instantiation platform in an embedded environment. This study should contribute to creating a tool capable of automatically adapting models for deployment in embedded systems. Moreover, the research includes the development of a script to facilitate the instantiation of these adjusted models on embedded devices. 1.4 Dissertation organization The first chapter, titled ’Introduction,’ delves into the study’s theoretical framework, general motivation, and primary objectives. The second chapter, ’Literature Review,’ presents essential concepts crucial for the dissertation’s development. Also, it includes exploring machine learning and its subsections, computer vision, machine learning tools, and instantiation frameworks available. Moving on to the third chapter, ’System Design,’ this section explores the chosen framework for deploying the machine learning solution. The chapter also provides possible modifications to a machine learning model and possible solutions. Also, it will cover the project workflow, from data collection and analysis (stage one) to the inference stage (stage three). In the fourth chapter, ’Implementation,’ we will explore implementing a machine learning model instantiation. This section will encompass the detailed implementation steps, and the next chapter, ’Tests and Results,’ will showcase the comprehensive tests conducted to evaluate the chosen approach. Finally, the last chapter - Conclusions and Future Work - presents the main conclusions of the project, as well as some suggestions for future work. 2 2. Literature Review The specific chapter referred to is the literature review section, which delves into the theoretical aspects of the topics explored in this dissertation, primarily focusing on machine learning and computer vision. This section will have an intricate analysis of the fundamental concepts underpinning machine learning to provide a comprehensive understanding of the composition of a machine learning model. Such an in-depth understanding is paramount for the development of the project. Furthermore, the chapter also addresses various machine learning tools and related subjects, including instantiation APIs. 2.1 Artificial Intelligence Many people need more knowledge about artificial intelligence (AI). Most people need to become more familiar with AI, and those who claimed AI was friendly had uncertainties about what AI entails. Despite its widespread, as said before, it is unfamiliar among the public, but it is a technology reshaping various aspects of our lives. It is a versatile tool that allows us to review how data is processed and how information is taken into account in decision-making. What is the artificial intelligence? Artificial Intelligence is a multidisciplinary field that focuses on creating intelligent machines capable of performing tasks that typically require human intelligence. These tasks include learning, reasoning, problem-solving, perception, and language understanding. AI technologies have advanced significantly, enabling machines to process vast amounts of data, recognize complex patterns, and make decisions in real-time. AI systems are used in various applications, from virtual assistants and language translation to autonomous vehicles and healthcare diagnostics [1]. Figure 2.1: Artistic vision of artificial intelligence 3 Artificial Intelligence, or AI, is a broad field encompassing different types of intelligent systems designed to mimic human cognitive functions. These types of AI can be categorized into several distinct groups, each serving specific purposes in the realm of technology and innovation [2]. •Narrow AI (Weak AI): Narrow AI refers to AI systems designed to perform specific tasks or solve specific problems. Examples include virtual assistants like Siri and chatbots used in customer service applications. •General AI (Strong AI): General AI is a theoretical concept where machines possess human-like intelligence and are capable of understanding, learning, and reasoning across diverse tasks. Achieving General AI remains a long-term goal in the field of AI research. •Machine Learning: Machine learning is a subset of AI that involves training algorithms to learn patterns from data and make predictions or decisions without being explicitly programmed. It is widely used in applications such as image and speech recognition, recommendation systems, and fraud detection. AI has become a linchpin in various sectors, shaping the landscape of innovation and efficiency. AI facilitates medical imaging analysis in healthcare, aids in drug discovery, tailors personalized treatment plans, and even predicts disease outbreaks. Diagnostic accuracy and efficiency have significantly improved with the integration of AI-powered tools. Figure 2.2: Artificial intelligence applications Similarly, the financial sector harnesses the power of AI through algorithms that analyze market data, predict stock prices, and optimize trading strategies. AI-driven robo-advisors offer tailored investment advice, enhancing the financial decision-making process for individual investors. Moreover, AI is the cornerstone in developing autonomous systems, including self-driving cars, drones, and robots. These systems rely on AI algorithms to perceive their environment, make decisions, and navigate safely without human intervention. In robotics, AI-powered robots find applications in manufacturing, warehouses, and healthcare settings, undertaking tasks such as assembly, material 4 handling, and surgery assistance. The integration of advanced robotic systems has significantly enhanced efficiency and precision across various industries, underscoring the transformative impact of AI in today’s world [3]. The continuous evolution of AI technologies holds the promise of transforming various sectors, driving innovation, and shaping the future of human-machine interactions. Researchers and developers continue to explore new avenues, ensuring that AI systems become increasingly sophisticated, reliable, and beneficial for society. As the name says, artificial intelligence models and simulates how humans think and act. As an old concern, ancient philosophers tried to discover different methods to describe thought and human knowledge. A machine can help humans solve problems without human intervention if this is possible. Artificial Intelligence is the foundational concept in intelligent systems, empowering machines to simulate human intelligence. It encompasses diverse technologies, reshaping how we perceive and interact with the digital world. AI is the cornerstone upon which the entire framework of intelligent systems is constructed, representing the inception point for technological advancement. Beneath the overarching concept of AI lies machine learning (ML), a pivotal domain that enables machines to recognize patterns, predict outcomes, and optimize decisions without explicit programming. ML algorithms are the foundation for numerous intelligent applications, forming the practical realization of AI’s potential. They enhance efficiency across various industries, revolutionizing how tasks are accomplished. Moving further down the hierarchy, we encounter Artificial Neural Networks (ANNs), intricate systems inspired by the complex workings of the human brain. Comprising interconnected nodes or ”neurons,” ANNs specialize in pattern recognition tasks. They mirror the biological processes of learning and decision-making, adding a layer of sophistication to machine learning applications. At the forefront of technology within the AI domain, Deep Learning (DL) Networks operate within complex configurations of Artificial Neural Networks, often comprising multiple hidden layers. Deep Learning algorithms empower machines to decipher intricate patterns from vast datasets autonomously. This capability enables them to excel in tasks such as image recognition, language processing, and autonomous decision-making, marking the pinnacle of AI implementation. In summary, AI provides the foundation, machine learning refines practical applications, Artificial Neural Networks introduce complexity, and Deep Learning Networks exemplify the highest level of sophistication within the progressive hierarchy of intelligent systems, as it is possible to see in Figure 2.3. 5 Figure 2.3: Artificial intelligence underneath concepts 2.2 Machine Learning Machine learning is a scientific field exploring the development of algorithms and statistical models computer systems utilize to execute specific tasks without the need for explicit programming. Learning algorithms find applications in our daily lives, such as when we perform web searches using engines like Google. A significant factor contributing to their effectiveness is the utilization of learning algorithms that have acquired the ability to rank web pages intelligently. These algorithms have many applications, including data mining, image processing, and predictive analytics. One of the primary advantages of employing machine learning is its automation; once an algorithm has learned how to process data, it can autonomously carry out its designated tasks [4]. Machine learning utilizes a variety of algorithms to tackle diverse data-related challenges. Data scientists emphasize that there is a variety of algorithms that excel in every situation. The choice of algorithm hinges on factors such as the specific problem at hand, the number of variables involved, the ideal model for the task, and similar considerations. Let’s briefly overview some commonly employed machine learning algorithms. 2.2.1 Supervised Learning Supervised learning is a fundamental task in machine learning, where the objective is to learn a function that can map input data to corresponding output data based on provided example pairs of input-output data. This process involves deriving a procedure from a labeled training dataset, which consists of a collection of training examples, where each example has both input and corresponding output labels. Supervised machine learning algorithms require external guidance and follow a specific workflow. Initially, the input dataset is typically divided into two subsets: the training and test datasets. The training dataset contains instances with known output variables the algorithm aims to predict or classify. These algorithms learn underlying patterns and relationships from this training dataset. Once trained, they apply this knowledge to the test dataset to make predictions or classifications for previously unseen data. The workflow of supervised machine learning algorithms can be visualized in the figure 2.4. In the subsequent 6 sections, we will delve into some of the most renowned supervised machine learning algorithms [4]. Figure 2.4: Workflow of Supervised Learning Process. Insights from [4]. Decision Tree A decision tree is like a roadmap that shows different choices and what happens when you make those choices. It’s called a tree because it looks like an upside-down tree with branches and nodes. In this tree, the nodes are like stops along the way, representing things you can do or decide. The lines connecting them are like the directions or rules for making those decisions. So, each node is a group of things you want to sort into categories, and each line tells you what choice or value that group can have [5]. In picture 2.5, it is possible to observe an example of a decision tree that involves a choice between a small animal group. Figure 2.5: Decision Tree Analysis for Animal Classification. Insights from [4]. Naive Bayes Bayes’ rule allows us to determine the chance of something (Y) happening based on a particular characteristic or feature (X). However, in real-world situations, we usually have more than one characteristic to consider. When these characteristics don’t affect each other, Naive Bayes can be used. It’s called ”naive” because it assumes that all the elements are independent, meaning changing one doesn’t impact the others. This simplification makes the math easier. Naive Bayes can be handy in many applications like recognizing faces, predicting the weather, diagnosing 7 medical conditions, sorting news articles, understanding sentiments in text, and much more [6]. Support Vector Machines Support Vector Machines (SVM) are the most widely used ML technique-based pattern classification techniques available nowadays. It is based on statistical learning theory and was developed by Vapnik in 1995 [7]. Support Vector Machines have found use in various real-world challenges, including tasks like sorting text into categories, recognizing handwritten numbers, identifying tones in audio, classifying images and spotting objects within them, analyzing data related to gene expression on microarrays, and categorizing data. Also, SVMs have demonstrated effectiveness by consistently outperforming other supervised learning methods in many situations. However, it’s important to note that how well SVMs perform for specific datasets can be significantly influenced by how we set two key parameters: the cost and kernel parameters. 2.2.2 Unsupervised Learning Unsupervised learning, unlike the supervised learning discussed earlier, operates differently. There are no correct answers here, and no teacher is guiding the algorithms. These algorithms are left to their own devices to uncover and reveal exciting patterns within the data. In unsupervised learning, algorithms extract key features from the data. When new data is introduced, these algorithms rely on the previously learned features to classify or group the latest data. Unsupervised learning is primarily used for two primary purposes: reducing the number of features in the data to simplify its analysis and clustering similar data points together based on some inherent characteristics of the pictures like color, size, and shape. The image describes the training network connection. It is equally denoted as self-organizing. Figure 2.6: Workflow of Unsupervised Learning Process. Insights from [4]. Figure 2.6 illustrates the training network connection. This type of connection is also known as a self-organizing or adaptive learning algorithm because it operates without external guidance. Instead, it relies solely on the information in the data it encounters. This algorithm doesn’t require external sources to provide it with information. Instead, it uses its internal mechanisms to learn and adapt to the essential information present in the input data. The system is presented with training figures and input patterns during the training process. The system then organizes this data into 8 categories or clusters based on the inherent patterns it discovers [8]. For a more precise understanding, you can refer to the illustration in Figure 2.7, which provides a straightforward example of unsupervised learning. In this scenario, they work with unlabeled input data, which lacks predefined categories or corresponding outputs. The goal is to train a machine learning model using this unlabeled data. The process begins with data interpretation, where the raw data is analyzed to uncover concealed patterns. Following this interpretation, the model applies appropriate algorithms, such as k-means clustering, to process and categorize the data further. Figure 2.7: Visualization of Unsupervised Learning in Action: An Example Showcase K-Means Clustering K-means is a straightforward, unsupervised learning algorithm that addresses the widely recognized clustering problem. The process offers a simple and effective means of categorizing a given dataset into a specific number of clusters. The core concept involves establishing ”k” centers, each corresponding to a cluster. Positioning these centers is crucial because their locations can significantly impact the clustering outcome. The preferred strategy is to set them as far apart as possible to achieve more accurate results [9]. To better understand how K-means addresses the clustering problem, refer to the visual representation in Figure 2.8. As depicted, K-means establishes three centers in separate regions. Figure 2.8: Workflow of K-means Clustering Process. Insights from [4]. Principal Component Analysis Principal Component Analysis (PCA) is a technique for reducing the complexity of large datasets by 9 transforming numerous variables into a smaller set while retaining the most essential data information. It’s important to acknowledge that there will be some loss of precision when reducing the number of variables in a dataset. However, the key to dimensionality reduction is to trade off some accuracy for simplicity. Smaller datasets are more manageable and visually comprehensible. Moreover, they eliminate unnecessary variables, making data analysis more efficient and quicker for machine learning algorithms [10]. Figure 2.9: Visualizing the Workflow of Principal Component Analysis Process. Insights from [4]. Examining Figure 2.9 gives you a clearer insight into how PCA works. In this illustration, you’ll notice that the arrow and the square in the initial data have been removed from the final dataset because they don’t correlate significantly with the other data points. 2.2.3 Reinforcement Learning Reinforcement Learning (RL) involves learning by interacting with the environment. In RL, an agent knows the consequences of its actions rather than being explicitly taught, and it makes decisions based on its experiences and new choices, essentially using a trial-and-error learning approach. Unlike traditional supervised learning, where specific input/output datasets are provided, RL doesn’t rely on such precise data sets. Instead, the focus is on a process that balances exploration, trying out new uncharted paths, and exploitation of the known data [11]. To get a detailed view of the training network in the context of reinforcement learning, you can refer to Figure 2.10. Figure 2.10: Workflow of Reinforcement Learning Process. Insights from [4]. An example is presented in Figure 2.11 that illustrates reinforcement learning is similar to a situation involving a rat as the agent, a maze as the environment, and a piece of cheese as the target. In this scenario, the rat attempts to discover the shortest route from a starting point within the maze to the cheese. 10 To classify an image, it must pass through a classification network. However, before this step, the outputs from convolutional and pooling layers must be flattened into a single vector. This process is crucial to transform the extracted features into a format suitable for input into a classification neural network, allowing for accurate image categorization [22]. Figure 2.18: Unraveling the Flatten Layer Process: A Visual Explanation To determine the number of neurons after the Flatten layer, it was necessary to multiply the height, the width, and the channels. In the example of Figure 4.10, if the input has dimensions 3∗3∗5, the resulting vector will have 3∗3∗5 = 45. Each position corresponds to a specific neuron in the flattened layer, representing the extracted features from the original input. Fully connected layer The output feature maps from the final convolution or pooling layer are usually flattened, transforming them into a one-dimensional (1D) array or vector of numbers. One or more fully connected layers, also known as dense layers, link to this array. Every output in these layers connects every input through learnable weights. A subset of fully connected layers processes the features extracted by the convolutional layers and downsampled by the pooling layers. They are prepared to generate the final outputs of the network, like the probabilities for each class in classification tasks. The last fully connected layer typically has the same number of output nodes as the total number of classes. A nonlinear function, such as ReLU, follows each fully connected layer to introduce the necessary non-linearity into the network, as described previously [23]. 17 Figure 2.19: Illustration of a Connection Between Two Fully Connected Layers In Figure 2.19, the diagram illustrates the connection between two fully connected layers. As observed, the output neurons in ”fully connected layer 2” receive information from all the preceding neurons. The three fundamental layers in a convolution neural network were explained regarding their associated mathematical functions or functionalities. Before reaching the fully connected step, it’s crucial to transform the three-dimensional input into a one-dimensional output. Specific layers exist designed to achieve this dimension alteration. Therefore, it is essential to delve deeper into layers related to data shaping for effective processing. Dropout layer Various layers play a crucial role in enhancing inference performance and optimizing memory usage in neural networks. For instance, the dropout layer is a notable example. It helps by deactivating specific neurons during training, thus reducing memory requirements and enhancing overall network efficiency. In deep learning, more trainable parameters are desirable for extracting detailed features. However, an excessive number of parameters can lead to overfitting, where the model becomes too specialized and performs poorly on new data. Dropout addresses this issue by introducing randomness, and various layers play a crucial role in enhancing inference performance and optimizing memory usage in neural nodes to work independently and distribute responsibilities more evenly, preventing overreliance on specific nodes or features. This approach disrupts situations where layers might excessively co-adapt to correct prior mistakes. By breaking up these co-adaptations, dropout builds a robust and generalizable model. It is widely used in deep learning tasks to enhance overall performance and generalization of neural networks [24]. 18 Figure 2.20: A: Standard Neural Network. B: Neural Network with Dropout Layer - Depicting the Impact of Dropout. Figure 2.20 illustrates the impact of dropout in a neural network. Specifically, specific neurons in the hidden layer lose their connections temporarily during training, effectively being ignored in that stage. This dropout mechanism enhances the network’s robustness, improving generalization during learning. Batch Normalization layer Continuing with another essential layer in enhancing inference performance and optimizing neural networks, the batch normalization layer plays a pivotal role. It has markedly improved the efficiency and ease of training deep convolutional neural networks in deep learning. As networks grow deeper, training them becomes challenging due to various problems. Batch normalization addresses these challenges by normalizing the output of convolutional layers after scaling and shifting, occurring before activation layers. This process is followed by passing the normalized output to activation layers and subsequent convolutional layers [25], [26], [27]. µi=1 MXXi(2.4) σi=r1 MX(Xi−µi)2(2.5) Xi=Xi−µi σi (2.6) Mrepresents the total number of available samples. Xisignifies an individual feature, while µiand σidenote the mean and variance, respectively, for each feature. Figure 2.21: Exploring the Internal Phases of Batch Normalization 19 Figure 2.21 exposes all the process interior of a Batch Normalization. Firstly, the outcomes from the previous layer are passed as input to the Batch Normalization. There is one vector for each feature in the data. After that comes the mean and variance that can be calculated through the equations 2.4 and 2.5, respectively, for each feature and each value calculated to estimate the feature normalized through the function 2.6 The innovation introduced by Batch Normalization is groundbreaking. Unlike the input layer, where all normalized values must have zero mean and unit variance, BatchNorm allows values to be shifted (to a different mean) and scaled (to an additional variance). This is achieved by multiplying the normalized values by γand adding a factor, β. These factors are not fixed hyperparameters provided by the model designer; they are trainable parameters learned by the network. In other words, each Batch Norm layer can dynamically determine the best factors for itself. This ability allows Batch Norm to optimize the shifting and scaling of normalized values, leading to more accurate predictions [28]. . It’s crucial to understand that batch normalization functions differently during training and inference. During training, mean and variance are calculated for each batch individually, as was explained in the previous paragraphs. During the inference phase (when the trained model is used to predict new, unseen data), the model must work with individual samples or smaller batches rather than a large dataset. Therefore, using the mean and variance of the current batch for normalization might be better. Instead, batch normalization uses the moving average of mean and variance calculated during the training phase. These moving averages are stored and utilized during inference to normalize the inputs. This approach ensures that the model’s behavior is consistent between training and inference, and it also helps generalize well to unseen data [25]. 2.5 Computer Vision One of the most compelling applications of AI is computer vision. Computer vision is the field of computer science that focuses on replicating parts of the complexity of human vision and enabling computers to identify objects in images or videos [29]. Computer vision’s primary goal is to interpret spatial data and events from input scenes, employing methods that vary based on the application domain and data characteristics. It aims to replicate human vision abilities, although limitations in system performance exist compared to the human eye. Challenges include algorithm sensitivity and accuracy, impacting the complexity of evaluating system performance. 20 Figure 2.22: Contrasting Human Vision with Computer Vision: Insights from [30]. Figure 2.22 illustrates the comparison between human vision and computer vision. Human vision relies on the eye as the sensing device, capturing environmental images. In contrast, computer vision utilizes cameras as the sensing devices. Regarding the interpreting process, the human brain comprehends image content, while in computer vision, this role is performed by the computer. The development of computer vision depends on advancements in computer technology, focusing on improving image quality and recognition. There is an overlap with image processing, but computer vision emphasizes extracting information from images, while image processing focuses on computational transformations. Additionally, computer vision intersects with human-computer interaction, involving technology interaction’s design and interface aspects. Researchers have categorized computer vision into various areas, such as image processing, object recognition, and machine learning. Efforts to enhance computer vision’s performance have led to diverse applications, including automation, remote sensing, robotics, and tools for the visually impaired [31], [32]. Here are a few common tasks that computer vision systems can be used for: •Object detection. The system parses content and classifies the object on a image/video. For example, the system can find a dog among all the objects in the image. •Object identification. The system parses content and classifies the object on a image/video. For example, the system can find a specific dog among all the dogs in the image. •Object tracking. The system processes video the object/objects that match search criteria and track its movement. At its core, computer vision revolves around pattern recognition. A common approach to enable a computer to comprehend visual data involves providing a vast dataset of labeled images, ranging from thousands to millions. These images are then processed through various algorithms designed to identify specific patterns associated with the provided labels [33]. For instance, if the algorithm is exposed to a million images of cats, it meticulously analyzes elements such as colors, shapes, and the spatial relationships between these shapes. This analysis allows the algorithm to construct a detailed cat profile, enhancing its ability to recognize cats in new images. 21 Notably, computer vision algorithms often exhibit higher precision when working with grayscale images. A single 8-bit number, ranging from 0 (black) to 225 (white), represents each pixel’s brightness in grayscale, which simplifies the complexity of the data, enabling more accurate pattern recognition [33]. Machine learning introduced a novel method for addressing computer vision challenges. Machine learning offered a different paradigm, unlike the traditional approach that required developers to code all the rules for their vision applications manually. Developers now focused on creating ”features,” smaller applications that recognize specific patterns within images. These features were then integrated into the system, and statistical learning algorithms like linear regression, logistic regression, decision trees, or support vector machines (SVM) were applied. These algorithms enabled the detection of patterns, classification of images, and identification of objects within them, eliminating the need for extensive manual coding. 2.6 Machine Learning Frameworks Machine learning frameworks are software libraries or platforms that simplify the development and deployment of machine learning models. They provide a comprehensive set of tools, APIs, and infrastructure to handle various tasks such as model building, compilation, training, evaluation, and deployment. These frameworks offer a high-level API that abstracts away the complexities of machine learning algorithms, making it easier for developers to manage all the functionalities efficiently. With these frameworks, developers can focus on designing and implementing models, leveraging the provided tools and APIs to streamline the entire machine learning workflow, from data preprocessing to model deployment. The upcoming sections will provide information about some of the most widely used machine learning frameworks. These tools share similarities, but each possesses unique features that make them valuable in specific situations. Additionally, the choice of framework compatibility can influence the selection of a particular tool during the instantiation process. 2.6.1 TensorFlow TensorFlow (TF) is highly versatile, supporting deep learning and traditional machine learning algorithms. Its flexible architecture allows for efficient execution on diverse hardware platforms, including Central Processing Units (CPUs) and Graphical Processinf Units (GPUs). TensorFlow’s extensive ecosystem offers a wealth of pre-built models, tools, and resources, making it suitable for various applications. Also, it provides a diverse range of available datasets for its users to use. These datasets are designed to facilitate developing and evaluating machine learning models across various domains and tasks. This dataset can be accessed in different ways. Firstly, it can be accessed through TensorFlow Datasets. This library provides a collection of preprocessed, ready-to-use datasets and utility functions for loading, preprocessing, and manipulating the data. It also covers various domains, including computer vision, natural language processing, audio, etc. The second way is TensorFlow Addons, a repository of community- 22 contributed extensions and additional functionality for TensorFlow. It includes various datasets and data loaders, such as image datasets like CelebA and CIFAR-10, text datasets like IMDB sentiment analysis, and more. TensorFlow can also work with datasets from external sources. You can manually download datasets from websites or other repositories and load them into TensorFlow using standard file I/O operations. TensorFlow provides flexible APIs to handle diverse data formats, including CSV, JSON, image files, audio files, and more. Users can create custom datasets by implementing their data loading and preprocessing pipeline using TensorFlow’s data API. This allows you to leverage TensorFlow’s powerful data manipulation capabilities and integrate your data seamlessly with the training process [34]. 2.6.2 TensorFlow Lite TensorFlow Lite is a lightweight and efficient version of the TensorFlow framework, specifically designed for mobile and embedded devices. It enables the deployment of machine learning models on resource-constrained platforms, such as smartphones, IoT devices, and microcontrollers, while maintaining high performance and low latency. TensorFlow Lite offers a range of features that enable efficient deployment of machine learning models: • Model Optimization: TensorFlow Lite incorporates various optimization techniques to reduce models’ size and improve inference speed and memory usage. One of these techniques is model quantization, which reduces the precision of model weights and activations while maintaining acceptable accuracy levels. Additionally, weight pruning can be applied to remove unnecessary parameters from the model, further reducing its size and enhancing efficiency. • Cross-Platform Support: TensorFlow Lite supports multiple platforms, including Android, iOS, Linux, microcontrollers, and custom hardware accelerators. This versatility allows developers to deploy models across various devices and operating systems, ensuring broad accessibility and applicability. • Model Conversion: TensorFlow Lite offers convenient tools for converting models from popular deep learning frameworks, such as TensorFlow and Keras, into the TensorFlow Lite format. This conversion process optimizes the models for deployment on mobile and embedded devices. By converting models into the TensorFlow Lite format, developers can take advantage of its lightweight nature and specific optimizations for efficient execution on resource-constrained platforms. • Support for Neural Networks: TensorFlow Lite supports a wide range of neural network architectures, including convolutional neural networks (CNN), recurrent neural networks (RNNs), and transformer models. This extensive support allows developers to deploy diverse machine learning models on resource-constrained devices, enabling a wide range of applications, including image and speech recognition, object detection, and natural language processing [35]. 23 2.6.3 PyTorch PyTorch is a popular open-source machine learning framework known for its dynamic computational graph and robust GPU acceleration. It provides a user-friendly interface and rich tools for developing and training deep learning models. With its seamless integration with Python and extensive ecosystem, PyTorch has become a go-to choice for researchers and developers. Its dynamic nature allows for on-the-fly graph modification, making debugging and experimentation easier. PyTorch also offers various pre-defined modules and functions for building complex neural network architectures. Its efficient GPU support through Compute Unified Device Architecture (CUDA) enables accelerated training and provides convenient utilities for data loading, model evaluation, and serialization. With its active community support and popularity in the deep learning community, PyTorch remains a preferred framework for building cutting-edge machine learning models [36]. 2.6.4 Scikit-learn Scikit-learn is a widely used open-source machine-learning library in Python. It provides a comprehensive set of tools and algorithms for various machine learning tasks, including classification, regression, clustering, and dimensionality reduction. Scikit-learn is known for its simple and intuitive API, making it accessible for beginners and experienced practitioners. It also offers extensive data preprocessing, feature engineering, and model evaluation support. With its rich collection of algorithms and ease of use, Scikit-learn is a valuable tool for building machine learning models and conducting data analysis [37]. 2.6.5 Keras Keras is a high-level deep learning library with a user-friendly interface for building neural networks. It is built on top of other deep learning frameworks like TensorFlow, allowing users to define and train complex neural network architectures efficiently. Keras focuses on simplicity and productivity, providing a consistent and intuitive API for designing models, handling data, and optimizing parameters. It offers a wide range of pre-built layers, activations, optimizers, and support for advanced features like transfer learning and model serialization. With its user-friendly approach and compatibility with popular deep learning frameworks, Keras is widely used for prototyping and developing deep learning models [38]. 2.6.6 MXNet MXNet is a flexible and efficient deep learning framework for research and production. It provides a scalable and distributed architecture, allowing users to train and deploy deep learning models on various platforms and devices. MXNet offers a hybrid front-end that combines declarative and imperative programming paradigms, allowing users to define models with symbolic graphs or crucial code. It supports a wide range of neural network architectures and 24 provides GPU acceleration for fast and efficient training. MXNet also offers comprehensive APIs for data loading, model visualization, and deployment to production environments. With its focus on performance and scalability, MXNet is a powerful tool for developing and deploying deep learning models at scale [39]. 2.6.7 Caffe Caffe is a deep learning framework specializing in efficiency, speed, and model optimization. It is trendy in the computer vision community and is widely used for image classification, object detection, and segmentation tasks. Caffe provides a simple and expressive architecture definition language, allowing users to define complex neural network architectures easily. It leverages GPU acceleration to speed up training and inference, making it suitable for real-time applications. Caffe also includes a model zoo with pre-trained models, enabling users to apply state-of- the-art models to their tasks quickly. With its emphasis on efficiency and its extensive use in computer vision, Caffe is a valuable tool for developing and deploying vision-based deep learning models [40]. 2.7 Instantiation API Instantiation of machine learning involves preparing the development environment and installing the essential libraries and tools that enable the implementation and deployment of machine learning models. Several steps need to be followed to instantiate machine learning models. Firstly, one must identify the specific requirements of the project or task at hand. This includes determining the programming language, framework, and libraries that align with the project’s objectives and constraints. Next, the selected machine learning framework needs to be installed. Popular frameworks such as TensorFlow, PyTorch, or scikit-learn are commonly chosen for their extensive functionalities and community support. Once the framework is installed, additional libraries and dependencies may need to be incorporated. These can include data manipulation libraries like NumPy and Pandas or specialized libraries for tasks such as natural language processing or computer vision. 2.7.1 NVIDIA Jetpack NVIDIA JetPack is a software development package designed to facilitate the creation of AI-powered applications on NVIDIA Jetson devices. It includes various components, tools, and libraries that simplify and accelerate development. JetPack leverages the CUDA Toolkit for GPU-accelerated computing, enabling developers to harness the power of NVIDIA GPUs. The Deep Learning Software Development Kit (SDK) optimizes deep learning workflows and inference with libraries like cuDNN and TensorRT. VisionWorks provides GPU-accelerated computer vision capabilities. JetPack also includes Jetson-specific software components for seamless integration with hardware. NVIDIA continuously updates JetPack, offering the latest features and resources, comprehensive 25 documentation, and samples for efficient development. Overall, JetPack empowers developers to build cutting-edge AI solutions for edge applications. 2.7.2 TIDL Texas Instruments Deep Learning (TIDL) is a software framework developed by Texas Instruments for enabling deep learning on their embedded processors. Designed for edge computing applications, TIDL simplifies the deployment of deep learning models on Texas Intruments (TI) processors by providing tools, libraries, and APIs. It optimizes models for efficient execution on resource-constrained devices through techniques like quantization and model compression. TIDL includes a runtime library for seamless integration, supporting offline and real-time inferencing scenarios. Additionally, it offers tools for model conversion, profiling, and optimization, streamlining the development process. TIDL empowers developers to leverage deep learning capabilities on TI embedded processors, enabling intelligent and autonomous systems in edge computing applications. Begin by installing the TIDL software framework and ensuring access to the necessary hardware resources, such as TI processors based on the C66x Digital Signal Processors (DSP) architecture. Creating a solution using TIDL is similar to using NVIDIA JetPack, with the main difference lying in the tools and libraries utilized in each framework, as is seen in the following steps. 2.8 Hardware Description When choosing the hardware for deploying a model, the Jetson TX2 and the BeagleBone AI are two popular options. Different companies produce these devices and have distinct characteristics that set them apart. The Jetson TX2 is a product of NVIDIA, a renowned company in the field of GPUs and AI. It is a compact, robust, single-board computer designed for edge AI applications. The Jetson TX2 features a quad-core ARM Cortex CPU and an NVIDIA Maxwell GPU, providing excellent computing power for running deep learning models. It supports popular AI frameworks like TensorFlow, PyTorch, and Caffe, making it easy to deploy trained models. With GPU acceleration capabilities, the Jetson TX2 excels in applications that require real-time inference on the edge. 26 three main modules were identified: model transformation, model training, and finally, model inference. Figure 3.2: System overview Examining the illustrative workflow diagram in Figure 3.2, it is imperative to guarantee that the model used in training is incompatible with TIDL. These possible transformations are done in the module one. Ensuring compatibility, the ML model can train through TensorFlow using the dataset that the user must have previously identified. Once the training is accomplished, all the configurations needed by TIDL are assured. Finally, in the inference module, the inference is done according to the target the user identifies. Some images from the dataset are used for instantiation, where the predictions are saved, and when all photos are instantiated, all the projections are shown with respective accuracy. 3.4.1 Model transformation Module The module’s name is enlightening and responsible for making any change or not making the ML model compatible with the instantiation API. But firstly, it is necessary to identify the possible incompatibilities with the TIDL. As previously presented, TIDL is a set of packages and tools for ML inference supporting the EVE and DSP hardware accelerators implemented on TI SoCs, hiding the complexity of managing this heterogeneous computing device in the context of ML applications. The BeagleBone AI contains the TI AM5729 processor compatible with TIDL being a primary testbed for instantiation of ML models. Despite being a small platform with a lack of resources and unable to deploy large models, it allows us to address the issue of deploying an ML model into these devices using TIDL. Table 3.1 shows the supported layers by TIDL and its direct mapping to TensorFlow Lite layers. Other TFLite layers must be, in one way or another, mapped in one of these TIDL layers when they appear in a model. 33 TensorFlow Lite Operator TIDL Layer Placeholder TIDL DataLayer CONV 2D TIDL ConvolutionLayer TRANSPOSE CONV TIDL Deconv2DLayer DEPTHWISECON 2D TIDL ConvolutionLayer ADD TIDL EltWiseLayer MUL TIDL ScaleLayer RELU TIDL ReLULayer MAX POOL 2D TIDL PoolingLayer AVERAGE POOL 2D TIDL PoolingLayer CONCATENATION TIDL ConcatLayer RESHAPE See note below SOFTMAX TIDL SoftMaxLayer ARG MAX TIDL ArgMaxLayer PAD TIDL PadLayer MEAN TIDL PoolingLayer FULLY CONNECTED TIDL InnerProductLayer Table 3.1: The TensorFlow Lite Operators that can be acepted by TIDL Note: If “Reshape” immediately follows TIDL InnerProductLayer, it is coalesced into TIDL InnerProductLayer. Upon analyzing the table, it becomes evident that a crucial layer is absent. Specifically, the Flatten layer is not present in terms of TensorFlow Lite. Additionally, there are notable omissions of layers that significantly enhance a model’s efficiency and accuracy. This includes the absence of the Batch Normalization Layer and the Dropout Layer, which are not allowed according to the documentation. Another essential aspect to consider is the constraints imposed on layer parameters. Notably, specific limitations apply to convolution and fully connected layers. For convolution layers, the kernel size is fixed at 7x7, and both input and output channels are capped at a maximum of 1024. There are distinct constraints in the case of Fully Connected layers, also known as Inner Product layers in TIDL. The maximum allowable output nodes are 4096. Furthermore, input data must be flattened, meaning C (channel) equals one and H (height) equals one. Additionally, the input size must be a multiple of 8, aligning with the DSP implementation of the layer, which performs aligned 8-byte double word loads. 34 Figure 3.3: Flowchart representing module one By examining the diagram presented in Figure 3.3, it is possible to understand better the tasks assigned to this module. The initial step involves loading the TensorFlow model to gain access to its layers. Subsequently, each model layer is analyzed to determine whether it and its parameters are compatible with TIDL. In the affirmative case, the analysis proceeds to the next layer, repeating the process. In an adverse determination, the layer is replaced with a TIDL-compatible layer or a combination of layers. If there are restrictions on layer parameters, such as the number of output neurons or kernel size, they are decreased to ensure compatibility. The modified model is saved in the appropriate path without incompatibility in the final step. 3.4.2 Training Stage During the second module, the Training ML Model stage, the user must define the dataset and the target for the machine learning model. The dataset can be sourced from various options available in TensorFlow. The target can be directed to the machine (Computer) using simulation tools or to the BeagleBone AI. Regardless of the chosen target, it is necessary to establish the configuration file, which plays a crucial role in configuring and optimizing the model for the specific target environment. The project focuses explicitly on image identification; therefore, in the Training ML Model stage, the emphasis is placed on image classification. While various datasets are available in TensorFlow, the project narrows down to datasets for image classification. 35 Figure 3.4: Flowchart representing module two The first step in the process is to prepare the dataset, ensuring that the images within the selected dataset align with the input shape requirements of the model. This involves resizing the photos to match the dimensions expected by the model’s input. Once the dimensions are confirmed, the training process can proceed successfully. Several variables can influence the training process in TensorFlow. Some of the key variables include: •Learning Rate: The learning rate determines the step size at each iteration during gradient descent. It controls how quickly or slowly the model learns from the data. A higher learning rate may lead to faster convergence but could result in overshooting the optimal solution. In comparison, a lower learning rate may result in slower convergence or getting stuck in local minima. •Batch Size: The batch size refers to the number of training examples used in each iteration of the optimization algorithm. A larger batch size can provide a more stable gradient estimate but may require more memory. Conversely, a smaller batch size introduces more noise in the gradient estimate but may allow faster training. •Number of Epochs: An epoch refers to one complete pass through the training dataset. The number of epochs determines how often the model will be trained on the entire dataset. Training for too few epochs may result in underfitting. Training for too many epochs can lead to overfitting, where the model becomes too specific to the training data and performs poorly on unseen data. •Optimizer Choice: The optimizer determines the specific algorithm used to update the model’s parameters during training. TensorFlow offers various optimizers, such as stochastic gradient descent (SGD), Adam, or RMSProp. The choice of optimizer can impact the convergence speed, stability, and generalization of the model. 36 •Data Preprocessing: The preprocessing steps applied to the data, such as normalization, feature scaling, or data augmentation, can impact training. Properly preprocessing the data can help reduce biases, improve convergence, and enhance the model’s generalization ability. Once the training results are satisfactory, you can proceed to the next step. TIDL framework requires the use of two configuration files. The first one, the import file, facilitates the model’s conversion from TensorFlow or Caffe format into a TIDL-compatible binary file. This import file contains essential specifications and parameters the conversion tool needs to successfully transform the model into a TIDL-readable format. Depending on the user’s chosen platform for model instantiation, the import file varies to accommodate the specific requirements. It consists of both mandatory and optional variables. The required variables include the input model shape, the path to the neural network, the input image path, the model type, and other crucial parameters. On the other hand, the optional variables are related to data format or optimization techniques, such as quantization. Parameter Configuration modelType 0 - caffe, 1 - Tensorflow , 2 - ONNX , 3 - TFlite. quantizationStyle can be ‘0’ for fixed quantization. ‘1’ for dynamic quantization by TIDL. Default 1. quantRoundAdd quantRoundAdd/100 will be added while rounding to integer. Default 50. numParamBits This is the number of bits used to quantize the parameters. inElementType Default 0. Set it to 0 for 8-bit unsigned input or to 1 for 8-bit signed input. inQuantFactor can take values >0. Default value is -1. rawSampleInData Set it to 0, if the input data is encoded, or set it to 1, if the input is RAW data. numSampleInData can be > 0. Default value is 1. foldBnInConv2D can be either 0 or 1. Default value is 1. inWidth is Width of the input image, it can be >0. inHeight is Height of the input image, it can be >0. inNumChannels is input number of channels. It can be from 1 to 1024. sampleInData is Input data File name. TIDLStatsTool is TIDL reference executable for calibration. inputNetFile is Input net file name (From Training framework). inputParamsFile is Input Params file name (From Training framework). outputNetFile is Output Model net file name, to be updated with stats. outputParamsFile is Output Params file name. Table 3.2: Some parameters that can or must be set in the configuration file related to the importation tool 37 In the import file, the user must set six specific variables according to the chosen ML model. Among these variables, the inputNetFile variable should be assigned the path of the ML model file. The model file will then be converted into two binary files and saved in the locations specified by the outputNetFile and outputParamsFile variables, respectively. The value of the inChannels variable depends on the type of image being processed. If the image is RGB (Red, Green, Blue), the variable should be set to three to account for the three color channels. On the other hand, if the image is black and white, the variable should be set to one, as only one channel represents the grayscale intensity. The variables inHeight and inWidth must equal the model input shape. After generating the binary files, the configuration process involves setting up the second file, referred to as the inference file. This file needs to be configured to obtain the inference results and may consist of the variables listed in Listing 3.1, including variables that require definition. 1rawData = 0 inData = "img.png" outData = #Output of the image inference netBinFile = #path of the network file generated paramsBinFile = #path of the parameters file generated 6numFrames = #Number of inference times inNumChannels = #number of input channels inHeight = #height of input image shape inWidth = #width of input image shape Listing 3.1: Example of inference file The model can accept input images in various formats, with PNG being the specific format in this case. The paths for the binary files generated by the imported tool are referred to as inNetFile and inParamsFile . These files contain the necessary information for the model. The numFrames parameter represents how many times the development board will instantiate each picture. The input shape parameters, inWidth , inHeight , and inNumChannels , indicate the dimensions and number of channels in the input image. During the training stage of the model, the dataset is typically split into two parts. One part is used to train the model, while the other is reserved for the inference stage. The usual practice is to allocate approximately 70% of the dataset for training the model, while the remaining 30% is set aside for testing the model’s performance. This split allows the model to learn from the training data while providing a separate data set for evaluating the model’s accuracy and generalization capabilities during the inference stage. 38 3.4.3 Inference Stage During the inference stage, the user can select the platform they want to use. They can choose between using BeagleBone AI or utilizing simulation tools. The simulation tool serves as a project to calibrate the model and configure its parameters. It allows for obtaining inference results, although it should be noted that since it is a simulation tool, some of the results may not correspond to real-world values. However, these results can still be helpful for statistical analysis and data evaluation. If the choice falls on the simulation tool, the results are placed on the path described in outData , and it is possible to see the predicted value. But, to know if the prediction was correct, it is necessary to recognize the input picture and the corresponding true value. To better understand, see Figure 3.5. Figure 3.5: Flowchart representing module three After saving the predicted values during the inference stage, the next step is to calculate the percentage of correct predictions by comparing them to the true values that were saved earlier. This calculation involves determining the accuracy of the model’s predictions. To analyze the model’s performance further, all the images with their corresponding true values and predicted values are listed. This allows for a detailed examination of cases where the model fails to correctly predict the true value. By reviewing these instances, it becomes possible to identify patterns or specific examples where the model struggles and may require further improvement or analysis. This evaluation process helps in understanding the model’s strengths and weaknesses, providing insights into areas where it may need additional training or adjustments to enhance its accuracy and performance. 39 4. Implementation To validate the proposed architecture, this section provides a detailed description of model inference on the Beagle Bone platform and the corresponding results. Additionally, the methods employed in conceiving this project are discussed, focusing on adhering to the design phase as closely as possible. The implementation phase is crucial in concluding the project and resolving any encountered issues. The system configuration is initially presented, outlining the required packages and tools to be installed. Subsequently, the entire process is comprehensively explained, starting from the initial stages and progressing towards the final solution. The selected approach will undergo thorough testing using diverse TensorFlow datasets chosen explicitly for analysis. These tests validate the approach’s robustness, accuracy, and generalization. The chapter will present detailed results and comparisons, offering valuable insights into the performance and adaptability of the chosen methodology. 4.1 System Configuration In this section, it will be presented the necessary configuration steps required to deploy this project. The first step is to acquire the required Python packages for defining a model using TensorFlow. Following that, it is necessary to obtain the processor SDK provided by Texas Instruments. This SDK includes the essential libraries and tools to deploy a model in TIDL for optimal performance. Python packages A TXT file was created to simplify the installation process of the required packages. This file contains a list of the necessary packages and their specific versions. By using this file, users can easily ensure they have the correct versions of the packages installed, facilitating the setup process. 1imutils ==0.5.4 keras==2.10.0 matplotlib==3.6.1 numpy==1.23.4 opencv_python ==4.6.0.66 6pandas==2.0.2 tensorflow==2.10.0 tensorflow_datasets==4.8.1 Listing 4.1: requirements.txt file The following text overviews several essential Python libraries in data science and machine learning. These libraries are crucial in model development, data manipulation, visualization, and image processing. 40 •TensorFlow - The core package for building and working with deep learning models. •NumPy - A fundamental package for scientific computing in Python, offering support for large, multi-dimensional arrays and mathematical operations. •Matplotlib - A plotting library that enables visualization of data and model performance by creating various graphs and charts. •Keras - A high-level neural networks API that runs on top of TensorFlow, simplifying the process of model creation, training, and evaluation. •Imutils - A library that provides utility functions for working with images, such as resizing, rotating, and translating images. It simplifies common image-processing tasks. •OpenCV - is a powerful computer vision library that provides various functions and algorithms for image and video processing. The opencv python package allows Python users to access and utilize the functionalities of OpenCV. •tensorflow datasets - A library that simplifies accessing and preparing various datasets for machine learning tasks. It provides a collection of preprocessed and ready-to-use datasets and functions to download, load, and preprocess data efficiently. •Pandas - A versatile data manipulation and analysis library, providing convenient data structures and functions for handling structured data. To install this packages it only necessary run the following command. pip3 install -r requirements.txt Listing 4.2: Command to install the libraries correctly Processor SDK - TIDL The Processor SDK (Software Development Kit) is a comprehensive software platform TI offers for their embedded processors. It simplifies the development process by providing a convenient setup and quick access to benchmarks and demonstrations. Regardless of the specific TI device being used, all versions of Processor SDK are compatible, enabling developers to reuse and transition software across different devices effortlessly. This SDK facilitates the creation of scalable platform solutions and is seamlessly integrated with TI’s embedded processor solutions. To utilize the TIDL, the Processor SDK must be downloaded from the TI website. This process grants access to importation and simulation tools, along with the corresponding libraries and example code. These resources 41 significantly aid in creating and deploying applications, allowing developers to obtain model results efficiently. With the code example, deploying an application with a base in this example is possible. In our case, it will focus only on the results and check the accuracy, setting aside which will be the best evaluation of hardware where the model will perform. 4.2 Project Workflow Implementation The workflow in the last chapter is implemented as depicted in Figure 4.4. On the left side, Module One represents the stage where the model is adapted to the deployment technology. This adaptation, detailed in Section 4.1.1, involves tasks described in Section 3.4.1. The modifications in this stage are performed manually without a script. The gray rectangle corresponds to Section 4.1.2, where tasks outlined in Sections 3.4.2 and 3.4.3 are implemented using a script. Figure 4.1: Demonstration of the implemented modules 4.2.1 Model Adaption To implement the previously described approach in the last chapter, which involves mapping layers to ensure compatibility with TIDL, three approaches were devised. These approaches were developed sequentially, with the first one being initially applied. After observing the results of the initial method, it became apparent that further refinement was necessary, prompting the development of the second approach. This iterative process was repeated for the second approach, ultimately leading to the formulation of the third approach. These three approaches were crafted to guarantee the accuracy of all modifications. When considering the available layers, examining potential challenges that may arise during the migration from TensorFlow Lite to TIDL is essential. One notable challenge is the absence of particular layers responsible for reshaping, such as the Flatten Layer. The Flatten layer plays a crucial role in CNN models, particularly in classification tasks for the output layer. Further challenges arise when looking at layer parameters. Specific layers have restrictions; for instance, the InnerProduct layer limits the maximum number of input and output nodes, 42 After training, the trained model is converted into the TFLite format using the TensorFlow Lite Converter. The resulting TFLite model is then saved to a file with the extension ”.tflite” for future use. The focus will be creating the import file to generate the binaries file required to TIDL. The solution was designed to be filled automatically according to the model, as it can be possible to see in listing 4.7. f = open(dataset + "/\acrshort{TIDL}_model_import_config.txt","w") configFile = """ modelType = 3 4numParamBits = 12 inputNetFile = "<modelName >/<modelName >.tflite" outputNetFile = "<modelName >/<modelName >_net.bin" outputParamsFile = "<modelName >/<modelName >_io.bin" inNumChannels = <C> 9inHeight = <H> inWidth = <W> """ f.close() configFile = configFile.replace("<C>",str(configC)) 14 configFile = configFile.replace("<H>",str(configH)) configFile = configFile.replace("<W>",str(configW)) configFile = configFile.replace("<DIR >",str(dataset)) configFile = configFile.replace("<modelName >",str(dataset)) f.write(configFile) Listing 4.5: Training stage: How the configuration file is automatically structured. Firstly, a file named TIDL_model_import_config.txt is opened in write mode, located in the specified directory indicated by the dataset variable. Subsequently, a string variable called configFile is defined, which holds the configuration file’s content. This content encompasses various configuration parameters and placeholders, carefully organized in a structured format. Using the replace method, the placeholders in the configFile string are meticulously replaced with the actual values stored in the corresponding variables. The <C> , <H> , <W> , <DIR> , and <modelName> placeholders are successively substituted with their respective values, ensuring the accurate representation of the desired configuration. This way, the configuration file can be dynamically managed for various models, eliminating manual user intervention. Once the placeholders have been successfully replaced, the modified contents of configFile are effectively written to the opened file, capturing the updated configuration settings. Finally, the file is reliably closed, ensuring the proper preservation of any changes made to the configuration file. Now, it is required to create the inference configuration files. 49 fileEve = open(dataset + "/eve_test_dl_algo_ref_config.txt","w") 2configFile=""" rawData = 1 inData = "<modelName >/img.raw" outData = "<modelName >/outData.bin" netBinFile = "<modelName >/<modelName >_net.bin" 7paramsBinFile = "<modelName >/<modelName >_io.bin" numFrames = <N> inNumChannels = <C> inHeight = <H> inWidth = <W> """ 12 configFile = configFile.replace("<C>",str(configC)) configFile = configFile.replace("<H>",str(configH)) configFile = configFile.replace("<W>",str(configW)) configFile = configFile.replace("<N>",str(numberSamples)) 17 configFile = configFile.replace("<modelName >",str(dataset)) fileEve.write(configFile) fileEve.close() Listing 4.6: Training stage: How the inference file is automatically structured. Similar to the previously established configuration file, the placeholders ’<C>’, ’<H>’, ’<W>’, ’<DIR>’, and ’<modelName>’ are replaced with their corresponding values. However, there are additional parameters that require configuration. The parameter ’rawData’ is set to 1, representing the selected input data format. The variable ’inData’ pertains to the input image, explicitly named ’img.raw’. The resultant output of the inference process is stored in the ’outData’ variable. Lastly, the parameter ’numFrames’ designates the frequency of inference iterations. Another configuration file must be explicitly generated to enable inference through simulation tools. Although this file is uncomplicated, its absence would render the utilization of simulation tools incapable of generating predictive outcomes. 1sim = open(dataset +"/sim.txt","w") sim.write("1 " +str(dataset) + "/eve_test_dl_algo_ref_config.txt\n") sim.write("0") sim.close() Listing 4.7: Training stage: File required to use in simulation tools In this scenario, just two lines suffice. The first line comprises the number 1, followed by the directory of the 50 previously established inference configuration file (refer to Listing [lst:eve]). The second line consists solely of the number 0. The entire configuration file creation or modification is automated for each specific model and dataset, eliminating manual intervention. This systematic approach to configuration file generation streamlines the inference process and enhances the comparability between different models, as they are subjected to identical conditions. With this objective in focus, the subsequent code segment has been formulated to capture and retain specific images. These images will be employed as input for the model in successive stages. 1for image , label in test_examples: img = tf.image.resize(image , (configW , configH)) new_labels = np.zeros((new_model.output_shape[1])) label = np.array(label) x_train.append((img)) 6y_train.append(label) labels = [] for iin range(Nimages): image_name = "images_" +str(dataset)+ "/" +str(i)+ ".png" labels.append(y_train[i]) 11 cv2.imwrite(image_name , x_train[(i)]) Listing 4.8: Inference stage: Preparing images and their labels for use in inference This listing 4.8 undertakes a systematic series of actions. It effectively prepares and transforms a batch of images and their corresponding labels from the test examples . The images are resized and thoughtfully organized in tandem with their labels. This structured data is then methodically saved as individual PNG files. The ultimate objective here is to compile images suitable for future inference processes. Moreover, an essential component is accurate labeling, which is vital for post-inference comparisons. A code segment has been devised to ensure the accuracy of the model’s inference results and overall performance. This code validates that the inference process is executed correctly and automates the visualization of all pertinent information. 51 resultFile = open(str(dataset) + "/results.txt","w") folder = 'images_' +str(dataset) result = str(dataset) + '/result.txt' 4if ip_address != None: os.system("scp -r " +str(dataset) + ""+str(ip_address) + ":") os.system("scp " +str(dataset) + "/eve_test_dl_algo_ref_config.txt" +""+str(ip_address) + ":") for filename in os.listdir(folder): 9index = filename.replace(".png","") os.system("convert " +str(folder) +"/"+str(filename) + "-separate + channel -swap 0,2 -combine -colorspace sRGB ./" +str(dataset) + "/sample_rgb.png") os.system("convert "+str(folder) + "/" +str(filename) + " -interlace plane RGB:" +str(dataset) + "/img.raw") 14 if ip_address != None: os.system("scp -r " +str(dataset) + "/img.raw " +str(ip_address) +":~/" +str(dataset)) os.system("ssh " +str(ip_address) + " sudo ./inference_main ") print("True Value : " +str(labels[int(index)]) ) 19 os.system("ssh " +str(ip_address) + " hd outdata.bin ") os.system("scp " +str(ip_address) + ":~/outdata.bin ./" +str(dataset) +"/outData.bin") else : os.system("./executables/eve_test_dl_algo_ref.out " +str(dataset) + 24 "/sim.txt") Listing 4.9: Inference stage: How all images are converted into a binary file and how the communication of BeagleBone AI is accomplished. This portion of the code encompasses the entire inference procedure. When the user opts for the ”ip address” selection, the associated configuration file and all requisite files, including images and importation files, are duplicated via the designated IP address. Following this, the code sequentially processes each pre-saved image to perform inference operations. An observation was made throughout this process: the images within the dataset are initially in the BGR format. To enhance user-friendliness, a conversion to the RGB format is executed using two commands, as depicted in lines 10 and 12 regarding listing 4.10. As the culmination of this process, the image is labeled as ’img.raw’, corresponding to the directory specified by the variable ’inData’ in the configuration file created as shown in listing 4.6. It is crucial to reevaluate the ’ip address’ option. When chosen, a sequence of actions is triggered: transferring ’img.raw’ to the device via the IP address, executing the command to manage the inference, and finally sending the model prevision to the host. If that option is not selected, it is the same that the inference will be made through the 52 simulation tools, as is possibly seen in line 24. Now that the outcome of the inference is available, evaluating the results provided by the model inference is necessary. For that reason, the following portion of the code was developed. 1f = open(str(dataset) + "/outData.bin","rb") predict = inDataGet(f, numOut) f.close() indexTrue= np.argmax(labels) indexPre= np.argmax(predict) 6if indexPre==labels[int(index)]: correct +=1 resultFile.write ( str(folder) +"/" +str(filename) + "\n" ) resultFile.write ("Output: " +str(predict) + "\nPredicted: " +str(indexPre) +" \nTrue Value : " +str(labels[int(index)]) +"\n" ) 11 total +=1 percent = (correct/Nimages)*100 resultFile.write( "\n\nCorrects: "+str(correct) +"\n") resultFile.write("Number of images: " +str(Nimages) + "\n") 16 resultFile.write("Percentage of correct matches: " +str(percent) + "%\n") resultFile.close() Listing 4.10: Inference stage: How is the output binary file obtained, and how the comparison between the prediction and correct values is done. The initial step involves opening an output file containing predictions. These predictions are then compared against the actual values of the images used during the inference process. When the predicted output matches the correct value, a variable called ćorrect’ is incremented by one. Finally, all pertinent information is logged into a file, creating a historical record of past inferences for reference and analysis. In this section, the selected approach will undergo thorough testing using diverse TensorFlow datasets chosen explicitly for analysis. These tests are designed to validate the approach’s robustness, accuracy, and generalization. The chapter will present detailed results and comparisons, offering valuable insights into the performance and adaptability of the chosen methodology. Through these tests, a comprehensive understanding of the approach’s strengths and limitations will be gained, contributing significantly to the overall findings and conclusions of the study. The tests will use both methods available to infer a model, using the simulation tools and the BeagleBone AI. 53 4.3 System Workflow Deployment The initial step to becoming familiar with the TIDL tool involved selecting a small dataset. After achieving satisfactory results with this dataset, a larger dataset will be introduced to validate the robustness of the approach. A comparison between the training and inference results will offer a comprehensive understanding of the model’s performance in each approach. 4.3.1 Model Instantiating Following First Approach Moving on to the implementation of this approach, it was started by selecting a small model, namely the MNIST dataset. This model, designed specifically for recognizing and classifying the ten different digits (0-9), consists of five layers, as depicted in Figure 4.9. Figure 4.9: Composition of the model for MNIST dataset. Executing the import tool command, as will be expected, the Flatten layer will not be supported in TIDL, as it is possible to see in Figure 4.10. Flatten Layer is recognized as the TIDL ReshapeLayer. Observing the sentences inside the red rectangle, it says that the Reshape layer can be merged with another layer if an AveragePooling layer or an InnerProduct/Dense Layer is placed before it. Each layer has its characteristics to consider. The InnerProduct layer is typically used in classification and is set when the model has only one dimension. 54 Figure 4.10: TIDL does not recognized Flatten layer So, following the approach, adding an AveragePooling layer with a window size 1x1 in the model introduces an extra layer, but there are no internal changes. The ML model used to use the MNIST dataset is represented in Figure 4.11 already with the Average Pooling layer placed before the Flatten layer. Figure 4.11: Constitution of the MNIST model with the modifications As it is possible to see, in Figure 4.11, the introduction of the AveragePooling Layer does add no parameters as known params to the model. 55 Figure 4.12: Result of TIDL import without any limitation or error Upon executing the simulation tool command, the changes made were found to effectively resolve any errors or limitations associated with TIDL import, as depicted in Figure 4.12. However, a detailed analysis of the inference results (Figure 4.13) reveals a concerning outcome: only eleven out of a hundred images match, which is notably inferior when compared to the training results shown in Figure 4.14. Figure 4.13: Inference results following the first approach Figure 4.14: Training results following the first approach With these inference results, developing another approach capable of better results was necessary. 4.3.2 Models Instantiation Following Second Approach After evaluating the initial approach, a second approach is adopted to assess whether the inference results can be improved for deploying a more robust solution. The second approach involves replacing the InnerProduct/Dense layer with a Convolution layer. Considering the same model used in the previous approach present in Figure 4.11, the MNIST model suffered some modifications, as depicted in Figure 4.15. 56 Figure 4.15: MNIST mode composition following the second approach It is necessary to replace two Dense layers with the respective Convolution layers. The first replacement is not considered ideal due to the necessity of two Convolution layers to replace one Dense layer. However, the second replacement is perfect, as evident from the comparison of the number of param (parameters) shown on the right side of Figures 4.9 and 4.15. As anticipated, the import process proceeded without encountering any errors or limitations. The results of both training and inference can be observed in Figure 4.16 and Figure 4.17, respectively. Figure 4.16: Training results following the second approach Figure 4.17: Inference results following the second approach Despite the excellent results obtained, there are better ways of implementing a CNN model than this one, following the documentation presented in the second chapter. A typical CNN model consists of two distinct tasks: the feature extraction task involving convolutions and pooling layers and the classifier task comprising shape and fully connected layers. In the present method, the classifier task is executed using convolutions instead of fully connected layers, which is not the most effective approach. The main problem is that it is impossible to transform features from three dimensions to one dimension. These excellent results highlight that the issue persists with the Flatten layer. It became necessary to develop another approach to maintain these positive outcomes while adhering to the default structure of a CNN ML model. 4.3.3 Models Instantiation Following the Third Approach Moving on to the implementation, as in the previous approach, will be used the same ML model presented in Figure 4.11. Using the convolution to reduce the shape of the feature, the ML model is composed of the layers 57 present in Figure 4.18. Figure 4.18: Model composition with the new changes The feature’s shape is progressively downsampled until it becomes a 1x1 representation. This process allows the classifier task to be done with the right approach. The combination of Average Pooling and Flatten layers is not a limitation or an error in TIDL as seen before. Figure 4.19: Inference results following the third approach Figure 4.19 illustrates the results obtained using this approach. Surprisingly, the performance is comparable to the previous approach, where the three-dimensional representation was maintained. The combination of Average Pooling and Flatten layers proves highly effective when the dimension is reduced to 1x1. With these adjustments, this approach is a suitable and robust solution for the classifier task. The TensorFlow model was subjected to the Netron application to enhance comprehension of the methodology employed, offering enhanced visualization capabilities. 58 5. Tests and Results The third approach, demonstrating superior results, has been chosen for further testing. This selected approach will undergo evaluations using various TensorFlow datasets to assess its robustness and overall performance. Two testing options will be employed: the simulation tool and the BeagleBone AI. The simulation tool offers a controlled environment for a comprehensive analysis before deployment on an instantiation board. As for the BeagleBone AI, the chosen instantiation board, a sample script named ”test”, given by TIDL, will be utilized for model deployment. During the implementation, some TensorFlow datasets with small images were already used, particularly the MNIST and CIFAR10 datasets. The simulation tool results of each dataset can be seen in the previous chapter. 5.1 MNIST Dataset Starting with MNIST, a relatively simple dataset consisting of grayscale images with just one input channel. The training phase resulted in near-perfect accuracy, nearly reaching 100%, as depicted in Figure 5.1. This exceptional training accuracy signifies a highly successful training process. Figure 5.1: Training results for the MNIST dataset with 28x28 pixels images As the simulation tool results were evaluated, it is time to observe the instantiation in the BeagleBone AI. By following Figure 5.2, the inference results reached 97%, which is a great result. Figure 5.2: Inference results for the MNIST dataset 5.2 CIFAR-100 Dataset Building upon exploring the CIFAR-10 dataset, it is imperative to delve into its counterpart, CIFAR-100, in this section. CIFAR-100 is an extension of CIFAR-10, designed for more complex image recognition tasks. Unlike CIFAR- 10, which contains ten classes, CIFAR-100 expands the scope to one hundred classes, each with fine-grained categories. This dataset poses a higher level of challenge due to its diverse range of object categories, making it an ideal choice for evaluating the robustness and versatility of machine learning models. The adjustment needed for training with the CIFAR-100 dataset was a simple alteration: changing the number of output neurons from 10 to 100. Despite extending the training duration to fifty epochs from the initial twenty, the results remained underwhelming, as depicted in Figure 5.3. Despite these efforts, the model’s performance did not meet the desired expectations. 65 Figure 5.3: Training results for the cifar100 dataset However, regarding model inference, the results can be regarded as favorable, as Figure 5.4 illustrates, despite the training results. The disparity in validation performance between CIFAR-10 and CIFAR-100 datasets arises from the increased complexity and granularity of object categories in CIFAR-100. The finer distinctions between classes in CIFAR-100 make it more challenging for the model to learn and generalize effectively, resulting in a lower overall accuracy than CIFAR-10. Notably, the accuracy observed during inference closely aligns with the training results, a synchronicity that was previously considered unattainable with the approaches used in the past. Figure 5.4: Inference results for the cifar100 dataset 5.3 Rock-Paper-Scissors Dataset The Rock-Paper-Scissors dataset consists of labeled images depicting hand gestures representing rock, paper, and scissors. It is widely used in machine learning and computer vision education for tasks related to image classification. Due to its simplicity, it serves as an ideal starting point for beginners, helping them understand key concepts in image recognition and neural network training. Figure 5.5: Example of images presented in the rock-paper-scissors dataset In this scenario, higher performance results are anticipated due to the dataset’s simplicity compared to, for example, the CIFAR-100 dataset. The input images were resized to 128x128 pixels to assess the model’s performance with larger images. Regarding training outcomes, the model demonstrated exceptional readiness, achieving a perfect 100% accuracy, as illustrated in Figure 5.6. Figure 5.6: Training results for the rock-paper-scissors dataset Regarding inference results, the percentage of correct hits reached a remarkable 100%, as demonstrated in Figure 5.7. This outcome is exceptionally favorable. Moreover, the alignment between inference and training results 66 mirrors the consistency observed in the previous test. Figure 5.7: Training results for the rock-paper-scissors dataset 5.4 Imagenette Dataset The Imagenette dataset is a reduced version of the ImageNet dataset, offering a smaller and more manageable collection of images for experimentation and learning in deep learning and computer vision. It consists of ten classes representing everyday objects, making it more straightforward and accessible, especially for beginners. Imagenette serves as a valuable benchmark for researchers, allowing them to efficiently test and compare various machine learning models. Its practical size enables swift experimentation and iteration, making it an essential resource for educational purposes and computer vision research endeavors. Figure 5.8: Example of images presented in the imagenette dataset In this particular test, the input shape remained at 128x128 pixels, but it was necessary to increase the output neurons to ten, as required by this dataset. In comparison with the previous test, the training accuracy, as it is possible to see in Figure 5.9, reached 74%, which, although slightly lower, is still considered a satisfactory result. To have this result in the training was necessary to increase the number of epochs to thirty. Figure 5.9: Training results for the tf-flowers dataset Similar to previous tests, the accuracy of the inference closely mirrors the training accuracy, as depicted in Figure 5.10. This comparison aims to validate the training accuracy and ensure its consistency during the inference process. Figure 5.10: Inference results for the tf-flowers dataset 67 5.5 Tf-Flowers Dataset The TF Flowers dataset is a diverse collection of labeled flower images used in machine learning and computer vision tasks. It is a valuable resource for training and evaluating image recognition models due to its varied flower species and high-quality images. Researchers and students commonly use this dataset to explore image classification and transfer learning techniques. Its real-world applicability makes it a popular choice for educational purposes and research projects in computer vision. It generally includes common flower types such as roses, daisies, sunflowers, tulips, and dandelions. Figure 5.11: Example of images presented in the tf-flowers dataset The training feedback indicated an accuracy rate of 70%, which is a commendable result, as shown in Figure 5.12. The number of epochs was maintained from the previous training. Figure 5.12: Training results for the tf-flowers dataset Here in this scenario, as well as the previous tests, the inference accuracy result follows the training accuracy, 71%, as it is possible to see in Figure 5.13. Figure 5.13: Inference results for the tf-flowers dataset To better understand the performance of a development board using large images, this dataset will also be used on BeagleBone. After the deployment, it was observed that the accuracy results reached 63%, as depicted in Figure5.14, which is lower than the previous test results using the same dataset. Figure 5.14: Inference results for the tf-flowers dataset 68 5.6 Imagennet Dataset with 256x256 Pixels Images In this test, the input images were enlarged to 256x256 pixels to assess the algorithm’s performance with higherresolution images. The test conditions were consistent with the previous Imagenette test, including the number of epochs. This test yielded a slightly improved accuracy of just over 78%, as illustrated in Figure 5.15. Figure 5.15: Training results for the imagenette dataset with 256x256 pixels images In this situation, akin to previous scenarios, the accuracy observed during inference aligns with the training accuracy of 78%, as depicted in Figure 5.16. This consistency emphasizes the reliability of the model’s performance during both training and inference phases. Figure 5.16: Inference results for the imagenette dataset with 256x256 pixels images 5.7 Tf-flowers Dataset with 256x256 Pixels Images As the test made previously, the the input images were enlarged to 256x256 pixels. In this case, the results are almost the same compared with 128 and 256 pixels images. The training accuracy reaches 70%, as illustrated in Figure 5.17. Figure 5.17: Training results for the tf-flowers dataset with 256x256 pixels images In this situation, as in previous scenarios, the accuracy obtained through the validation dataset during the training follows the accuracy obtained in model inference, which is 70% as depicted in Figure 5.18. Figure 5.18: Inference results for the imagenette dataset with 256x256 pixels images 5.8 Results This section will present a comparison of the results obtained from the tests conducted across different datasets. This analysis aims to provide insights into the variations and similarities in the outcomes, shedding light on the performance of the algorithms in diverse contexts. 69 Model Input Training Inference Accuracy - Inference Accuracy - Dataset Name Shape Output Size Accuracy Simulation tool BeagleBone MNIST 28x28x1 10 99% 97% 97% CIFAR-10 32x32x3 10 84% 83% —– CIFAR-100 32x32x3 100 45% 46% —– Rock-Paper-Scissors 128x128x3 3 100% 100% —– Tf-Flowers 128x128x3 5 70% 71% —– Imagenette 128x128x3 10 74% 73% —– Tf-Flowers 256x256x3 5 69% 70% 63% Imagenette 256x256x3 10 78% 78% —– Table 5.1: Comparison of the results obtained in the accomplished tests In Table 5.1, all the test results are presented side by side for a comprehensive overview of the obtained results. Throughout the tests, it was observed that the percentage of inference results is directly linked to the rate of the last training epoch, even in ML models with a significant number of output neurons, as demonstrated in the CIFAR-100 test. Therefore, if the training results do not meet expectations, adjustments may be necessary, such as increasing the number of epochs or reducing the batch size to enhance accuracy during training. Once the training results are satisfactory, the percentage of inference accuracy using the simulation tool closely matches the percentage of training accuracy. The best accuracy result was achieved with the rock-paper-scissors dataset, achieving 100% accuracy in both training and inference processes. On the other hand, the inference results obtained using the BeagleBone AI do not adhere to the previously observed rule, especially when dealing with RGB images or images with higher pixel counts. These variations observed during the tests are attributed to the script used on BeagleBone, where the code primarily focuses on verifying if the model can be deployed rather than achieving better accuracy. TIDL provides flexibility, allowing the code to be divided into segments and determining which part is instantiated in the EVEs or the DSPs. This introduces variability to the TIDL environment, where inference results can be influenced by the hardware (DSP or EVE) deployed on a particular layer. 70 6. Conclusion 6.1 Discussion This dissertation primarily aimed at developing a specialized automatic application capable of adapting a machine learning model, whose instantiation was previously in a computer with powerful resources, to an embedded platform with a few resources. However, the objective was not fully accomplished because the adaption was not automated. The adaption is done by changing the layers manually. Some limitations and incompatibilities were identified throughout this research period when attempting to infer a model. To address this, a layer block was created, designed to be repeated throughout the model composition to enhance results. Additionally, the research paved the way for developing a script that simplifies the process of inferring a model in TIDL. This script generates configuration files and executes commands automatically. In this streamlined process, the user only needs to select the model they have defined and choose an appropriate dataset. The script then displays all the predictions obtained and provides the accuracy percentage, offering a user-friendly solution for model inference in TIDL. In summary, this dissertation was dedicated to developing a specialized application for the automotive industry. While challenges arose in integrating the application seamlessly, extensive studies focused on ensuring consistent accuracy between training and inference phases, regardless of the dataset used. The research identified limitations in model inference, creating a versatile layer block for enhanced results. Efforts to automate transformations were made, resulting in a user-friendly script for model inference in TIDL. This script simplifies the process by generating configuration files, executing commands automatically, and displaying accurate predictions. 71 6.2 Future Work Since the objective still needs to be fully achieved, future work should focus on developing an automatic application for the model adaptation in TIDL. This will become a more efficient application where the user only has to define a model in TensorFlow and indicate its path when executing the script and the dataset that wants to be used to make the instantiation. The following stages should focus on choosing or creating a dataset tailored to the specific environmental context, such as traffic environments. TensorFlow provides the necessary features to create custom datasets, a foundational step for building machine learning models with meaningful accuracy. Training with this dataset, coupled with insights from the research conducted in this dissertation, can yield valuable conclusions about inference accuracy. Enhancing the user interface is another critical aspect, especially considering that accuracy results depend on selecting the highest value among output neuron values. Working with the final dataset streamlines precision establishment among output values, as these values are predefined. For instance, in cases where two neurons exhibit similar values, selecting the higher value might not always represent the correct choice. While accuracy may not be affected, precision can be compromised. Ensuring a user-friendly interface becomes pivotal for meaningful interpretations of the model’s outputs and user interactions. Addressing the limitations of the existing code in BeagleBone’s inference process emerges as a critical focus for future work. Enhancing the code to fully leverage BeagleBone’s hardware capabilities and harnessing all the advanced features within the TIDL will be crucial steps toward optimizing the machine learning model’s performance in real-world scenarios. 72 Bibliography [1] “Explaining Artificial Intelligence, Machine Learning, and Deep Learning Models”. In: Risk Modeling . John Wiley & Sons, Ltd, 2022. Chap. 4, pp. 55–70. ISBN: 9781119824961. DOI: https://doi.org/10. 1002/9781119824961.ch4. eprint: https://onlinelibrary.wiley.com/doi/pdf/10. 1002/9781119824961.ch4. URL: https://onlinelibrary.wiley.com/doi/abs/10. 1002/9781119824961.ch4. [2] Sara Brown. What is Artificial Intelligence (AI)? - ai definition and how it works . URL: https : / / www . techtarget.com/searchenterpriseai/definition/AI-Artificial-Intelligence. [3] David Gunning et al. “XAI: Explainable artificial intelligence”. In: Science Robotics 4.37 (2019). DOI: 10. 1126/scirobotics.aay7120. eprint: https://robotics.sciencemag.org/content/4/ 37/eaay7120.full.pdf. URL: https://robotics.sciencemag.org/content/4/37/ eaay7120. [4] Batta Mahesh. Machine learning algorithms - a review - researchgate . URL: https : / / www . researchgate . net / profile / Batta - Mahesh / publication / 344717762 _ Machine _ Learning _ Algorithms_ - A _ Review / links / 5f8b2365299bf1b53e2d243a / Machine - Learning - Algorithms - A - Review.pdf. [5] Yan-Yan Song and Ying Lu. “Decision tree methods: applications for classification and prediction”. In: Shanghai archives of psychiatry 27 (Apr. 2015), pp. 130–5. DOI: 10.11919/j.issn.1002-0829.215044. [6] Anshul Saini. Naive Bayes Algorithm: A complete guide for data science enthusiasts . July 2023. URL: https: //www.analyticsvidhya.com/blog/2021/09/naive-bayes-algorithm-a-complete- guide-for-data-science-enthusiasts/. [7] andeep Kumar Satapathy and Shruti Mishra. “EEG brain signal classification for epileptic seizure disorder detection”. In: Analysis Vidhya (July 2019). DOI: 10.1016/c2018-0-01888-5. [8] Happiness Ugochi Dike et al. “Unsupervised learning based on Artificial Neural Network: A Review”. In: 2018 IEEE International Conference on Cyborg and Bionic Systems (CBS) (2018). DOI: 10.1109/cbs.2018. 8612259. [9] Youguo Li and Haiyan Wu. “A Clustering Method Based on K-Means Algorithm”. In: Physics Procedia 25 (2012), pp. 1104–1109. ISSN: 1875-3892. DOI: https : / / doi . org / 10 . 1016 / j . phpro . 2012 . 03 . 206. URL: https://www.sciencedirect.com/science/article/pii/S1875389212006220. 73 [10] Samreen Naeem et al. “An unsupervised machine learning algorithms: Comprehensive review”. In: International Journal of Computing and Digital Systems 13 (2023), pp. 911–921. DOI: 10.12785/ijcds/130172. [11] Yuxi Li. “Reinforcement learning and deep reinforcement learning”. In: Deep Learning in Science (2021), pp. 282–307. DOI: 10.1017/9781108955652.016. [12] Jean-Pierre Briot and Francois Pachet. “Music Generation by Deep Learning - Challenges and Directions”. In: Neural Computing and Applications 32 (Feb. 2020). DOI: 10.1007/s00521-018-3813-6. [13] Kenji Suzuki. Artificial Neural Networks - methodological advances and biomedical ... URL: https : / / www.researchgate.net/publication/319316102_Artificial_Neural_Networks_- _Methodological_Advances_and_Biomedical_Applications. [14] Iqbal H Sarker. Deep learning: A comprehensive overview on techniques, taxonomy, applications and Research Directions . 2021. URL: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC8372231/. [15] Ahmad Shawahna, Sadiq M. Sait, and Aiman El-Maleh. “FPGA-based accelerators of deep learning networks for learning and classification: A Review”. In: IEEE Access 7 (2019), pp. 7823–7859. DOI: 10.1109/ access.2018.2890150. [16] Zewen Li et al. “A Survey of Convolutional Neural Networks: Analysis, Applications, and Prospects”. In: IEEE Transactions on Neural Networks and Learning Systems 33.12 (2022), pp. 6999–7019. DOI: 10.1109/ TNNLS.2021.3084827. [17] Ian Goodfellow, Yoshua Bengio, and Aaron Courville. Deep learning . The MIT Press, 2017. [18] Rikiya Yamashita et al. Convolutional Neural Networks: An overview and application in radiology - insights into imaging . June 2018. URL: https://insightsimaging.springeropen.com/articles/10. 1007/s13244-018-0639-9. [19] Sakshi Indolia et al. “Conceptual Understanding of Convolutional Neural Network- A Deep Learning Approach”. In: Procedia Computer Science 132 (2018), pp. 679–688. ISSN: 1877-0509. DOI: https : / / doi . org / 10 . 1016 / j . procs . 2018 . 05 . 069. URL: https://www.sciencedirect.com/science/article/pii/S1877050918308019. [20] Huang Jin Jie and Putra Wanda. “RunPool: A Dynamic Pooling Layer for Convolution Neural Network”. In: Int. J. Comput. Intell. Syst. 13 (2020), pp. 66–76. URL: https://api.semanticscholar.org/ CorpusID:211089631. 74