We use cookies to ensure our website works properly and to personalise your experience. Cookies policy
1 Department of Information Science and Engineering, Yenepoya Institute of Technology, Moodbidri, Karnataka, India.
2 Department of Computer Science & Engineering (Data Science), Yenepoya Institute of Technology, Moodbidri, Karnataka, India.
In modern healthcare, it is crucial to obtain accurate and trustworthy medical information quickly. General-purpose language models can struggle in clinical settings because they may produce incorrect information, misuse medical terminology, or lack suitable safety checks. To address these limitations, this work presents a medical question-answering system that combines a biomedical language model with a retrieval-based knowledge source. The system uses BiomedNLP-PubMedBERT as an encoder and a custom Transformer decoder, together with a FAISS vector database containing approximately 60,000 medical question–answer records gathered from sources includ-ing MedQuAD and NHS UK. The proposed framework com-bines a domain-adaptive Seq2Seq Transformer with Retrieval-Augmented Generation (RAG), allowing relevant medical in-formation to be retrieved before an answer is generated. The reported evaluation compares the proposed approach with re-current, convolutional, and Transformer-based baselines. The manuscript reports an accuracy of 98.2% and an average inference time below 50 ms. These results indicate the potential of retrieval-enhanced biomedical language models for healthcare information systems.
The rapid advancement of Artificial Intelligence (AI) and Natural Language Processing (NLP) has enabled the devel-opment of intelligent systems capable of understanding and generating human language. In healthcare, these technologies have gained significant attention for applications such as medi-cal information retrieval, clinical decision support, and medical question answering (MQA). However, healthcare applications require high levels of accuracy, reliability, and contextual understanding because incorrect or unsupported information may lead to inappropriate decisions. Traditional rule-based and keyword-based medical question-answering systems are often limited in their ability to understand complex medical queries and provide contextually relevant responses.
The development of Transformer-based architectures has significantly improved natural language understanding by us-ing self-attention mechanisms to capture relationships be-tween words and contextual information [1]. BERT further demonstrated the effectiveness of bidirectional pretraining for a wide range of natural language understanding tasks [6]. However, general-purpose language models may have limited understanding of specialized biomedical terminology and domain-specific knowledge. Biomedical language models such as BioBERT and PubMedBERT address this limitation by using biomedical literature for domain-specific pretraining, improving the representation of medical concepts and termi-nology [3], [4].
Despite these advances, pretrained language models primar-ily depend on knowledge stored within their model parameters and may generate plausible but unsupported information when relevant knowledge is unavailable. This limitation is particu-larly important in healthcare, where answers should be based on reliable medical evidence. Retrieval-Augmented Generation (RAG) provides an effective approach by combining language generation with retrieval from an external knowledge source [2]. Instead of relying only on information stored in the model, RAG retrieves relevant documents and provides them as contextual information during answer generation. This can improve the relevance and factual grounding of generated responses.
Efficient retrieval is an important component of a RAG-based medical question-answering system. FAISS provides efficient similarity-search capabilities for dense vector rep-resentations and can therefore be used to retrieve relevant medical information from a large knowledge base [5]. By combining semantic retrieval with biomedical language under-standing, a healthcare question-answering system can provide responses that are more closely connected to relevant medical information.
Motivated by these challenges, this work proposes a hybrid Medical Question Answering system that combines a domain-adaptive Seq2Seq Transformer with RAG. The proposed framework uses BiomedNLP-PubMedBERT as the encoder to capture biomedical context and a custom Transformer decoder for answer generation. A FAISS-based vector database is used to retrieve relevant medical question–answer records from a knowledge base containing information from sources such as MedQuAD and NHS UK. The proposed system also incorpo-rates input validation and response-formatting mechanisms to reduce irrelevant queries and improve the safety and usability of generated answers.
The major contributions of this work are summarized as follows:
Early NLP research used Recurrent Neural Networks (RNNs) and Long Short-Term Memory (LSTM) networks to process text sequentially. RNNs process input sequences one element at a time and maintain information from previous inputs through their hidden states. LSTM networks improve this approach by using memory mechanisms that help preserve important information over longer sequences. Bidirectional LSTMs read text in both forward and backward directions to capture additional contextual information from the input sequence.
One-dimensional Convolutional Neural Networks (1D-CNNs) can identify local patterns in text by applying con-volution operations over sequences of words or tokens. These models can be useful for identifying important local features and patterns in medical text. However, recurrent and convolu-tional approaches may have difficulty representing long-range dependencies in lengthy clinical documents. This limitation becomes important in healthcare applications because medical information may contain relationships between terms that are separated by large portions of text.
The Transformer architecture enables parallel sequence pro-cessing and contextual representation through self-attention [1]. Unlike traditional sequential models, Transformer-based architectures can consider relationships between different parts of an input sequence more effectively. BERT introduced bidi-rectional pretraining for language understanding and demon-strated the effectiveness of pretrained Transformer representa-tions for NLP tasks [6].
Biomedical variants of Transformer models adapt this ap-proach to scientific and clinical text. BioBERT was pre-trained on biomedical literature and evaluated on biomedical text-mining tasks [4]. PubMedBERT uses biomedical-domain pretraining and vocabulary to improve biomedical language representation [3]. Since medical questions frequently contain specialized terminology, biomedical pretrained models provide useful representations for domain-specific NLP applications.
Retrieval-Augmented Generation combines parametric lan-guage generation with retrieval from an external knowledge source [2]. Instead of depending exclusively on information encoded in model parameters, a RAG system retrieves relevant documents and uses them as context for generation. This allows the generation model to access additional information related to the user’s query before producing an answer.
FAISS provides efficient similarity-search functionality for dense vector representations [5]. By converting documents and user queries into vector representations, relevant information can be identified based on semantic similarity. The retrieved information can then be provided to the language-generation model as additional context. This retrieval process can help ground answers in relevant source material, which is important in healthcare applications.
The proposed MQA system uses publicly available biomed-ical information to cover a range of healthcare topics. The pri-mary dataset is MedQuAD, which contains medical question–answer pairs collected from National Institutes of Health (NIH) websites [7]. Additional information is collected from NHS UK public-health resources [8]. The combined knowl-edge base covers topics such as diseases, symptoms, diagnosis, treatments, medications, and preventive care.
The source manuscript describes a collection of approxi-mately 60,000 medical question–answer records. The exact number of records from each source, licensing conditions, and dataset version should be specified in the final experimental report.
Before training, the collected data is cleaned to improve consistency. Duplicate and incomplete question–answer pairs are removed. Text is standardized by converting it to lowercase and removing unnecessary symbols, special characters, and extra spaces. Common medical abbreviations, such as BP (blood pressure), HTN (hypertension), and Tx (treatment), are expanded where appropriate.
Informal patient expressions are mapped to their corre-sponding medical terms when this can be done without changing the meaning. Negation terms such as “no,” “not,” “without,” and “never” are preserved because they are impor-tant for clinical interpretation. The cleaned text is tokenized and converted into numerical representations. The dataset is divided into 90% for training and 10% for testing, as described in the source manuscript.
The proposed medical question-answering framework in-tegrates biomedical language understanding, retrieval-based knowledge enhancement, and Transformer-based sequence generation to generate contextually relevant and informa-tive medical responses. The framework combines a pre-trained biomedical language model with a custom Trans-former decoder and a similarity-based retrieval mechanism. BiomedNLP-PubMedBERT is employed as the encoder to extract domain-specific semantic representations from medical questions, while a FAISS-based vector database facilitates the retrieval of relevant medical knowledge. The retrieved information is incorporated into the answer-generation process through a Retrieval-Augmented Generation (RAG) mecha-nism. The overall architecture is designed to improve con-textual understanding, semantic relevance, and the reliability of generated medical responses. The proposed methodology consists of the following stages.
Figure 1 illustrates the overall architecture of the pro-posed Retrieval-Augmented Generation (RAG)-based medical question-answering framework. Initially, medical question-answering records are collected and processed through data preprocessing and tokenization to ensure textual consis-tency and generate suitable input representations. The pre-processed medical questions are passed to the BiomedNLP-PubMedBERT encoder, which extracts contextual biomedical embeddings to capture domain-specific terminology and se-mantic relationships. Simultaneously, the FAISS-based vec-tor database retrieves relevant medical information using similarity-based search. The encoded question representations and retrieved medical context are subsequently integrated through a context fusion mechanism to provide enriched information for response generation. A custom Transformer decoder processes the integrated representations using masked self-attention, cross-attention, and feed-forward network layers to generate contextually relevant medical answers. The de-coder predicts output tokens sequentially until the complete response is generated. Finally, the proposed framework under-goes comprehensive performance evaluation using accuracy, precision, recall, F1-score, test loss, perplexity (PPL), BLEU score, BERTScore, and inference time. This integrated archi-tecture combines biomedical language understanding, external knowledge retrieval, and neural text generation to support reliable and contextually relevant medical question answering.
A. Medical Question Preprocessing
The initial stage involves preprocessing the input medical question to ensure consistency and compatibility with the pro-posed architecture. Medical questions may contain abbreviations, special characters, inconsistent whitespace, and domain-specific terminology. Therefore, preprocessing operations are performed to normalize the input text while preserving its original medical meaning. These operations include removal of unnecessary characters, whitespace normalization, handling of special symbols, and correction of textual inconsistencies. The preprocessing stage avoids aggressive text transformations that could remove clinically relevant terminology or alter the meaning of medical expressions.
Fig. 1. Overall Architecture of the Proposed RAG-Based Medical Question-Answering Framework Integrating PubMedBERT, FAISS-Based Knowledge Retrieval, and a Custom Transformer Decoder
Fig. 2. System workflow.
Following preprocessing, the input question is tokenized us-ing the corresponding PubMedBERT tokenizer. The tokenizer converts the textual input into subword tokens and maps them into numerical token identifiers. Attention masks are generated to distinguish meaningful tokens from padding tokens. The resulting token representations are provided to the biomedical encoder for contextual feature extraction.
B. Biomedical Feature Extraction Using PubMedBERT
The proposed framework employs BiomedNLP-PubMedBERT as its primary biomedical language encoder. PubMedBERT is a domain-specific pretrained Transformer model designed to capture biomedical terminology, contextual relationships, and semantic information from medical text.
Unlike conventional general-purpose language models, its biomedical pretraining provides suitable representations for understanding medical questions and related terminology.
For an input question Q, the tokenizer generates a sequence of token embeddings, which are processed through the Pub-MedBERT encoder. The encoder applies multiple Transformer layers containing multi-head self-attention and feed-forward neural networks to capture contextual dependencies among the input tokens.
The encoder representation is mathematically expressed as:
H = PubMedBERT(Q) (1)
where Q represents the preprocessed medical question and H denotes the contextual hidden representations generated by the encoder. These representations capture the semantic characteristics of the medical query and provide contextual in-formation for the retrieval and answer-generation components.
C. Medical Knowledge Representation and Indexing
The proposed framework incorporates a vector-based med-ical knowledge retrieval mechanism to provide additional contextual information during answer generation. Medical question-answering records are transformed into dense vector representations using a suitable biomedical embedding model. Each medical record is represented through its semantic em-bedding, allowing the system to identify relevant information based on contextual similarity rather than relying exclusively on exact keyword matching.
The generated embeddings are indexed using the FAISS similarity-search framework. FAISS provides efficient vector indexing and nearest-neighbor retrieval capabilities, enabling the system to search for semantically related medical informa-tion. The indexing mechanism stores the vector representations together with their corresponding medical records, allowing retrieved embeddings to be mapped back to their original textual information.
The vector representation of a medical document can be expressed as:
Di = Embed(di) (2)
where di represents an individual medical knowledge record and Di denotes its corresponding dense vector representation. The indexed representations are subsequently utilized during query-time retrieval.
D. FAISS-Based Medical Knowledge Retrieval
When a new medical question is submitted, its semantic representation is generated using the biomedical encoder. The resulting query embedding is compared with the indexed med-ical knowledge representations to identify the most relevant records.
Cosine similarity is employed to measure the semantic relationship between the query representation and candidate document embeddings. It is calculated as:
where Q denotes the query embedding and Di represents the
embedding of a candidate medical document. The similarity score indicates the degree of semantic correspondence between the input question and the retrieved medical information.
Based on the similarity scores, the retrieval component se-lects the most relevant records for subsequent processing. The retrieved information provides additional contextual knowl-edge that supports the answer-generation mechanism. This retrieval process helps reduce dependence on the parametric knowledge of the language model and provides access to relevant external medical information.
The proposed framework incorporates a custom Trans-former decoder to generate natural-language medical re-sponses. The decoder receives contextual representations from the biomedical encoder and relevant information obtained through the FAISS retrieval mechanism. Its architecture con-sists of masked multi-head self-attention, encoder-decoder cross-attention, feed-forward neural networks, positional en-coding, and normalization layers.
The masked self-attention mechanism captures dependen-cies among previously generated tokens while preventing access to future tokens during autoregressive generation. The cross-attention mechanism establishes relationships between the decoder representations and the contextual information obtained from the PubMedBERT encoder and retrieved medi-cal knowledge. This allows the decoder to generate responses based on both the semantic representation of the question and the retrieved supporting information.
The decoder operation can be represented as:
Z = TransformerDecoder(H, R) (4)
where H represents the biomedical encoder output, R denotes the retrieved contextual information, and Z represents the decoder hidden representations.
The output projection layer maps the decoder represen-tations into vocabulary probabilities using the softmax ac-tivation function. The next token is selected based on its predicted probability, and the process continues until an end-of-sequence token is generated or the predefined generation limit is reached.
The central component of the proposed methodology is the integration of biomedical contextual representations with retrieval-based knowledge enhancement. The RAG mechanism combines the semantic understanding capabilities of PubMed-BERT with the external knowledge retrieval capabilities of FAISS and the generative capabilities of the custom Trans-former decoder.
Initially, the input medical question is processed by the biomedical encoder to obtain contextual representations. Sub-sequently, the retrieval component identifies semantically rel-evant medical records from the indexed knowledge base. The retrieved information is transformed into contextual represen-tations and integrated with the encoded question information through the decoder’s cross-attention mechanism.
The conditional answer-generation process is formulated as:
where A represents the generated answer, Q denotes the input medical question, R represents the retrieved medical context, and at denotes the generated token at time step t.
This integration enables the model to generate responses using both biomedical contextual representations and retrieved external information. Consequently, the generated answers can incorporate relevant medical context rather than relying exclusively on the information encoded during pretraining.
The proposed encoder-decoder framework is trained using supervised sequence-to-sequence learning. During training, medical questions are provided as input sequences, while their corresponding reference answers serve as target sequences. The encoder extracts contextual representations, and the de-coder learns to generate the expected responses using the encoded question information and retrieved context.
Cross-entropy loss is employed as the primary optimization objective to minimize the difference between the predicted token probabilities and the corresponding reference tokens. The training objective is expressed as:
where N denotes the number of training examples, Ti represents the target answer length, and ai,t denotes the reference token at position t.
The model parameters are optimized through backpropa-gation and gradient-based optimization. Training performance is monitored using validation loss to assess generalization and identify potential overfitting. Appropriate learning-rate scheduling, gradient management, and regularization tech-niques are incorporated to improve training stability.
During inference, the framework accepts a medical ques-tion and performs preprocessing, biomedical encoding, and similarity-based knowledge retrieval. The retrieved contextual information is integrated with the encoder representations and passed to the Transformer decoder. The decoder generates the response autoregressively by predicting successive tokens based on the input question, previously generated tokens, and retrieved medical context.
The final generated response is presented as a natural-language answer to the user. The retrieval mechanism provides supporting medical context, while the biomedical encoder and Transformer decoder facilitate domain-specific semantic understanding and response generation. Since medical infor-mation is safety-critical, the generated responses should be treated as informational assistance rather than a substitute for professional medical diagnosis or treatment.
The proposed medical question-answering framework is evaluated using a comprehensive set of performance metrics to assess classification effectiveness, answer-generation quality, semantic similarity, and computational performance. The eval-uation metrics include accuracy, precision, recall, F1-score, test loss, perplexity (PPL), BLEU score, and BERTScore.
where N represents the number of test samples and P (yi|xi) denotes the predicted probability of the target output.
where wi represents the current token and w<i denotes the preceding tokens in the sequence.
where BP represents the brevity penalty, pn denotes the modified n-gram precision, and wn represents the correspond-ing n-gram weight.
where C and R represent the generated and reference answer tokens, respectively. The cosine similarity measures the semantic correspondence between contextual token em-beddings.
Overall, these evaluation metrics provide complementary insights into the performance of the proposed framework. Classification metrics assess prediction effectiveness, while perplexity, BLEU, and BERTScore evaluate language gener-ation and semantic similarity. Test loss provides additional information regarding model optimization and generalization. These metrics collectively support a comprehensive assess-ment of the proposed retrieval-enhanced biomedical question-answering system.
The proposed framework is evaluated on unseen medi-cal queries and compared with baseline deep-learning and Transformer-based approaches. The comparison reported in the source manuscript includes RNN, LSTM, BiLSTM, 1D-CNN, DistilBERT, BERT-Base, RoBERTa, T5, and BioBERT. Table I summarizes the reported accuracy values.
Table I presents the comparative performance evaluation of the proposed RAG + PubMedBERT Seq2Seq framework against nine baseline models, including RNN, LSTM, BiL-STM, 1D-CNN, DistilBERT, BERT-Base, RoBERTa, T5, and BioBERT. The models are evaluated using accuracy, precision, recall, F1-score, test loss, perplexity (PPL), BLEU score, and BERTScore to assess their predictive performance and answer-generation quality. As illustrated in Table I, the conventional recurrent architectures, including RNN, LSTM, and BiLSTM, achieve accuracy values of 84.7%, 88.5%, and 90.9%, respectively. The 1D-CNN model achieves 91.8% accuracy, demonstrat-ing improved feature extraction capabilities. Transformer based architectures exhibit better performance, with Distil-BERT, BERT-Base, and RoBERTa achieving accuracies of 93.9%, 95.1%, and 95.8%, respectively. Furthermore, T5 and BioBERT achieve 96.5% and 97.4% accuracy, respectively, highlighting the effectiveness of pretrained language models in biomedical question-answering tasks.
The proposed RAG + PubMedBERT Seq2Seq framework achieves the highest reported accuracy of 98.2%, with pre-cision, recall, and F1-score values of 98.4%, 98.2%, and 98.3%, respectively. These results indicate improved predic- tion performance compared with the baseline architectures. Furthermore, the proposed framework obtains the lowest test loss of 0.086 and perplexity of 1.94, suggesting improved predictive confidence and language-modeling performance.
In terms of answer-generation quality, the proposed frame-work achieves a BLEU score of 33.6 and a BERTScore of 0.968, outperforming the other evaluated models in the reported comparison. The improvement in BLEU indicates greater lexical similarity between generated and reference answers, while the higher BERTScore demonstrates stronger semantic correspondence. These improvements can be at tributed to the integration of biomedical contextual repre-sentations from PubMedBERT and retrieval-based knowledge enhancement through the FAISS vector database.
Overall, the comparative evaluation demonstrates the po-tential of integrating biomedical language modeling with Retrieval-Augmented Generation for medical question answer-ing. The proposed framework provides competitive classifica-tion and text-generation performance, making it a promising approach for developing domain-specific healthcare informa-tion systems.
In addition to retrieval and generation, the system includes input validation and response-formatting mechanisms. These components are designed to filter greetings, meaningless in-puts, and questions unrelated to healthcare before the answer-generation stage. The final response can include an overview, supporting medical information, relevant advice, emergency warnings when appropriate, and a disclaimer encouraging consultation with a qualified healthcare professional. Such mechanisms are important because the system is intended to provide healthcare information rather than replace professional medical diagnosis or treatment.
Overall, the experimental results indicate that the pro-posed combination of Retrieval-Augmented Generation and PubMedBERT-based Seq2Seq generation provides promising performance for medical question answering. The reported accuracy is 98.2%.
TABLE I: Performance Comparison of Medical Question-Answering Models
|
Model |
Accuracy (%) |
Precision (%) |
Recall (%) |
F1-Score (%) |
Loss |
PPL |
BLEU |
BERTScore |
|
RNN |
84.7 |
85.1 |
84.7 |
84.6 |
0.421 |
3.82 |
18.4 |
0.842 |
|
LSTM |
88.5 |
88.9 |
88.5 |
88.4 |
0.356 |
3.45 |
20.6 |
0.861 |
|
BiLSTM |
90.9 |
91.2 |
90.9 |
90.8 |
0.298 |
3.12 |
22.8 |
0.879 |
|
1D-CNN |
91.8 |
92.1 |
91.8 |
91.7 |
0.274 |
2.98 |
23.5 |
0.886 |
|
DistilBERT |
93.9 |
94.1 |
93.9 |
93.8 |
0.221 |
2.71 |
25.1 |
0.901 |
|
BERT-Base |
95.1 |
95.3 |
95.1 |
95.0 |
0.184 |
2.53 |
26.4 |
0.914 |
|
RoBERTa |
95.8 |
96.0 |
95.8 |
95.7 |
0.159 |
2.39 |
27.8 |
0.923 |
|
T5 |
96.5 |
96.7 |
96.5 |
96.4 |
0.137 |
2.21 |
29.3 |
0.935 |
|
BioBERT |
97.4 |
97.6 |
97.4 |
97.3 |
0.112 |
2.08 |
30.7 |
0.946 |
|
Proposed RAG + PubMedBERT Seq2Seq |
98.2 |
98.4 |
98.2 |
98.3 |
0.086 |
1.94 |
33.6 |
0.968 |
Fig. 3. Confusion matrix.
Fig. 4. Training and validation curves.
CONCLUSION
This paper presents a domain-adaptive Medical Question Answering framework that combines RAG with a Seq2Seq Transformer. By integrating biomedical datasets, semantic retrieval, and a PubMedBERT-based encoder, the framework aims to generate context-aware medical responses grounded in retrieved information. The source manuscript reports improved performance over the listed baseline approaches, with 98.2% accuracy and an average inference time below 50 ms. The system also includes input validation and response guardrails to improve reliability. These results indicate the potential of retrieval-enhanced language models for healthcare information systems.
Future work can expand the knowledge base by incor-porating additional medical datasets, clinical guidelines, and recent biomedical literature. The retrieval mechanism can be improved through stronger embedding models and hybrid search techniques. Multilingual support could make the system more accessible to users from different linguistic backgrounds. Further research may investigate medical-image understanding and integration with electronic health records. Extensive vali-dation with healthcare professionals and evaluation in appro-priate real-world settings will be necessary before considering clinical deployment.
REFERENCES
Mohith Shetty, Pranam Prabhu, Sharath R., Mohith Raj, Dr. Manish Prajapati, Enhancing Healthcare Question Answering with Domain-Adaptive Large Language Models and Retrieval-Augmented Generation, Int. J. Sci. R. Tech., 2026, 3 (12), 38-48. https://doi.org/10.5281/zenodo.24717626
10.5281/zenodo.24717626