scieee AI-readable full text Open interactive document viewer

Computer assisted diagnosis (CAD) with enhanced cognitive architectures (BorisCAD)

Samorinha, Rafael André Escalhão

Abstract

Computer-assisted medical image diagnosis plays a vital role in modern healthcare by enabling accurate and timely detection of various medical conditions. However, conventional image classification techniques often fail to integrate crucial elements such as perception, reasoning, and episodic experiences, essential for achieving optimal performance. This research endeavours to bridge this gap by designing, implementing, and evaluating a cognitive architecture incorporating these elements. The findings of this research will contribute to the development of a deployable cognitive architecture that can provide accurate and reliable diagnoses for a wide range of medical conditions, benefiting both healthcare professionals and patients alike. Furthermore, the potential impact of this research extends beyond medical image analysis, with implications in autonomous systems, robotics, and intelligent decision support systems. By harnessing the potential of cognitive architectures, computer-assisted systems can be revolutionised, leading to improved diagnostic accuracy and fostering innovation in diverse industries reliant on advanced cognitive capabilities. In order to achieve this objective, sub-symbolic methods for perception and symbolic methods for reasoning will integrate the cognitive architecture. The bottom level, responsible for sub-symbolic processing, will incorporate advanced segmentation and classification using convolutional neural networks to handle perception tasks. In contrast, the top level will utilise a decision forest, an ensemble of decision trees, to perform sophisticated reasoning tasks using symbolic data. Additionally, this study will focus on integrating episodic experiences within the architecture by incorporating working and long-term memory mechanisms, enhancing its predictive capabilities. The evaluation of the cognitive architecture demonstrated its effectiveness within the context of the tested datasets and image sizes. However, it is essential to acknowledge that developing a deployable version for medical image diagnosis requires further testing and validation. Expanding the evaluation to include a broader range of pathologies and imaging modalities is crucial to ensure the architecture’s robustness and adaptability in diverse clinical scenarios. By incorporating a more diverse set of pathologies and imaging modalities into the evaluation process, the cognitive architecture can undergo rigorous testing to assess its performance across various medical conditions. This expanded evaluation will help identify potential limitations and areas for improvement, ensuring that the architecture can deliver accurate and reliable diagnoses across a broader spectrum of medical conditions.

Full text

