FC-DI - Master Thesis (dissertation)
Permanent URI for this collection
Browse
Recent Submissions
- Benchmarking Contrastive Learning for Multimodal Medical ImagingPublication . Silva, Martim Dourado da; Garcia, Nuno CruzDeep learning has achieved remarkable success in complex tasks, but its reliance on large, annotated datasets limits scalability in medical imaging, where expert labeling is costly and scarce. Contrastive learning, a self-supervised approach, offers a way to learn useful visual representations from unlabeled data by training models to distinguish between different images while aligning augmented views of the same instance. This thesis investigates the effectiveness of three state-of-the-art contrastive learning frameworks - SimCLR, MoCo, and BYOL - in generating transferable representations from medical images for two downstream tasks: multiclass classification and binary segmentation of breast tissue. It also examines whether combining ultrasound and mammography images during pretraining supports or hinders model generalization, reflecting real-world multimodal diagnostic workflows. Using seven public datasets, three modality-specific pretraining sets were constructed (ultrasound, mammography, and a balanced multimodal mix), each used to train the three frameworks. The resulting models were then fine-tuned for each downstream task. All networks shared a ResNet-18 backbone, and segmentation models used U-Net architectures with pretrained encoders. Results show that contrastive pretraining improves classification performance, particularly with ultrasound data and using BYOL or MoCo. These models outperformed randomly initialized baselines. For segmentation, however, random initialization yielded superior results, suggesting that standard contrastive objectives and augmentations do not capture the spatial precision needed for pixel-wise tasks. Mammography images posed further challenges due to small lesion size and detail loss from uniform resizing. This work underscores both the promise and the limitations of contrastive learning in clinical imaging. While effective for classification with limited labels, adapting contrastive methods for segmentation requires the design of specialized modality-aware pipelines.
- Algorithms to Maximize the Availability of Flying ad-hoc NetworksPublication . Catarro, Miguel do Couto Pereira; Sá, Alan Oliveira de; Pinto, Luís RamosFlying ad-hoc networks (FANETs) are networks comprised of highly mobile nodes called unmanned aerial vehicles (UAVs). Due to the ease of deployment of the UAVs, FANETs are very advantageous in scenarios where there is no functioning infrastructure, either because it has not been built yet or because natural or man-made disasters have destroyed it. However, these networks have the disadvantage of being energy-constrained - i.e., UAVs are battery-powered - meaning that they have a limited time of operation. Beyond that, to aggravate the situation, UAVs handling heavy traffic will become inoperative sooner than those handling less (hot-spot problem), limiting the operation time even more, as the network can’t operate without heavy traffic UAVs. To address the hot-spot problem, this dissertation proposes a UAV swapping strategy to maximize network Availability, prioritizing user-perceived Quality of Service (QoS) over network lifetime. For example, in a network of three UAVs, if UAV1 serves more users than the others and its battery runs low, exchanging positions with UAV2 (or UAV3) ensures UAV1’s area remains covered, minimizing disruption for users. In this work, Particle Swarm Optimization (PSO) and a novel algorithm, called RAMNA, are presented as viable options - delivering good solutions with low computational cost - to determine when and which UAVs should swap. Lastly, PSO and RAMNA performance were evaluated, with both algorithms showing an average Availability improvement, relative to doing nothing, of 62.5% and 61%, respectively, for all topologies tested. Furthermore, this work showed that by using RAMNA instead of a state-of-the-art algorithm - named SwapLevel - the network Availability is improved, on average, by 14.8 percentage points (pp), achieving an improvement up to 31.8 pp. Additionally, every result shown during this work was supported by energy models developed using real-world data collected from UAVs in the field.
- Protecting Web applications with secure code by identifying and removing vulnerabilities using similarity techniquesPublication . Prates, David António Cota; Medeiros, Ibéria Vitória de Sousa; Cogo, Vinicius VielmoWeb applications are frequently targeted due to vulnerabilities in their source code, particularly weaknesses such as Cross-Site Scripting (XSS) and SQL injection (SQLi). When exploited, these vulnerabilities can compromise the confidentiality, integrity, and availability of data, potentially putting users at risk. Given the constant discovery of new security flaws, continuous monitoring is essential. However, remediation teams face significant challenges, as detecting and fixing vulnerabilities is a time-consuming process that can take months, leaving systems exposed to malicious exploitation. Although automated tools exist to detect vulnerabilities, they often provide limited guidance on remediation, offering only vague or insufficient recommendations. As a result, the teams spend additional time identifying appropriate fixes, further delaying the remediation process. To address this issue, this research proposes the development of a tool designed to minimize human intervention in the remediation of vulnerabilities. Specifically, the tool aims to automatically identify and correct security flaws in PHP code. Unlike existing solutions, this project will use Locality Sensitive Hashing (LSH) to detect vulnerabilities based on similarity patterns. This approach enables the identification of both known and structurally similar vulnerabilities, mitigating the risks associated with code modifications, a common tactic used by attackers to evade traditional signature-based detection. Furthermore, the tool is designed to maintain a low false positive rate and to be easily adaptable to the needs of remediation teams. Its modular design allows for future enhancements, ensuring scalability and continuous improvement in vulnerability detection and mitigation. The evaluation performed, which included the comparison to other existing tools, has returned good and promising results.
- Personalised image emotion-based recommender systemPublication . Marcelino, Inês Guerreiro; Barros, Márcia Cristina Afonso; Pires, Soraia Vanessa Meneses Alarcão Castelo de AlmeidaIn today’s digital age, users face the challenge of information overload,making it difficult to ac cess personalised and relevant multimedia content. Recommendation systems play a crucial role in addressing this issue by analysing large datasets and providing tailored content based on user preferences and behaviours. Traditional approaches, such as content-based and collaborative fil tering, have been widely explored, but they often neglect the emotional context of users. Although emotion-based recommendation systems have been studied, there remains a gap in knowledge about successfully integrating demographic data with emotional insights to enhance personali sation. This thesis addresses the problem of information overload by developing two systems, within the EmoRecSys project, which aims to enhance user experience by integrating emotional information into the recommendation process. We propose two systems: an emotion-based rec ommendation system, which uses a collaborative filtering approach, and a demographic-based recommendation system that leverages users’ characteristics to group them according to similari ties between user profiles. Our evaluation showed that the emotion-based recommendation system achieved the best results using the Non-Negative Matrix Factorisation algorithm, with precision achieving scores of 0.972 and 0.433 for Top@1 and Top@5, respectively. We further evaluated it with users. To do so, we compared the emotion-based system developed with content-based and random recommendation systems. In the first recommendation (Top@1), the emotion-based recommendation system presented a precision of 0.850, while the content-based and random rec ommendations presented precision scores of 0.800 and 0.700, respectively.
- Deep Learning to optimize viral vector production for human gene therapyPublication . Ferraz, João Lucas Figueiredo; Pesquita, Cátia Luísa Santana Calisto; Rodrigues, Ana FilipaThis work explores the potential of Protein Language Models (PLMs) to advance the design of novel Adeno-Associated Virus 2 (AAV2) sequences, while focusing on two primary objectives: sequence classification and generative design. For the classification task, we fine-tuned a PLM (ProtBERT) to accurately differentiate between viable and non-viable AAV2 sequences. Results demonstrated high classification performance across multiple trained models, validating the hypothesis that domain-specific fine-tuning enables PLMs to effectively capture important AAV2 sequence features. For sequence generation, we fine-tuned a conditional generative PLM (ProGen) to design viable AAV2 capsid protein sequences. While the model generated structurally diverse sequences, extensive evaluations indicated that additional refinements are necessary to consistently align with viability criteria. The classification model highlights the potential of PLMs in predicting sequence viability, offering a reliable approach that could help reduce experimental costs. We consider that the generative approach, though requiring further optimization, introduces a novel avenue for designing diverse AAV2 variants. Future efforts will focus on refining the generative framework by incorporating explicit viability tags, classifier feedback, and more extensive generation hyperparameter testing, as well as expanding its application to additional AAV2 properties. This work lays a foundation for leveraging PLMs in AAV2 sequence engineering, offering promising prospects for the use of Language Models for viral vector design.
- Predicting Clinically Relevant Endpoints in ALS using Multi-label ClassificationPublication . Oliveira, Joel Pereira de; Tomás, Helena Isabel Aidos Lopes; Madeira, SaraAmyotrophic Lateral Sclerosis (ALS) is a devastating disease, characterized by the progressive loss of motor neurons, causing muscular impairment. This disease has no cure, and has a reduced life expectancy of 3-5 years. The common procedure is to perform clinical interventions that aid the patient, being it to either improve their life expectancy or to improve their quality of life. However, this disease has an highly clinical heterogeneity making it a hard task for clinicians to perform decisions. Some relevant clinical interventions performed as the disease progresses are: 1) Non-invasive Ventilation - shown in multiple studies to increase life expectancy; 2) Auxiliary Communication Device - increases the well being of the patients by enabling communication; 3) Percutaneous Endoscopic Gastrostomy - increases life expectancy by providing nutrition; 4) Caregiver - improves quality of life when the disease starts spreading; 5) Wheelchair - improves quality of life by enabling the patient to move after losing the ability to walk. This dissertation presents a study on the evolution of these endpoints, by showing the common progression patterns between them and which onset regions might have an impact on the progression. Then, two prognostic models are trained to predict which of these clinical endpoints will occur within k days. The first uses independent models for each of the endpoints. The second uses multi-label classification methods that take into account the interrelation between the labels. To my knowledge, this is the first approach that uses multi-label classification to perform prognosis prediction on ALS. The multi-label prognostic model obtained promising results to perform prognosis prediction, but further studies need to be performed to create a validation method for this kind of approach and to have an accurate comparison with the independent models.
- Revisiting blockchain consensus with trusted componentsPublication . Antão, Tiago Miguel Gomes; Bessani, Alysson Neves; Heydari, HasanBlockchain technology, renowned for its robustness and decentralized nature, has revolutionized the way we secure and verify digital transactions. However, most blockchain protocols are not straightforward and require moderate to advanced blockchain expertise to understand them completely. Therefore, simplicity is essential for better comprehending the scope of such protocols, as it improves the verification of their correctness and reduces the possibility of bugs during implementation. Streamlet fills this gap by presenting a simple blockchain protocol that is easy to understand and implement. Nevertheless, some of the design choices hinder the protocol’s efficiency and scalability, leaving room for improvement. Streamlet lacks responsiveness, requires six communication steps to finalize a block, and has a message complexity of O(n3) due to the mechanism of implicit echo. For these reasons, we introduce MINSTREAMLET+, a novel protocol to address the limitations of Streamlet. Specifically, MINSTREAMLET+ is responsive and lowers the message complexity to O(n2) by removing the echo messages. Additionally, this variant of Streamlet employs a local trusted service to improve resilience and block finalization latency. Streamlet and MINSTREAMLET+’s prototypes were developed and evaluated in terms of software metrics and throughput. Cyclomatic complexity analysis demonstrates that MINSTREAMLET+ is 14% more complex than Streamlet with scores of 2.80 and 2.45, respectively. Results from the experimental evaluation show that MINSTREAMLET+ exhibits better performance than Streamlet with an average increase of approximately 215% in throughput. This increase can primarily be attributed to the protocol’s responsiveness, which allows the system to progress optimistically at a faster pace.
- A comparative analysis of the effectiveness of contrastive learning for P300 classificationPublication . Conceição, David Miguel Baptista; Fonseca, Manuel João Caneira Monteiro daBrain-Computer Interfaces (BCIs) translate brain activity into precise commands for controlling external devices, providing crucial assistance to individuals with motor disabilities. Within this domain, P300 Speller systems serve as a vital communication tool. However, these systems face significant challenges, including the inherently noisy nature of EEG data and the high variability of signals both across and within individuals. This variability often leads these systems to require an extensive calibration phase, reducing the practicality of P300 spellers in real-world applications. Developing robust models that generalize effectively across users is therefore a key objective in this field. Contrastive learning approaches have recently gained attention for their ability to produce models capable of extracting meaningful features from data. While these techniques have shown great success in domains like computer vision and natural language processing, their application to the P300 paradigm remains underexplored. This study addresses this gap by conducting a comparative analysis of three pre-training strategies: SimCLR, SupCon, and Supervised learning. These approaches were evaluated using three state-of-the-art neural network architectures, EEGNet, EEG-Inception, and Conformer. The pre-trained models were evaluated in both intra-dataset and cross-dataset scenarios. The results indicate that the impact of contrastive learning is highly dependent on the model architecture and on the evaluation setup. In an intra-dataset scenario, SimCLR exhibited the worse performances across all models, while SupCon and Supervised displayed comparable results with SupCon achieving slightly higher performances for higher values of retraining data. However, in cross-dataset scenarios, contrastive learning approaches, particularly SimCLR, demonstrated superior performance compared to supervised learning, showcasing their ability to generalize effectively across diverse data distributions. These findings underscore the potential of contrastive learning and their robustness to address the challenges of variability and reduce the reliance on extensive calibration in P300 speller systems, by leveraging data coming from multiple sources.
- Triclustering-based patient stratification : a case study in Multiple and Amyotrophic Lateral SclerosisPublication . Dias, André Teixeira; Tomás, Helena Isabel Aidos Lopes; Madeira, Sara Alexandra CordeiroA Esclerose Múltipla é uma doença inflamatória autoimune que afeta o Sistema Nervoso Central, levando à perda de mielina por parte dos neurónios, que, por sua vez, resulta em neurodegeneração. Esta doença pode ser dividida em vários tipos, sendo o mais comum denominado de Recidivante Remitente. Este tende a manifestar-se de duas maneiras distintas: ataques agudos, denominados de recaídas, onde nova atividade da doença é detetada, e dos quais o paciente pode recuperar totalmente ou parcialmente, e progressão silenciosa, caracterizada pela ausência dos ataques previamente mencionados, mas onde deterioração irreversível dos sintomas ocorre. A Esclerose Amiotrófica Lateral é uma condição que também leva a neurodegeneração, resultando em perda progressiva das capacidades motoras. Apesar disto, esta é mais agressiva no seu ataque, tendo uma progressão mais rápida que culmina na morte do paciente entre três a cinco anos depois do diagnóstico. Atualmente, o diagnóstico de ambas é limitado pela ausência de um teste definitivo. Para Esclerose Múltipla, a combinação de Ressonância Magnética de Imagem com outros exames e a ocorrência de ataques agudos com danos cerebrais são necessários para confirmar a presença da doença. Para Esclerose Amiotrófica Lateral, vários testes têm de ser feitos, de modo a confirmar que os sintomas sentidos não podem ser atribuídos a outras doenças. Adicionalmente, para haver confirmação da mesma, a sua progressão tem de ser confirmada através do agravamento dos sintomas ou disseminação dos mesmos para zonas previamente não afetadas. Dependendo do tipo de Esclerose Múltipla e da gravidade do diagnóstico, a doença pode culminar na morte do paciente, mas os sintomas mais comuns prendem-se na perda de mobilidade e funções cognitivas. Apesar de perda de mobilidade também ser um dos sintomas de Esclerose Amiotrófica Lateral, um dos sintomas mais graves que acaba por ocorrer e levar à morte do paciente é insuficiência respiratória. Em relação ao tratamento de qualquer uma das doenças, devido à inexistência de uma cura definitiva, estes estão limitados à diminuição da taxa de progressão da doença e dos sintomas das mesmas, de forma a melhorar a qualidade de vida dos doentes. Para avaliar a progressão das mesmas, várias métricas de progressão são recolhidas ao longo de exames que o paciente vai fazendo com frequência. Uma das escalas mais usadas para a Esclerose Múltipla é a Escala Expandida do Estado de Incapacidade e os seus derivados intitulados de Sistemas Funcionais. No caso da Esclerose Lateral Amiotrófica, análogos destas escalas, intitulados de Escala Funcional de Avaliação de Esclerose Lateral Múltipla e os seus derivados são usados. Estas escalas providenciam informação relativa à gravidade dos sintomas ao longo do tempo e permitem avaliar o seu estado de progressão. Dado que estas doenças possuem uma progressão heterogénea que varia de paciente para paciente, a sua compreensão é difícil e a administração de cuidados adequados e avaliação do seu impacto demonstram ser tarefas árduas. A estratificação de pacientes pode ser vantajosa neste problema, visto que pode inserir um paciente num grupo com progressão já mapeada, providenciando uma ideia de como a doença vai evoluir ao longo do tempo. Adicionalmente, através da descoberta de grupos de progressão da doença, ensaios clínicos podem ser melhorados e as características mais importantes destas doenças identificadas. Ainda assim, a natureza sensível ao tempo dos dados aumenta a complexidade desta tarefa, sendo que a maioria dos métodos de estratificação comumente aplicados são incapazes de capturar padrões temporais. Com isto em mente, e com o objetivo de identificar grupos de progressão das doenças mencionadas, dois métodos descritos na literatura foram aplicados a um conjunto de dados de cada doença: ClusTric e agrupamento baseado em Dynamic Time Warping. O primeiro é uma técnica de Triclustering que permite descobrir padrões de pacientes que ocorrem apenas em algumas variáveis e instantes temporais, denominados triclusters. O segundo é um método que compara séries temporais que descrevem as variáveis de cada paciente, estando limitado à utilização de todas as variáveis para obter uma solução. Adicionalmente, um novo método, denominado Metatriclustering, foi desenvolvido durante esta tese e aplicado ao mesmo conjunto de dados, de modo a tentar melhorar a explicabilidade e a atribuição de grupos aos pacientes. Este último é também uma técnica de Triclustering que visa agrupar os padrões mais semelhantes, de modo a reduzir a quantidade de grupos de pacientes. Para aplicar estes métodos, um conjunto de dados para cada doença foi utilizado. Para Esclerose Múltipla, o conjunto de dados foi cedido pela Fondazione Istituto Neurologico Nazionale Casimiro Mondino, sob o projeto Europeu BRAINTEASER. Por outro lado, o conjunto de Dados Clínicos de Esclerose Lateral Amiotrófica de Lisboa, obtido no âmbito do projeto AIpALS, foi utilizado para a outra doença. Ambos estes conjuntos de dados necessitaram de metodologias de pré processamento antes de serem utilizados nos métodos de agrupamento previamente mencionados. A partir destes foi possível criar snapshots de pacientes (instância temporal onde vários exames, realizados ao longo de uma curta janela temporal, foram agrupados), lidar com valores em falta, etc. Durante este processo, as variáveis temporais que viriam a ser utilizadas foram escolhidas. Para avaliar os agrupamentos obtidos, uma estrutura de validação foi utilizada, que visava a obtenção de métricas internas, externas e de classificação. Adicionalmente, dendrogramas, boxplots, gráficos de evolução e de pertença (membership) foram utilizados para comparar resultados. Dada a forma com que o método de Metatriclustering foi implementado, a validação dos seus resultados foi mais limitada, ausente de métricas de avaliação. Para o método ClusTric e Metatriclustering, vários parâmetros foram testados, enquanto que para o agrupamento baseado em Dynamic Time Warping, apenas os parâmetros padrão foram avaliados. A utilização de diferentes números de snapshots foi analizado para cada um destes métodos. Adicionalmente, para cada conjunto de parâmetros e número de snapshots, os resultados obtidos quando dois a seis grupos de pacientes eram selecionados foram investigados. Para o primeiro e último método, a remoção de determinadas variáveis dos conjuntos de dados foi testada, assim como o impacto que o escalonamento dos dados tem nos seus resultados. Para Esclerose Múltipla, todos os métodos produziram grupos de pacientes com boa separabilidade, sendo que ClusTric obteve melhores resultados quando cinco grupos de pacientes foram descobertos, enquanto que Metatriclustering sugeriu a existência de quatro e o agrupamento baseado em Dynamic Time Warping três. Devido à ausência de métricas de avaliação para o método Metatriclustering, não foi possível fazer uma comparação mais profunda com os outros métodos. Relativamente aos outros dois métodos, os grupos com melhores métricas foram os obtidos através do método ClusTric. Adicionalmente, através deste foi possível identificar que apenas quatro das nove variáveis inicialmente consideradas eram relevantes. Por último, o efeito de escalonamento dos dados foi mínimo para este método, enquanto que o seu impacto foi mais significativo para o agrupamento baseado em Dynamic Time Warping. Para Esclerose Amiotrófica Lateral, a separabilidade dos grupos foi aceitável para ClusTric, que identificou a existência de quatro grupos, e Metatriclustering, que sugeriu a existência de três, mas melhor para o agrupamento baseado em Dynamic Time Warping, que detetou três grupos. Este último método foi também o que produziu as melhores métricas de avaliação. Através dos resultados de ClusTric, uma das variáveis foi identificada como não importante no agrupamento dos pacientes. Adicionalmente, a remoção de uma outra variável levou a um melhoramento dos resultados obtidos tanto para ClusTric como para agrupamento baseado em Dynamic Time Warping. Semelhantemente ao que havia sido verificado para Esclerose Múltipla, foi possível concluir que o escalonamento dos dados teve um impacto mais significativo para agrupamento baseado em Dynamic Time Warping. Com escalonamento, este método passou a sugerir a existência de quatro grupos de pacientes e os seus resultados eram comparáveis aos obtidos por ClusTric. Dado que escalonamento das variáveis é um passo que deve ser efetuado na aplicação deste método (uma vez que Dynamic Time Warping é baseado em distância euclidiana), estes resultados foram considerados os mais relevantes. Através destes resultados, foi possível identificar várias vantagens de cada um dos métodos em estudo: (ClusTric) – pouco afetado pelo escalonamento dos dados e capaz de identificar variáveis mais importantes; agrupamento baseado em Dynamic Time Warping – método mais simples, com menos parâmetros para otimizar e capaz de produzir bons resultados quando todas as variáveis são significativas; Metatriclustering – explicabilidade melhorada dos grupos e facilidade de atribuir um grupo a um novo paciente. Uma vez que Metatriclustering foi capaz de produzir bons agrupamentos, mais investigação do mesmo é justificado, de modo a obter métricas de avaliação e comparar os seus resultados com os dos outros métodos de forma mais aprofundada.
- Full Polymorphism in Context-Free Session TypesPublication . Roldão, Miguel Segura Trillo; Poças, Diogo; Vasconcelos, Vasco Thudichum, 1964-Context-free session types allow syntactic validation of communication protocols. These offer an extension over regular session types in making it possible to have nested protocols. With the introduction of polymorphism in the language of context-free session types, the addition of abstraction over types takes expressiveness a step further. This paper focuses on extending context-free session types to full polymorphism, tackling the challenges that arise with the inclusion of polymorphic session types. Enabling the programmer to define types such as ∀α.T and its dual type, ∃β.U, where T and U are session types. With this extended universe of types, we want to enable sequential composition of polymorphic types and other session types. The current state of the art of session types and type equivalence was studied, and a novel type equivalence system was designed, based on canonical renaming and conversion of types to simple grammars, implemented and evaluated in the FREEST language.