Universidade do Minho Escola de Engenharia Rafael André Escalhão Samorinha Computer Assisted Diagnosis (CAD) with Enhanced Cognitive Architectures (BorisCAD) julho de 2023 UMinho | 2023 Rafael Samorinha Computer Assisted Diagnosis (CAD) with Enhanced Cognitive Architectures (BorisCAD) Rafael André Escalhão Samorinha Computer Assisted Diagnosis (CAD) with Enhanced Cognitive Architectures (BorisCAD) Dissertação de Mestrado Engenharia Eletrónica Industrial e Computadores Sistemas Embebidos e Computadores Trabalho efetuado sob a orientação do(a) Professor Doutor Carlos Manuel Gregório Santos Lima e Professor Doutor Adriano José da Conceição Tavares Universidade do Minho Escola de Engenharia julho de 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. Atribuição-NãoComercial-SemDerivações CC BY-NC-ND https://creativecommons.org/licenses/by-nc-nd/4.0/ Agradecimentos Desde já, gostaria de expressar o meu agradecimento a todos aqueles que contribuíram para finalizar esta etapa. A concretização deste trabalho não teria sido possível sem a ajuda e o apoio de várias pessoas que fizeram parte do meu percurso académico, permitindo-me crescer como pessoa e profissional. À minha família, agradeço todo o apoio, força e motivação ao longo destes anos, bem como por nunca terem desistido de mim, incentivando-me a prosseguir e lutar por aquilo que sempre desejei fazer. Aos meus orientadores, Adriano Tavares e Carlos Lima, agradeço pela disponibilidade e ajuda prestadas, bem como por nunca terem reduzido os níveis de exigência. Aos restantes inquilinos da Casinha do Povo, quero agradecer pela companhia durante estes looooooongos anos, sempre a incentivar-me para fazer mais e melhor, muitas das vezes por caminhos dúbios. Como já vários sábios disseram, sem vocês acabava um ano mais cedo. À Marcela... por tudo aquilo que fizeste por por mim neste último ano. Por todos os dias em que foste chatinha comigo para eu fazer coisas, e por nunca desistires de mim. Eu tenho toda a certeza que sem ti não estaria tão confiante no meu potencial como estou hoje, nem teria alcançado tudo o que consegui. Obrigado por estares sempre ao meu lado e nunca duvidares. “So gimme some fin… noggin… dude!” - Crush i Statement of Integrity I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Code of Ethical Conduct of the University of Minho ii Abstract Computer-assisted medical image diagnosis plays a vital role in modern healthcare by enabling accurate and timely detection of various medical conditions. However, conventional image classification techniques often fail to integrate crucial elements such as perception, reasoning, and episodic experiences, essential for achieving optimal performance. This research endeavours to bridge this gap by designing, implementing, and evaluating a cognitive architecture incorporating these elements. The findings of this research will contribute to the development of a deployable cognitive architecture that can provide accurate and reliable diagnoses for a wide range of medical conditions, benefiting both healthcare professionals and patients alike. Furthermore, the potential impact of this research extends beyond medical image analysis, with implications in autonomous systems, robotics, and intelligent decision support systems. By harnessing the potential of cognitive architectures, computer-assisted systems can be revolutionised, leading to improved diagnostic accuracy and fostering innovation in diverse industries reliant on advanced cognitive capabilities. In order to achieve this objective, sub-symbolic methods for perception and symbolic methods for reasoning will integrate the cognitive architecture. The bottom level, responsible for sub-symbolic processing, will incorporate advanced segmentation and classification using convolutional neural networks to handle perception tasks. In contrast, the top level will utilise a decision forest, an ensemble of decision trees, to perform sophisticated reasoning tasks using symbolic data. Additionally, this study will focus on integrating episodic experiences within the architecture by incorporating working and long-term memory mechanisms, enhancing its predictive capabilities. The evaluation of the cognitive architecture demonstrated its effectiveness within the context of the tested datasets and image sizes. However, it is essential to acknowledge that developing a deployable version for medical image diagnosis requires further testing and validation. Expanding the evaluation to include a broader range of pathologies and imaging modalities is crucial to ensure the architecture’s robustness and adaptability in diverse clinical scenarios. By incorporating a more diverse set of pathologies and imaging modalities into the evaluation process, the cognitive architecture can undergo rigorous testing to assess its performance across various medical conditions. This expanded evaluation will help identify potential limitations and areas for improvement, ensuring that the architecture can deliver accurate and reliable diagnoses across a broader spectrum of medical conditions. Keywords : convolutional neural networks; decision tree; memory; cognitive architecture; image classification; learning; adaptation; medical diagnosis; artificial intelligence; Boris iii Resumo O diagnóstico assistido por computador a partir de imagens médicas desempenha um papel vital na saúde moderna, permitindo a detecção precisa e atempada de várias condições médicas. No entanto, as técnicas convencionais para classificação de imagens não integram elementos cruciais da análise humana, tais como a percepção, raciocínio e experiências episódicas. O trabalho apresentado procura preencher esta lacuna através do design, implementação e avaliação de uma arquitetura cognitiva que incorpora estes elementos. Os resultados obtidos contribuem para o desenvolvimento de novos métodos capazes de fornecer diagnósticos precisos e confiáveis para uma ampla gama de condições médicas, beneficiando tanto os profissionais de saúdo como os pacientes. Além disto, o potencial deste trabalho estende-se além da análise de imagens médicas, com possíveis implicações em sistemas autónomos, robótica e sistemas inteligentes de suporte à decisão. Ao aproveitar o potencial das arquiteturas cognitivas, estes sistemas podem ser revolucionados, levando a uma melhoria na precisão e a estimulação para a inovação em diversas indústrias que dependem de capacidades cognitivas avançadas. Para alcançar o objetivo principal de diagnóstico, serão integrados na arquitetura cognitiva métodos sub-simbólicos para percepção e métodos simbólicos para raciocínio. O nível mais abaixo, responsável pelo processamento sub-simbólico, incorporará redes neuronais convolucionais para segmentação e classificação, de forma a emular percepção no sistema. Por outro lado, o nível superior irá usar uma floresta de decisão, um conjunto de árvores, para realizar tarefas de raciocínio usando dados simbólicos. Além disto, este estudo irá focar-se na integração de experiências episódicas, incorporando mecanismos de memória de trabalho e a longo prazo, de forma a incluir dados passados na decisão atual. A avaliação desta arquitetura demonstrou a sua eficácia no contexto do conjunto de dados e tamanhos de imagem usados. No entanto, é essencial reconhecer que o desenvolvimento de uma versão aplicável ao diagnóstico de imagens médicas requer testes e validações adicionais. Desta forma, a expansão do sistema para incluir uma ampla gama de patologias e modalidades de imagem é crucial para garantir a robustez e adaptabilidade da arquitetura em diversos cenários clínicos. Ao incorporar um conjunto mais diversificado de patologias e modalidades de imagem no processo de avaliação, a arquitetura pode ser submetida a testes rigorosos de forma a avaliar o seu desempenho no mundo real. Esta ampla avaliação ajudará a identificar possíveis limitações, garantindo que o sistema fornece diagnósticos precisos e confiáveis num espectro vasto de condições médicas. Palavras-chave : redes neuronais convolucionais; árvore de decisão; memória; arquitetura cognitiva; classificação de imagens; aprendizagem; adaptação; diagnóstico médico; inteligência artificial; Boris iv Contents 1 Introduction 1 1.1 GeneralMotivations.................................. 2 1.2 Contributions of this Thesis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.3 Structure of the Dissertation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 2 Literature Review / State of the Art 5 2.1 Artificial Intelligence In The Medical Field . . . . . . . . . . . . . . . . . . . . . . . 5 2.2 ComputerVision ................................... 7 2.3 CognitiveArchitectures ................................ 7 2.3.1 ACT-R (Adaptive Control of Thought-Rational) . . . . . . . . . . . . . . . . . 8 2.3.2 CLARION .................................. 9 2.3.3 SOAR .................................... 12 2.4 Meta-Learning .................................... 15 2.5 Rule-Based and Case-based Reasoning . . . . . . . . . . . . . . . . . . . . . . . . 15 2.6 SimilarWork ..................................... 16 3 Architectural Planning 18 3.1 The Blueprint: Designing a Brain-like Architecture . . . . . . . . . . . . . . . . . . . 19 3.2 Computation System: The Cognitive Engine . . . . . . . . . . . . . . . . . . . . . . 23 3.2.1 Sub-Symbolic Processing: The Bottom Level . . . . . . . . . . . . . . . . . 23 3.2.2 Symbolic Reasoning: The Top Level . . . . . . . . . . . . . . . . . . . . . . 34 3.3 Storage System: Working and Long-Term Memory . . . . . . . . . . . . . . . . . . . 46 3.4 Learning System: Optimisation and Adaptation . . . . . . . . . . . . . . . . . . . . 54 3.5 Holistic Approach to Decision-Making . . . . . . . . . . . . . . . . . . . . . . . . . 63 3.6 IntegratedTechnologies................................ 67 v List of Listings Segmentation Network __init__function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 UNetblock__init__function. .................................. 77 Attention Gate block __init__function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 Attention Gate forward method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 Attention U-Net __init__function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 Attention U-Net forward method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 Attention U-Net number of channels property. . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Segmentation Network fit method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 IgnoreWarningcontext...................................... 83 Segmentation Network epoch training method. . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Segmentation Network batch training method. . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Segmentation Network batch training forward with context. . . . . . . . . . . . . . . . . . . . . 84 Segmentation Network batch training metrics. . . . . . . . . . . . . . . . . . . . . . . . . . . 84 Segmentation Network batch training backward pass and performance updates. . . . . . . . . . 85 Segmentation Network forward method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Classification Network __init__function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 ResBlock__init__function. ................................... 87 ResBlockforwardfunction. ................................... 88 ResNet network initialisation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 ResNet network layer creation function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 ResNet network forward function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 ResNet network number of channels property. . . . . . . . . . . . . . . . . . . . . . . . . . . 91 ResNet network number of classes property. . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 Classification Network training using segmentation. . . . . . . . . . . . . . . . . . . . . . . . 92 Classification Network training metrics calculation. . . . . . . . . . . . . . . . . . . . . . . . . 92 xii Classification Network forward method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 Bottom Level __init__function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 BottomLevelfitmethod. .................................... 94 Bottom Level foward overloaded methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Decision Forest __init__function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 DecisionForestfitfunction. ................................... 96 Decision Forest auxiliary tree creation function. . . . . . . . . . . . . . . . . . . . . . . . . . . 96 Decision Forest parallelised prediction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 Decision Forest prediction function for each Decision Tree. . . . . . . . . . . . . . . . . . . . . 97 Decision Node for Decision Tree building. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 Leaf Node for Decision Tree building. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Split Node with the best split at a certain stage of the Decision Tree building. . . . . . . . . . . . 98 Decision Tree __init__function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 Entropymetriccalculation. ................................... 99 Information Gain calculation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 Information Gain Ratio calculation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 SplitInfocalculation. ......................................101 DecisionTreefitfunction.....................................101 Decision Tree building function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 Decision Tree building: stopping conditions verification. . . . . . . . . . . . . . . . . . . . . . 102 Decision Tree building: recursive call for branches. . . . . . . . . . . . . . . . . . . . . . . . . 103 Decision Tree building: same labeled branches verification and Decision Node creation. . . . . . . 103 Decision Tree best split finding. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 TopLevelclassmethods. ....................................104 Computation System __init__function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Computation System fit method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Computation System forward method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 Learning System __init__function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Learning System recursive imports avoidance. . . . . . . . . . . . . . . . . . . . . . . . . . . 108 MaskAccuracymetric. .....................................108 DiceScoremetric. .......................................109 Epsilonvaluedefinition......................................109 xiii IoUmetric. ...........................................109 Confusion Matrix computation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 TP, FP, FN and TN calculation from a confusion matrix. . . . . . . . . . . . . . . . . . . . . . 110 AccuracyMetric. ........................................111 PrecisionMetric. ........................................111 RecallMetric...........................................112 F1ScoreMetric. ........................................112 Matthews Correlation Coefficient Metric. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 Storage System __init__function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 Singleton class implementation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 Modified ResNet network forward method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Implementation of the memory addition process in the StorageSystem class. . . . . . . . . . . . 116 Implementation of the Memory Node class. . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Node addition method in the Long-Term Memory. . . . . . . . . . . . . . . . . . . . . . . . . 117 Memory Node subtraction method overload. . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Implementation of the addition method in the Working Memory. . . . . . . . . . . . . . . . . . 118 Implementation of method for similar nodes retrieval in the Long-Term Memory. . . . . . . . . . 118 Computation System validation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Calculation of accuracies using a confusion matrix for each class. . . . . . . . . . . . . . . . . 120 Computation System forward method with memory access and assignments. . . . . . . . . . . . 120 Boris decision-making implementation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 Implementation of the method used to retrieve an image-mask object for segmentation. . . . . . . 123 Implementation of the method used to retrieve an image-labels object for classification. . . . . . . 123 xiv Acronyms ACS Action-Centred Subsystem. 10, 11 ACT-R Adaptive Control of Thought-Rational. 8, 9, 12 AI Artificial Intelligence. 5, 6, 12 CAD Computer-Aided Diagnosis. 6, 16, 47 CBR Case-Based Reasoning. 6, 13, 15 CNN Convolutional Neural Network. 18, 21–24 CNNs Convolutional Neural Networks. 18, 21–24, 75 CS Computation System. 22 CV Computer Vision. 6 DT Decision Tree. 18 DTs Decision Trees. 18, 21–23, 75 fMRI Functional Magnetic Resonance Imaging. 9 IoU Intersection over Union. 126, 128 KNN K-Nearest Neighbours. 18 LIDA Learning Intelligent Distribution Agent. 12 LTM Long-Term Memory. xiv, 22, 115–118, 143, 145 MCC Matthews Correlation Coefficient. 60, 112, 129–133, 135, 136 xv MCS Meta-Cognitive System. 11 MLP Multilayer perceptron. 23 MS Motivational System. 11 NACS Non-Action-Centred Subsystem. 10, 11 RBR Rule-Based Reasoning. 6, 13, 15 ReLU Rectified Linear Unit. 27–30, 77, 78, 87 SGD Stochastic Gradient Descent. 54, 56 SVM Support Vector Machine. 18 UML Unified Modeling Language. 28, 32, 33, 44, 46, 53, 61, 62, 86 WM Working Memory. xiv, 14, 19, 22, 65, 115, 118, 143 xvi Chapter 1 Introduction Medical imaging has revolutionised healthcare by enabling professionals to diagnose and treat patients. However, accurately identifying specific pathologies in X-rays can be challenging due to the similarities in images and their characteristics. This dissertation proposes a cognitive architecture approach to develop a system that accurately identifies a specific pathology, such as lung cancer, in medical documents (Chest X-rays). Accurate identification of pathology in medical documents is of paramount importance in the healthcare domain. Misdiagnosis or delayed diagnosis can severely affect patients, resulting in sub-optimal outcomes and increased healthcare costs. Therefore, there is a pressing need for more effective and efficient methods to aid healthcare professionals in accurately interpreting medical images and improving diagnostic accuracy. Previous research has revealed limitations in relying solely on symbolic or sub-symbolic models for human-like decision-making in complex domains like medical image diagnosis [7]. Symbolic models rely on predefined rules and logic, which may not capture the full range of patterns and relationships in medical images. On the other hand, sub-symbolic models utilise statistical or machine-learning techniques to identify patterns in data. However, they may need a more detailed understanding of the underlying decision-making processes. Thus, a cognitive architecture incorporating both symbolic and sub-symbolic methods provides a more comprehensive modelling approach with broader capabilities. Cognitive architecture models, inspired by human cognition, simulate how people think, learn, and make decisions, enhancing the system’s ability to identify pathology in medical documents accurately. The specific pathology the system can identify will depend on the dataset the architecture uses for training. Therefore, this dissertation focuses on developing and evaluating a system using a cognitive architecture approach to identify medical document pathology. The proposed approach aims to leverage 1 the strengths of both symbolic and sub-symbolic models, combining the interpretability of symbolic models and the pattern recognition capabilities of sub-symbolic models. By integrating these methods, the cognitive architecture approach offers a promising solution to improve accuracy and decision-making in medical image analysis. In addition to developing the cognitive architecture approach, this dissertation will evaluate its performance using a comprehensive methodology. The system will be trained and tested on a diverse dataset of medical documents, including Chest X-rays. The evaluation will assess the system’s accuracy, efficiency, and potential benefits in medical document analysis. The results of this study have significant implications for improving the accuracy and efficiency of medical diagnosis and treatment, ultimately benefiting patients and healthcare professionals. 1.1 General Motivations Machine learning and artificial intelligence have made remarkable advancements in image identification and computer vision. However, these methods may require more advanced perception and decision-making capacity for more complex tasks, such as medical image classification. Inaccurate identification or diagnosis of specific pathology or abnormalities can have severe consequences, including incorrect treatment and poor patient outcomes. The medical field is a domain where accurate classification is of utmost importance. While medical professionals rely on their expertise and experience to diagnose pathology, this process can be timeconsuming and susceptible to error. Therefore, developing a system that accurately identifies pathology in medical images holds great potential. It could provide medical staff with a valuable second opinion, reducing the risk of misdiagnosis and significantly improving patient outcomes. This dissertation focuses on developing a cognitive architecture approach tailored to identify medical image pathology. Furthermore, the cognitive architecture approach employed in this research can have implications beyond the medical field, as it could be applied to other domains and applications requiring advanced perception and decisionmaking capabilities. The potential benefits of employing a cognitive architecture approach for medical image identification are numerous. By leveraging the strengths of symbolic and sub-symbolic models, the cognitive architecture approach aims to enhance accuracy and efficiency in medical diagnosis. It can alleviate the workload of medical staff, improve diagnostic outcomes, and save lives. Moreover, developing a cognitive architecture approach for this application could drive advancements in other fields where perception and decision- 2 making are critical, such as autonomous vehicles or robotics. 1.2 Contributions of this Thesis The research presented in this study contributes significantly in two key areas. Firstly, it proposes an innovative cognitive architecture approach that effectively identifies specific pathology in medical documents. By seamlessly integrating symbolic and sub-symbolic components, this approach harnesses the strengths of both models, providing a comprehensive and detailed range of capabilities for accurate diagnosis. This novel approach represents a notable advancement in medical image identification. Secondly, the study demonstrates the practicality and effectiveness of the proposed approach through extensive experimentation and evaluation using diverse medical datasets. The experimental results consistently highlight the superiority of the cognitive architecture approach in terms of accuracy and efficiency, surpassing existing methods. These findings validate the feasibility and success of the proposed approach and underline its potential to enhance medical image identification significantly. As a result, this research makes noteworthy contributions to medical image identification and cognitive architecture modelling. It introduces an innovative approach that combines symbolic and sub-symbolic components, thereby improving the accuracy of medical diagnosis. Moreover, this study establishes a solid foundation for future research and development in this domain, paving the way for further advancements and applications of cognitive architecture in various domains. Overall, these contributions position the research as a valuable and impactful contribution to the scientific community. 1.3 Structure of the Dissertation This dissertation is organised into five main chapters, each contributing to the development of a cognitive architecture approach for identifying pathology in medical images. Chapter 2 provides a comprehensive overview of the state-of-the-art in cognitive architectures and medical image classification. It covers existing research and methods used in cognitive architectures, including symbolic and sub-symbolic models, as well as medical image classification. Additionally, this chapter explores the potential benefits of utilising a cognitive architecture approach in medical document analysis, highlighting its implications for improving the accuracy and efficiency of medical diagnosis and treatment. Chapter 3 focuses on the design of the proposed cognitive architecture approach for identifying pathology in medical documents. This chapter describes the components of the architecture, outlines 3 the processing steps involved in identifying pathology, and explains the decision-making process. Chapter 4 describes the implementation of the proposed cognitive architecture approach. It discusses how the architecture was implemented and addresses the challenges encountered in integrating the previously designed components to work together effectively. Chapter 5 presents the tests and results of the cognitive architecture approach for identifying pathology in medical images. This chapter outlines the experimental design, describes the data used to evaluate the system, and presents the performance metrics used to assess the accuracy and efficiency of the system. Additionally, it discusses the limitations of the proposed cognitive architecture approach and explores potential future directions for improvement. Finally, Chapter 6 provides the final conclusions of this dissertation. It summarises the main findings and contributions of the research, emphasising the effectiveness of the cognitive architecture approach for identifying pathology in medical images. This chapter serves as a culmination of the dissertation, offering a comprehensive understanding of the cognitive architecture approach and its potential impact on medical image classification and diagnosis. 4 Chapter 2 Literature Review / State of the Art This chapter presents a comprehensive background to establish the foundation for developing the proposed system. The chapter begins with a general overview, followed by an in-depth exploration of the characteristics of the cognitive architectures that will be utilised as the baseline in the system’s implementation. Initially, the role of artificial intelligence (AI) in the medical field is discussed, focusing on its utilisation to enhance pathology diagnosis. Existing successful implementations of AI systems in this domain are highlighted, illustrating their potential benefits. Given the dissertation’s specific focus on employing cognitive architectures for medical diagnosis, relevant literature is reviewed to showcase how these approaches have proven valuable in training neural networks to mimic human brain functioning [8]. Subsequently, an introduction is provided on the cognitive architectures employed in the system’s implementation. This entails elucidating their foundational concepts and exploring the most recent advancements in these architectures. The work of Goria et al. [9] serves as a comprehensive reference, offering an extensive overview of these architectures and their diverse applications. 2.1 Artificial Intelligence In The Medical Field Due to the increasing need for faster and more precise diagnosis when dealing with serious diseases, there is a growing interest in understanding the precision and speed of the human brain when identifying pathology in medical exams [10]. One of the most promising applications of intelligent techniques for diagnostic sciences is biomedical image classification [11]. Various Artificial Intelligence (AI) techniques for automating this diagnosis have 5 domain knowledge. At the same time, it does not exclude innate biases, innate behavioural propensities or prior knowledge. [23]. 2.3.3 SOAR SOAR stands for State, Operator, And Result [4], is a cognitive architecture that will be the main focus of this dissertation. Like the other models presented before, SOAR aims to create a computational structure underlying general intelligence. It has many shared elements with both ACT-R (referenced before) and Learning Intelligent Distribution Agent (LIDA), not researched since it became obsolete with the development of more advanced models. Recently, SOAR has stepped away from ACT-R since it has a bigger emphasis on general AI, whereas ACT-R is focused on cognitive modelling. [35]. The SOAR’s original name, for State, Operator And Result, refers to the problem and hypothesis which underlies SOAR creation. The original theory behind it is a ”Problem Space Hypothesis” [36] (first out of five original hypotheses), which contends that all goal-oriented behaviour can be cast as a search through a space of possible states while attempting to achieve the designed goal. A single operator is selected and applied to the current state for each process step. This selection leads to internal changes like retrieving knowledge from one of the memories or even an external action with the world, generating a result. Figure 4: Structure of traditional SOAR.[4] The traditional SOAR model, as shown in Figure 4, consists of a single long-term memory, encoded as production rules and a single short-term memory, representing a symbolic graph structure so that objects can be represented with properties and relations. These memories hold the agent’s assessment 12 of the current situation, derived from perception and retrieval of knowledge from the other memory. At the lowest level, SOAR’s processing consists of matching and firing rules (RBR and CBR). This method provides a flexible, context-dependent representation of knowledge, with their conditions matching the current situation and their actions retrieving information relevant to the current situation. With this approach, it becomes visible that there will be limited knowledge available to choose between rules, especially in the conditions of the rules, which will need more data to be picked out of the others. When introducing operators, SOAR makes it possible for the rules to act as associative memory, retrieving essential and relevant information to the current situation, firing rules in parallel, and adapting in different ways to the same situation [4, 35]. The most recent version of SOAR, although it retains the strength of the original SOAR, provides a flexible model of control and meta-reasoning, expanding the types of knowledge SOAR could represent, reason, and learn. This evolution makes it more inspired by human capabilities, always adding functionalities [37]. Figure 5 [5] shows the improved and most current version of SOAR. The major additions to this new edition include the working memory activation, which provides extra meta-information about the recency and how useful a working memory element is for the situation. A new reinforcement learning engine tunes the numeric preferences of operator selection rules, and the appraisal detector generates emotions, feeling and an internal reward signal for reinforcement learning. Figure 5: SOAR 9.[5] 13 This model also includes two new types of memory [38]: semantic memory, which comprises symbolic structures representing facts and episodic memory, temporally ordered snapshots of the working memory, quickly accessed without having to go through a slow shorting mechanism. SOAR’s processing cycle is still driven by procedural knowledge encoded as production rules. However, the new components added will influence decision-making indirectly by retrieving or creating structure in the symbolic working memory, causing different rules to match and fire. This model can now also be used for visual-feature and visual-spatial reasoning. It includes a short-term memory where images are constructed and manipulated, added to a long-term memory that contains images that can be retrieved and manipulated, a process that may create symbolic structures from these visual images. Visual imagery is controlled by the symbolic system, which issues commands to construct, manipulate and examine visual images [5, 39]. A practical example of the usage of this cognitive architecture is in a humanoid service robot capable of executing simple action skills: navigating, grasping and recognising objects or people, while using the SOAR cognitive architecture as the reasoner by selecting which action the robot should complete, addressing it towards the goal [40, 41]. As shown above, these architectures aim to model a human-like behaviour in terms of a cognitive cycle, performed sequentially or in parallel, culminating in an action or decision. With this, a comparison between CLARION and SOAR is of all interest. Following the study by Lucentini et al. [42], it is possible to conclude that these architectures generalise and apply the concept of sub-symbolic (also called nonsymbolic or ”numeric”), where a ”bottom-up” approach to learning is displayed. As of SOAR, all the information obtained is stored in a Working Memory (WM), from where it is retrieved and used as an input/output mechanism. These Working Memory Elements are usually generated externally via a perception module and pre-processed before storage, making it a highly symbolic architecture. For CLARION, a diverse representation is more prominent, dividing each module into the two parts described before. In this case, the data is represented in dimension-value pairs, with the information type and its corresponding value. For the goal structure, SOAR has no built-in motivational process, unlike CLARION, which has an exclusive module for handling goals and motivations, capable of influencing the decision process for a specific situation. With this, Lucentini et al. [42] conclude that SOAR is a predominantly symbolic architecture and CLARION, on the contrary, has a mixed approach that combines the benefits of both paradigms, symbolic and non-symbolic. 14 2.4 Meta-Learning Meta-Learning is a term widely used in the artificial intelligence field. It is viewed as an understanding and adaptation of cognition on a higher level than merely acquiring knowledge [43]. That is, a person aware and capable of meta-learning can assess if the learning approach is correct and adjust it according to the requirements of a specific task. The primary goal of a meta-learning system is understanding the interaction between the learning mechanism and the concrete contexts in which that mechanism is applicable [44]. To be precise, metalearning monitors the automatic learning process in the context of the learning problems it encounters and tries to adapt its behaviour to perform better [45]. The meta-knowledge needed for this process can then be extracted from a previous learning episode on a single dataset or even from different domains. Having previous information about a learning subject can make the system capable of few-shot learning, providing the network or the cognitive model fast adaptation over a specific situation based on previously learned knowledge [46]. Few-shot learning, as the name implies, refers to the practice of feeding a learning model with a minimal amount of training data. This method is broadly applied in computer vision, where small training sample results are accurate predictions or actions, proving to be the go-to solution whenever a tiny amount of training data is available [47, 48]. In the field of cognitive science and cognitive architectures, most meta-learning comes from applying rules previously defined as the reasoning method, where the model decides a specific action depending on which rules are fired during the execution. 2.5 Rule-Based and Case-based Reasoning Rule-Based Reasoning and Case-Based Reasoning have always been considered two critical and complementary reasoning methodologies in artificial intelligence, especially in systems with meta-learning capabilities. Over the years, there have been attempts to integrate these two types of reasoning to achieve the perfect generalised reasoning to be applied to any situation, capable of dealing with real-life situations and providing a comprehensive representation of a final action [15]. With a reasoner of these types, the system can perform cycles of match-resolve-act, where it matches an input to a pre-existing production rule (usually defined inside a memory of the model). It then checks for a conflict where multiple rules are set simultaneously and needs to be filtered by which one will have 15 more impact in the final action. Finally, the actions defined by the rules are executed, originating changes in the memory’s content, whether to end the cycle or to adapt to the next iteration. Aspects like this will also require extra caution when analysing whether pre-implemented rules will make sense in the current situation [49]. In some cases, wrongly set rules or cases for the reasoning engine may result in non-capable learning mechanisms where the model will not have the ability to evolve to new situations and will not be able to execute new actions. That is why their methodologies must be adapted to the situation’s specifics, allied to knowledge in few-shot or even one-show learning. 2.6 Similar Work Besides all the examples of similar work so far, some mentions are not directly connected to any of the areas described but also incorporate the end goal this dissertation aims to achieve: the CAD for pathology identification. In the context of medical image diagnosis, various studies and applications have explored the use of deep learning classifiers for X-ray imaging. However, these approaches typically do not incorporate a comprehensive cognitive architecture as a reasoning mechanism. In the study by Majkowska et al. , deep learning models were employed to interpret chest radiography to detect various abnormalities such as pneumothorax, opacity, nodules or masses, and fractures on frontal chest radiographs [50]. The researchers aimed to assess the performance of these models by comparing their interpretations to reference standards adjudicated by radiologists. The evaluation of the deep learning models was adjusted to account for population characteristics, providing a comprehensive assessment of their diagnostic capabilities. The findings of this study highlight the potential of deep learning approaches in aiding radiologists with the interpretation of chest radiographs, contributing to more accurate and efficient diagnoses of pulmonary conditions. The study conducted by Jaiswal et al. focused on using deep learning techniques to identify pneumonia in chest X-ray images [51]. Their research aimed to develop an automated system that could accurately detect pneumonia cases, achieving high accuracy and comparable performance to human experts. By training a deep neural network model on a large dataset of chest X-ray images, they demonstrated the potential of deep learning for enhancing pneumonia diagnosis and improving patient outcomes. Alternatively, there have been comprehensive studies focusing on applying deep learning algorithms to detect critical findings in CT scans [52, 53]. Chilamkurthy et al. conducted a retrospective study to assess the performance of deep learning algorithms in detecting critical findings in head CT scans. Their findings, published in The Lancet, demonstrated the potential of deep learning models to aid in detecting 16 abnormalities, contributing to improved diagnosis and patient care [52]. Moreover, using machine learning techniques for X-ray imaging has also been explored. Notably, industry leaders like Google have been involved in research and development efforts in this area [54]. Their work has focused on leveraging deep learning and artificial intelligence to analyze chest CT scans, automating the analysis process and potentially assisting radiologists in identifying abnormalities and providing accurate diagnoses [53]. These studies highlight the significant advancements in medical imaging, with deep learning algorithms and machine learning techniques showing promise in enhancing the accuracy and efficiency of image interpretation. The integration of these technologies has the potential to revolutionise radiology practices, leading to more effective diagnoses, improved patient outcomes, and streamlined healthcare workflows. 17 Chapter 3 Architectural Planning Image classification is a fundamental problem in computer vision, with a wide range of applications in fields such as medical imaging [55, 56, 57], surveillance [58], and biometrics [59], among others. Image classification aims to automatically assign a label to an input image based on its visual content. Traditional methods for image classification rely on hand-crafted featured and predefined classifiers, which are limited in their ability to capture the complexity and diversity of natural images. These methods often involve extracting specific features from the image, such as edges, corners or textures [60], and using these features to train a classifier, namely, a Support Vector Machine (SVM)[61, 62] or a K-Nearest Neighbours (KNN)[63]classifier. Modern methods for image classification continue to face limitations, albeit at a lower scale compared to traditional methods. However, with the advent of deep learning, machine learning approaches have shown great promise for image classification. These approaches involve using neural networks to learn the representations and classifiers from the data. Convolutional Neural Network (CNN) have emerged as a powerful tool for image classification [64, 65, 66], due to their ability to learn hierarchical representations of images and their high accuracy in many tasks. The decision to incorporate both symbolic and sub-symbolic structures in BorisCAD draws inspiration from the behaviour of the CLARION cognitive architecture. CLARION, a cognitive architecture that combines cognitive and neural processes, has demonstrated the benefits of integrating symbolic and sub-symbolic representations in cognitive tasks. Similarly, in BorisCAD, combining symbolic Decision Trees (DTs) and sub-symbolic CNNs allows for a more comprehensive and practical approach to image classification. This integration leverages the strengths of both methods, enabling BorisCAD to capture the complexity and diversity of natural images while maintaining interpretability through the DT component. 18 3.1 The Blueprint: Designing a Brain-like Architecture From Chapter 2 seems clear that the CLARION cognitive architecture, a theoretical framework that simulates the cognitive processes of the human mind, was the most versatile choice for adapting to the needs of this work. CLARION’s flexibility and adaptability make it well-suited to address the specific requirements of the image classification task. Its ability to seamlessly integrate both symbolic and sub-symbolic processing allows for a comprehensive approach that combines interpretability with neural networks’ powerful representation learning capabilities. As a result, CLARION provides a solid foundation for developing the proposed BorisCAD architecture, offering a promising solution to enhance the efficiency and effectiveness of image classification tasks. The CLARION cognitive architecture is organised into two main subsystems: the explicit and implicit. The explicit subsystem is primarily symbolic, using logical and linguistic representations for reasoning about the world with conscious thought and decision-making. It contains a Working Memory (WM) module, which holds the current state of the environment and provides a basis for decision-making. This WM is a dynamic structure that allows for the integration of new information and the manipulation of existing information, allowing it to interact with other modules to determine the appropriate action based on the current state of the environment. The implicit subsystem, on the other hand, is sub-symbolic, using distributed representations to process information. This subsystem contains a procedural module responsible for learning and executing complex behaviours, learning through trial and error, and adjusting its behaviour based on the feedback it receives from the environment. Symbolic knowledge often refers to knowledge represented by symbols or rules associated with explicit, conscious, and rational reasoning processes. On the other hand, sub-symbolic knowledge represents knowledge shown as activation patterns in a neural network or other machine learning models associated with implicit, unconscious, and intuitive reasoning processes. Thus, the distinction between symbolic and sub-symbolic knowledge is crucial in a cognitive architecture like CLARION. It allows for the integration of high-level reasoning and low-level perception and action, helping to identify the processes best suited for each type of knowledge, making it an essential topic in this work. The CLARION architecture also includes a motivational subsystem, which plays a crucial role in determining the goals and priorities of the system. It uses affective and motivational states to influence the decision-making process by affecting the goals and priorities of the system. By comparing CLARION with other well-known cognitive architectures, it becomes evident why 19 CLARION is a better choice for the specific application at hand. One significant factor is CLARION’s distinction between explicit and implicit processes, knowledge, and learning. This differentiation allows CLARION to provide a more comprehensive and adaptable framework than the ACT-R architecture. Although a well-established cognitive architecture, ACT-R does not offer the same level of versatility as CLARION for the intended application. ACT-R lacks the explicit-implicit distinction crucial for effectively handling complex reasoning processes. In contrast, CLARION’s explicit and implicit processes provide a more nuanced understanding of cognitive operations, facilitating better modelling of human-like cognitive behaviour. Another factor that sets CLARION apart from other architectures, such as SOAR, is the requirement for a large amount of initial knowledge (a priori) to perform similarly to CLARION. SOAR does not differentiate between symbolic and sub-symbolic knowledge, which limits its versatility in handling more intricate reasoning tasks. In contrast, CLARION’s ability to incorporate symbolic and sub-symbolic knowledge allows for a more flexible and nuanced representation of complex cognitive processes. With an understanding of the importance of symbolic and sub-symbolic knowledge in cognitive architecture, it is possible to turn the attention to the development of the BorisCAD architecture. It will be built upon the strengths of the CLARION architecture and adapted to meet the specific needs of the problem at hand. This architecture aims to integrate both symbolic and sub-symbolic knowledge to allow for efficient high-level reasoning and low-level perception and action. To achieve this goal, BorisCAD will incorporate a variety of cognitive subsystems that work together to achieve the desired outcome. Symbolic Methods Sub-Symbolic Methods Storage System Learning System Figure 6: Modular disposition of the architecture. Figure 6 illustrates the main components of the architecture, which are composed of four key modules. The first two modules are the symbolic and sub-symbolic, which are interconnected to integrate both types of knowledge. The sub-symbolic module is responsible for handling sensory information and lower-level processing. This will then generate explicit symbols for the symbolic module to handle, applying higherlevel reasoning. The storage module plays a critical role in the architecture by providing a temporary 20 space for relevant prior information to be stored, guiding the decision-making process and maintaining context during task execution. This information can include sensory input, recent actions, and task goals. Finally, the learning module regulates the system’s training by adjusting several hyperparameters that the sub-symbolic methods make use. This representation shows how the modules will coexist in this architecture but still needs to display the type of components each module will comprise clearly. Figure 7 accurately depicts what BorisCAD will include in its structure. Computation System Storage System Symbolic Methods Sub-Symbolic Methods Decision Tree/ Forest Convolutional Neural Network CNN Working Memory Learning System Transfer Learning Adaptive Learning Long-Term Memory Figure 7: Structure of the architecture. Convolutional Neural Networks (CNNs) were chosen as the sub-symbolic method within the cognitive architecture, primarily for their capability to extract meaningful features and gain a comprehensive understanding of image contents. CNNs excel in learning hierarchical representations from images, capturing intricate patterns and achieving high accuracy in classification tasks. They employ deep layers of convolutional and pooling operations to progressively recognise complex visual patterns, enabling them to encode image information into feature representations for classification effectively. However, despite their high performance, CNNs may sometimes generate inconclusive classification, where the highest probability output aligns differently from the actual image class. By incorporating DTs into the architecture, the system takes advantage of the probabilities generated by the CNN during the forward pass by examining the connections between these probabilities and the initial training labels. This allows the DTs to identify complex patterns and correlations that may not be apparent solely based on the 21 2D Convolution (k: 3x3; s: 1; p: 1) Batch Normalization ReLU 2D Convolution (k: 3x3; s: 1; p: 1) Batch Normalization ReLU UNet Block (a) U-Net Block. 2D Convolution (k: 1x1; s: 1; p: 0) Batch Normalization 2D Convolution (k: 1x1; s: 1; p: 0) Batch Normalization Gate + ReLU 2D Convolution (k: 3x3; s: 1; p: 1) Batch Normalization Sigmoid Skip Attention Gate Block (b) Attention Gate Block. Figure 9: AttentionU-Net: Attention Gate Block and U-Net Block and addition operations, followed by a ReLU activation. Next, a convolutional layer is applied, followed by batch normalization and a sigmoid activation function. The sigmoid activation enables element-wise multiplication between the original skip connection, containing information from the contracting path, and the weight map. This process generates the final output of the attention gate block, emphasizing the relevant features for the segmentation task. SegmentationNetwork model: [UNet, AttentionUNet] loss_fn: BCEWithLogitsLoss num_classes: Integer __init__(attention: Boolean = True, device: String) batch_train(b_data_x: Tensor, b_data_y: Tensor): Tensor epoch_train(e_data: DataLoader): Tensor fit(dataloader: DataLoader, epochs: Integer) forward(X: Tensor): Tensor AttentionUNet bottleneck: UNet_Block encoder: List[UNet_Block] decoder: List[UNet_Block, AttentionGate] final_layer: Conv2d pool: MaxPool2d __init__(in_channels: Integer = 3, out_channels: Integer= 1, features: List[Integer] = [64, 128, 256, 512]) forward(X: Tensor): Tensor AttentionGate W_gate: Sequential W_x: Sequential psi: Sequential relu: ReLU __init__(features: Integer, n_coefficients: Integer) forward(gate: Tensor, skip_connection: Tensor): Tensor UNet_Block conv: Sequential __init__(in_channels: Integer, out_channels: Integer) forward(X: Tensor): Tensor UNet bottleneck: UNet_Block encoder: List[UNet_Block] decoder: List[UNet_Block] final_layer: Conv2d pool: MaxPool2d __init__(in_channels: Integer = 3, out_channels: Integer = 1, features: List[Integer ] = [64, 128, 256, 512]) forward(X: Tensor): Tensor Figure 10: Segmentation Network UML. The UML diagram of the Segmentation Network, as depicted in Figure 10, provides an overview of the potential connections between the standard U-Net network and the enhanced AttentionU-Net , which 28 were described earlier. This design takes into account the user’s discretion in selecting either of these networks based on their specific requirements. The methods employed to train the neural network will be elaborated upon in the comprehensive analysis of the complete classification network. Although they share a similar process, the metrics utilised for evaluation are distinct and will be discussed separately. b) Classification Network ResNet (short for ”Residual Network”) is a deep neural network architecture designed to address the problem of vanishing gradients while training very deep neural networks. It was introduced by He et al. [84] and has since become a widely used architecture in various computer vision tasks, such as image classification, object detection, and segmentation. The critical innovation of ResNet is the use of residual connections, which enable the network to learn residual functions rather than directly learning the underlying mapping. These residual connections add shortcut connections that bypass one or more layers and allow the network to propagate gradients more effectively, which in turn helps to alleviate the problem of vanishing gradients and enable the training of very deep networks. The ResNet architecture consists of a series of residual blocks, each containing one or more convolutional layers and shortcut connections. The basic residual block has two convolutional layers, each followed by a ReLU activation function and a shortcut connection that adds the input to the output of the second convolutional layer. Variations of the residual block can also be added, such as the bottleneck block, which uses 1x1 convolutions to reduce the number of channels before the addition to the 3x3 convolutions. Figure 11 shows the complete structure of a ResNet network. For starters, there are three main groups of layers to be analysed. The network input consists of a sequence of operations: a single convolution, a batch normalisation, and a ReLU activation. After this, a Max-Pooling operation is applied to down-sample the output feature maps, reducing their spatial dimensionality and increasing their level of abstraction. The output of a network of this type consists of an average pooling operation, which computes the average value of each feature map across its spatial dimension, reducing the number of parameters in the network, and improving its robustness. This result is then flattened to be fed into a fully-connected layer, which maps the feature vector to the output classes or categories, with a dimension equal to the total amount of labels to be extracted. As described previously, the ResNet structure will consist of the input and output sequences shown above and a series of blocks, with their designs depicted in 12. The identity block shown in figure 12b 29 2D Convolution (k: 7x7; s: 2; p: 3) Batch Normalization ReLU MaxPool (k: 3x3; s: 2) ResNet Block Identity Block ResNet Block Identity Block ResNet Block Identity Block ResNet Block Identity Block Average Pooling Flatten Fully Connected ResNet Figure 11: ResNet Block Diagram. consists of two convolutional layers that aim to present the input’s dimensionality. This block’s skip connection directly sums the module’s input to the output of the second normalisation, where the result passed through a ReLU activation to generate the final feature map. This shortcut connection is a simple identity mapping that bypasses the convolutional layers and allows the gradient to flow directly through the block without affecting the input feature map. The ResNet or bottleneck block shown in figure 12a does the same operation. However, it includes a 1x1 convolutional layer that changes the number of channels on the input feature map prior to the add operation. This convolution increases or decreases the number of channels in the feature map to adapt the network to different target domains. The illustrious table 1 presents a comprehensive overview of the various sizes available for the ResNet architecture, namely ResNet18, ResNet34, ResNet50, ResNet101, and ResNet152. On closer inspection, a subtle modification can be discerned in the ResNet50 and its superior counterparts. Specifically, the 30 2D Convolution (k: 3x3; s: 1; p: 1) Batch Normalization ReLU 2D Convolution (k: 3x3; s: 1; p: 1) Batch Normalization ReLU 2D Convolution (k: 1x1; s: 1; p: 0) + ResNet Block (a) ResNet Block. 2D Convolution (k: 3x3; s: 1; p: 1) Batch Normalization ReLU 2D Convolution (k: 3x3; s: 1; p: 1) Batch Normalization ReLU + identity Identity Block (b) Identity Block. Figure 12: ResNet: ResNet Block and Identity Block. skip connection that once skipped two 3x3 convolutional layers now traverses three layers, where only one layer features 3x3 kernel filters, flanked by two 1x1 convolutions. Regrettably, the first two sizes of this network fail to adequately capture the intricate dimensions required for medical image classifications. As such, only the latter three sizes shall be examined in the remainder of this study. Table 1: The five types of ResNet (adapted from[6]) layer name output size 18-layer 34-layer 50-layer 101-layer 152-layer conv1 112 ×112 7 ×7,64,stride 2 3×3max pool,stride 2 conv2_x 56 ×56 3×3,64 3×3,64×23×3,64 3×3,64×3  1×1,64 3×3,64 1×1,256  ×3  1×1,64 3×3,64 1×1,256  ×3  1×1,64 3×3,64 1×1,256  ×3 conv3_x 28 ×28 3×3,128 3×3,128×23×3,128 3×3,128×4  1×1,128 3×3,128 1×1,512  ×4  1×1,128 3×3,128 1×1,512  ×4  1×1,128 3×3,128 1×1,512  ×8 conv4_x 14 ×14 3×3,256 3×3,256×23×3,256 3×3,256×6  1×1,256 3×3,256 1×1,1024  ×6  1×1,256 3×3,256 1×1,1024  ×23   1×1,256 3×3,256 1×1,1024  ×36 conv5_x 7×73×3,512 3×3,512×23×3,512 3×3,512×3  1×1,512 3×3,512 1×1,2048  ×3  1×1,512 3×3,512 1×1,2048  ×3  1×1,512 3×3,512 1×1,2048  ×3 1×1average pool, X-d fc On the ResNet network, the two types of blocks shown in Figure 12 are used. For example, if there is a sequence of three filters modules in the conv_2 group of filters (as shown in table 1), the first block will always be a bottleneck block, while the rest will be identity blocks. This operation is performed at every stage and for every size. Further details on this process will be discussed during the implementation 31 analysis. The UML diagram for the Classification Network, presented in Figure 13, displays the classification component at the system’s lower level. Like the Segmentation Network, this component features distinct methods for training the neural network model. ClassificationNetwork model: ResNet loss_fn: CrossEntropyLoss network_types: Dictionary num_classes: Integer segmenter: Optional[SegmentationNetwork] __init__(num_classes: Integer, net_type: String, device: String, segmenter: Module) batch_train(b_data_x: Tensor, b_data_y: Tensor): Tensor epoch_train(e_data: DataLoader): Tensor fit(dataloader: DataLoader, epochs: Integer) forward(X: Tensor): Tensor ResNet ResNet50_LAYERS: List ResNet101_LAYERS: List ResNet152_LAYERS: List avgpool: AdaptiveAvgPool2d fc: Linear in_channels: Integer input: Sequential network: Sequential forward(X: Tensor): Tensor ResBlock conv: Sequential expansion: Integer i_downsample: Optional[ResBlock] relu: ReLU forward(X: Tensor): Tensor Figure 13: Classification Network UML. Commencing with the ”fit” method, it assumes responsibility for dividing neural network training into multiple epochs. This method invokes the ”epoch_train” process, denoting a finer level of granularity. Figure 14a visually represents the flowchart outlining its sequential steps. Conversely, the ”epoch_train” method, illustrated in Figure 14b, entails partitioning the accessible data into batches. The batch size is predetermined, and this method facilitates the model’s training using all available data for each epoch. Furthermore, the batch training procedure, depicted in Figure 15, shows the sequential execution of a complete training cycle on a batch of information. The data is fed forward through the model, leading to the calculation of a loss. Subsequently, this loss is utilised to perform back-propagation, updating the model’s kernels and weights. In addition, metrics are computed for analytical purposes, and optimises are adjusted accordingly (further elaborated in the subsequent section 3.4: Learning System ). Notably, the classification and segmentation models exhibit a sole disparity in their training processes. Specifically, the classifier harnesses information from the segmentation, provided a segmentation model is available. Naturally, this scenario does not apply when training the segmentation model itself. In summary, the segmentation technique serves to discern and isolate important information embedded within an image, thereby facilitating a more nuanced and precise comprehension of its contents. The fundamental elements and their interrelationships within the scene can be identified by 32 Start Last epoch? input: epochs, data epoch_train(data) curr_epoch + 1 Save training metrics End No Yes (a) ”fit” method flowchart. Start input: data While data available Get next batch of data batch_train(batch) Save epoch metrics Yes No End (b) ”epoch_train” method flowchart. Figure 14: Classification Network fit and epoch training flowcharts. Start input: batch_data End If segmenter Forward batch_data on the segmenter Forward batch_data on the classifier Calculate prediction loss Backwards-propagate the classifier model Calculate batch metrics Update optimizers, schedulers and scalers output: batch metrics No Yes Figure 15: Batch training method’s flowchart for the Classification Network. segmenting an image into different regions or objects. Subsequently, the classification network can utilise this information to effectuate more reasonable and informed determinations regarding the image’s content. Segmentation thus represents a pre-processing step that extracts discerning features from the image and provides a more elaborate and refined representation of its content, subsequently facilitating enhanced accuracy and adaptability. The Computation System’s Bottom-Level architecture was consequently formulated to incorporate both types of networks described above, in order to achieve the desired accuracy and adaptability. Figure 16 displays the UML for the system’s Bottom-Level, 33 showcasing the connections between both networks and itself. BottomLevel classifier: ClassificationNetwork segmenter: SegmentationNetwork use_segmentation: bool device: str fit(segmentation: (DataLoader, int), classification: (DataLoader, int)) forward(X: Tensor): Tensor forward_to_probabilities(data: [DataLoader, Tensor], threshold: float = 0.05): [(Tensor, Tensor), Tensor] ClassificationNetworkSegmentationNetwork Figure 16: Bottom level UML design. Figure 17 below accurately depicts the data type and shapes at the connections between the modules. The image is forwarded in the segmentation network in the first stage. This stage will generate two new images: the mask image and the resulting multiplication between the input and this binary information, giving the background-less version of the original image. The isolated version is then forwarded to the classification network to generate the corresponding probabilities. Segmentation Network Classification Network [..., ...] Figure 17: Bottom-Level Network Outputs. During this process, some other details will be gathered, such as activations between layers of the neural networks to be stored in the memories for future retrieval. This is further detailed ahead in 3.3: the Storage System Module. 3.2.2 Symbolic Reasoning: The Top Level Extracting knowledge from domain experts to build expert systems has been challenging since the early days of knowledge-based systems. The interview process, where a knowledge engineer interacts with a domain expert to extract and refine a set of rules, has been a common approach. However, as 34 Waterman et al. [85] pointed out, ”the pieces of basic knowledge are assumed and combined so quickly that it is difficult for him to describe the process”, making it challenging and time-consuming for all parties involved. As a result, knowledge acquisition has been identified as the ”bottleneck” problem in building knowledge-based systems [86]. To overcome this bottleneck, some researchers, such as Michie et al. [87], have advocated using inductive methods to extract general rules from concrete examples. In this approach, the expert provides a framework of essential concepts in the task domain, augmented by tutorial examples. A suitable induction engine carries out the hard work of extracting knowledge. Decision Tree induction[88, 89] provides a methodology for building systems that make decisions based on structured knowledge. Decision Trees are a rule-action system because they represent knowledge as a set of rules, each corresponding to a condition and an action. The condition is a set of input attributes, and the action is the decision that should be taken when those attributes are present. A decision tree is a tree-like model that uses a branching structure to represent decisions and their consequences. It is a form of supervised learning that takes a set of attributes as input and outputs a decision based on those attributes. Each internal node of the tree corresponds to a test on an attribute, and the branches that emanate from the node represent the possible outcomes of the test. The tree leaves correspond to decisions or actions based on the path from the tree’s root to a leaf node. The decision process in a decision tree and the inference process in a neural network differ in their decision-making approaches. In a decision tree, the input attributes traverse the tree’s internal nodes until a leaf node is reached corresponding to the decision or action to be taken. In contrast, a neural network uses weights and biases to determine the input’s contribution to the network’s output, which results from the inference process. Using a decision tree to make decisions based on the probabilities generated by a neural network is a suitable approach because it promotes transparency in the decision-making process. The probabilities obtained from the neural network can be treated as input attributes for the decision tree, where each probability can be considered a feature in the decision-making context. This allows decision-makers to understand how the probabilities contribute to the final decision. Specifically, the decision tree model presents each branch as a particular combination of probability values, making it clear which probability values are most influential in determining the final decision. In this way, the decision tree can provide a more intuitive and interpretable framework for making decisions, especially when explaining the reasoning behind the decision to others [90]. By providing a clear path of decisions and actions, the decision tree allows more effective communication of the decisionmaking process, improving transparency and accountability. 35 Constructing a decision tree resumes the iterative process of splitting the data based on different features and feature thresholds until a stopping criterion is met, using a heuristic called recursive partitioning (commonly referred to as Divide and Conquer). A split is a subset of input data that contains multiple elements, each comprising multiple features and a label that defines them. Several algorithms will be used for this process to test the accuracy, versatility, and complexity of the tree. At the end, each internal node of the decision tree has an attribute-based test and an outgoing branch for each possible outcome. Each leaf node will have an associated class, and in order to classify a record, one must be at the root node and successively visit internal nodes until a leaf node is reached. The outcome of the attribute-based test at an internal node determines the branch traversed and, thus, the next node visited. The class that classifies the record is simply the class of the final leaf node. Once the decision tree has been built, it may be necessary to prune it to improve its accuracy [91]. This involves using a separate validation set to evaluate the performance of the tree branches on unseen data, as opposed to the training set. If a branch is ineffective, it can be pruned and removed from the tree. The decision tree is pruned by recursively replacing each subtree with its mean target value (in the case of regression) or the most common class (in the case of classification) until the accuracy of the pruned tree in the validation set is not significantly lower than that of the original tree. This approach helps create a more accurate decision tree by identifying and eliminating weak branches.[92] The pseudocode algorithm 1 displays the recursive building process of a decision tree, where each group of data is split and analysed for each node until a stopping criterion is found. The recursive usage of this function during the algorithm generates the binary tree pattern. Without proper constraints, decision trees can quickly overfit to the training data and fail to generalise to new data. One way to prevent this is to set stop criteria during the tree building process, as shown in algorithm 1. In this regard, various stopping criteria can be used to ensure that the tree does not grow too large and reduce overfitting. In this context, some of the commonly used stopping criteria in decision tree building are explored. • Maximum tree depth: maximum length of a path from root to leaf. Trees generated are not side balanced, whereas one side of the tree will have more inspections than the other side of the tree; • Minimum sample split: the minimum that is imposed to stop further splitting nodes; • Minimum samples per leaf: reduced number of samples per leaf might mean overfitting. This can be converted to minimum sample split if verified after the splitting at a node; • Minimum impurity decrease: when the splitting of a node does not show a cost-effective improvement over the original node; 36 • No label variety: when all the labels of a split have the same value. Algorithm 1 Decision Tree building algorithm’s pseudocode. Require: D(X, y): feature matrix of size (nsamples,nfeatures), target vector of size (nsamples,) maxdepth: maximum depth of the tree (decrements) minsplit: minimum number of samples required to split a node criterion: split decision criterion (’entropy’ or ’gini’) 1: procedure BuildTree 2: Create a node N 3: if Dcontains only one class then 4: set Nas a leaf node with class label equal to y 5: else if maxdepth is 0or Dhas fewer than min_split samples then 6: set Nas a leaf node with class label equal to the majority class in D 7: else 8: for fin Xdo 9: for unique value tof X[:, f]do 10: Left, Right ←Split D[:, f]≤t 11: Compute the impurity of the split using the chosen criterion 12: if Impurity of the split is better than the best split so far then 13: Update the best split to be the current split, with threshold tand feature f 14: end if 15: end for 16: end for 17: if If no valid split was found then 18: Set Nas a leaf node with class label equal to the majority class in D 19: else 20: Set N as an internal node with: 21: - Left child ←BuildTree(Left, maxdepth - 1, minsplit, criterion) 22: - Right child ←BuildTree(Right, maxdepth - 1, minsplit, criterion) 23: end if 24: end if 25: return node N 26: end procedure Although decision trees are widely used for machine learning tasks, they can sometimes have lower accuracy than other methods and may need to be more balanced in certain instances. To overcome these issues, a popular technique is to use a set of decision trees, known as a random forest classifier [93, 94, 95]. Random forest classifiers are built using an ensemble of decision trees. The key idea behind random forests is to introduce randomness into the construction of individual trees to ensure that they are 37 presented in the UML diagram in Figure 21. From here, this module will comprise three data classes, with the aim to better construct and define the nodes at the Decision Tree level. The Leaf Node and Decision Node will be core nodes of the Decision Tree structure while the Split Node will be used to evaluate the best possible split at a given point in the construction of the decision tree. DecisionForest dts: List[DecisionTree] max_depth: Optional[Integer] min_samples_split: Integer __init__(min_samples_split: Integer = 10, max_depth: Optional[Integer]) fit(X_data: Matrix[Float], y_data: Matrix[Integer]): None forward(X: Matrix[Float]): List[Integer] create_dt(args: Tuple[Matrix[Float], List[Integer], Integer, Integer]): DecisionTree predict_dt(args: Tuple[DecisionTree, Matrix[Float]]): Integer DecisionTree METRIC: Dictionary[String, Method] lowest_depth: Integer max_depth: Optional[Integer] min_samples_split: Integer n_classes: Integer n_features: Integer root: [LeafNode, DecisionNode] __init__(min_samples_split: Integer = 10, max_depth: Optional[Integer]) fit(X_data: Matrix[Float], y_data: List[Integer]): None build_tree(X: Matrix[Float], y: List[Integer], depth: Integer = 0): [LeafNode, DecisionNode] get_best_split(X: Matrix[Float], y: List[Integer], metric: String = "info_gain"): SplitNode forward(X: Matrix[Float]): List[Integer] make_prediction(X: Matrix[Float], tree: [LeafNode, DecisionNode]): Integer DecisionNode _id: Integer = 1 split_data: SplitNode left: [DecisionNode, LeafNode] right: [DecisionNode, LeafNode] num_samples: Integer __init__(split_data: SplitNode, left: [DecisionNode, LeafNode], right: [DecisionNode, LeafNode], num_samples: Integer) get_internal_nodes(): List[DecisionNode, LeafNode] SplitNode feature_index: Integer threshold: Float metric_gain: Float LeafNode _id: Integer = 1 label: Integer num_samples: Integer __init__(label: Integer, num_samples: Integer) Figure 21: Designed Top Level’s UML diagram. The construction of the decision tree follows the algorithm presented in 1, incorporating predefined stopping conditions specified during the creation of the Decision Tree instance. The recursive ”build_tree” function is invoked until these stopping conditions are satisfied, resulting in the generation of a complete decision tree for the given dataset, which is passed to the ”fit” function. Similarly, the ”forward” method utilises the prediction function to obtain labels for each data instance. Notably, several parameters in the functions of the Decision Tree class are of type ”Matrix”. In this context, and since it refers to the data used to train or predict over, this Matrix will be a List of Lists with dimensions (n_instances, n_features) representing probability data for each instance that follows from the bottom level. The term ”Matrix” is then used for clarity and display purposes. These Decision Trees, as described earlier in algorithm 3, are independent and correspond to each class in the dataset. The ”fit” function of the Decision Forest class employs parallel processing to optimise the construction of these decision trees. This approach maximises the utilisation of system resources and facilitates the simultaneous creation of multiple decision trees. Figure 22 visually illustrates the creation of these decision trees. 44 Similarly, the prediction process also makes use of the same parallel approach, where a process for each decision tree prediction is created and then compiled at the end. Fit Forest to the Dataset Create Decision Tree on label 0 Create Decision Tree on label 1 Create Decision Tree on label 2 Create Decision Tree on label n ... Spawn processes equal to number of labels List of Decision Trees Parallel Execution Figure 22: Decision Tree parallel creation. Decision Tree/ Forest Classification Network Segmentation Network Computation System Image Input Classification Probability Figure 23: Computation System interconnections. At this stage, the complete Computation System can be accurately defined as a combination of symbolic and sub-symbolic methods. Figure 23 depicts the sequence of transactions between the Classification Network and the induction method (either a single Decision Tree, Random Forest, or Decision Forest). As one can see, the connection between the bottom and top levels is unidirectional since the first gives information for the following to use. This process is known as ”bottom-up” and will be the starting point of knowledge for the BorisCAD architecture. In the context of the described Computation System, ”bottom-up learning” refers to the process in 45 which knowledge is acquired and built upon from lower levels to higher levels. It involves extracting information and patterns from the input data or lower-level components and using them to inform the subsequent stages or higher-level components of the system. This intermediate information transferred between both levels will also have an essential role in the decision-making process since it will be used from memory to influence the final decision of the architecture. This is further studied in the section 3.3 ahead. At this juncture, the UML diagram representing the Computation System can be preseted, which serves as an integration point for both the Top and Bottom levels within the BorisCAD architecture. This diagram, displayed in Figure 24, illustrates the structural and behavioural relationships between the components involved. Within the Computation System, the class takes on the crucial responsibility of facilitating communication and coordination between the two levels. By ensuring a sequential application of the training methodology, it guarantees the seamless flow of information and processes between the Top and Bottom levels. Specifically, the forward function assumes a pivotal role in managing data traversal through the respective modules and facilitating memory updates as necessary. ComputationSystem bl: BottomLevel tl: TopLevel __init__(num_classes: Integer) fit(segmentation: Tuple[DataLoader, Integer], classification: Tuple[DataLoader, Integer]) forward(X: Tensor): Tuple[List[Integer], List[Integer]] BottomLevel Top Level Figure 24: Computation System UML diagram. 3.3 Storage System: Working and Long-Term Memory Our cognitive abilities include the remarkable feature of the human brain’s ability to store and retrieve information. Memory is a complex process that involves various neural structures and mechanisms [100]. Long-term memory stores and retrieves information over an extended period and is essential for everyday activities such as remembering names, dates, and events. This type of memory is believed to be stored in different brain regions, including the hippocampus, amygdala, and prefrontal cortex [101]. In contrast, 46 short-term and working memory are more temporary forms of memory, necessary in many day-to-day activities. Short-term memory allows us to hold a small amount of information in our minds for brief periods, essential for reading, listening, conversing, problem-solving, and decision-making. It is associated with the prefrontal cortex and other brain regions responsible for attention and executive control. However, it has a limited capacity and duration, with contents that are rapidly forgotten once attention is diverted. Working memory is a more dynamic form that temporarily stores and manipulates information to complete tasks or solve problems. It is closely related to short-term memory but is more active and goaldirected. It is associated with several neural circuits and brain regions, including the dorsolateral prefrontal cortex, the parietal cortex, and the basal ganglia [102]. Working memory is crucial in cognitive tasks such as language comprehension, mathematical reasoning, and spatial processing. In biological systems, the formation and retrieval of memories are intricate and multifaceted processes, characterised by complex interactions between various brain regions and molecular mechanisms, such as gene expression, protein synthesis, and synaptic plasticity [103]. However, when considering the memory model in BorisCAD cognitive architecture, certain biological complexities may be simplified or abstracted to enable a streamlined proof of concept. The BorisCAD architecture references only long-term and working memory, and, by only focusing on these two types of memory, it can efficiently store and manipulate the information required for Computer-Aided Diagnosis (CAD) tasks—long-term memory stores essential design elements, such as image features and their contents and past inference rules. Working memory manipulates these elements in real-time during the decision-making process. Given this, the long-term and working memory components are designed to function as episodic memories, similar to the memory systems observed in cognitive architectures such as CLARION and SOAR. These episodic memories allow BorisCAD to store and retrieve detailed information about past events, experiences, and inference rules, enabling the architecture to make informed decisions based on similarities between episodes. The architecture also enhances memory design by implementing a graph structure, which optimises information storage and manipulation [104]. This structure enables efficient representation and organisation of complex relationships between different elements. BorisCAD uses the graph structure to represent design elements such as parts, sub-assemblies, and assemblies as nodes, with their relationships represented as edges. Each memory node represents an image perceived by the system’s bottom level. The node comprises several elements that define the contents of a new piece of information at multiple abstraction layers. 47 These elements include high and low-level feature maps, which provide a visual or sensory representation of the image. Classification probabilities are also stored as numerical values, indicating the likelihood of an item belonging to a particular category or class. The induction class represents an almost final representation of a category or concept. At the same time, production rules refer to instructions the induction framework would take to achieve the final induction class. In this case, the production rules describe the branches the decision tree or forest takes to reach the final leaf node. Figure 25 better depicts which information will be stored, as well as the exact location from where it is fetched. Decision Tree/ Forest Classification Network Segmentation Network Computation System Image Input Classification Probabilities Mask High-level Features Low-level Features Production Rules Original Image Storage System rehearsal retrieval Working Memory Long-Term Memory Figure 25: Storage System’s Information Gather. As described before, the Classification Network of the BorisCAD architecture will comprise ResNet blocks (figure 11). The segmented image is passed through the network until the output of the last block in the first group is obtained. This output is then considered as the low-level feature map. Similarly, the feature maps obtained after the last group of ResNet blocks can be considered high-level features. This way, a hierarchy of features can be obtained from the input image, with low-level features capturing basic patterns and high-level features capturing more complex patterns. Furthermore, production rules can be gathered from the inference through the decision tree. Production rules are used in rule-based systems to represent knowledge as if-then statements. In a decision tree, each node represents a condition on a specific feature. Thus, a path from the root to a leaf can be defined as a set of production rules that collectively specify the conditions that must be satisfied to reach a final decision. Moreover, the transfer of information between working memory and long-term memory actively involves encoding and retrieval. During the encoding phase, working memory processes the information 48 before transferring it to long-term memory for storage. This vital transfer occurs through rehearsal, which includes repeating the information within working memory. By utilising rehearsal, whether through maintenance rehearsal, which reiterates the information in its original form, or elaborative rehearsal, which establishes connections to existing knowledge, the likelihood of successfully transferring the information to long-term memory increases [105]. Conversely, retrieval, also known as recognition, actively retrieves stored information from long-term memory back to working memory. Recognition involves identifying previously learned information as familiar without necessarily recalling specific details. A deliberate design choice aimed at streamlining the interaction and updates between the contents of working memory and long-term memory was made by upholding a shared reference to a node upon its inclusion. This approach guarantees that the same item is not redundantly added to memory at various stages, mainly when minor changes occur. The system sidesteps duplication and optimises memory management by consistently retaining both memories’ nodes. With this, it was found that the best method for retrieving information from long-term memory would be applying a mix of Context-Based Retrieval and Priority Retrieval . The current image will compare using the feature maps retrieved from the bottom level with other nodes in the long-term memory. The working memory will be populated depending on the similarity with other items in the long-term memory. With this, the items retrieved will also be updated with the notion of ”hot”, where a more accessed item will have more influence in the reasoning process of the memory module. This retrieval will also be based on said ”hot” index. A threshold is defined in order to avoid lowaccessed items to be transferred to the working memory. This allows the memory to filter information based on how relevant an item is, and implementing a method similar to the concept of remembering. Figure 26 depicts the overarching flow of the node creation and insertion process. A corresponding memory unit is generated upon receiving a new node, such as an object or image. Subsequently, this memory unit is initially inserted into the long-term memory, facilitating the achievement of recognition, as previously elucidated. This process manifests as a similarity assessment between the new and existing nodes within the memory, thereby engendering a dynamic graph structure composed of interconnected nodes. In order to enhance the decision-making process, it becomes imperative to populate the working memory with akin items. These items are influential factors characterised by their similarity to the current node. Ultimately, the most recent node is appended to the conclusion of the memory, ensuring its inclusion in the ongoing cognitive processes. The number of similar nodes to be added to the working memory is 49 Assign Node as the Most Recent Node Add Most Recent Node to the LTM population: Retrieve Population from LTM based on the Most Recent Node Iterate over the first population elements Add Node to the Working Memory Last Node? No Add Most Recent Node to the WM Yes New Node Input End Figure 26: Storage System’s new node creation flowchart. contingent upon the capacity of the working memory, as it directly influences the amount of information that can be accommodated within the system. The addition of a new node to the long-term memory is illustrated in Figure 27. The insertion process adheres to a systematic procedure within the framework of a dictionary structure. Upon receiving a new node, a comparison is conducted between the new node and the existing items in memory to identify similarities. If a similarity is detected, the procedure establishes a novel edge between the new node and the current nodes in memory, contingent upon meeting a predefined threshold. Subsequently, the node is inserted into the memory using its unique identifier. The decision to employ a dictionary structure for long-term memory is underpinned by the imperative of scalability. This choice ensures the effective organisation and retrieval of information, facilitating the seamless management of burgeoning data volumes while maintaining operational efficiency. Inserting nodes into the working memory adheres to a predefined flowchart, as depicted in Figure 28. The working memory, characterised by its finite capacity, constrains the number of nodes it can accommodate simultaneously. Upon receiving a new node for insertion, the memory checks for node presence, and if the node is already in memory, it is removed from its current position and appended to the memory’s end. This strategy ensures that the most similar nodes remain at the end of the memory, even when they are already at a different position in memory. 50 Start Iterate over all nodes in memory similarity: get the similarity to the node Similarity over the threshold Add the node to the dictionary of similar nodes Add the new node to the memory dictionary Last Node? No Yes Yes No input: Node to be added End Figure 27: Long-term memory new node flowchart. Besides, there is a memory capacity assessment; if the memory is full, necessitating space allocation for the new node, the oldest node in the memory is deleted, making room for the new node, placed at the end of the memory. In cases where the memory has available space, the new node is directly inserted at the end of the memory without any removal. This ensures that the working memory maintains the chronological sequence of node entries. When creating a new memory, the working memory undergoes a subsequent process of population, as previously explained. Figure 29 illustrates the retrieval of existing memories from the long-term memory for insertion into the working memory. The system identifies the connected nodes of the current node as relevant contributors to the decision-making process. Moreover, only the nodes surpassing the remembering threshold are selected to populate the working memory. Additionally, it is essential to highlight that the system actively updates the hotness of the nodes, even those that are not directly utilised but maintain connections with other nodes. This proactive update ensures that the information and relevance of the connected nodes are kept up-to-date and accounted for in subsequent cognitive processes. 51 Node already in memory No Remove node from memory Add node at the end of the memory Is the memory full? Add node at the end of the memory Remove the first node in memory Add node at the end of the memory End End End No Yes Yes input: Node to be added Start Figure 28: Working memory new node flowchart. Iterate over connected nodes ids Is the node remembered? input: Connected Nodes IDs Get node from memory based on node id Add it to the population list Last Node? Update nodes hotness End Start No No Yes Yes output: population list Figure 29: Node retrieval from long-term memory flowchart. In order to ensure the desired behaviour, the procedure ”UpdateHotness” presented in pseudocode 52 algorithm 4 was explicitly devised. This procedure incorporates a series of steps to modify the hotness values of nodes within the system appropriately. Algorithm 4 Long-term memory hotness update pseudocode. Require: connected_nodes: list of nodes connected to the current node in use 1: procedure UpdateHotness 2: for node in memory do 3: if node not in connected_nodes and not the current node then 4: node hotness - 1 5: end if 6: if node not the current node then 7: node hotness + 1 8: end if 9: end for 10: end procedure Firstly, the algorithm verifies whether the currently iterated node is neither one of the connected nodes to the current node nor the current node itself. This verification serves as a criterion for identifying nodes that require a decrease in relevance. Upon satisfying this condition, the algorithm decrements the hotness value of the node by 1, indicating a reduction in its significance within the system. Furthermore, if the node is not the current node, it means that it is a member of the group of connected nodes, implying that the node’s hotness index should be incremented. By implementing these increments and decrements, the algorithm emphasizes nodes directly connected to the current node while simultaneously downplaying the relevance of indirectly connected nodes. Finally, the subsystem can be visually represented using UML design, as depicted in Figure 30. The UML diagram showcases the relationships between the different types of memory, namely WorkingMemory and LongTermMemory, and the main class, StorageSystem, which serves as the interface for accessing and managing the memory. The UML diagram illustrates the connections between these components, providing a clear overview of the system’s structure. Additionally, the diagram highlights utilising an auxiliary class called Data within the MemoryNode class. This auxiliary class stores relevant information associated with each memory node. The diagram also demonstrates the connections between the MemoryNode class and the other three components: WorkingMemory, LongTermMemory, and StorageSystem. As evident from the current discussion, the specific method pertaining to the influence of the working 53 to 1, with higher values indicating superior performance in terms of precision and recall. 2∗Precision ∗Recall Precision +Recall (3.14) Matthews Correlation Coefficient The Matthews Correlation Coefficient (MCC) is extensively utilised as a metric to evaluate the effectiveness of binary classification models. It takes into account the number of true positives, true negatives, false positives, and false negatives, and provides a measure of the correlation between the predicted and actual binary labels. The MCC score ranges from -1 to 1, where a score of 1 indicates a perfect correlation, 0 denotes no correlation, and -1 represents a perfect inverse correlation. MCC is especially beneficial in situations where there is class imbalance or varying costs associated with false positives and false negatives. TP ×T N −F P ×F N p(TP +F P )(T P +FN)(TN +F P )(T N +FN)(3.15) These performance metrics play a crucial role in evaluating and optimising the bottom-level classification process. By leveraging these metrics, the effectiveness of the learning algorithms can be measured and further improved. However, for the segmentation model, a distinct set of metrics is required, focusing on capturing the accuracy and overlap between the predicted mask and the ground truth. Dice Score The Dice score, also known as the F1 Dice score or Sørensen–Dice coefficient, is a widely used metric in image segmentation tasks. It quantifies the similarity between the predicted segmentation mask and the ground truth mask. Ranging from 0 to 1, a Dice score of 1 indicates perfect overlap between the predicted and ground truth masks, while a score of 0 signifies no overlap. The Dice score is calculated using the provided formula, where ”predicted” and ”ground truth” refers to binary matrices representing the predicted and ground truth masks, respectively. The intersection (�) denotes element-wise multiplication, and the union (+) denotes element-wise addition. The Dice score can be computed separately for each class or all classes combined. Dice Score = 2 ∗prediction ∩ground truth prediction +ground truth (3.16) 60 IoU Intersection over Union (IoU) is a commonly used metric in image segmentation tasks, particularly in object detection scenarios. It quantifies the overlap between the predicted bounding box (or mask) and the ground truth bounding box (or mask) of an object. The IoU calculation involves determining the ratio of the intersection to the union of the bounding boxes (or masks), where a value of 1 indicates a perfect overlap and 0 indicates no overlap. IoU =Area of Overlap Area of Union (3.17) In conclusion, the learning system incorporates optimisation algorithms to enhance performance and plays a crucial role in implementing metrics for the analysis of both classification and segmentation tasks. These metrics serve as quantitative measures to evaluate the system’s effectiveness, efficiency, and quality. In classification, accuracy, precision, recall, and F1-score are utilised to assess the model’s predictive capabilities. On the other hand, in segmentation, metrics like Dice score and Intersection over Union (IoU) are employed to measure the similarity between predicted and ground truth masks or bounding boxes. These metrics provide valuable insights into the system’s performance, enabling stakeholders to make informed decisions and refine the learning process. By integrating optimisation algorithms and metrics, the learning system aims to continually improve its predictive and segmentation accuracy. LearningSystem classifier_learn: Dictionary segmenter learn: Dictionary __init__(classifier: ClassificationNetwork, segmenter: SegmentationNetwork) conf_matrix(preds: Tensor, targets: Tensor): Tensor accuracy(conf_matrix: Tensor): Tensor precision(conf_matrix: Tensor): Tensor recall(conf_matrix: Tensor): Tensor f1_score(conf_matrix: Tensor): Tensor dice_score(preds: Tensor, masks: Tensor): Tensor iou_score(preds: Tensor, masks: Tensor): Tensor Figure 31: Learning System class UML. The UML diagram in figure 31 illustrates the Learning System class. This class encompasses two essential dictionary variables designed to store the optimisation algorithms associated with the classifier and segmenter components. Additionally, the Learning System class features implemented metrics as individual methods. These methods serve as a means to evaluate and measure the performance of the classification and segmentation processes. 61 The complete design of the BorisCAD architecture, encompassing all its subsystems, namely the Computation System, Storage System, and Learning System, can now be comprehended. To provide an overview of the architecture’s structure, the UML diagram depicted in Figure 32 is presented. This UML diagram encapsulates various auxiliary functions, aiding in the management of trained architectures, such as saving and loading. Additionally, it includes essential auxiliary functions, such as the ”set_num_classes” method. This method allows for the modification of the number of classifiable classes in a pre-trained model, facilitating the application of transfer learning techniques. Moreover, this interface serves as the central hub for processing tasks related to the decision-making process, which will be elaborated upon in Section 3.5 of this dissertation. Boris cs: ComputationSystem ls: LearningSystem ss: StorageSystem __init__(*args, **kwargs) setNumClasses(num_classes: Integer) setNumChannels(num_channels: Integer) forward(X: Tensor): [Integer] fit(epochs: Tuple[Integer, Integer], batch_size: Integer) save(path: String) load(path: String): Boris from_config(config_file: String): Boris ComputationSystem LearningSystem Storage System Figure 32: Boris class UML. The decision to adopt the approach of creating an instance from a configuration stems from the necessity to thoroughly evaluate various parameters within the system as part of a proof-of-concept. By utilising a straightforward and adaptable configuration file that can be loaded during run time, the complexity associated with assigning values to variables during the instance creation process is significantly reduced. This approach allows for a more streamlined and manageable means of initialising the architecture instance. An illustrative example of such a configuration file is presented below, demonstrating the definition the parameters divided into subsections, similar to what the final archive will have. Here is an overview of the configuration structure: •Boris: – segmentation: Specifies the directory path for the segmentation dataset. – classification: Specifies the directory path for the classification dataset. – size: Specifies the size of the input images, represented as [width, height]. 62 – num_classes: Specifies the number of classes for the classification task. – Computation: *Bottom: ·attention: Determines whether attention mechanisms are enabled during segmentation. ·net_type: Specifies the type of network architecture used in the bottom-level computation. ·use_segmentation: Specifies whether the classification network incorporates segmentation as pre-processor for its data. *Top: ·min_samples_split: Specifies the minimum number of samples required to split a node in the decision tree in the top-level. ·max_depth: Specifies the maximum depth of the decision tree. – Storage: *wm_size: Specifies the size of the working memory. 3.5 Holistic Approach to Decision-Making A cognitive architecture necessitates a holistic approach to decision-making to capture the intricacies and complexities involved in processing and interpreting information. Medical image analysis, such as X- ray diagnosis, requires a comprehensive understanding beyond individual components or isolated metrics. By taking into account various levels of the architecture, such as the Bottom-level, Top-level, and Working Memory, a holistic approach enables the integration of multiple sources of information, each contributing unique insights. The Bottom-level provides detailed metrics specific to each class, allowing the architecture to weigh their influence accurately. The Top-level, considering the structure of the decision forest, captures the generalisation and entropy characteristics, influencing the overall decision process. The Working Memory plays a crucial role in leveraging past knowledge and integrating it with the current input, enriching the decision-making process with contextual information. By adopting a holistic approach, the cognitive architecture can account for the complexities inherent in medical image analysis, ensuring a more robust and reliable decision-making process that leverages the collective knowledge and information available throughout the architecture. The diagram provided in Figure 33 offers a comprehensive depiction of the cognitive architecture, 63 X-Ray Image Segmentation Classification Induction Training Metrics Node WM LTM Decision-making Segmentation Dataset Classification Dataset Segmentation Training Segmentation Classification Training Induction Training Classification Training Results Induction Training Results Feature Maps -> Trigger Node Creation Probabilities Predictions Working Memory Contents Run-Time Inference Training Figure 33: Decision-Making Diagram. encompassing training and real-time inference processes. During the training phase in BorisCAD, a meticulous ”bottom-up” approach is adopted where the segmentation network is first trained on an independent dataset, enabling the system to differentiate the foreground from the background in x-ray images accurately. This initial training step proves instrumental as the segmented output is a preprocessing step for the subsequent classification model, trained on a different dataset. Significantly, even during the training phase, this segmentation network is utilised as a preprocessing step for the classification model, ensuring consistent and cohesive training. Furthermore, the same dataset is employed to generate probabilities for the Induction training. Leveraging the power of a Decision Forest consisting of an ensemble of Decision Trees, the architecture extracts valuable insights from the data, culminating in the formulation of meaningful probabilities for each class. The metrics garnered during the induction and classification training process are recorded as essential references for the decision-making process. During the real-time inference of newly received x-ray images, the Storage System, which remained inactive throughout the training process, becomes an integral component of the architecture. Each incoming image undergoes a segmentation process, followed by classification using the trained model. This two-step process facilitates the generation of probabilities but also triggers the extraction of feature maps. As a result, a new memory node is dynamically created, seamlessly integrating with both the Working Memory and Long-Term Memory. 64 The decision-making mechanism encompasses a comprehensive evaluation of all components within the architecture. The Computation System influences the final decision by combining the probabilities and predictions with the pertinent metrics obtained during training. Moreover, employing a similarity-based reasoning approach similar to the CLARION cognitive architecture [110] via the Working Memory, the architecture judiciously considers the historical information stored in the memory nodes. By embracing this holistic approach, the cognitive architecture maximises its potential to provide accurate and robust predictions by considering procedural, semantic, and episodic components within the decision-making process. The influence of the probabilities from the classification model on the decision-making process can be determined by multiplying the probabilities by the corresponding metric value. Denoting the probabilities as Pcfor class cand the metric value as Mcfor class c. The influence (Ic) of the probabilities from the classification can be calculated as: Ic=Pc∗Mc(3.18) From here, a list of weighted probabilities is created, depending on how the class defining each probability is accurately evaluated within the model. Similarly, the influence of predictions from the induction method can be computed by multiplying the predictions by the corresponding metric value. Defining the predictions as Predcfor class cand the metric value as Mcfor class c. The influence (Ic) of the predictions from the induction can be calculated as: Ic=Predc∗Mc(3.19) For the Working Memory influence, a similar process can be achieved, this time by using the similarity index calculated during the node insertion in the Storage System. Denoting the final classification decision from previous nodes as Di= [D1, D2, ..., Df]with fequal to the total number of existing classes and Direpresenting the decision values for node iin memory. The similarity score between the current node and memory node iis Si. To calculate the influenced decision by the similarity weights and normalise these values, each decision value is multiplied by the corresponding similarity scores, summed in the class dimension and then divided by (n−1), where nis the total number of nodes in memory. The influenced decision (ID)can be calculated as: ID =Pn i=1 Di∗Si n−1(3.20) To incorporate the influence of the various methods, an equation is employed to determine the final 65 decision. The equation incorporates the weighted contributions of classification probabilities, induction predictions, and the influence of working memory nodes that exhibit similarity to the current node. The equation for the final decision is as follows: FinalDecision =α∗Iclass[P] + β∗Iind[Pred] + ω∗ID (3.21) In this equation, each component is multiplied by a corresponding weighting factor to emphasise its relative importance. The term Iclass[P]represents the weighted list of classification probabilities, reflecting the confidence associated with each class. Similarly, Iind[Pred]denotes the weighted list of induction predictions, which accounts for the predictions made by the induction model. Lastly, ID represents the weighted final decision of working memory nodes that exhibit similarity to the current node. The alpha factor determines the weight of the classification probabilities, the beta controls the influence of the induction predictions, and the omega governs the impact of the working memory nodes. By adjusting the weighting factors, the cognitive architecture can adapt to different scenarios and prioritise certain factors over others, enabling a flexible and robust decision-making process. During the training stage of the BorisCAD procedure, a crucial step involves evaluating the trained models on a separate testing subset to obtain the necessary metrics for classification and induction. The models, trained on a separate training subset, are applied to the testing subset containing unseen data. This allows the computation of various metrics to assess the models’ performance and generalisation ability. By analysing these metrics, informed decisions can be made regarding potential areas that require attention or adjustments in the decision criteria based on consistent misclassification or poor validation results. To ensure unbiased evaluation, the train-test split process follows data shuffling to eliminate any bias introduced by the original order of the dataset. This randomisation allows the machine learning models to learn patterns and relationships in the training set without being influenced by specific ordering. The shuffled data is divided into two subsets: the training and testing sets. The allocation of the shuffled data is typically predefined, with a percentage assigned for training and the remaining portion used for testing. Most of the data is used for training the models, while the remaining samples in the testing set are reserved for evaluating the models’ performance on unseen data. 66 3.6 Integrated Technologies In the current era of rapid technological advancements, the seamless integration of various technologies has become essential across different domains, including academia, industry, and research. This integration is vital in developing innovative and efficient infrastructures that effectively address complex challenges and achieve remarkable outcomes. Python , a high-level interpreted programming language, is a powerful tool for creating integrated technological solutions. Renowned for its adaptability, user-friendliness, and extensive libraries, Python is widely acclaimed in the industry. Its simplicity, readability, and versatility make it a preferred choice for programmers, allowing them to express complex concepts using fewer lines of code than other programming languages. Given its strengths, Python has been adopted as the primary programming language for implementing the cognitive architecture presented throughout this chapter. The broad range of libraries offered by Python, including NumPy , Pandas , and Matplotlib , empowers efficient processing, manipulation, and analysis of large datasets. These libraries provide robust data structures, statistical functions, and visualisation tools that facilitate data-driven decision-making and enable the extraction of valuable insights. PyTorch , an increasingly popular open-source machine learning framework, has gained substantial traction due to its dynamic computational graph and extensive support for deep learning applications. Leveraging PyTorch’s vast library of pre-built neural network modules, it provides a flexible platform for rapidly developing and deploying advanced machine learning models. Moreover, Python’s integration capabilities extend to PyTorch’s support for distributed computing, enabling the scalability of machine learning models across multiple Graphics Processing Units (GPUs) or even clusters of machines. This scalability empowers the training of larger and more intricate models, thereby enhancing the performance and accuracy of integrated technological solutions. Consequently, all previously explored machine learning mechanisms will be implemented utilising the existing frameworks of PyTorch. Additionally, the NetworkX library is valuable for visualising and analysing complex network structures within BorisCAD, the Storage System’s memories. As a Python library, NetworkX provides comprehensive tools for studying intricate networks. Its intuitive interface and extensive functionality make it suitable for visualising and analysing interconnected nodes and edges within these networks. 67 3.7 Data Catalogue The ”Data Catalogue” subsection introduces the primary use case of analysing X-ray images within BorisCAD, a cognitive architecture context. Its fundamental purpose is to identify and detect pathologies present in these images. By leveraging integrated technologies, BorisCAD aims to enhance diagnostic capabilities and provide valuable support to healthcare professionals. This subsection focuses on the data catalogue employed by BorisCAD, which plays a critical role in enabling accurate pathology identification. The data catalogue encompasses a diverse range of X-ray images from two large datasets, facilitating the training and evaluation of machine-learning models. Through the exploration of this data catalogue, the subsection highlights the importance of comprehensive and representative datasets in developing and implementing integrated technological solutions for X-ray image analysis. During the training of the segmentation network, a single dataset is employed, sourced from the studies conducted by Candemir et al., [111] and Jaeger et al., [112]. This dataset encompasses original lung X-ray images along with their corresponding masks. This dataset aims to facilitate the training of the segmentation network to accurately identify and delineate specific regions or objects of interest within the lung X-ray images. By utilising the paired images and masks, the segmentation network can learn to effectively distinguish the lung structures from the surrounding background and other adjacent tissues, thereby enabling precise and reliable segmentation results. 3.7.1 CheXpert Dataset The CheXpert dataset [113] is a widely used and highly regarded medical imaging dataset specifically designed for training and evaluating machine learning models in chest X-ray interpretation. It consists of an extensive collection of chest X-ray images and corresponding radiologist interpretations. It is crucial as medical imaging is inherently subjective, and radiologists often have varying levels of certainty in their diagnoses. The dataset provides detailed annotations that reflect the degree of uncertainty associated with each radiologist’s interpretation, enabling the exploration of uncertainty modelling and analysis within machine learning algorithms. The CheXpert dataset encompasses a wide range of pathologies and abnormalities commonly encountered in chest X-ray imaging, including pneumonia, lung nodules, pleural effusion, and cardiomegaly. Moreover, the CheXpert dataset addresses the challenge of imbalanced data, a common issue in medical imaging datasets. It annotates many images with positive and negative pathology labels, ensuring a balanced representation of different pathologies and enabling robust training and 68 evaluation of machine learning models. Although this dataset is extensive and provides a valuable resource for chest X-ray interpretation, it is essential to note that the images within the CheXpert dataset come from various view positions. This variation necessitates a pre-processing step to isolate the frontal view images, which serve as the standardised position for analysis. This pre-processing ensures consistency and enables accurate comparison and diagnosis when developing machine learning algorithms based on this dataset. In addition to the abundant collection of X-ray images, the CheXpert dataset is accompanied by a meticulously documented file that encompasses vital information for each image, including details regarding the specific view position from which the X-ray was captured. This comprehensive file plays a pivotal role in facilitating efficient data management and analysis, eliminating the need for manual review or reliance on image processing techniques to determine the view position. The bar graph in figure 34 visually represents the label distribution in the CheXpert dataset, displaying the total occurrences of each label. It provides an informative overview of the frequencies of different pathologies and abnormalities within the dataset, allowing easy identification of the most common and rare labels. This graph offers valuable insights into the prevalence of specific conditions, contributing to a comprehensive understanding of the label distribution in the CheXpert dataset. The accompanying pie chart in figure 35 presents a clear comparison of the percentage composition of each label in the CheXpert dataset. Each label is depicted as a distinct segment, with the size of each segment indicating the proportionate occurrence of that label. This visual representation allows for a quick assessment of the label distribution, highlighting the relative importance of different pathologies and abnormalities. The pie chart provides a concise overview, enabling a straightforward interpretation and comparison of the various labels in the CheXpert dataset. Figure 34: CheXpert total occurrences for each label. 69 a) Segmentation Network The implementation process begins with the construction of the Segmentation Network, as seen in Listing 1, a pivotal component of the module. The initial phase revolves around the instantiation of the network’s essential attributes, primarily dedicated to training the UNet or AttentionUNet models. User input through a Boolean variable, denoted as attention , determines the selection between these models. Additionally, the initialisation of optimisers and schedulers is deferred to the Learning System, thus currently employing type hints and placeholders. A crucial consideration in implementing the Segmentation Network is the utilisation of the BCEWithLogitsLoss function for semantic segmentation. This choice stems from its effectiveness in handling binary pixel-wise classification tasks, where each pixel is assigned to either foreground or background classes. By employing BCEWithLogitsLoss, the network can effectively address the challenges associated with the class imbalance and overlapping regions, ensuring accurate and robust segmentation results. Listing 1 Segmentation Network __init__function. 11 class SegmentationNetwork(nn.Module): 12 def __init__( 13 self, 14 attention: bool =True, 15 device: torch.device =torch.device("cuda:0" if torch.cuda.is_available() else "cpu"), 16 )-> None: 17 """Segmentation Network constructor 18 Args: 19 attention (bool, optional): if attention or not. Defaults to True. 20 device (_type_, optional): Defaults to torch.device("cuda:0" if torch.cuda.is_available() else "cpu"). 21 """ 22 super(SegmentationNetwork, self).__init__() 23 self.device =device 24 # conditional usage of the attention network 25 self.model =AttentionUNet() if attention else UNet() 26 self.loss_fn =nn.BCEWithLogitsLoss() # loss function to evaluate the model 27 # optimizer and scheduler are started in the Learning System 28 self.optim: torch.optim.Adam =None 29 self.scheduler: torch.optim.lr_scheduler.ReduceLROnPlateau =None 30 # scaler used when CUDA is available 31 self.scaler =torch.cuda.amp.GradScaler() if torch.cuda.is_available() else None 32 self.prev_training: torch.Tensor =None # tensor to hold previous training metrics 33 self.to(self.device) # sends the module to CUDA or keeps it in the CPU The provided code segment demonstrates a pattern commonly observed in the bottom-level modules, highlighting the similarities between classes and methods within this section of the architecture. Notably, the inclusion of a device parameter allows for the specification of the device on which the networks will be executed. By default, this parameter assumes a value of either "cpu" or "cuda:0", depending on the availability and compatibility of a suitable GPU for hardware acceleration 76 within the system. The incorporation of a device parameter enables the code to be more flexible and adaptable to different hardware configurations. It caters to scenarios where GPU acceleration is preferred when available, and seamlessly falls back to CPU execution if a compatible GPU is not present. This design choice enhances the code’s generalisability and allows it to effectively utilise the available hardware resources. Furthermore, the final line of the code segment, labeled as Line 32 , demonstrates the utilisation of the specified device for executing the module. This step ensures that the module is appropriately assigned to the desired device, thus aligning with the chosen hardware configuration for efficient execution. Another characteristic that will be prevalent in the subsequent code snippets is the usage of the super() initialisation method in the context of inheriting from the nn.Module class. Through this inheritance, a subclass extends the base class and gains access to its properties and methods, relevant in facilitating tasks like forward and back propagation of the networks. The nn.Module class, in particular, has its own initialisation method, __init__(), responsible for initialising critical components such as parameters, buffers and sub-modules, while also performing necessary setup operations. To ensure the proper execution of these operations, it is needed for the subclass’s __init__() method to invoke super().__init__(). Listing 2 UNet block __init__function. 5class UNet_Block(nn.Module): 6def __init__(self, in_channels: int, out_channels: int)-> None: 7"""Convolution Module, two consecutive convolution with Normalization and ReLU activation 8Args: 9in_channels (int): number of input channels (either last layer output or number of channels in the image (RGB-3, Gray-1)) 10 out_channels (int): number of output channels 11 """ 12 super(UNet_Block, self).__init__() 13 # Define the convolutional layers 14 self.conv =nn.Sequential( 15 nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, padding=1, bias=False), 16 nn.BatchNorm2d(num_features=out_channels), 17 nn.ReLU(inplace=True), 18 nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, padding=1, bias=False), 19 nn.BatchNorm2d(num_features=out_channels), 20 nn.ReLU(inplace=True), 21 ) Delving deeper into the specific networks designed for the segmentation task, the code snippet that represents the implementation of the block discussed earlier (referenced as ”Listing 2”) is examined. This block corresponds to the architecture illustrated in Figure 9a. Within the UNet_Block class, the block’s layers are defined using the nn.Sequential module. The layers consist of a 2D convolutional layer, batch normalisation, ReLU activation, another 2D convolutional layer, batch normalisation again, 77 and another ReLU activation. These layers collectively form the desired architecture of the block. Similarly, the Listing 3 presents the implementation of the Attention Gate block designed in Figure 9b. The AttentionGate class is designed to incorporate attention mechanisms into a neural network. It takes two input parameters: features, representing the number of input channels or features, and n_coefficients, denoting the number of attention coefficients to be calculated. Within the class’s __init__() method, the attention gate components are defined. These components include the W_gate,W_x,psi, and relu layers. The W_gate and W_x layers consist of a 1x1 convolution followed by batch normalisation, while the psi layer performs another 1x1 convolution followed by batch normalisation and a sigmoid activation. The relu layer utilises the ReLU activation function. Listing 3 Attention Gate block __init__function. 27 class AttentionGate(nn.Module): 28 def __init__(self, features: int, n_coefficients: int)-> None: 29 """Attention Gate 30 Args: 31 features (int): number of features to 32 n_coefficients (int): number of transitory coefficients 33 """ 34 super(AttentionGate, self).__init__() 35 # Define the W_gate module with a convolutional layer and batch normalization 36 self.W_gate =nn.Sequential(nn.Conv2d(in_channels=features, out_channels=n_coefficients, kernel_size=1), nn.BatchNorm2d(n_coefficients)) 37 # Define the W_x module with a convolutional layer and batch normalization 38 self.W_x =nn.Sequential(nn.Conv2d(in_channels=features, out_channels=n_coefficients, kernel_size=1), nn.BatchNorm2d(n_coefficients)) 39 # Define the psi module with a convolutional layer, batch normalization, and sigmoid activation 40 self.psi =nn.Sequential(nn.Conv2d(in_channels=n_coefficients, out_channels=1, kernel_size=1), nn.BatchNorm2d(1), nn.Sigmoid()) 41 self.relu =nn.ReLU(inplace=True)# ReLU activation The forward function in the AttentionGate class seen in listing 4 implements the attention mechanism. It takes a gate tensor and a skip connection tensor as input. The gate tensor is processed through the W_gate layer, while the skip connection tensor is processed through the W_x layer. The attention coefficients are calculated by adding these processed tensors and applying the ReLU activation. The attention coefficients are then passed through the psi layer, which performs a convolution, batch normalisation, and sigmoid activation. Finally, the skip connection tensor is multiplied element-wise by the attention coefficients to obtain the modified tensor, which is returned as the output. This allows the network to dynamically weigh the importance of different elements in the skip connection based on the attention mechanism. The implementation of the AttentionUNet class, as demonstrated in listing 5, introduces a customised variation of the UNet architecture. This modified version integrates attention gates, which are illustrated in Figure 8. It consists of encoder and decoder blocks responsible for the downsampling and upsampling operations, respectively. 78 Listing 4 Attention Gate forward method. 43 def forward(self, gate: torch.Tensor, skip_connection: torch.Tensor) -> torch.Tensor: 44 """Forward function for the attention gate 45 Args: 46 gate (torch.Tensor): gate tensor 47 skip_connection (torch.Tensor): tensor of the skip connection 48 Returns: 49 torch.Tensor: weighted attention gate tensor 50 """ 51 g1 =self.W_gate(gate) # Pass the gate tensor through the W_gate module 52 x1 =self.W_x(skip_connection) # Pass the skip connection tensor through the W_x module 53 psi =self.relu(g1 +x1) # Element-wise addition of g1 and x1 followed by ReLU activation 54 psi =self.psi(psi) # Pass the combined tensor through the psi module for attention weighting 55 return skip_connection *psi # Multiply the skip connection tensor with the attention weights The input image passes through a series of UNet_Block layers in the encoder ladder. The in_channels argument determines the number of input channels for the first UNet_Block, while the features list defines the number of output channels. The output of each UNet_Block is fed as input to the next block in the encoder ladder, progressively reducing the spatial dimensions of the feature maps and increasing the number of channels. Listing 5 Attention U-Net __init__function. 110 class AttentionUNet(nn.Module): 111 # Encoder and decoder blocks are pretty much the same, but the decoder has a Transposed Convolution that receives the skip connection from the previous encoder 112 def __init__(self, in_channels: int = 1, out_channels: int = 1, features: list[int]=[64,128,256, 512]) -> None: 113 """UNet Structure definition but with Attention gates 114 Args: 115 in_channels (_type_): number of input channels (channels of the image) 116 out_channels (_type_): number of output channels (usually one image, so 1 output channel) 117 features (list, optional): number of features for each layer in the network. Defaults to [64, 128, 256, 512]. 118 """ 119 super(AttentionUNet, self).__init__() 120 self.pool =nn.MaxPool2d(kernel_size=2, stride=2)# Max pooling layer for downsampling 121 self._num_channels =in_channels 122 # Encoder and Decoder modules 123 self.encoder =nn.ModuleList() 124 self.decoder =nn.ModuleList() 125 # Encoder ladder 126 for feature in features: 127 self.encoder.append(UNet_Block(in_channels=in_channels, out_channels=feature)) 128 in_channels =feature 129 # Decoder ladder with the attention gate blocks 130 for feature in reversed(features): 131 self.decoder.append(nn.ConvTranspose2d(in_channels=feature * 2, out_channels=feature, kernel_size=2, stride=2)) 132 self.decoder.append(AttentionGate(feature, feature // 2)) 133 self.decoder.append(UNet_Block(feature * 2, feature)) 134 # Connection between encoder and decoder, the bottom of the U in the network 135 self.bottleneck =UNet_Block(features[-1], features[-1]* 2) 136 # Output Layer 137 self.final_layer =nn.Conv2d(in_channels=features[0], out_channels=out_channels, kernel_size=1) In the decoder ladder, transposed convolutions (nn.ConvTranspose2d()) are used for upsampling the feature maps, increasing their spatial dimensions while reducing the number of 79 channels. The decoder also incorporates attention gate blocks (AttentionGate), which receive the output of the corresponding transposed convolution and the skip connection from the encoder ladder. The attention gate blocks dynamically compute attention coefficients based on these inputs, selectively emphasising or suppressing features. The skip connection allows information from the encoder to be integrated into the decoder. The forward() method of the AttentionUNet class shown in Listing 6 better depicts the processing within the network. During the encoding phase, the input passes through the encoder blocks, and the output of each block is stored in the skip_connections list. The bottleneck layer performs the final encoding step without a skip connection. Listing 6 Attention U-Net forward method. 158 def forward(self, X: torch.Tensor) -> torch.Tensor: 159 """Forward method for the AttentionUnet 160 Args: 161 X (torch.Tensor): input tensor 162 Returns: 163 torch.Tensor: segmented output tensor 164 """ 165 # Connections between an encoder block and the assigned decoder block 166 skip_connections =[] # List to store skip connections from the encoder 167 # Encoding 168 for block in self.encoder: # Iterate through the encoder blocks 169 X=block(X) # Pass input through the current encoder block 170 skip_connections.append(X) # Store the skip connection 171 X=self.pool(X) # Max Pooling after each block to downsample 172 X=self.bottleneck(X) # Final encoding layer, with no skip connection assotiated 173 skip_connections =skip_connections[::-1]# Reverse the skip connections 174 # Decoding 175 for idx in range(0,len(self.decoder), 3): # Iterate through the decoder blocks 176 X=self.decoder[idx](X) # Transposed Convolution (Upsampling) 177 skip_connection =skip_connections[idx // 3]# Retrieve the corresponding skip connection 178 X=self.decoder[idx + 1](X, skip_connection) # Attention module combining skip connection and current output 179 concat_skip =torch.cat((X, skip_connection), dim=1)# Concatenate skip connection and output 180 X=self.decoder[idx + 2](concat_skip) # Double convolution to refine the concatenated features 181 return self.final_layer(X) # Output layer In the decoding phase, the skip_connections are reversed to match the decoding order. The decoder blocks are applied in reverse order, upsampling the feature maps while dynamically computing attention coefficients. The output of the attention gate is concatenated with the corresponding skip connection and passed through the UNet block for further refinement. The property num_channels shown in Listing 7 allows accessing and modifying the number of channels in the UNet model. When accessed, it returns the current number of channels. When modified using the setter method, it updates the number of channels to the specified value. Additionally, it updates the first encoder block of the UNet model with the new number of channels. The num_channels property is useful for handling changes in the number of input channels dynamically, enabling flexibility in adapting the UNet model to different input configurations. 80 Listing 7 Attention U-Net number of channels property. 139 @property 140 def num_channels(self)-> int: 141 """Get the number of channels. 142 Returns: 143 int: The number of channels. 144 """ 145 return self._num_channels 146 147 @num_channels.setter 148 def num_channels(self, num_channels: int, feature: int = 64)-> None: 149 """Set the number of channels. 150 Args: 151 num_channels (int): The number of channels. 152 feature (int, optional): The feature size. Defaults to 64. 153 """ 154 self._num_channels =num_channels # Set the number of channels 155 # Update the first encoder block with the new number of channels 156 self.encoder[0]=UNet_Block(in_channels=num_channels, feature=feature) In order to regulate the training process, a mechanism was implemented within the Segmentation Network class, as described earlier in the design section. The general fit() method, depicted in Figure 14a, demonstrates the flow of operations involved in training and is presented in Listing 8, where the underlying logic behind the training process is illustrated. This initial stage of training takes as input a DataLoader object that contains both the images and corresponding masks, as well as the specified number of epochs for training. To ensure the proper functioning of the architecture’s Learning System, the existence of an optimiser and a scheduler is verified. If these mechanisms are not assigned, an error will be raised, thus ensuring their availability throughout the training process. The training process is then carried out for each epoch, iterating over the dataset. At the end of each epoch, the training results, such as loss values or evaluation metrics, are collected and stored in a list. This allows for further analysis, storage, or utilisation of these results beyond the immediate training context. As one can see, a context is used in Line 05 . During the verification stage, some desynchronisation in the execution of the scheduler step was verified, thus throwing a warning. This warning does not affect the execution, but for display purposes, it is ignored. The context implementation is depicted in Listing 9, where the decorator @contextlib.contextmanager is used to allow the function to be used as a context manager. The with statement is used to create a context where warnings are caught and filtered. It ensures that any warnings within the indented code block are handled appropriately. The line warnings.filterwarnings("ignore", category=warning) configures the warnings module to ignore a specific category of warning. The category parameter is passed as an argument to 81 Listing 8 Segmentation Network fit method. 35 def fit(self, dataloader: DataLoader, epochs: int = 8)-> torch.Tensor: 36 """Fit method for the Segmentation Network Model. 37 Args: 38 dataloader (DataLoader): Dataloader containing image and mask data for training. 39 epochs (int, optional): Number of epochs to train the model. Defaults to 8. 40 Returns: 41 torch.Tensor: Training metrics for the current training. 42 """ 43 # Verifies if the model is correctly initialized, as in, if a Learning System is assigned to the Network 44 assert self.optim is not None and self.scheduler is not None,"No Learning System assigned to the model" 45 results =[] # List to store the results of each epoch 46 since =time.time() # Time at the start of training 47 for epoch in range(epochs): 48 print(f"Epoch {epoch+1}/{epochs}") 49 epoch_results =self.epoch_train(e_data=dataloader) # Trains the network on the current epoch 50 with ignore_warning(UserWarning): # A UserWarning is sometimes triggered because of desynchronization, it is not relavant so this context is used to avoid it 51 self.scheduler.step(sum(epoch_results[:, 0]) /len(dataloader)) # Adjusts the learning rate based on the average loss 52 # Print training metrics for the current epoch 53 print(f"Loss: {sum(epoch_results[:, 0])/len(dataloader)}; Dice score: {sum(epoch_results[:, 1])/len(dataloader)}; Accuracy: {sum(epoch_results[:, 2])/len(dataloader)*100:.2f}%; IoU: {sum(epoch_results[:, 3])/len(dataloader)}\n") 54 results.append(epoch_results) # Stores the epoch results 55 time_elapsed =time.time() -since # Total training time 56 print(f"Training complete in {time_elapsed // 60:.0f}m{time_elapsed % 60:.0f}s") 57 self.prev_training =torch.cat(results, dim=0)# Concatenates the epoch results into a single tensor 58 return self.prev_training # Returns the training metrics for the current training the ignore_warning function, specifying the type of warning to be ignored. The yield statement is used as a placeholder for the block of code that will be executed when the context manager is entered. In this case, it allows the user to execute their desired code within the context where the warning is ignored. Once the indented block of code is executed, the context manager automatically exits, and any temporarily ignored warnings are no longer suppressed. For each epoch of training, the process done is presented in Listing 10 based on what was described in Figure 14b. The provided code snippet presents a method named epoch_train() within the SegmentationNetwork class. This method is responsible for training the model on a single epoch of data. It takes a DataLoader object named e_data as input, which holds the training images and masks. During each iteration, the method trains on a batch of images and labels, obtained from the e_data DataLoader . The training metrics for each batch are stored in a tensor called epoch_metrics, which is concatenated with the metrics from previous batches. At the end, the method returns the aggregated epoch_metrics tensor, representing the metrics obtained during the entire epoch of training. The specific implementation for batch training is depicted in Listing 11, aligning with the previously discussed design illustrated in Figure 15. To ensure the proper handling of data, specifically the images 82 Listing 9 Ignore Warning context. 68 import contextlib 69 70 71 @contextlib.contextmanager 72 def ignore_warning(warning: Type[Warning]): 73 """Context manager to ignore a specific warning type. 74 Args: 75 warning (Type[Warning]): The type of warning to ignore. 76 """ 77 import warnings 78 79 with warnings.catch_warnings(): # Catches all warnings that occur within the context 80 warnings.filterwarnings("ignore", category=warning) # Ignores the specified warning type 81 yield # Yields control back to the caller while ignoring the warning Listing 10 Segmentation Network epoch training method. 60 def epoch_train(self, e_data: DataLoader) -> torch.Tensor: 61 """Trains in a single epoch of data 62 Args: 63 e_data (DataLoader): holds the training DataLoader, it contains the training images and masks 64 Returns: 65 torch.Tensor: returns the epoch_metrics for training 66 """ 67 epoch_metrics =torch.zeros(0,4, device=self.device) # Initializes an empty tensor to store the metrics 68 for images, labels in tqdm(e_data, unit=" batch"): # Iterates over the batches of training images and labels 69 batch_metrics =self.batch_train(b_data_x=images, b_data_y=labels) # Trains on a single batch of training images and labels 70 epoch_metrics =torch.cat([epoch_metrics, batch_metrics], dim=0)# Concatenates the batch metrics to the epoch metrics tensor 71 return epoch_metrics and masks, on the appropriate device (CPU or GPU), Lines 81-82 are utilised. These lines confirm that the data is correctly placed on the designated device, considering that this system supports both CPU and GPU utilisation. Listing 11 Segmentation Network batch training method. 73 def batch_train(self, b_data_x: torch.Tensor, b_data_y: torch.Tensor) -> torch.Tensor: 74 """Trains on a single batch of data 75 Args: 76 b_data_x (torch.Tensor): Image data; b_data_y (torch.Tensor): Mask data 77 Returns: 78 torch.Tensor: Batch training metrics 79 """ 80 # Moves the input image data to the device (GPU if available) 81 b_data_x =b_data_x.to(self.device, non_blocking=True) 82 b_data_y =b_data_y.to(self.device, non_blocking=True) The code snippet in Listing 12 performs a forward pass through the model to obtain predictions (output) given an input tensor (b_data_x). It then computes the loss between the predictions and the target mask (b_data_y) using the specified loss function. The autocast context manager in PyTorch enables automatic mixed precision training by automatically casting computations to a lower-precision data 83 type. It helps reduce memory usage and improve computational efficiency without sacrificing accuracy. The output is then thresholded using a sigmoid function with a threshold of 0.5 to obtain binary predictions (predictions). Next, the code stacks the loss and other calculated metrics into a single tensor (batch_metrics). The metrics are calculated by calling a private method _calculate_metrics() with the predictions and target mask as inputs. The loss tensor is detached from the computation graph using detach() to prevent gradients from flowing back during metric calculation. Finally, the batch metrics tensor is unsqueesed to add a batch dimension and returned. Listing 12 Segmentation Network batch training forward with context. 83 with torch.autocast(device_type=self.device.type, dtype=torch.bfloat16, enabled=True): # autocasts to the specific device type 84 output: torch.Tensor =self.model(b_data_x) # Forward pass: computes the model's output 85 loss: torch.Tensor =self.loss_fn(output, b_data_y) # Computes the loss between the output and target mask 86 predictions =(torch.sigmoid(output) > 0.5).float() # Applies a threshold to the output to obtain binary predictions 87 # Stacks the metrics into a single tensor and unsqueezes it to have a batch dimension 88 # Detaches the loss tensor from the computation graph and calculates metrics 89 batch_metrics =torch.stack([loss.detach(), *self._calculate_metrics(predictions, b_data_y)], dim=0).unsqueeze(0) The _calculate_metrics function seen in Listing 13 takes predicted masks (preds) and ground truth masks (masks) as input and calculates several metrics. These metrics include the dice score, mask accuracy, and intersection over union (IoU) score. The function returns a list of torch Tensors, where each element represents a specific metric. The metrics are calculated using the corresponding functions dice_score(),mask_accuracy(), and iou_score() from the LearningSystem class and will be discussed further in this chapter. Listing 13 Segmentation Network batch training metrics. 100 def _calculate_metrics(self, preds: torch.Tensor, masks: torch.Tensor) -> list[torch.Tensor]: 101 """Calculates various metrics based on the predicted masks and ground truth masks. 102 Args: 103 preds (torch.Tensor): Predicted masks. 104 masks (torch.Tensor): Ground truth masks. 105 Returns: 106 list[torch.Tensor]: List of metrics including dice score, mask accuracy, and intersection over union (IoU) score. 107 """ 108 return [ 109 LearningSystem.dice_score(preds, masks), # Calculate the dice score metric 110 LearningSystem.mask_accuracy(preds, masks), # Calculate the mask accuracy metric 111 LearningSystem.iou_score(preds, masks), # Calculate the intersection over union (IoU) score metric 112 ] Between Line 90-98 from Listing 14, the provided code snippet involves a conditional block that handles the backpropagation and optimisation step during the training process. If the self.scaler 84 object exists, it implies that automatic mixed-precision training is enabled. In this case, the loss value (loss) is scaled using the self.scaler.scale method, followed by the backward pass (backward()) to compute gradients. Then, the optimiser (self.optim) performs a step based on the scaled gradients using the self.scaler.step method. Finally, the self.scaler.update method updates the scaling factor for future iterations. On the other hand, if the self.scaler object does not exist, indicating that mixed-precision training is not enabled, the backward pass is performed directly on the loss value (loss.backward()). Then, the optimiser (self.optim) performs a step based on the gradients. In both cases, the batch_metrics tensor is returned as the output of this code snippet, which contains the computed metrics for the batch, concluding the training for the specific batch of data. Listing 14 Segmentation Network batch training backward pass and performance updates. 90 self.optim.zero_grad(set_to_none=True)# Clears the gradients of the optimizer 91 if self.scaler: 92 self.scaler.scale(loss).backward() # Backward pass: computes the gradients using automatic mixed precision (if enabled) 93 self.scaler.step(self.optim) # Updates the model's parameters using the optimizer (scaled gradients) 94 self.scaler.update() # Updates the scale for automatic mixed precision 95 else: 96 loss.backward() # Backward pass: computes the gradients 97 self.optim.step() # Updates the model's parameters using the optimizer (un-scaled gradients) 98 return batch_metrics # Returns the batch training metrics The forward pass of the segmentation model, described in Listing 15, takes an input tensor X and moves it to the specified device (GPU if available). It creates a clone of the input tensor X_skip for later multiplication. The input tensor Xis then passed through the model, computing the model’s output. To ensure that the output values are between 0 and 1, element-wise clamping and rounding are applied. Finally, the output tensor is obtained by performing element-wise multiplication between the processed output tensor and the cloned input tensor. Listing 15 Segmentation Network forward method. 114 def forward(self, X: torch.Tensor) -> torch.Tensor: 115 """Forward pass of the model 116 Args: 117 X (torch.Tensor): Input tensor 118 Returns: 119 torch.Tensor: Output tensor 120 """ 121 X=X.to(self.device) # Moves the input tensor to the device (GPU if available) 122 X_skip =X.clone() # Creates a clone of the input tensor for later multiplication 123 X=self.model(X) # Forward pass: computes the model's output 124 X=torch.clamp(X, min=0,max=1).round() # Applies element-wise clamping and rounding to ensure values are between 0 and 1 125 return X*X_skip # Element-wise multiplication of the output tensor and the cloned input tensor 85 Listing 24 Classification Network training using segmentation. 90 if self.segmenter: # forwards the segmentation model if available 91 with torch.no_grad(): # avoid the computation of gradients 92 b_data_x =self.segmenter(b_data_x) Listing 25 Classification Network training metrics calculation. 109 def _calculate_metrics(self, preds: torch.Tensor, labels: torch.Tensor) -> list[torch.Tensor]: 110 """Calculates various performance metrics based on the predicted values and the ground truth labels. 111 Args: 112 preds (torch.Tensor): Predicted values. 113 labels (torch.Tensor): Ground truth labels. 114 Returns: 115 list[torch.Tensor]: List of performance metrics, including class accuracy, precision, recall, F1 score, and Matthews correlation coefficient (MCC). 116 """ 117 _conf_matrix: torch.Tensor =LearningSystem.confusion_matrix(preds, labels) # Compute confusion matrix 118 return [ 119 LearningSystem.class_accuracy(_conf_matrix).mean(), # Calculate mean class accuracy 120 LearningSystem.precision(_conf_matrix).mean(), # Calculate mean precision 121 LearningSystem.recall(_conf_matrix).mean(), # Calculate mean recall 122 LearningSystem.f1_score(_conf_matrix).mean(), # Calculate mean F1 score 123 LearningSystem.mcc(_conf_matrix).mean(), # Calculate mean Matthews correlation coefficient (MCC) 124 ] a segmenter is available. If a segmenter is present, it applies segmentation to the input tensor before passing it through the classifier’s model. The function then returns the output tensor obtained from the model. Listing 26 Classification Network forward method. 126 def forward(self, X: torch.Tensor) -> torch.Tensor: 127 """Classification network forward method 128 Args: 129 X (torch.Tensor): Input tensor 130 Returns: 131 torch.Tensor: Output tensor 132 """ 133 X=X.to(self.device) # Move input tensor to the specified device 134 # Check if a segmenter is available and apply segmentation 135 if self.segmenter: 136 X=self.segmenter(X) 137 return self.model(X) # Pass the segmented tensor through the model and return the result It is now possible to define the full Bottom Level structure, following the code in Listing 27. It initialises an instance of ClassificationNetwork and SegmentationNetwork with the appropriate arguments, such as the number of classes, whether attention is used, the type of network architecture. The use_segmentation parameter controls the usage of segmentation. If segmentation is enabled, the segmenter instance is assigned to the segmenter attribute of the ClassificationNetwork. Finally, the module is sent to the specified device using the to() method. 92 Listing 27 Bottom Level __init__function. 11 class BottomLevel(object): 12 def __init__(self, num_classes: int, attention: bool, net_type: str, use_segmentation: bool)-> None: 13 """Bottom level interface constructor 14 Args: 15 num_classes (int): number of classification classes 16 attention (bool, optional): if the segmentation will use attention. Defaults to True. 17 net_type (str, optional): name of the network. Defaults to "resnet50". 18 use_segmentation (bool, optional): if the classifier will use segmentation. Defaults to True. 19 """ 20 # Initialize the classifier network 21 self.classifier =ClassificationNetwork(num_classes=num_classes, net_type=net_type) 22 self.segmenter =SegmentationNetwork(attention=attention) # Initialize the segmentation network 23 self._use_segmentation =use_segmentation 24 if self._use_segmentation: 25 # Connect the segmentation network to the classifier if segmentation is enabled 26 self.classifier.segmenter =self.segmenter In order to provide a higher level of abstraction in the training process of the bottom level, the fit() method is implemented as seen in Listing 28. This method allows for training both the segmentation and classification tasks. The method takes two optional arguments: segmentation and classification, which are tuples containing the DataLoader and the number of epochs for training each task. If the segmentation argument is provided, the segmenter is trained using the specified data and number of epochs. Similarly, if the classification argument is provided, the classifier is trained using the specified data and number of epochs. The method also checks if segmentation is enabled and whether the segmenter has been previously trained. If segmentation is enabled but no previous training has been found, a warning is issued to alert the user about this mismatch. Since the Bottom-Level has a direct connection with the Top-Level of the Computation System, the forward() method of this module (Listing 29) was adapted to support two types of data structures commonly used at this stage. To achieve this, and as a mechanism to overload functions or methods in Python, the decorator @singledispatchmethod was employed to have the same method behave differently depending on the data type received. @singledispatchmethod is a decorator in Python’s functools module used to define a singledispatch generic function in a class. It allows you to define multiple methods with the same name in a class, where each method handles a specific type of the first argument. When invoking the method, the appropriate implementation is automatically selected based on the type of the argument. It simplifies the implementation of polymorphic behaviour in a class by dispatching the method based on the argument’s type. The forward method is initially defined to handle a single input tensor Xand return a tensor after passing it through the segmentation and classification models. However, by using the 93 Listing 28 Bottom Level fit method. 50 def fit(self, segmentation: Tuple[DataLoader, int]=None, classification: Tuple[DataLoader, int]= None): 51 """Trains the BottomLevel model. Can be used for both segmentation and classification. 52 The training can be done for both segmentation and classification. 53 Args: 54 segmentation (Tuple[DataLoader, int], optional): segmentation tuple with the DataLoader and the number of epochs for training. Defaults to None. 55 classification (Tuple[DataLoader, int], optional): classification tuple with the DataLoader and the number of epochs for training. Defaults to None. 56 use_segmentation (bool, optional): enables if the classification network will use segmentation as a pre-processor for it's data. Defaults to True. 57 """ 58 if segmentation: 59 segmentation_data, seg_epochs =segmentation 60 assert isinstance(segmentation_data, DataLoader) and isinstance(seg_epochs, int) 61 if classification: 62 classification_data, class_epochs =classification 63 assert isinstance(classification_data, DataLoader) and isinstance(class_epochs, int) 64 # Perform segmentation training if specified 65 if segmentation: 66 self.segmenter.fit(segmentation_data, epochs=seg_epochs) 67 # Check if segmentation is enabled but no previous training is found 68 if self.use_segmentation and self.segmenter.prev_training is None: 69 warnings.warn("Segmentation is enabled but no previous training was found.") 70 # Perform classification training if specified 71 if classification: 72 self.classifier.fit(classification_data, epochs=class_epochs) @forward.register decorator, an additional implementation of the forward method is defined to handle input of type DataLoader. When the forward() method is called with an argument of type DataLoader, the registered implementation is automatically invoked. Inside this implementation, it iterates over the batches of the DataLoader, passes each batch through the segmentation and classification models, and compiles the probabilities and labels. The final output is a tuple containing the concatenated probabilities and labels, to be used by the Top-Level in it’s processing. Listing 29 Bottom Level foward overloaded methods. 78 @singledispatchmethod 79 def forward(self, X: torch.Tensor) -> torch.Tensor: 80 # Check if segmentation is enabled but no previous training was found 81 if self.use_segmentation and self.segmenter.prev_training is None: 82 warnings.warn("Segmentation is enabled but no previous training was found.") 83 # Check if classifier training is available 84 if self.classifier.prev_training is None: 85 warnings.warn("No Classifier training is available.") 86 X=self.classifier(X) # Apply classification to the input tensor 87 X=torch.softmax(X, dim=1)# Convert output scores to probabilities using softmax 88 return X# Return the processed tensor 89 90 @forward.register 91 def _(self, X: DataLoader) -> Tuple[torch.Tensor, torch.Tensor]: 92 # Iterate over batches and compile probabilities 93 X_probs, y_labels =zip(*[(self(X_data), y_true) for X_data, y_true in tqdm(X, desc="Compiling probabilities...")]) 94 # Concatenate the collected probabilities and labels 95 X_probs =torch.cat(X_probs, dim=0) 96 y_labels =torch.cat(y_labels, dim=0) 97 return X_probs, y_labels # Return the compiled probabilities and labels 94 4.1.2 Top-Level Subsystem This subsection provides a detailed exploration of the implementation of Decision Forests and Decision Trees. Decision Forests, regarded as an ensemble learning technique, employ the collective intelligence of multiple Decision Trees to achieve precise predictions. The induction mechanism of these algorithms relies on the probabilities derived from the bottom-level, resulting in an enhanced overall predictive performance. By examining the code and underlying principles, valuable insights into the intricate workings of Decision Forests and Decision Trees can be gained, elucidating their effectiveness in addressing complex learning tasks through collaborative decision-making. Starting with the Decision Forest implementation, the code in Listing 30 showcases the __init__() function of the DecisionForest class. This function is responsible for creating an instance of the Decision Forest. It takes two optional parameters: min_samples_split, which specifies the minimum number of samples required for a split during tree building, and max_depth, which defines the maximum depth that the Decision Trees within the forest can reach. Setting max_depth to None implies no depth limit. Listing 30 Decision Forest __init__function. 7class DecisionForest: 8def __init__(self, min_samples_split: int, max_depth: int)-> None: 9"""Create a DecisionForest, the parameters are used in the decision tree building 10 Args: 11 min_samples_split (int, optional): Minumum number of samples per split. Defaults to 10. 12 max_depth (int, optional): maximum depth the Decision Trees can reach, None mean no cap. Defaults to None. 13 """ 14 self.max_depth =max_depth # maximum depth the Decision Trees can reach 15 self.min_samples_split =min_samples_split # minimuym number of samples to split 16 self.dts: list[DecisionTree] =[] # list to hold the decision trees Furthermore, the generation of the Decision Forest using Decision Trees can be observed in the fit() method, as seen in Listing 31. This method takes as input the feature matrix X_data and the corresponding target vector y_data, ensuring that their shapes are compatible. To parallelise the process, a multiprocessing pool is then created using mp.Pool(num_processes), where num_processes represents the number of CPU cores, determined using the mp.cpu_count() function from the multiprocessing module. The map function is used to distribute the workload across multiple processes. The auxiliary method _create_dt() defined in Listing 32 is invoked within the map function, passing a set of arguments for each Decision Tree in the forest. These arguments consist of the index, the feature matrix, a specific column of the target vector, the min_samples_split, and the max_depth. 95 Listing 31 Decision Forest fit function. 18 def fit(self, X_data: np.ndarray, y_data: np.ndarray): 19 """Fit method for the decision forest, to create decision trees 20 Args: 21 X_data (np.ndarray), y_data (np.ndarray) 22 """ 23 assert X_data.shape == y_data.shape # verifies that the data has the same number of instances and features 24 num_processes =mp.cpu_count() # number of processes the cpu is capable of running simultaneously 25 pool =mp.Pool(num_processes) 26 self.dts =pool.map( 27 self._create_dt, 28 [(i, X_data, column, self.min_samples_split, self.max_depth) for i, column in enumerate(y_data.T)], 29 )# splits the data into columns, each column generating a process to create a decision tree 30 pool.close() # indicates that no more tasks will be added to the pool 31 pool.join() # waits for all the processes in the pool to finish their execution Listing 32 Decision Forest auxiliary tree creation function. 47 @staticmethod 48 def _create_dt(args: Tuple[np.ndarray, np.ndarray, int,int]) -> DecisionTree: 49 """Auxiliary function to create a new decision tree 50 Args: 51 args (Tuple[np.ndarray, np.ndarray, int, int]): Collection of arguments 52 Returns: 53 DecisionTree: generated decision tree 54 """ 55 i, X, column, min_samples_split, max_depth =args # retrieves the arguments 56 print(f"Building DecisionTree on class {i}") 57 # Creates a DecisionTree instance from the arguments 58 dt =DecisionTree(min_samples_split=min_samples_split, max_depth=max_depth) 59 dt.fit(X, column) # Fit the decision tree 60 return dt # Returns the constructed decision tree The _create_dt() is a static method decorated with the @staticmethod decorator. The static method is advantageous in this scenario as it can be executed independently within a parallelised context without relying on the instance or any shared state. Once all the Decision Trees have been called to generate, the pool of processes is closed using pool.close(), and the program waits for all the processes to complete using pool.join(). The resulting Decision Trees are stored in the self.dts attribute of the Decision Forest. This mechanism allows for efficient and parallelised construction of the Decision Forest, leveraging the collective intelligence of multiple Decision Trees to achieve accurate predictions. Similarly, the prediction process in the Decision Forest is parallelised using multiple processes as seen in Listing 33. In the call method, a multiprocessing pool is created to distribute the prediction task among the trained Decision Trees. The _predict_dt() method in Listing 34 is called for each Decision Tree, where it performs the prediction using the feature matrix. The results are collected and returned as anumpy array, providing efficient and collective predictions from the Decision Forest. Before moving to the implementation of the Decision Tree class, it is essential to understand the 96 Listing 33 Decision Forest parallelised prediction. 33 def __call__(self, X: np.ndarray) -> np.ndarray: 34 """Forward method for the decision forest 35 Args: 36 X (np.ndarray): feature array 37 Returns: 38 np.ndarray: array of predicted labels 39 """ 40 num_processes =mp.cpu_count() 41 pool =mp.Pool(num_processes) 42 preds =pool.map(self._predict_dt, [(dt, X) for dt in self.dts]) # predicts for each of the decision tree 43 pool.close() # waits for the process to finish 44 pool.join() 45 return np.array(preds).T# returns the predictions array, in a list wise shape Listing 34 Decision Forest prediction function for each Decision Tree. 62 @staticmethod 63 def _predict_dt(args: Tuple[DecisionTree, np.ndarray]) -> np.ndarray: 64 """Auxiliary function to predict from a decision tree 65 Args: 66 args (Tuple[np.ndarray, np.ndarray, int, int]): Collection of arguments 67 Returns: 68 np.ndarray: predicted from the decision tree 69 """ 70 dt, X =args # gets the decision tree argument and the feature array 71 return dt(X) # call predict, same as forward methods for neural networks fundamental building blocks that comprise the structure of the tree. These building blocks, known as nodes, play a crucial role in the decision-making process of the tree. The DecisionNode presented in Listing 35 represents an internal node in the tree. It contains crucial information such as the splitting criteria, which determines how the tree branches out at that node. Additionally, the DecisionNode holds references to its left and right child nodes, indicating the subsequent branches in the tree. Each DecisionNode also keeps track of the number of samples associated with it, providing insights into the data distribution at that specific point in the tree. Listing 35 Decision Node for Decision Tree building. 5class DecisionNode: 6_id: int = 1 7 8def __init__(self, split_data: SplitNode, left: Union[DecisionNode, LeafNode], right: Union[DecisionNode, LeafNode], num_samples: int)-> None: 9self.split_data =split_data 10 self.left =left 11 self.right =right 12 self.num_samples =num_samples 13 self.id: int =DecisionNode._id 14 DecisionNode._id += 1 On the other hand, the LeafNode in Listing 36 serves as a terminal or leaf in the Decision Tree. It signifies the endpoint of a particular branch and carries a label assigned to it. The label in the LeafNode 97 represents the predicted class or outcome associated with the samples that reach that leaf. Similar to the DecisionNode, the LeafNode also stores the number of samples it represents, offering valuable information about the data distribution at the leaf level. Listing 36 Leaf Node for Decision Tree building. 17 class LeafNode: 18 _id: int = 1 19 20 def __init__(self, label: int, num_samples: int)-> None: 21 self.label =label 22 self.num_samples =num_samples 23 self.id: int =LeafNode._id 24 LeafNode._id += 1 Additionally, the SplitNode (Listing 37) is a specialised data structure used to store the information related to a split in the Decision Tree. It is implemented as a TypedDict, a dictionary subclass introduced in Python that provides type hints for the keys and their associated values. The SplitNode includes the feature index, indicating the feature used for the split, the threshold value representing the decision boundary, and the metric gain, which quantifies the improvement achieved by the split. The usage of a TypedDict in this context ensures type safety and provides clarity about the expected structure of the split data. Listing 37 Split Node with the best split at a certain stage of the Decision Tree building. 27 class SplitNode(TypedDict): 28 feature_index: int 29 threshold: float 30 metric_gain: float Having defined the nodes that the tree will encompass, the decision tree’s construction process can now be explained. It begins with the initialisation method,__init__() in Listing 38, of the DecisionTree class. This method sets up various attributes of the decision tree. The root attribute represents the tree’s root node, initially set to None as no tree has been constructed yet. The lowest_depth attribute tracks the lowest depth achieved by the tree during construction. The stopping conditions of the decision tree construction are also specified. The min_samples_split parameter determines the minimum number of samples to split at a node. If the number of samples is below this threshold, further splitting is halted, and a leaf node is created. The max_depth parameter defines the maximum depth that the decision tree can reach. If the depth exceeds this limit, the construction process stops, and leaf nodes are created. Additionally, the METRIC dictionary is defined, which associates different metrics for evaluating the quality of splits. 98 Listing 38 Decision Tree __init__function. 56 class DecisionTree: 57 METRIC ={"info_gain": info_gain, "info_gain_ratio": info_gain_ratio} 58 59 def __init__(self, min_samples_split: int, max_depth: int)-> None: 60 """Initializes a decision tree with the specified parameters. 61 Args: 62 min_samples_split (int): The minimum number of samples required to split a node. 63 max_depth (int): The maximum depth of the decision tree. 64 """ 65 self.root: Union[LeafNode, DecisionNode] =None # root node of the tree, initialy a None since no tree was built yet 66 self.lowest_depth = 0 # lowest depth achieved by the tree during the construction process 67 # Stopping conditions 68 self.min_samples_split =min_samples_split 69 self.max_depth =max_depth These metrics, namely information gain and information gain ratio, serve as evaluators for assessing the performance of splits in the decision tree. They rely on the concept of entropy, which plays a fundamental role in quantifying the impurity or disorder in a set of labels. Entropy can be defined as the measure of uncertainty or randomness in the distribution of labels within a subset. To calculate the entropy of a given subset of labels, the entropy() function is utilised. This function takes in a numpy array of labels and performs the following steps: First, it calculates the total count of each class by utilising the np.unique function. Then, it computes the probability of each class by dividing the class counts by the total number of labels. Finally, the entropy is calculated by taking the negative sum of the element-wise product of the normalised class probabilities and their logarithms base 2. This process is seen in the code segment in Listing 39. Listing 39 Entropy metric calculation. 7def entropy(labels: np.ndarray): 8"""Calculate the entropy for a given subset of labels 9Args: 10 labels (np.ndarray): subset of labels 11 Returns: 12 np.ndarray: entropy of the given labels 13 """ 14 _, counts =np.unique(labels, return_counts=True)# calculate total count of each class 15 norm_counts =counts /len(labels) # calculate the probability of each class 16 return -np.sum(norm_counts *np.log2(norm_counts)) # calculate the probability of each class The info_gain() function in Listing 40 takes three numpy arrays as input: the parent label array (labels), the labels corresponding to the left branch obtained from thresholding a feature (left_labels), and the labels corresponding to the right branch obtained from the same thresholding (right_labels). This threshold process is better described ahead when explaining the splitting function during the decision tree construction. To calculate the information gain, the function first computes the entropy of the parent labels by 99 invoking the entropy() function. It then subtracts from the parent entropy the weighted sum of the entropies of the left and right branches. The weights are determined by the ratios of the number of samples in each branch to the total number of samples in the parent. The resulting information gain reflects the reduction in entropy achieved by the split. A higher information gain indicates that the split effectively separates the data into more homogeneous subsets, which is desirable for building an accurate decision tree model. Listing 40 Information Gain calculation. 19 def info_gain(labels: np.ndarray, left_labels: np.ndarray, right_labels: np.ndarray) -> float: 20 """Info gain for splitting the labels into two branches 21 Args: 22 labels (np.ndarray): parent label array 23 left_labels (np.ndarray): left generated branch from thresholding a feature 24 right_labels (np.ndarray): right generated branch from thresholding a feature 25 Returns: 26 float: information gain for the split 27 """ 28 return entropy(labels) -((len(left_labels) /len(labels)) *entropy(left_labels)) - ((len(right_labels) /len(labels)) *entropy(right_labels)) The process of calculating the information gain ratio, as discussed earlier, is implemented in the code presented in Listing 41. This code snippet defines the info_gain_ratio() function, which takes the same input parameters as the info_gain() function: the parent label array (labels), the labels corresponding to the left branch obtained from thresholding a feature (left_labels), and the labels corresponding to the right branch obtained from the same thresholding (right_labels). Listing 41 Information Gain Ratio calculation. 44 def info_gain_ratio(labels: np.ndarray, left_labels: np.ndarray, right_labels: np.ndarray) -> float: 45 """Information Gain ratio for splitting the labels into two branches 46 Args: 47 labels (np.ndarray): parent label array 48 left_labels (np.ndarray): left generated branch from thresholding a feature 49 right_labels (np.ndarray): right generated branch from thresholding a feature 50 Returns: 51 float: information gain ratio 52 """ 53 return abs(np.nan_to_num(info_gain(labels, left_labels, right_labels) /split_info(labels, left_labels, right_labels))) Inside the info_gain_ratio() function, the information gain is computed by invoking the info_gain() function, and the result is divided by the split information, which is calculated using the split_info() function defined in Listing 42. The split_info() function calculates the split information for a given split. It takes the same input parameters as the info_gain() and info_gain_ratio() functions. To avoid numerical instability, a small constant (epsilon) is added to the denominator when calculating the logarithms. The split 100 Listing 42 Split Info calculation. 31 def split_info(labels: np.ndarray, left_labels: np.ndarray, right_labels: np.ndarray) -> float: 32 """Split infotmation for splitting the labels into two branches 33 Args: 34 labels (np.ndarray): parent label array 35 left_labels (np.ndarray): left generated branch from thresholding a feature 36 right_labels (np.ndarray): right generated branch from thresholding a feature 37 Returns: 38 float: split information 39 """ 40 epsilon = 1e-8 41 return -((len(left_labels) /len(labels)) *np.log2(len(left_labels) /len(labels) +epsilon)) + ((len(right_labels) /len(labels)) *np.log2(len(right_labels) /len(labels) +epsilon)) information is obtained by applying the formula that combines the proportions of samples in the left and right branches. The information gain ratio is computed as the absolute value of the information gain divided by the split information. This ratio provides a normalised measure that accounts for the inherent bias of the information gain towards splits with many outcomes. The specific building process of the decision tree starts in the fit() method, as seen in Listing 43, where the recursive function _build_tree() is called. This method takes two parameters: X, representing the feature values of the dataset, and y, corresponding to the labels. Within the fit() method, the number of features (n_features) is determined from the shape of the feature matrix X, and the number of classes (n_classes) is obtained by finding the number of unique labels in the target vector y. The root of the decision tree is then set to the result of calling _build_tree() with Xand yas arguments. This recursive function handles the splitting and node creation process, ultimately constructing the complete decision tree. Listing 43 Decision Tree fit function. 71 def fit(self, X: np.ndarray, y: np.ndarray) -> None: 72 """Fits the decision tree to the given data set 73 Args: 74 X (np.ndarray): X values of the dataset 75 y (np.ndarray): y values of the dataset (labels) 76 """ 77 self.n_features =X.shape[1]# number of features in the dataset 78 self.n_classes =len(np.unique(y)) # number of uniqe classes in the dataset 79 self.root =self._build_tree(X, y) # builds the decision tree recursively using the dataset The _build_tree() method is a recursive function responsible for constructing the decision tree, presented in Listing 44. It takes three parameters: X, representing a subset of features, y, corresponding to a subset of labels, and depth, indicating the current depth of the tree, initially set to 0. The function also asserts that the number of rows in Xmatches the number of elements in y. The lowest_depth attribute of the decision tree is updated to the maximum value between the current depth and the existing 101 during run-time. Thus, when the code is not in run-time, the modules are imported, and only work to provide the coder with type checking capabilities from the IDE. Listing 54 Learning System recursive imports avoidance. 5from typing import TYPE_CHECKING 6 7if TYPE_CHECKING: 8from cs.bl.classification import ClassificationNetwork 9from cs.bl.segmentation import SegmentationNetwork 4.2.1 Training Metrics This section will present the implementation of metrics, focusing on their role in evaluating the performance of classification and segmentation tasks. These metrics can be divided into two categories: classification metrics and segmentation metrics. Classification metrics assess the accuracy and quality of classification models by measuring precision, recall, and F1-score, as seen in Listing 25. Segmentation metrics, conversely, evaluate the accuracy and consistency of segmentation models using metrics such as intersection over union (IoU), Dice coefficient, and pixel-wise accuracy, evident in Listing 13. By examining the implementation of these metrics within the system, valuable insights can be gained regarding the performance of the models, and informed decisions can be made regarding their training and optimisation. Regarding the segmentation metrics, the first metric presented is the mask_accuracy() function in Listing 55. This function calculates the accuracy of the given predictions and masks. It takes two 2D tensors as inputs: preds representing the predicted masks and masks representing the true masks. The function computes the element-wise comparison between the predictions and masks and calculates the sum of the correct predictions. This sum is then divided by the total number of elements in the predictions tensor using the torch.numel() function. The result is a one-element tensor representing the mask accuracy. Listing 55 Mask Accuracy metric. 132 def mask_accuracy(preds: torch.Tensor, masks: torch.Tensor) -> torch.Tensor: 133 """Calculates the accuracy of the given predictions and masks. 134 Args: 135 preds (torch.Tensor): 2D tensor with the mask predictions. 136 masks (torch.Tensor): 2D tensor with the true masks. 137 Returns: 138 torch.Tensor: One element tensor with the mask accuracy. 139 """ 140 return (preds == masks).sum() /torch.numel(preds) 108 Next, the dice_score() function is available in Listing 56, serving the purpose of calculating the Dice Score for a given set of predictions and masks. This function expects two 2D tensors, namely preds for the predicted masks and masks for the true masks. The computation involves multiplying the elementwise product of the predictions and masks by 2, followed by summing up the results. This sum is then divided by the sum of the predictions and masks, adding a small epsilon value to avoid potential division by zero, defined in Listing 57. Listing 56 Dice Score metric. 143 def dice_score(preds: torch.Tensor, masks: torch.Tensor) -> torch.Tensor: 144 """Calculates the Dice Score of the given predictions and masks. 145 Args: 146 preds (torch.Tensor): 2D tensor with the mask predictions. 147 masks (torch.Tensor): 2D tensor with the true masks. 148 Returns: 149 torch.Tensor: One element tensor with the Dice Score. 150 """ 151 return (2*(preds *masks).sum()) /((preds +masks).sum() +EPS) Listing 57 Epsilon value definition. 11 EPS = 1e-8 # small value to avoid division by zero Finally, the iou_score() function is provided in Listing 58 to compute the Intersection over Union (IoU) Score for a given set of predictions and masks. The computation involves calculating the sum of the element-wise product of the predictions and masks. This sum is divided by the difference between the sum of the predictions and masks and the sum of the element-wise product of the predictions and masks, with the addition of a small epsilon value to prevent division by zero. Listing 58 IoU metric. 154 def iou_score(preds: torch.Tensor, masks: torch.Tensor) -> torch.Tensor: 155 """Calculates the IoU Score of the given predictions and masks. 156 Args: 157 preds (torch.Tensor): 2D tensor with the mask predictions. 158 masks (torch.Tensor): 2D tensor with the true masks. 159 Returns: 160 torch.Tensor: One element tensor with the IoU Score. 161 """ 162 return (preds *masks).sum() /((preds +masks).sum() -((preds *masks).sum()) +EPS) The confusion_matrix() function as seen in Listing 59 is employed in classification metrics to establish the necessary framework for metric calculations. By taking the predicted and true labels as 1D tensors, this function generates a 2D tensor called confusion with a shape of (2, 2), specifically designed for binary classification scenarios. The function examines pairs of predictions and targets through 109 an iterative process, updating the corresponding coordinates in the confusion tensor based on the relationship between the prediction and the true label. In cases where the prediction aligns with the true label, the diagonal elements are incremented, indicating correct predictions. Conversely, discrepancies between the prediction and the true label signify instances of false positives or false negatives. Finally, the resulting confusion tensor, capturing the distribution of predictions and targets, is returned as the outcome of the function. Listing 59 Confusion Matrix computation. 37 def confusion_matrix(preds: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: 38 """Calculates the confusion matrix for the given predictions and targets. 39 Args: 40 preds (torch.Tensor): 1D tensor of predicted labels. 41 targets (torch.Tensor): 1D tensor of true labels. 42 Returns: 43 torch.Tensor: 2D tensor with the confusion matrix. 44 """ 45 # Creates a tensor with the shape (2, 2) for binary classification 46 confusion =torch.zeros(2,2, dtype=int) 47 # Iterates over the prediction/target pairs and increments to the coordinates of these pairs 48 # When the prediction is the same as the true label, the value is incremented in the diagonal meaning that the prediction is correct 49 # The difference between the prediction and the true label means either a false positive or a false negative. 50 preds =preds.flatten() 51 targets =targets.flatten() 52 for p, t in zip(preds, targets): 53 confusion[p, t] += 1 54 return confusion The computation logic for the specific parameters related to confusion matrix analysis is outlined in the comment block accompanying this module, given the Listing 60. True positives (TP) are identified when both the true label and the predicted label are the same, whereas false positives (FP) are determined by elements in the same column that were predicted as positive but are not true positives. Similarly, false negatives (FN) are identified by elements in the same row that belong to a specific class but were predicted incorrectly. True negatives (TN) are computed by subtracting the sum of TP, FP, and FN from the total number of instances. Listing 60 TP, FP, FN and TN calculation from a confusion matrix. 14 = [i, i] # true positives have the same true label and predicted label 15 = [i, :] - TP # false positives are the ones that are in the same collumn (were predicted but are not true) 16 = [:, i] - TP # false negatives are the ones that are in the same row (are from that class but were predicted wrong) 17 = total - TP - FP - FN # true negatives are everything that is not in the same row collumn By utilising the obtained confusion matrix, it becomes possible to calculate the overall accuracy of the classification. The accuracy metric measures the proportion of correctly classified instances out of 110 the total number of instances. The provided function in Listing 61, accuracy(), takes in the confusion matrix as a 2D tensor and returns a one-element tensor representing the overall accuracy. The calculation is performed by summing the diagonal elements of the confusion matrix, which correspond to the true positives, and dividing it by the sum of all elements in the matrix plus a small epsilon value ( EPS) to avoid division by zero. The resulting accuracy value is then returned, ensuring it is on the same device as specified by the device parameter. Listing 61 Accuracy Metric. 57 def accuracy(conf_matrix: torch.Tensor) -> torch.Tensor: 58 """Gives the overall accuracy of the given confusion matrix. 59 Args: 60 conf_matrix (torch.Tensor): 2D tensor with the confusion matrix. 61 Returns: 62 torch.Tensor: One element tensor with the overall accuracy. 63 """ 64 return conf_matrix.diagonal().sum() /(conf_matrix.sum() +EPS) Similarly, precision and recall metrics can be calculated, as seen in Listings 62 and 63. The precision() function, shown in Listing 62, takes in the confusion matrix as a 2D tensor and returns a 1D tensor containing the precision value for each class. Precision measures the proportion of true positive predictions out of all positive predictions (true positives and false positives). To compute precision, the function extracts the true positives (TP) from the diagonal of the confusion matrix. False positives (FP) are obtained by summing the elements in each column of the confusion matrix and subtracting the corresponding TP value. The precision for each class is then computed by dividing TP by the sum of TP, FP, and a small epsilon value (EPS) to prevent division by zero. Listing 62 Precision Metric. 81 def precision(conf_matrix: torch.Tensor) -> torch.Tensor: 82 """Gives the precision for each class of the given confusion matrix. 83 Args: 84 conf_matrix (torch.Tensor): 2D tensor with the confusion matrix. 85 Returns: 86 torch.Tensor: 1D tensor with the precision for each class. 87 """ 88 TP =torch.diag(conf_matrix) 89 FP =conf_matrix.sum(dim=0)-TP 90 return TP /(TP +FP +EPS) The recall() function, shown in Listing 63, calculates the recall for each class using the provided confusion matrix. Recall, also known as sensitivity or true positive rate, measures the proportion of true positive predictions out of all actual positive instances (true positives and false negatives). The function begins by extracting the TP values from the diagonal of the confusion matrix. False negatives (FN) are 111 obtained by summing the elements in each row of the confusion matrix and subtracting the corresponding TP value. The recall for each class is then computed by dividing TP by the sum of TP, FN, and EPS. Listing 63 Recall Metric. 93 def recall(conf_matrix: torch.Tensor) -> torch.Tensor: 94 """Gives the recall for each class of the given confusion matrix. 95 Args: 96 conf_matrix (torch.Tensor): 2D tensor with the confusion matrix. 97 Returns: 98 torch.Tensor: 1D tensor with the recall for each class. 99 """ 100 TP =torch.diag(conf_matrix) 101 FN =conf_matrix.sum(dim=1)-TP 102 return TP /(TP +FN +EPS) Using these two metrics, the f1_score() function shown in Listing 64 calculates the F1 Score for each class based on the precision and recall values. The F1 Score provides a balanced evaluation of a classifier’s performance. By calling the precision() and recall() functions, the function obtains the precision and recall values for each class using the given confusion matrix. The F1 Score is then computed using these values. Listing 64 F1 Score Metric. 105 def f1_score(conf_matrix: torch.Tensor) -> torch.Tensor: 106 """Gives the F1 Score for each class of the given confusion matrix. 107 It uses the precision and recall for each class. 108 Args: 109 conf_matrix (torch.Tensor): 2D tensor with the confusion matrix. 110 Returns: 111 torch.Tensor: 1D tensor with the F1 Score for each class. 112 """ 113 precisions =LearningSystem.precision(conf_matrix) 114 recalls =LearningSystem.recall(conf_matrix) 115 return 2 * ((precisions *recalls) /(precisions +recalls +EPS)) Concluding this section, the mcc() function in Listing 65 calculates the Matthews Correlation Coefficient (MCC) for each class based on the given confusion matrix. The MCC is a measure of the quality of binary classification models, taking into account true positives, true negatives, false positives, and false negatives. By computing the values of TP, FP, FN, and TN using the confusion matrix, the function then applies the MCC formula to obtain the MCC values for each class. 4.3 Storage System The Storage System module in BorisCAD’s cognitive architecture focuses on efficiently storing and manipulating long-term and working memory, which is crucial for performing complex Computer-Aided 112 Listing 65 Matthews Correlation Coefficient Metric. 118 def mcc(conf_matrix: torch.Tensor) -> torch.Tensor: 119 """Calculates the Matthews Correlation Coefficient for each class of the given confusion matrix. 120 Args: 121 conf_matrix (torch.Tensor): 2D tensor with the confusion matrix. 122 Returns: 123 torch.Tensor: 1D tensor with the MCC for each class. 124 """ 125 TP =torch.diag(conf_matrix) 126 FP =conf_matrix.sum(dim=0)-TP 127 FN =conf_matrix.sum(dim=1)-TP 128 TN =conf_matrix.sum() -(TP +FP +FN) 129 return ((TP *TN) -(FP *FN)) /(torch.sqrt((TP +FP) *(TP +FN) *(TN +FP) *(TN +FN)) +EPS) Design (CAD) tasks. By simplifying certain biological complexities, the Storage System module provides a streamlined proof of concept while capturing the fundamental aspects of memory processes. In BorisCAD, the Storage System module is a repository for storing and retrieving essential design elements, such as image features and their contents, enabling the architecture to make informed decisions based on past experiences. Long-term memory retains information over an extended period, while working memory actively manipulates this stored information in real-time during decision-making. The Storage System module incorporates a graph structure into its memory design to optimise information storage and manipulation. This graph structure efficiently represents and organises complex relationships between design elements, such as parts, sub-assemblies, and assemblies. Each memory node within the graph represents an image perceived by the system’s bottom level and contains multiple abstraction layers, including high and low-level feature maps that provide visual or sensory representations of the image. Starting with the high-level interface, the StorageSystem class depicted in Listing 66 connects the working and long-term memory within the cognitive architecture. It facilitates various operations in encoding, recognition, retrieval, and decision-making processes. This class is implemented as a singleton, ensuring that there is only one instance of the class throughout the system. This design allows multiple components within the system to access the StorageSystem without creating new instances, promoting efficiency and consistency. Upon initialisation, the __init__() method takes in a parameter wm_size, representing the working memory’s size. It creates an instance of the WorkingMemory class, representing the working memory object with the specified size. Additionally, it creates an instance of the LongTermMemory class, representing the long-term memory object. The _most_recent_node attribute of the StorageSystem class is used to store the most recent memory node. This attribute refers to the MemoryNode object representing the most recently encoded information in the memory system. 113 Listing 66 Storage System __init__function. 7class StorageSystem(metaclass=Singleton): 8""" 9This class works as a connection between the working and long-term memory. 10 It calls all operations that need to be performed during the encoding, recognition, retrieval, and decision-making process. 11 It is implemented as a singleton class, allowing it to be accessed by multiple places in the system without creating a new instance. 12 """ 13 14 def __init__(self, wm_size: int)-> None: 15 """Initialize the StorageSystem object. 16 Args: 17 wm_size (int): The size of the working memory. 18 """ 19 self.working_memory =WorkingMemory(wm_size) # Create a working memory object 20 self.long_term_memory =LongTermMemory() # Create a long-term memory object 21 self._most_recent_node: MemoryNode =None # Store the most recent memory node To implement the StorageSystem class as a singleton, the auxiliary type class Singleton is utilised. This class, depicted in Listing 67, acts as a metaclass that creates a base class with singleton behaviour when called. The Singleton class includes a dictionary attribute _instances, which is used to store instances of classes that implement the singleton pattern. The __call__() method within the class overrides the default behaviour of creating a new instance when a class is called. Instead, it enforces the singleton behaviour by checking if an instance of the class already exists in the _instances dictionary. If the class doesn’t have an instance yet, a new one is created and stored in the dictionary. Subsequent calls to the class will then return the stored instance rather than creating a new one. Listing 67 Singleton class implementation. 1class Singleton(type): 2"""A metaclass that creates a Singleton base class when called.""" 3 4_instances ={} # Dictionary to store instances of Singleton classes 5 6def __call__(cls,*args, **kwargs): 7"""Overrides the __call__ method to enforce singleton behavior. 8Args: 9cls: The class being instantiated. 10 *args: Positional arguments passed to the class constructor. 11 **kwargs: Keyword arguments passed to the class constructor. 12 Returns: 13 The instance of the Singleton class. 14 """ 15 if cls not in cls._instances: 16 # If the class doesn't have an instance yet, create a new one and store it 17 cls._instances[cls]=super(Singleton, cls).__call__(*args, **kwargs) 18 return cls._instances[cls]# Return the stored instance for subsequent calls To enable the creation of a new node in memory, a property was added to the StorageSystem class. When this property is assigned a value, it triggers adding the node to the memories, as illustrated in Figure 26. This triggering point is achieved by modifying the forward() function in the ResNet architecture, which is responsible for gathering feature maps during inference time. The modified forward() function, 114 depicted in Listing 68, demonstrates this process. In this modified function, the low-level and high-level features are stored from the first and last layers of the network, respectively. When the network is not in the training mode, a MemoryNode is created using the stored features, and it is assigned to the most recent node in the StorageSystem. Listing 68 Modified ResNet network forward method. 120 def forward(self, X: torch.Tensor) -> torch.Tensor: 121 """Forward pass of the network. 122 Args: 123 X (torch.Tensor): Input tensor. 124 Returns: 125 torch.Tensor: Output tensor after passing through the network. 126 """ 127 X=self.input(X) # Pass the input through the initial layers 128 for i, layer in enumerate(self.network): 129 X: torch.Tensor =layer(X) # Pass the input through each layer in the network 130 if self.training: 131 continue 132 if i== 0: 133 _low_level_features =X.clone() # Store the low-level features at the first layer 134 elif i== len(self.network) - 1: 135 _high_level_features =X.clone() # Store the high-level features at the last layer 136 if not self.training: 137 # Create a MemoryNode with the stored low-level and high-level features and assign it to the most recent node in the StorageSystem 138 StorageSystem().most_recent_node =MemoryNode((_low_level_features, _high_level_features)) 139 X=self.avgpool(X) # Apply adaptive average pooling 140 X=X.reshape(X.shape[0], -1)# Reshape the tensor to a 2D shape for the fully connected layer 141 # Pass the reshaped tensor through the fully connected layer for classification 142 return self.fc(X) The memory addition process in the StorageSystem class is fully implemented, as depicted in Listing 69. This implementation involves the most_recent_node setter method, which sets the provided MemoryNode as the _most_recent_node attribute of the StorageSystem class. Furthermore, it triggers adding the new node to the memories. First, the method adds the new node to the LTM by calling the add_node() method of the LongTermMemory class. This step establishes connections between the new node and similar nodes in the LTM that surpass a predefined threshold during recognition. Next, the method populates the WM with similar nodes retrieved from the LTM. Using the get_population() method of the LongTermMemory class, a list of similar nodes is obtained based on the specified similarity criteria. The method then iterates through the retrieved nodes in reverse order and adds them to the WM. This ensures that the most similar node is added last, closely positioned to the newly inferred node. Finally, the method adds the most recent node to the beginning of the working memory by invoking the add_node() method of the WorkingMemory class. To gain a clearer understanding of the system’s structure, it is essential to visualise the composition of a ”memory.” The MemoryNode class provides a representation of a memory node, as shown in 115 Listing 69 Implementation of the memory addition process in the StorageSystem class. 31 @most_recent_node.setter 32 @add_logging 33 def most_recent_node(self, node: MemoryNode): 34 """Setter method for the most_recent_node property. 35 Args: 36 node (MemoryNode): The memory node to set as the most recent node. 37 """ 38 self._most_recent_node =node 39 # Create/add new node to the memories 40 # Connect the new node with nodes in the LTM that are similar and above the threshold (first stage of recognition) 41 self.long_term_memory.add_node(self._most_recent_node) 42 # Populate the working memory with similar nodes (n nodes, the most similar, depending on the working memory size) 43 population =self.long_term_memory.get_population(self._most_recent_node) 44 # Add the similar nodes to the working memory (maximum number of nodes to be added is one less than the working memory size) 45 for node in reversed(population[: self.working_memory.size - 1]): 46 # By reversing this list, the most similar node is added last and closest to the inferred node 47 self.working_memory.add_node(node) 48 # Add the most recent node to the beginning of the working memory 49 self.working_memory.add_node(self._most_recent_node) Listing 70. This class consists of a nested Data class, defined using the dataclass decorator. This class encapsulates the attributes associated with a memory node, including low_level_features and high_level_features, represented as tensor objects. Additionally, the probabilities, classification, and final decision attributes are optional lists, assigned to the node throughout the execution of the program. The MemoryNode class also contains other attributes and functionalities. The connected_nodes attribute is a SortedDict that stores the connected nodes, facilitating efficient retrieval. The data attribute is initialised using the Data class, taking the provided data set as arguments. An ID is generated for each node using uuid.uuid4().hex. Lastly, the hot index attribute is set to 50, representing the default value. The add_node() method in the LTM utilises the properties of MemoryNode objects during the recognition task. It compares the similarity between the new node and existing nodes in the memory, based on a recognition threshold. If the similarity meets the threshold, a connection is established between the new node and the existing node. In addition, the connected_nodes dictionary, which stores these connections, is automatically sorted when a new similar node is found and inserted. This sorting ensures that the connected nodes are ordered based on their similarity to the new node, allowing for efficient retrieval and decision-making processes. This process is displayed in Listing 71. The calculation of node similarity is achieved through the implementation of the overloaded __sub__() function, as shown in Listing 72. This function computes the similarity score between two MemoryNode instances. It calculates the similarity for both the low-level features and high-level features 116 Listing 70 Implementation of the Memory Node class. 9class MemoryNode: 10 @dataclass 11 class Data: 12 low_level_features: torch.Tensor 13 high_level_features: torch.Tensor 14 probabilities: Optional[list]=None 15 classification: Optional[list]=None 16 final_decision: Optional[list]=None 17 18 def __repr__(self)-> str: 19 return f"Data(low_level_features={self.low_level_features.shape}, high_level_features={self.high_level_features.shape}, probabilities={self.probabilities}, classification={self.classification})" 20 21 def __init__(self, data: set): 22 """Initialize a MemoryNode instance. 23 Args: 24 data (set): A set containing the required data attributes for the MemoryNode. 25 """ 26 self.connected_nodes =SortedDict() # Dictionary to store connected nodes 27 self.data =MemoryNode.Data(*data) # Initialize the data attribute 28 self.id =uuid.uuid4().hex # Generate a unique ID for the node 29 self.hot_index: int = 50 # Set the hot index to 50 (default value) Listing 71 Node addition method in the Long-Term Memory. 13 def add_node(self, node: MemoryNode) -> None: 14 """Add a node to the memory. 15 Args: 16 node (MemoryNode): The node to be added to the memory. 17 """ 18 # Perform recognition process and update connected nodes' hotness 19 for node_id in self.memory.keys(): 20 # Compute the similarity between the new node and existing nodes 21 similarity =node -self.memory[node_id] 22 # If the similarity meets the recognition threshold, add the connection 23 if similarity >= self.T_RECOGNITION: 24 node.connected_nodes[node_id] =similarity 25 # Add the new node to the memory 26 self.memory[node.id] =node by measuring the Euclidean distance between them. The similarity scores are then combined and averaged to obtain the overall similarity score. Listing 72 Memory Node subtraction method overload. 35 def __sub__(self, other: MemoryNode) -> float: 36 """Compute the similarity between two MemoryNode instances. 37 Args: 38 other (MemoryNode): The other MemoryNode instance to compare similarity with. 39 Returns: 40 float: The similarity score between the two MemoryNode instances. 41 """ 42 low_level_similarity: torch.Tensor =1/(1+torch.norm(self.data.low_level_features - other.data.low_level_features)) 43 high_level_similarity: torch.Tensor =1/(1 + torch.norm(self.data.high_level_features - other.data.high_level_features)) 44 return ((low_level_similarity +high_level_similarity).mean()).item() The addition process in the Working Memory is demonstrated in Listing 73. When a new node is 117 Chapter 5 Experimental Analysis and Verification This chapter will explore the testing process of the BorisCAD architecture. At this stage, the primary objective is to ensure the system performs optimally and reliably during training and inference. Given that the system handles real-world input data, the ability to make accurate predictions becomes a crucial requirement. Encompassing neural networks for segmentation and classification, the bottom level of the computation system forms the foundation of sub-symbolic data in this architecture. The segmentation network, responsible for partitioning input data into distinct regions, facilitates precise location and identification of relevant features. The classification network then uses this to assign accurate labels or classes to the previously segmented regions. At the top level, the system incorporates a decision forest composed of multiple decision trees. Decision trees offer a structured and hierarchical approach to decision-making, handling symbolic data to derive accurate conclusions. The decision forest integrates the outputs of individual decision trees to make robust and informed predictions. The main objective of testing this part of the system is to evaluate the generalisation of the induction mechanism based on the given dataset while avoiding overcommitting resources to overfitting the training data. Furthermore, the evaluation will occur during the inference phase involving memory. As the architecture processes new images over time, it actively constructs memory to enhance the final decision-making, resulting in more accurate information identification from previous data. During this testing phase, the focus will be on evaluating the overall performance and reliability of the system by simulating different input conditions, varying data and configuration parameters. By doing so, it will be graphically visible where the system needs to be optimised or improved. Thus, this chapter will outline the methodologies and techniques employed to conduct this 124 comprehensive testing of the system during training and inference time. Evaluation metrics and other relevant indicators will be explored to quantify the system’s effectiveness. In order to establish a benchmark, the testing framework incorporates a system comprising a NVIDIA GeForce RTX 3060 GPU housing 12GB of dedicated memory. This GPU is synergistically coupled with an AMD Ryzen 7 3700X processor and an 48GB of DDR4 RAM operating at a clock speed of 3600 MHz. The collective configuration presents a cumulative memory capacity of 36GB, ensuring optimal utilisation of the GPU’s capabilities. 5.1 Modular Testing Due to the cognitive architecture of this system, which employs bottom-up learning, the testing process is applied sequentially. It follows a modular approach, where each component of the system is individually assessed before evaluating their integration. This ensures a thorough examination of the performance and functionality of each module. Past inferences from lower methods are then utilised in higher methods, further emphasising the need for testing and validation before evaluating subsequent components in the chain. Therefore, the learning process is presented hierarchically, with each model utilising the previous one during both the training and inference stages. The testing process focuses on different modules within the system, starting with the segmentation network. This module undergoes independent training and testing to determine its effectiveness in partitioning input data into distinct regions. The assessment evaluates its accuracy and precision in identifying relevant features. Next, the evaluation shifts to the classification network. This module utilises the output of the segmentation network and assigns accurate labels or classes to the segmented regions. The analysis includes variations with and without the segmentation pre-processing step, aiming to understand the influence of this step on the final classification results. Furthermore, the classification network generates probabilities that play a crucial role in constructing the decision forest. These probabilities, derived from the classification module, enhance the robustness and reliability of the decision forest’s predictions. The image sizes and number of epochs used for training all the models in the computation system were selected based on previous research findings and to allow for a comprehensive range of evaluations without excessive resource allocation. 125 5.1.1 Bottom-level: segmentation and classification In the context of testing the segmentation network, a series of experiments has been designed to evaluate its performance and robustness. These tests involve varying image sizes and numbers of training epochs, aiming to accurately assess the network’s ability to partition input data into distinct regions. The testing configuration is explicit in Table 5. Table 5: Segmentation tests planning. Test Configuration Image Size Number of Epochs Test 1 224 ×224 8 Test 2 224 ×224 16 Test 3 224 ×224 32 Test 4 480 ×480 8 Test 5 480 ×480 16 Test 6 480 ×480 32 Test 7 512 ×512 8 Test 8 512 ×512 16 Test 9 512 ×512 32 The number of training epochs for each test configuration was carefully determined based on extensive experimentation and validation. Through iterative training and evaluation, the optimal point where the network achieves peak performance without overfitting or diminishing returns is found. Furthermore, the network’s capability to generalise across different image sizes and adapt to various training durations is of significant interest. Several metrics will be employed to measure the segmentation network’s performance, including mask accuracy, dice score, and Intersection over Union (IoU). Mask accuracy quantifies the pixel-wise precision of the generated segmentation masks. It quantitatively assesses how closely the network aligns with ground truth annotations, indicating its proficiency in identifying and classifying distinct regions within the input data. The dice score is a metric that measures the similarity between the predicted segmentation masks and the ground truth masks. It assesses the overlap between the two masks, considering both true and false positives. The dice score comprehensively evaluates the network’s ability to balance precision and recall in its segmentation outputs. IoU calculates the ratio of the area of overlap between the predicted segmentation masks and the ground truth masks to the total area encompassed by both masks. IoU provides a robust measure of segmentation accuracy, reflecting how well the network delineates regions of interest. Employing these metrics allows for a thorough evaluation of the segmentation network’s performance across various test configurations. By considering different image sizes and training 126 epochs, the network’s adaptability to varying input dimensions and training durations can be analysed, aiding in identifying optimal settings. Additionally, only a single dataset of image-masks will be used to evaluate the performance of the segmentation system. This dataset has been selected to represent a diverse range of images and provides the necessary ground truth masks for evaluation. To train the model, a configuration file can be created as seen bellow. In here, the segmentation dataset is defined, as well as the specific size that the images will have. Additionally, the network selected will include the attention mechanisms. To train the model, a save file is defined, as well as a number of epochs and the batch size. The same process will be done for every other module tested within the system, with specific configurations for the operation at hand. config_segmenter.yaml Boris: segmentation: K:\Dataset\masks size: [224, 224] Computation: Bottom: attention: true Training: epochs: [8] save_file: segmenter_224_224_16.boris batch_size: 32 A comprehensive display of the obtained results for the segmentation network training are displayed in Table 6. Table 6: Segmentation tests results. Test Configuration Loss Accuracy (%) Dice Score IoU Test 1 0.1223 96.62% 0.9567 0.9170 Test 2 0.1056 96.87% 0.9621 0.9269 Test 3 0.0857 97.42% 0.9738 0.9490 Test 4 0.1677 97.56% 0.9620 0.9268 Test 5 0.1253 97.73% 0.9654 0.9332 Test 6 0.0794 97.99% 0.9708 0.9432 Test 7 0.1719 96.98% 0.9495 0.9040 Test 8 0.1298 97.36% 0.9574 0.9184 Test 9 0.1115 96.80% 0.9468 0.8999 127 In Test 1, Test 2, and Test 3, the image size was kept constant at 224x224 pixels, while the number of epochs increased from 8 to 32. The loss values decreased gradually, indicating improved performance as the model was trained longer. The accuracy, Dice Score, and IoU also showed a positive trend, with higher values achieved with more epochs. Notably, the differences in these metrics between Test 2 and Test 3 were relatively minor compared to the improvement observed between Test 1 and Test 2. In Test 4, Test 5, and Test 6, the image size was increased to 480x480 pixels, maintaining the same number of epochs as in the previous tests. Surprisingly, the performance did not significantly improve despite the larger image size. The loss values were slightly higher, indicating a slightly less accurate prediction. The accuracy, Dice Score, and IoU values were slightly improved compared to the smaller image size tests, but the gains were not substantial, given the increase in computational time. Increasing the image size beyond a certain threshold may contribute little to the segmentation performance. In Test 7, Test 8, and Test 9, the image size was further increased to 512x512 pixels, while the batch size was reduced to 16. Similar to the previous tests, the loss values increased slightly compared to the smaller image size tests. The accuracy, Dice Score, and IoU values slightly decreased compared to the 480x480 pixel tests. In conclusion, the segmentation tests demonstrated that increasing the image size beyond a certain threshold did not substantially improve the model’s performance. While larger image sizes were expected to provide more detailed information for segmentation, the gains in accuracy, Dice Score, and IoU were relatively modest compared to the required computational time. These findings suggest a limit to the benefits of increasing image size in the context of segmentation. Therefore, it is essential to carefully consider the trade-off between computational resources and performance when deciding on the optimal image size for segmentation tasks. During the training, a verbose similar to what is seen in Figure 40 is presented. In here, the metrics associated with the model are seen, in addition to information referring the current batch and completion times. The adaptive learning rate is also displayed whenever there is a change. Additionally, an example of a graph generated using the training metrics is depicted in appendix Figure 51. Figure 40: Segmentation Network verbose during training and validation. 128 The evaluation of the classification network focuses on its ability to assign labels or classes to input images accurately. This assessment is conducted in two scenarios: with and without the segmentation network, analysing the model’s behaviour when given pre-processed data that isolates important image sections provides valuable insights. This comprehensive testing approach aims to evaluate the system’s capability to accurately identify and classify various objects or entities without relying solely on the input data. During the testing phase, multiple evaluation metrics are employed to assess the performance of the classification network. These metrics include accuracy, precision, recall, F1 score, and Mathews Correlation Coefficient (MCC). The network’s ability to correctly classify raw data and segmented regions in an image can be determined by measuring these metrics, enabling informed predictions. The testing involves three datasets: CheXpert, NIH Chest X-ray, and pneumonia-related X-ray images. The CheXpert dataset comprises a vast collection of chest X-ray images with annotations provided by radiologists, serving as valuable ground truth for evaluating the network’s ability to classify various thoracic pathologies accurately. The NIH Chest X-ray dataset consists of diverse chest X-ray images sourced from the National Institutes of Health, enabling comprehensive evaluation of the classification network’s performance across various conditions. Lastly, the pneumonia-related X-ray images dataset focuses specifically on pneumonia-related cases, allowing for an assessment of the network’s proficiency in accurately identifying and distinguishing pneumonia-related patterns. Similar to the segmentation network testing, the testing procedure for the classification network with the segmentation preprocessing is presented in Table 7. This procedure is repeated for each of the three datasets, ensuring the evaluation of the system’s performance when encountering different data types. Additionally, and as a mean to compare results, Table 8 was elaborated to compare these results with a classification model trained without the use of the segmentation preprocessing. Since this is only used as an extra comparison and justification for the full usage of the segmentation network, the pneumonia dataset was used for it’s low complexity and size. The results obtained from training the classification network for each of the datasets are presented in Tables 12, 11, and 10. The additionally tested model without the segmentation processing is depicted in Table 9. In the given Table 9, the results of the pneumonia dataset training without segmentation pre-processing are presented. For Test 1, which utilised an image size of 224x224 and trained for 32 epochs, the obtained results include a loss of 0.4183, an accuracy of 79.34%, precision of 0.7207, recall of 0.7983, F1 score of 0.7575, and MCC of 0.5126. 129 Table 7: Classification tests with segmentation planning. Test Configuration Image Size Number of Epochs Test 1 224 ×224 16 Test 2 224 ×224 32 Test 3 224 ×224 48 Test 4 480 ×480 16 Test 5 480 ×480 32 Test 6 480 ×480 48 Test 7 512 ×512 16 Test 8 512 ×512 32 Test 9 512 ×512 48 Table 8: Classification tests without segmentation and using the pneumonia dataset. Test Configuration Image Size Test 1 224 ×224 Test 2 480 ×480 Test 3 512 ×512 Similarly, Test 2 employed an image size of 480x480 and trained for 32 epochs. The results show a lower loss of 0.3590 and an improved accuracy of 82.97%. The precision, recall, F1 score, and MCC were calculated as 0.7739, 0.8330, 0.8023, and 0.4634, respectively. In Test 3, the image size was increased to 512x512 while training for 32 epochs. The results demonstrate a further reduction in loss to 0.3575 and an increased accuracy of 83.06%. The precision, recall, F1 score, and MCC were computed as 0.7760, 0.8327, 0.8033, and 0.4556, respectively. Table 9: Classification tests results on pneumonia dataset without segmentation. Test Configuration Loss Accuracy (%) Precision Recall F1 Score MCC Test 1 0.4183 79.34% 0.7207 0.7983 0.7575 0.5126 Test 2 0.3590 82.97% 0.7739 0.8330 0.8023 0.4634 Test 3 0.3575 83.06% 0.7760 0.8327 0.8033 0.4556 Analysing the provided results for the pneumonia classification tests, it is possible to observe the system’s performance across different image sizes and the number of epochs depicted in Table 10. For the tests conducted with an image size of 224x224, increasing the number of epochs from 16 to 32 (Test 1 to Test 2) led to a slight improvement in most metrics. The loss decreased from 0.4104 to 0.3942, and the accuracy increased from 79.55% to 80.48%. The precision, recall, F1 score, and MCC also demonstrated improvements. Similarly, increasing the number of epochs from 32 to 48 (Test 2 to Test 3) slightly decreased accuracy, precision, recall, F1 score, and MCC. However, the overall performance remained relatively consistent. 130 Moving to the larger image size of 480x480, the improvements across the board are noticeable. Increasing the number of epochs from 16 to 32 (Test 4 to Test 5) resulted in a significant increase in accuracy from 79.05% to 83.37%. The precision, recall, F1 score, and MCC also improved. Further increasing the number of epochs from 32 to 48 (Test 5 to Test 6) led to a continued enhancement in performance, with accuracy reaching 84.56%. For the most prominent image size of 512x512, the overall performance is slightly lower compared to the other image sizes. However, increasing the number of epochs from 32 to 48 (Test 8 to Test 9) showed improvements across most metrics, including accuracy, precision, recall, F1 score, and MCC. Table 10: Classification tests results on pneumonia dataset. Test Configuration Loss Accuracy (%) Precision Recall F1 Score MCC Test 1 0.4104 79.55% 0.7246 0.7990 0.7600 0.5178 Test 2 0.3942 80.48% 0.7369 0.8099 0.7717 0.5413 Test 3 0.3960 80.19% 0.7330 0.8061 0.7678 0.5337 Test 4 0.4121 79.05% 0.7173 0.7934 0.7535 0.5043 Test 5 0.3321 83.37% 0.7565 0.8368 0.7946 0.5318 Test 6 0.3123 84.56% 0.8065 0.8488 0.8271 0.5689 Test 7 0.4121 76.25% 0.6946 0.7231 0.7086 0.4324 Test 8 0.3231 85.57% 0.7795 0.8115 0.7952 0.4852 Test 9 0.3013 85.63% 0.7800 0.8121 0.7957 0.4855 Comparing the achieved results, including a segmentation network in the classification system results in improved performance across all image sizes. In Test 2, with an image size of 224x224 and 32 epochs, the accuracy increases from 79.34% to 80,48% with the segmentation network. This improvement is consistent with Test 5 (480x480, 32 epochs) and Test 8 (512x512, 32 epochs), where accuracy, precision, recall, F1 score, and MCC show notable enhancements when segmentation is incorporated. These results indicate that the segmentation network enhances the system’s ability to detect and classify pneumoniarelated features in the datasets accurately. Consequently, integrating the segmentation network positively impacts the overall performance of the pneumonia classification system. The testing done with the next two datasets (NIH and CheXpert) will always have the segmentation network, in order to increase the testing metrics obtained. The classification experiments depicted in Table 11 were conducted using the NIH dataset, and the results were obtained for different image sizes and varying numbers of epochs, as shown in Table 7. Test 1, performed on images of size 224x224 and trained for 16 epochs, yielded a loss of 0.6503. The accuracy achieved was 63.55%, with precision, recall, F1 score, and MCC values of 0.6700, 0.6990, 0.6842, and 0.2013, respectively. The relatively lower performance of Test 1 suggests that the model 131 Table 11: Classification test results on NIH dataset. Test Configuration Loss Accuracy (%) Precision Recall F1 Score MCC Test 1 0.6503 63.55% 0.6700 0.6990 0.6842 0.2013 Test 2 0.6233 65.23% 0.7162 0.7162 0.7162 0.5721 Test 3 0.5739 65.32% 0.7052 0.7183 0.7117 0.5710 Test 4 0.5335 81.23% 0.7219 0.7300 0.7259 0.4701 Test 5 0.5191 85.13% 0.7566 0.7650 0.7608 0.4927 Test 6 0.4648 86.00% 0.7643 0.7729 0.7686 0.4977 Test 7 0.5293 81.63% 0.7302 0.7414 0.7357 0.4501 Test 8 0.4547 85.03% 0.8092 0.8183 0.8137 0.5242 Test 9 0.3604 85.98% 0.8182 0.8092 0.8137 0.5521 still needs to be optimised for this dataset and thus requires further training. Test 2, conducted with the same image size but trained for 32 epochs, exhibited improvements across all metrics. The loss decreased to 0.6233, and the accuracy increased to 65.23%. The remaining metrics achieved 0.7162, 0.7162, 0.7162, and 0.5721, respectively. Continuing with Test 3, where the number of epochs increases to 48, the loss dropped to 0.5739 while the accuracy remained consistent at 65.32%. The precision, recall, F1 score, and MCC improved slightly compared to Test 2, reaching values of 0.7052, 0.7183, 0.7117, and 0.5710, respectively. Tests 2 and 3 demonstrate that increasing the number of epochs enhances the model’s ability to extract relevant features from the segmented images, improving the gathered metrics but stabilising near the end of the training. Test 4 was conducted on images of size 480x480 and trained for 16 epochs, an image size larger than the previous tests. This configuration yielded a significantly reduced loss of 0.5335 and an improved accuracy of 81.23%. The remaining metrics reached 0.7566, 0.7650, 0.7608, and 0.4927, respectively. In Test 5, with the same image size but trained for 32 epochs, the loss further decreased to 0.5191, and the accuracy significantly improved to 85.13%. Test 6 was performed on images of size 480x480 and trained for 48 epochs, resulting in a reduced loss of 0.4648 and an accuracy of 86.00%. The precision, recall, F1 score, and MCC achieved values of 0.7643, 0.7729, 0.7686, and 0.4977, respectively. These findings demonstrate the effectiveness of a larger image size combined with increased epochs in achieving superior classification performance. The subsequent tests, conducted on images of size 512x512, exhibited similar trends. Test 9, trained for 48 epochs on images of size 512x512, showcased superior performance. The loss reached its lowest value at 0.3604, and the accuracy achieved an outstanding 85.98%. Precision, recall, F1 score, and MCC obtained values of 0.8182, 0.8092, 0.8137, and 0.5521, respectively. 132 The experiments performed on the NIH dataset demonstrated that increasing the number of epochs and utilising larger image sizes improved metrics, with the best results achieved at the highest image size and for the most epochs. Although verified, these parameters make the system more resource heavy and might only sometimes be achievable in real-world tasks. Moving to the final dataset used to test the bottom-level performance, the results obtained using the CheXpert dataset are depicted in Table 12. Table 12: Classification test results on CheXpert dataset. Test Configuration Loss Accuracy (%) Precision Recall F1 Score MCC Test 1 0.6493 61.32% 0.6712 0.6754 0.6733 0.3292 Test 2 0.6306 63.87% 0.6980 0.7024 0.7002 0.3423 Test 3 0.5956 63.90% 0.6983 0.7027 0.7005 0.3425 Test 4 0.5713 81.23% 0.7312 0.7464 0.7387 0.4731 Test 5 0.5315 85.13% 0.7647 0.7806 0.7725 0.4948 Test 6 0.5084 86.00% 0.7724 0.7885 0.7804 0.4998 Test 7 0.5569 81.63% 0.7302 0.7914 0.7596 0.5301 Test 8 0.5491 86.13% 0.7683 0.8327 0.7992 0.5578 Test 9 0.4968 86.38% 0.7705 0.8352 0.8015 0.5594 Similar to previous tests, from increasing the number of epochs the model trains for, the metrics significantly improve between 16 and 32 epochs and stabilise afterwards. Test 1, trained for 16 epochs, resulted in a loss of 0.6493 and an accuracy of 61.32%. The precision, recall, F1 score, and MCC values were 0.6712, 0.6754, 0.6733, and 0.3292, respectively. Test 2, trained for 32 epochs, showed improvements across all metrics. The loss decreased to 0.6306, and the accuracy increased to 63.87%. With Test 3, trained for 48 epochs, the loss decreased to 0.5956, while the accuracy remained relatively consistent at 63.90%. Consistently with what happened in the previous testing for the image size of 224x224, the metrics obtained are significantly low compared to larger sizes. This decrease can be explained by the network being unable to capture the image’s intricacies with such low resolution and only being able to bias towards the most seen label within the dataset. Tests 4, 5 and 6 obtained improved results, with the maximum obtained in all metrics achieved at 48 epochs into training. The final loss obtained was 0.5084, and the maximum accuracy took a value of 86%. The remaining analysed metrics also had the highest values, with 0.7724, 0.7885, 0.7804 and 0.4998, respectively. Test 7, with an image size of 512x512 trained for 16 epochs, displayed a loss value of 0.5569 and an accuracy of 81.63%. The precision, recall, F1 score, and MCC values were 0.7302, 0.7914, 0.7596, and 0.5301, respectively. Test 8, trained for 32 epochs, resulted in a lower loss of 0.5491 and a higher 133