A training method, system, device and medium of a medical prescription recommendation model
Patent Information
- Application Number
- CN202610946276.1
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2026-06-29
- Publication Date
- 2026-10-13
- Estimated Expiration
- 2046-06-29
AI Technical Summary
该常规方案虽实现了处方推荐的基本功能,但存在明显局限:一方面,静态知识图谱无法适配药品库存变化、用药风险等实时临床约束,导致推荐结果可能出现“有药难配”或“用药风险超标”的问题;另一方面,浅层建模方式无法深度挖掘多维度节点间的关联信息,使得推荐结果仅能满足基础的医学匹配需求,无法适配复杂多变的实际诊疗场景
[0057]1、融合动态医疗知识图谱与上下文约束(库存、风险、区域用药强度),结合图神经网络深度消息传递,让处方推荐既贴合医学诊疗逻辑,又适配真实诊疗场景约束,提升推荐结果的精准度、合理性与落地可执行性。
Smart Images

Figure CN122455396B_ABST
Abstract
Description
Technical Field
[0001] This application relates to the technical field of medical auxiliary diagnosis, and in particular to a training method, system, device and medium for a medical prescription recommendation model. Background Technology
[0002] In the medical diagnosis and treatment process, the rational and standardized prescription is a core link in ensuring medical quality, reducing medication risks, and saving medical resources. Especially with the rapid development of medical informatization, medical institutions have accumulated massive amounts of electronic medical records and prescription data. How to use artificial intelligence technology to mine the value of this data and achieve precise and scenario-based prescription recommendations has become a key need to improve the efficiency of clinical diagnosis and treatment.
[0003] Currently, most medical prescription recommendation methods rely on static medical knowledge graphs and traditional machine learning training. During training, traditional graph embedding algorithms (such as TransE and TransH) are used to embed nodes in the static knowledge graph. Then, shallow neural networks are used to model the relationships between patient characteristics, diseases, and medications. Finally, candidate drug nodes are selected based on the similarity of node embeddings to complete the prescription recommendation. While this conventional approach achieves the basic function of prescription recommendation, it has significant limitations: First, static knowledge graphs cannot adapt to real-time clinical constraints such as changes in drug inventory and medication risks, potentially leading to problems like "difficulty in obtaining medication" or "excessive medication risk." Second, shallow modeling methods cannot deeply mine the multi-dimensional relationships between nodes, meaning the recommendation results only meet basic medical matching needs and cannot adapt to complex and ever-changing real-world diagnostic and treatment scenarios. Summary of the Invention
[0004] To improve the accuracy and rationality of prescription recommendations and adapt to complex and ever-changing real-world medical scenarios, this application provides a training method, system, device, and medium for a medical prescription recommendation model.
[0005] Firstly, this application provides a training method for a medical prescription recommendation model, employing the following technical solution:
[0006] A training method for a medical prescription recommendation model includes:
[0007] Define the node set and edge set of the graph to construct a dynamic medical knowledge graph. The node set includes disease nodes, drug nodes, virtual patient nodes, inventory nodes, and regional drug use intensity nodes. The edge set includes medical relationship edges and context association edges.
[0008] Based on historical diagnostic data, an offline training sample set is constructed, in which each training sample is a quadruple. The quadruple includes a patient feature vector, the corresponding disease node, the drug node used in the real prescription, and the context constraint set when the sample occurs. The context constraint set includes inventory constraints and risk constraints.
[0009] Receive the current training sample and map the current patient feature vector to the embedding space of the dynamic medical knowledge graph through a fully connected neural network to obtain the initial embedding vector of the virtual patient node;
[0010] On the dynamic medical knowledge graph, starting from the current disease node and the virtual patient node, message passing of an L-layer graph neural network is performed to obtain the updated embedding representation set of all nodes in the dynamic medical knowledge graph; wherein, before each layer of propagation, the attributes or connections of relevant nodes in the dynamic medical knowledge graph are modified according to the current context constraints.
[0011] Based on the embedded representation set, a set of candidate drug nodes that meet the current inventory constraints is selected from the dynamic medical knowledge graph.
[0012] By employing the aforementioned technical solution, the training samples constructed from historical diagnostic data using quadruples not only anchor the core diagnostic logic of patient characteristics, diseases, and prescription drugs, but also introduce a set of contextual constraints composed of inventory constraints and risk constraints. This extends model training from simple medical matching to full-dimensional adaptation to real-world diagnostic scenarios. During model training, a fully connected neural network maps patient feature vectors to the knowledge graph embedding space. Combined with the hierarchical message passing mechanism of an L-layer graph neural network, virtual patient nodes can deeply absorb multi-dimensional related information in the dynamic graph. Simultaneously, the dynamic adjustment mechanism of contextual constraints before each layer of propagation further strengthens the model's ability to perceive real-time inventory status, clinical risks, and other realistic factors. This ensures that the final output node embedding representation possesses both solid medical knowledge support and adaptability to current diagnostic scenario constraints. The step of selecting candidate drug nodes that meet inventory constraints based on the updated embedding representation directly bridges the last mile from knowledge learning to practical application, ensuring that the model's recommendation results not only conform to medical diagnostic logic but also possess strong executability and scenario adaptability.
[0013] Optionally, the steps following the selection of the set of candidate drug nodes that satisfy the current inventory constraints include:
[0014] For each candidate drug node, the corresponding comprehensive score is calculated. The comprehensive score is obtained by weighted summation of clinical utility score, contextual compliance score and risk penalty score.
[0015] Select the candidate drug node with the highest comprehensive score as the model's prediction output for the current sample;
[0016] Based on the graph structure, an interpretable path from the current disease node to the predicted drug node is generated, and the corresponding interpretable path is converted into a natural language description.
[0017] Calculate the total loss of the model, which includes recommendation loss, path ranking loss and interpretation consistency loss, and optimize the model parameters using gradient descent.
[0018] Iterative training is performed by traversing the offline training sample set until the model converges.
[0019] By adopting the above technical solution, using the drug with the highest comprehensive score as the predicted output, the accuracy of the recommendation results is ensured, and a clear and quantifiable judgment standard is provided for the model's decision-making, avoiding the problem of ambiguous decision-making logic in traditional recommendation models. The step of generating interpretable paths based on the graph structure and converting them into natural language descriptions directly addresses the trust pain point in intelligent medical prescription recommendations. It transforms the model's black-box decision-making process into a traceable path that conforms to medical logic. This not only helps doctors quickly understand the basis for recommendations and increases their trust in the model, but also provides verifiable support for the compliance and safety of medical decisions. At the model optimization level, recommendation loss, path ranking loss, and interpretation consistency loss are incorporated into the total loss function, constructing a multi-objective collaborative optimization training framework. This allows the model to learn accurate recommendation capabilities while simultaneously strengthening the rationality of path reasoning and the consistency of natural language interpretation, fundamentally improving the model's robustness and medical logic fit. By iteratively training through the offline sample set until convergence, the model can fully absorb the medical patterns and scenario constraints in historical medical data, continuously optimize its decision-making logic and interpretability, and finally form a mature medical prescription recommendation model that combines accurate recommendation, interpretability and scenario adaptability.
[0020] Optionally, the training method further includes:
[0021] The system receives real-time desensitized prescription streams from clinics and processes the data in units of a set sliding time window. The data processing includes calculating the prescription percentage and the usage intensity growth rate.
[0022] A risk index is calculated based on the prescription ratio and the usage intensity growth rate, and the risk index is mapped to a risk level.
[0023] The risk index and corresponding risk level are updated to the attributes of the corresponding regional medication intensity node in the dynamic medical knowledge graph.
[0024] By adopting the above technical solution and processing the real-time anonymized prescription flow from clinics in sliding time windows, the model can promptly capture the latest changes in medication habits within the region, calculate dynamic data on prescription proportions and usage intensity growth rates, ensuring that the model's decision-making is always synchronized with the actual medical needs of the region, avoiding recommendation bias caused by data lag. Furthermore, by transforming this dynamic data into risk indices and risk levels and updating the regional medication intensity node attributes in the dynamic medical knowledge graph, a real-time updated "regional medication dynamic dashboard" is constructed for the model. This allows the model to directly incorporate the current regional medication trends and risk status into its prescription recommendations, improving the regional adaptability of the recommendations and proactively identifying potential irrational medication risks, thus upgrading from passive recommendation to proactive prevention. This dynamic updating mechanism also keeps the medical knowledge graph alive, continuously absorbing the latest clinical practice experience within the region, allowing the model to continuously optimize its understanding of regional medication patterns during iterative training, further narrowing the gap between model recommendations and actual clinical needs.
[0025] Optionally, the training method further includes:
[0026] Record the doctor's final prescription decision and identify feedback signals;
[0027] The feedback signal, the quadruple of this interaction, and the model-recommended drug are stored in the online feedback log pool;
[0028] Periodically extract accumulated feedback samples from the online feedback log pool, and construct a new training target for each feedback sample based on the corresponding feedback signal;
[0029] The model is retrained using the constructed incremental training sample set based on the parameters of the already trained model.
[0030] By adopting the above technical solution, and recording doctors' final prescription decisions and determining feedback signals, the model can directly transform real clinical experience into the core basis for self-optimization. This allows the model's decision-making logic to move beyond simply learning from historical data and keep pace with the latest developments in clinical practice, continuously absorbing doctors' professional judgments and personalized needs in actual treatment. Storing feedback signals, interaction quadruples, and model-recommended drugs in an online feedback log pool, and periodically extracting accumulated feedback samples to construct new training objectives, is equivalent to building a continuously updated "clinical experience knowledge base" for the model. This allows the model to gradually correct its decision-making biases through incremental training without overturning the original training results, continuously narrowing the gap between model recommendations and clinical reality. This incremental learning method, which retrains based on already trained model parameters, avoids the resource waste and time costs of full-scale training while ensuring that the model retains its acquired medical knowledge and diagnostic logic during continuous evolution, achieving smooth iteration and efficient improvement of model capabilities.
[0031] Optionally, the training method further includes:
[0032] Periodically extract feedback signals representing cases of doctor refusal from the online feedback log pool to construct a negative feedback sample set;
[0033] Attribution analysis was performed on the negative feedback sample set to count the frequency of different reasons for rejection. The reasons for rejection included at least side effect risk, low patient compliance, drug cost discrepancy, and conflict with regional medication guidelines.
[0034] Based on the statistical results of the rejection reasons, a targeted update operation is performed on the dynamic medical knowledge graph. The update operation includes: adjusting the risk penalty parameters of the corresponding drug nodes for high-frequency rejection reasons, or modifying the weight coefficient of the association edge between the disease node and the drug node.
[0035] By adopting the above technical solutions, the model establishes a complete closed-loop mechanism of "error correction-knowledge graph evolution." By focusing on cases where doctors refuse recommendations, the model can capture the discrepancy between recommendation logic and actual clinical decisions, uncovering implicit constraints (such as extreme avoidance of specific side effects or sensitivity to costs) that are difficult to cover by training solely with historical data. Attribution analysis of these negative cases and updating the knowledge graph essentially transforms doctors' clinical experience into explicit constraints in the graph, reducing the likelihood of the model repeating errors in similar scenarios in the future. This dynamic evolution of the knowledge graph based on negative feedback not only improves the clinical acceptability of the recommendation results but also endows the model with the ability to continuously learn and self-correct, ensuring that the recommendation system keeps pace with the latest clinical medical understanding and the actual needs of patients, further enhancing the system's practical value and credibility.
[0036] Optionally, the message passing steps for performing an L-layer graph neural network specifically include:
[0037] During message passing at each layer, a multi-head attention mechanism is introduced to calculate the correlation score between the current node and its neighboring nodes.
[0038] An attention weight matrix is generated based on the relevance score, and differentiated weights are assigned to different types of medical relationship edges, wherein the initial weights of the corresponding side effect relationship edges and contraindication relationship edges are greater than those of ordinary relationship edges.
[0039] Based on the attention weight matrix, the features of neighboring nodes are summed in a weighted manner to update the embedding representation of the current node.
[0040] By adopting the above technical solution and introducing a multi-head attention mechanism, the limitations of the equal aggregation of neighbor nodes in traditional graph neural networks are overcome. This allows the model to autonomously identify and focus on key information nodes based on the actual needs of the medical scenario. Especially when dealing with high-risk information such as side effects and contraindications, assigning them higher initial weights forces the model to prioritize safety constraints during the embedding learning phase, thereby improving the safety and accuracy of the generated prescriptions. This differentiated weight allocation mechanism can also effectively filter redundant noise information in the graph, allowing the representation of virtual patient nodes to more accurately reflect core diagnostic and treatment characteristics.
[0041] Optionally, for each candidate drug node, the steps before calculating the corresponding comprehensive score also include:
[0042] Monitor whether the set of candidate drug nodes after screening is empty;
[0043] If so, then in the dynamic medical knowledge graph, drug nodes that have an indication relationship with the current disease node are retrieved as target drug nodes, and then associated drug nodes that have an alternative treatment relationship with the target drug node are retrieved to construct an alternative drug subgraph;
[0044] Based on the matching degree between the patient feature vector and each node in the alternative drug subgraph, an alternative recommendation score is calculated and a preset alternative discount factor is added, wherein the alternative discount factor is negatively correlated with the alternative priority;
[0045] The output of the drug node with the highest alternative recommendation score is used as the model's prediction output for the current sample, and an interpretable path containing out-of-stock information is generated.
[0046] By employing the aforementioned technical solutions, a proactive alternative drug recommendation strategy was constructed to address common clinical scenarios involving drug shortages or insufficient inventory. When the preferred drug becomes unavailable due to inventory constraints, the model does not simply stop recommending or output invalid results. Instead, it intelligently identifies readily available alternative drugs with similar pharmacological effects by utilizing predefined "alternative treatment" relationships within a knowledge graph. By overlaying a substitution discount factor, the model prioritizes recommending top-ranked alternatives in clinical guidelines, avoiding the misuse of alternative drugs. Furthermore, the generated interpretable paths include shortage alerts, allowing doctors to intuitively understand the reasons for changes in recommendation logic. This ensures continuity of care, improves doctors' understanding of the system's recommendation intent, and enhances the model's robustness and practicality in real-world, complex medical environments.
[0047] Secondly, this application provides a training system for a medical prescription recommendation model, which adopts the following technical solution:
[0048] A training system for a medical prescription recommendation model, comprising:
[0049] The graph construction module is used to define the node set and edge set of the graph to construct a dynamic medical knowledge graph. The node set includes disease nodes, drug nodes, virtual patient nodes, inventory nodes, and regional drug use intensity nodes. The edge set includes medical relationship edges and context association edges.
[0050] The sample construction module is used to construct an offline training sample set based on historical diagnostic data. Each training sample is a quadruple, which includes a patient feature vector, the corresponding disease node, the drug node used in the real prescription, and a set of context constraints when the sample occurs. The set of context constraints includes inventory constraints and risk constraints.
[0051] The model training module receives the current training samples and maps the current patient feature vector to the embedding space of the dynamic medical knowledge graph through a fully connected neural network to obtain the initial embedding vector of the virtual patient node. It then performs message passing through an L-layer graph neural network on the dynamic medical knowledge graph, starting from the current disease node and the virtual patient node, to obtain an updated set of embedding representations for all nodes in the dynamic medical knowledge graph. Before each layer of propagation, the module modifies the attributes or connections of relevant nodes in the dynamic medical knowledge graph according to the current context constraints, and selects a set of candidate drug nodes from the dynamic medical knowledge graph that satisfy the current inventory constraints based on the set of embedding representations.
[0052] Thirdly, this application provides a computer device that adopts the following technical solution:
[0053] A computer device includes a memory, a processor, and a computer program stored in the memory, the processor executing the computer program to implement a training method for a medical prescription recommendation model as described in the first aspect.
[0054] Fourthly, this application provides a computer-readable storage medium, which adopts the following technical solution:
[0055] A computer-readable storage medium storing a computer program capable of being loaded by a processor and executing a training method for a medical prescription recommendation model as described in the first aspect.
[0056] In summary, this application includes at least one of the following beneficial technical effects:
[0057] 1. By integrating dynamic medical knowledge graphs with contextual constraints (inventory, risk, regional drug use intensity) and combining them with deep message passing via graph neural networks, prescription recommendations not only align with medical diagnosis and treatment logic but also adapt to real-world treatment scenario constraints, thereby improving the accuracy, rationality, and feasibility of the recommendations.
[0058] 2. By constructing an interpretable recommendation path and combining it with multi-objective loss optimization and multi-head attention mechanism, we can solve the black box problem of intelligent prescription recommendation, enhance clinical safety and decision traceability, increase doctors' trust in the model, and at the same time enhance the model's robustness and medical logic fit.
[0059] 3. Establish a closed-loop evolution mechanism for online feedback, negative feedback attribution, and incremental training. Combine this with alternative recommendation strategies for drug shortage scenarios to achieve model self-correction and continuous iteration, dynamically optimize to fit clinical practice, ensure continuity of diagnosis and treatment, and improve the model's practicality and adaptability in complex medical scenarios. Attached Figure Description
[0060] Figure 1 This is a first flowchart of an embodiment of the method of this application;
[0061] Figure 2 This is a second flowchart of an embodiment of the method of this application;
[0062] Figure 3 This is a third flowchart of an embodiment of the method of this application;
[0063] Figure 4 This is the fourth flowchart of an embodiment of the method of this application;
[0064] Figure 5 This is the fifth flowchart of an embodiment of the method of this application;
[0065] Figure 6 This is the sixth flowchart of an embodiment of the method of this application;
[0066] Figure 7 This is the seventh flowchart of an embodiment of the method of this application. Detailed Implementation
[0067] To make the purpose, technical solution, and advantages of this application clearer, the following description is provided in conjunction with the appendix. Figures 1-7 The present application will be further described in detail below with reference to embodiments. It should be understood that the specific embodiments described herein are for illustrative purposes only and are not intended to limit the scope of the application.
[0068] The first embodiment of this application discloses a training method for a medical prescription recommendation model. (Refer to...) Figure 1 The training method includes S110-S150:
[0069] S110 defines the set of nodes and the set of edges of the graph to construct a dynamic medical knowledge graph. The set of nodes includes disease nodes, drug nodes, virtual patient nodes, inventory nodes and regional drug use intensity nodes, and the set of edges includes medical relationship edges and context association edges.
[0070] S120. Based on historical diagnostic data, construct an offline training sample set, where each training sample is a quadruple. The quadruple includes the patient feature vector, the corresponding disease node, the drug node used in the real prescription, and the context constraint set when the sample occurs. The context constraint set includes inventory constraints and risk constraints.
[0071] S130: Receive the current training sample and map the current patient feature vector to the embedding space of the dynamic medical knowledge graph through a fully connected neural network to obtain the initial embedding vector of the virtual patient node.
[0072] S140, on the dynamic medical knowledge graph, starting from the current disease node and virtual patient node, execute message passing of the L-layer graph neural network to obtain the updated embedding representation set of all nodes in the dynamic medical knowledge graph; wherein, before each layer of propagation, modify the attributes or connections of relevant nodes in the dynamic medical knowledge graph according to the current context constraints.
[0073] S150, based on the set of embedded representations, select a set of candidate drug nodes from the dynamic medical knowledge graph that meet the current inventory constraints.
[0074] Specifically, in step S110, the specific attribute definitions and data sources for each node are clearly defined to ensure the completeness and accuracy of node information. Among these, the disease ID for disease nodes uses both the hospital's internal standard disease code and the national ICD-10 code for dual labeling. The names uniformly use the standard names from the "Disease Classification and Codes," and the ICD codes strictly correspond to the ICD-10 clinical version. For example, the ICD code for "Type 2 Diabetes" is E11.900. Attribute values are extracted from the disease dictionary table of the hospital's electronic medical record system, ensuring that the attributes of each disease node are unique and standardized. The drug ID for each drug node uses the drug approval number from the National Medical Products Administration, and the name uses the generic name of the drug to avoid confusion with brand names. The ATC classification follows the World Health Organization's ATC classification system; for example, "Amoxicillin Capsules" corresponds to the ATC classification J01CA04. The pharmacological mechanism of action is based on the textbook "Clinical Pharmacology" and the drug's instructions, describing in detail the drug's target and pathway of action, such as "Amoxicillin exerts its bactericidal effect by inhibiting bacterial cell wall synthesis and is suitable for infections caused by susceptible bacteria." The attribute data for each drug node is extracted in batches from the hospital drug management system and the national drug database and manually verified. As a virtual node, the virtual patient node does not have predefined fixed attributes. Its attributes are dynamically generated from the patient's feature vector. Specifically, more than 20 core features, such as age, gender, weight, blood pressure, blood sugar, liver and kidney function indicators, past medical history, and allergy history, are extracted from the patient's electronic medical record. Through standardization processing (such as normalizing age to the 0-1 range and converting categorical features into vectors through one-hot encoding), a 64-dimensional patient feature vector is constructed. This vector is the dynamic attribute of the virtual patient node and is dynamically updated according to each training sample. Each inventory node has a unique drug ID associated with its corresponding drug ID. The institution ID uses the clinic's unified social credit code. The current inventory level is obtained in real time through the clinic's drug inventory management system. The expiration date is uniformly formatted as "YYYY-MM-DD", and an expiration date warning threshold is set (e.g., if there are less than 30 days until expiration, it is marked as a warning state). For example, the inventory node of a clinic's amoxicillin capsules (drug ID: H20180001) has the following attributes: associated drug ID: H20180001, institution ID: 91310101MA1G812XXX, current inventory: 50 boxes, expiration date: 2027-05-10. The inventory data is synchronized every hour to ensure the real-time nature of the node attributes.The associated drug IDs of regional drug use intensity nodes correspond to drug nodes. The regional IDs use administrative division codes (e.g., 6-digit codes for provincial levels, 9-digit codes for municipal levels). The time windows are set to two fixed dimensions: 7 days and 30 days. The prescription ratio is calculated as the proportion of prescriptions for this drug in a specific region and within a specific time window to the total number of prescriptions for all drugs. The growth rate is calculated as the difference between the prescription ratio in the current time window and the previous time window, divided by the prescription ratio in the previous time window. The risk level is determined based on a combination of the growth rate and the prescription ratio. For example, if the growth rate exceeds 50% and the prescription ratio exceeds 10%, the risk level is defined as "high risk"; if the growth rate is between 20% and 50% and the prescription ratio is between 5% and 10%, it is defined as "medium risk"; and the rest are "low risk". The attribute data of regional drug use intensity nodes are extracted from the regional public health information platform and updated daily.
[0075] In the implementation of the edge set, medical relationship edges are constructed using a triplet (head node, relationship type, tail node). The "Indication" relationship connects disease nodes and drug nodes. For example, "Type 2 Diabetes" (disease node) and "Metformin Extended-Release Tablets" (drug node) are linked by an "Indication" relationship, with the relationship type in the attribute labeled as "Indication." The confidence level is set according to the clinical guideline recommendation level (e.g., 0.9 for Grade A recommendation and 0.8 for Grade B). The "Similar Drugs" relationship connects drug nodes with similar mechanisms of action. For example, "Amoxicillin Capsules" and "Cephalexin Capsules" are linked by a "Similar Drugs" relationship, with the confidence level calculated based on the pharmacological similarity (e.g., 80% similarity corresponds to a confidence level of 0.8). The "Contraindications" relationship connects disease nodes and drug nodes that are contraindicated for use. For example, "Penicillin Allergy" (disease node) and "Amoxicillin Capsules" (drug node) are linked by a "Contraindications" relationship, with a confidence level set to 0.95 (very high confidence). In the context-related edges, the connection between drug nodes and inventory nodes adopts an "inventory exists" relationship, with attributes only indicating the relationship type, ensuring that each drug node is associated with a corresponding clinic's inventory node. The connection between drug nodes and regional drug usage intensity nodes adopts a "use intensity record exists" relationship, with attributes indicating the time window, ensuring that the same drug node corresponds to different regional drug usage intensity nodes in different regions and time windows. The graph is constructed using the Neo4j graph database. The import of nodes and edges is batch processed using a script written in Python's py2neo library, with incremental updates to node attributes and edge relationships performed every morning to ensure the dynamic nature of the graph.
[0076] In step S120, historical electronic medical records in the historical diagnostic data are extracted from the hospital's HIS and EMR systems, with a time range set to the past 3 years, covering all outpatient and inpatient diagnostic records. The extracted content includes basic patient information, chief complaint, present illness, past medical history, examination and test results, and diagnostic conclusions. Prescription records are extracted from the hospital's prescription management system, including prescription number, patient ID, disease diagnosis, drug name and dosage, and prescription issuance time. Inventory logs are extracted from the clinic's inventory management system, including drug entry time, exit time, inventory changes, and expiration date warning records. Regional public health data is extracted from the regional public health information platform, including the usage of each drug in the region, the number of prescriptions, and adverse reaction reports. After data extraction, preprocessing is performed. First, invalid data (such as records with missing patient characteristics, unclear disease diagnoses, or incomplete prescription information) is removed. Then, the data is standardized. For example, continuous features such as patient age and blood pressure are normalized, categorical features such as disease diagnosis and drug name are mapped to the IDs of corresponding nodes, inventory quantities in inventory logs are converted into numerical data, and the time format in regional public health data is unified to "YYYY-MM-DD HH:MM:SS". After preprocessing, each training sample is constructed as a quadruple (patient feature vector, corresponding disease node, drug node used in the actual prescription, and context constraint set at the time of sample occurrence). The patient feature vector is constructed according to the method defined in S110, with a dimension of 64. For example, a patient's feature vector might be [0.45 (age normalized), 0.5 (gender, 1 for male, 0 for female), 0.3 (blood pressure normalized), ..., 0.1 (allergy history, 0 for no allergy)]. The corresponding disease node is the disease node ID corresponding to the patient's diagnosis, for example, a diagnosis of "type 2 diabetes" corresponds to disease node ID D001. The actual prescription... The drug nodes used are the drug node IDs corresponding to each drug in the prescription. If the prescription contains multiple drugs, the node ID corresponding to the main treatment drug is taken as the real label. The inventory constraint in the context constraint set is the inventory status of the drug in the corresponding clinic at the time the sample occurs (prescription time), specifically "inventory quantity ≥ minimum inventory threshold" (the minimum inventory threshold is set according to the clinic's daily usage, such as the minimum inventory threshold of 20 boxes for amoxicillin capsules). If the inventory quantity is lower than this threshold, the inventory constraint is not satisfied. The risk constraint is the risk level of the regional drug use intensity node corresponding to the drug at the time the sample occurs. If the risk level is "high risk", the risk constraint is not satisfied. For example, the quadruple of a training sample is ([0.45,0.5,0.3,...,0.1], D001, M001, {inventory constraint: inventory quantity ≥ 20 boxes, risk constraint: risk level ≠ high risk}), where M001 is the drug node ID of metformin extended-release tablets.The size of the offline training sample set is determined by the amount of data, usually no less than 100,000 records. It is divided into training and validation sets in an 8:2 ratio. The samples are arranged in order of prescription issuance time. All samples are stored in JSON format for easy reading and processing by the model later.
[0077] In step S130, a fully connected neural network (FCNN) is constructed. This network contains three hidden layers: the input layer has a dimension of 64 (consistent with the dimension of the patient feature vector), the first hidden layer has a dimension of 128 and uses ReLU activation function, the second hidden layer has a dimension of 64 and uses ReLU activation function, and the third hidden layer has a dimension of 32 and uses tanh activation function. The output layer has a dimension of 32, consistent with the embedding dimension of all nodes in the dynamic medical knowledge graph. The embedding dimension of all nodes in the graph is uniformly set to 32 dimensions to facilitate subsequent message passing. The network parameters are initialized using the Xavier initialization method to avoid gradient vanishing or exploding problems during training. After receiving the current training sample, the patient feature vector in the sample is extracted and used as the input of the FCNN. Through forward propagation, the output vector is obtained, which is the initial embedding vector of the virtual patient node. For example, after a patient's feature vector is input, it is processed by three hidden layers of FCNN, resulting in an output vector of [0.12, 0.35, 0.21, ..., 0.46] (32 dimensions). This vector is the initial embedding of the virtual patient node, which will be updated subsequently through message passing in the graph neural network. To ensure the accuracy of the mapping, during training, the parameters of FCNN, along with other model parameters, are optimized using gradient descent. The optimization objective is to minimize the cosine distance between the virtual patient node embedding and the disease node embedding, so that the virtual patient node can accurately reflect the correlation between patient features and the disease.
[0078] Reference Figure 2 In S140, the message passing steps for executing the L-layer graph neural network specifically include S210-S230:
[0079] S210, In the message passing process of each layer, a multi-head attention mechanism is introduced to calculate the correlation score between the current node and its neighboring nodes;
[0080] S220: Generate an attention weight matrix based on the relevance score and assign differentiated weights to different types of medical relationship edges. The initial weights of the corresponding side effect relationship edges and contraindication relationship edges are greater than those of ordinary relationship edges.
[0081] S230, based on the attention weight matrix, performs a weighted summation of the features of neighboring nodes to update the embedding representation of the current node.
[0082] Specifically, the number of layers L in the graph neural network is determined. Considering the complexity and training efficiency of the medical knowledge graph, L is set to 3 layers (too many layers will lead to overfitting, while too few layers will not be able to fully integrate node information). Graph Attention Network (GAT) is used as the basic model because it can highlight important nodes and relationships through the attention mechanism, making it more suitable for the needs of multi-factor association in medical scenarios. Before message transmission at each layer, the attributes or connections of relevant nodes in the graph are modified according to the context constraints of the current sample: For inventory constraints, if the inventory of an inventory node corresponding to a certain drug node is lower than the minimum inventory threshold, the "recommended status" attribute of that drug node is set to "not recommended," and its message transmission is temporarily blocked; for risk constraints, if the risk level of the regional drug use intensity node corresponding to a certain drug node is "high risk," the "risk coefficient" attribute (initial value 1.0) of that drug node is adjusted to 1.5, increasing its risk weight.
[0083] In step S210, a multi-head attention mechanism, such as eight attention heads, is introduced during message passing at each layer. For the k-th attention head, the embedding vectors of the current node i and its neighboring nodes j are first linearly transformed, then concatenated, and then dot-producted with a learnable attention vector. Finally, the relevance score is obtained through the LeakyReLU activation function. The calculation formula is as follows:
[0084] e{ij} k =LeakyReLU((a k ) T ·[W k hi||W k hj]), where W k It is a learnable weight matrix with dimensions 4×32, a k It is an 8×1 learnable attention vector, where [·||·] denotes vector concatenation, hi is the embedding vector of the current node, and hj is the embedding vector of the neighboring nodes. The negative slope of LeakyReLU can be set to 0.2. The relevance score between the current node and each neighboring node is calculated using this formula.
[0085] In step S220, the relevance score of each attention head is normalized using softmax to obtain the attention weight z{ij}=softmax for a single attention head. j(e{ij}), and then concatenate the weights of the 8 attention heads to obtain the final attention weight matrix (dimension N×N, where N is the number of neighboring nodes of the current node); for different types of medical relationship edges, preset differentiated initial weights are used, among which the initial weights of side effect relationship edges and contraindication relationship edges are greater than those of ordinary relationship edges. Specifically, the initial weights are set as follows: initial weight of contraindication relationship edge 1.2, initial weight of side effect relationship edge 1.1, initial weight of indication relationship edge 1.0, initial weight of similar drug relationship edge 0.9, and initial weight of ordinary relationship edge 0.8. In the process of attention weight calculation, the initial weight of the edge is multiplied by the relevance score to obtain the final weighted relevance score, ensuring that key relationships such as contraindications and side effects are given attention.
[0086] In step S230, the node update rule of a Graph Attention Network (GAT) is adopted. For each attention head k, the updated embedding of node i is first computed. Where N(i) is the set of neighboring nodes of node i, z{ij} k The attention weights calculated for the k-th attention head, Wv k This is the learnable weight matrix (32×32 dimensions) corresponding to the kth attention head. The ReLU activation function is used. Then, the output vectors of all K attention heads are concatenated to obtain hi. {concat} =concat(hi 1 ,...,hi K Finally, an output linear layer Wo maps the dimension back from 256 to 32, obtaining the final embedding representation hi of node i in this layer. {new} =Wo*hi {concat} After three layers of GNN message passing, the embedding representations of all nodes in the dynamic medical knowledge graph (including disease nodes, drug nodes, virtual patient nodes, inventory nodes, and regional drug use intensity nodes) are updated, integrating patient characteristics, disease information, and semantic information constrained by the current specific context. For example, after the embedding vector of a drug node is updated, it not only includes its own pharmacological effects and ATC classification, but also integrates features such as the patient's age and blood pressure, as well as contextual information such as the drug's inventory status and regional drug use risk, providing support for subsequent candidate drug screening and score calculation.
[0087] Reference Figure 3 In S150, the steps following the selection of a set of candidate drug nodes that meet the current inventory constraints from the dynamic medical knowledge graph include S310-S340:
[0088] S310, monitor whether the set of candidate drug nodes after screening is empty;
[0089] S320, if so, then in the dynamic medical knowledge graph, retrieve drug nodes that have an indication relationship with the current disease node as the target drug node, and then retrieve associated drug nodes that have an alternative treatment relationship with the target drug node to construct an alternative drug subgraph;
[0090] S330: Based on the matching degree between the patient feature vector and each node in the alternative drug subgraph, calculate the alternative recommendation score and add a preset alternative discount factor, where the alternative discount factor is negatively correlated with the alternative priority;
[0091] S340 outputs the drug node with the highest alternative recommendation score as the model's prediction output for the current sample, and generates an interpretable path containing out-of-stock information.
[0092] Specifically, based on the updated node embedding representation, the embedding similarity between each drug node and the current disease node and virtual patient node is calculated (using cosine similarity, the formula is sim(hm,hd)=(hm·hd) / (||hm||×||hd||), where hm is the drug node embedding and hd is the disease node embedding; sim(hm,hp)=(hm·hp) / (||hm||×||hp||), where hp is the virtual patient node embedding). The average of the two similarities is used as the initial matching value between the drug node and the current sample. During the screening process, drug nodes whose "recommended status" is "not recommended" (i.e., drugs with insufficient inventory) are first filtered out. Then, drug nodes with an initial matching value ≥0.5 are retained (the threshold of 0.5 is adjusted based on the validation set data to ensure that the selected candidate drugs are somewhat related to the patient's disease and characteristics), thus forming the final candidate drug node set. For example, if the current disease node is "Type 2 Diabetes" (hd) and the virtual patient node is embedded as hp, the screening process first removes drug nodes with insufficient inventory, then calculates the similarity between the remaining drug nodes and hd and hp, and retains drug nodes with an average similarity ≥ 0.5, resulting in a candidate drug node set {M001 (metformin extended-release tablets), M002 (gliclazide tablets), M003 (acarbose tablets)}. If multiple drugs of the same type exist in the candidate drug node set, the top 10 nodes with the highest initial matching scores can be further retained to avoid the candidate set becoming too large and affecting the efficiency of subsequent calculations.
[0093] In step S310, the length of the candidate drug node set is determined. If the length is 0, the alternative drug retrieval process is triggered. The definition of an alternative therapy relationship is clarified: two drugs have similar pharmacological mechanisms of action, can treat the same disease, and can be used interchangeably in clinical practice (refer to the alternative therapy recommendations in *Clinical Pharmacotherapy*). In the graph, the alternative therapy relationship is treated as a type of medical relationship edge, connecting drug nodes with an alternative relationship, labeled with the attribute "alternative therapy," and the confidence level is set according to the clinical alternative recommendation level (e.g., 0.9 confidence for level one alternative, 0.8 confidence for level two alternative). If the candidate drug node set is empty, starting from the current disease node, all drug nodes with an "indication" relationship to that disease node are retrieved, and then nodes with alternative therapy relationships are selected from these drug nodes. After the retrieval is completed, an alternative medicine subgraph is constructed. This subgraph contains associated medicine nodes, current disease nodes, virtual patient nodes, and medical relationship edges (indications, alternative treatments, contraindications, etc.) and contextual relationship edges (inventory, regional drug use intensity) between these nodes. The subgraph is constructed using Neo4j's subgraph query function, extracting relevant nodes and edges using Cypher statements. For example, the query statement is "MATCH (m:medicine)-[r:alternative treatment]-(m2:medicine), (m2)-[s:indication]-(d:disease{id:'D001'}) RETURN m2,d, r, s". The extracted nodes and edges constitute the alternative medicine subgraph. Simultaneously, the associated medicine nodes in the alternative medicine subgraph are initially screened, removing nodes with insufficient inventory or high risk levels to ensure the availability of alternative medicines.
[0094] In step S320, the cosine similarity between the patient feature vector (virtual patient node embedding hp) and the embedding hm of each associated drug node in the alternative drug subgraph is calculated as the matching score. The formula is sim(hp,hm)=(hp·hm) / (||hp||×||hm||). The matching score ranges from 0 to 1, with a higher score indicating a better match between the drug and patient features. Then, a substitution discount factor is set. The substitution priority is determined based on the confidence level of the alternative treatment relationship. The higher the confidence level, the higher the substitution priority and the smaller the penalty factor. Specifically, the penalty factor is set as follows: Level 1 substitution (confidence 0.9) has a penalty factor of 0.1, Level 2 substitution (confidence 0.8) has a penalty factor of 0.2, Level 3 substitution (confidence 0.7) has a penalty factor of 0.3, and so on. The substitution priority and the penalty factor are negatively correlated. The formula for calculating the substitution recommendation score is: Substitution Recommendation Score = Matching Score × (1 - Substitution Discount Factor). For example, if a related drug node is a primary substitution for the target drug, with a matching score of 0.8 and a penalty factor of 0.1, then the substitution recommendation score = 0.8 × (1 - 0.1) = 0.72; if it is a secondary substitution, with a penalty factor of 0.2, then the score = 0.8 × 0.8 = 0.64. By accumulating penalty factors, it is ensured that higher-priority substitution drugs receive higher recommendation scores.
[0095] In step S330, the drug node with the highest alternative recommendation score is selected from the alternative drug subgraph and used as the prediction output. The drug ID, name, and other information of this node will be used as the model's recommendation result. The generation of interpretable paths is based on the structure of the alternative drug subgraph. The path starts at the current disease node, passes through alternative treatment relationship edges, and ends at the predicted alternative drug node, while also including a message indicating insufficient stock. The specific form of the path is "Disease node → Alternative treatment relationship → Alternative drug node (Original recommended drug XXX is in short supply, this drug is its primary alternative and is suitable for the current patient characteristics)". Then, the path is converted into a natural language description, such as "The patient is diagnosed with type 2 diabetes (disease node D001). The original recommended drug, metformin extended-release tablets (M001), is in short supply. The recommended primary alternative drug is gliclazide tablets (M002), which has a similar hypoglycemic effect to metformin extended-release tablets and is consistent with the patient's age, blood pressure, and other characteristics. The current stock is sufficient (30 boxes), and the regional drug use risk is low." The generation of interpretable paths uses Python scripts to parse the node and edge relationships of the subgraph and automatically convert them into natural language, making it easier for doctors to understand the recommendation logic. It also includes out-of-stock alerts to help doctors quickly understand the reasons for recommendation adjustments.
[0096] Reference Figure 4 In S150, the steps following the selection of the candidate drug node set that meets the current inventory constraints also include S410-S450:
[0097] S410, if not, then for each candidate drug node, calculate the corresponding comprehensive score, which is obtained by weighted sum of clinical utility score, contextual compliance score and risk penalty score;
[0098] S420: Select the candidate drug node with the highest comprehensive score as the model's prediction output for the current sample;
[0099] S430, based on the graph structure, generates an interpretable path from the current disease node to the predicted drug node, and converts the corresponding interpretable path into a natural language description;
[0100] S440, calculate the total loss of the model, which includes recommendation loss, path ranking loss and interpretation consistency loss, and optimize the model parameters using gradient descent.
[0101] S450 iterates through the offline training sample set until the model converges.
[0102] Specifically, in step S410, if the candidate drug node set is not empty, the calculation method and weight allocation of the three scores are specified. The weights are determined through cross-validation of the validation set. For example, the final weight is set as follows: clinical utility score 0.5, context compliance score 0.3, and risk penalty score 0.2. The formula for calculating the comprehensive score is: comprehensive score = clinical utility score × 0.5 + context compliance score × 0.3 + risk penalty score × 0.2. The clinical utility score is calculated based on factors such as the correlation between the drug node and the disease node, and the clinical efficacy of the drug. Specifically, the clinical utility score is calculated as follows: Clinical Utility Score = Indication Relationship Confidence × 0.6 + Clinical Efficacy Score × 0.4. The indication relationship confidence is the confidence level of the "indication" relationship between the drug node and the disease node (e.g., 0.9). The clinical efficacy score is determined based on the drug's effectiveness rate in historical prescriptions (e.g., if a drug has an effectiveness rate of 85% in historical treatment, then the clinical efficacy score is 0.85). For example, if a drug has an indication confidence of 0.9 and a clinical efficacy score of 0.85, then the clinical utility score is calculated as follows: Clinical Utility Score = 0.9 × 0.6 + 0.85 × 0.4 = 0.54 + 0.34 = 0.88. The contextual compliance score is calculated based on the drug's inventory status and regional drug use intensity, specifically: Contextual Compliance Score = Inventory Adequacy Score × 0.5 + Regional Drug Use Risk Score × 0.5. The inventory adequacy score is 1.0 if the inventory level is greater than or equal to the minimum inventory threshold, otherwise it is 0 (here, the candidate set has already filtered for drugs with sufficient inventory, so the inventory adequacy score is 1.0 for all). The regional drug use risk score is set according to the risk level of the regional drug use intensity node (low risk 1.0, medium risk 0.8, high risk 0.5). For example, if the regional drug use risk of a certain drug is low risk, then the contextual compliance score = 1.0 × 0.5 + 1.0 × 0.5 = 1.0. The risk penalty score is calculated based on factors such as the drug's side effects and contraindications. Specifically: Risk Penalty Score = 1.0 - (Side Effect Risk Coefficient × 0.5 + Contraindication Risk Coefficient × 0.5). The side effect risk coefficient is set according to the drug's side effect incidence rate (0.1 for incidence ≤ 5%, 0.2 for 5%-10%, and 0.3 for > 10%). The contraindication risk coefficient is 0.5 if the drug is contraindicated with the patient's characteristics, and 0.1 otherwise. For example, if a drug has a side effect incidence rate of 3% and has no contraindications with the patient, then the risk penalty score = 1.0 - (0.1 × 0.5 + 0.1 × 0.5) = 0.9. Based on the above calculations, the overall score for this drug = 0.88 × 0.5 + 1.0 × 0.3 + 0.9 × 0.2 = 0.44 + 0.3 + 0.18 = 0.92.
[0103] In step S420, the overall scores of all candidate drug nodes are sorted (from highest to lowest), and the node with the highest score is selected as the prediction output. If multiple nodes have the same score (score difference ≤ 0.01), the clinical utility score is further compared, and the node with the higher clinical utility score is given priority as the prediction output. If the clinical utility scores are also the same, the contextual compliance score is compared to ensure the uniqueness and rationality of the prediction results. For example, if candidate drug nodes M001 have an overall score of 0.92, M002 has a score of 0.88, and M003 has a score of 0.85, then M001 is selected as the prediction output, and its drug name, dosage, usage, and other information will be used as the model's recommendation result. At the same time, the overall score and the scores of each sub-item of this node are recorded.
[0104] In step S430, the generation of interpretable paths employs the shortest path algorithm (Dijkstra's algorithm). Starting from the current disease node, it finds the shortest path to the predicted drug node. The path includes the disease node, the predicted drug node, and medical relationship edges (such as indications, pharmacological effects, etc.) and contextual association edges (such as inventory, regional drug use intensity) connecting the two, ensuring that the path clearly reflects the logical basis of the recommendation. For example, if the current disease node is D001 (type 2 diabetes) and the predicted drug node is M001 (metformin extended-release tablets), the generated path would be "D001 (type 2 diabetes) → indication → M001 (metformin extended-release tablets) → inventory exists → inventory node (30 boxes in stock) → usage intensity record → regional drug use intensity node (low risk)". This path contains the core logic of the recommendation: the drug is suitable for the disease, inventory is sufficient, and regional drug use risk is low. The path is then converted into a natural language description, including the disease, medication, and the basis for the recommendation (indications, availability, and risks). For example, "The patient has been diagnosed with type 2 diabetes. Metformin extended-release tablets are recommended. This medication is indicated for type 2 diabetes, has good clinical efficacy, and is currently in sufficient stock at the clinic (30 boxes). The usage intensity of this medication in the region is moderate, and the risk level is low. It is suitable for the patient's age, blood pressure, and other characteristics." During the natural language conversion process, excessive use of technical jargon is avoided to ensure that doctors can quickly understand the recommendation logic, while retaining key information (such as availability and risk level) to improve the credibility of the recommendation.
[0105] In step S440, the recommendation loss uses the multi-class cross-entropy loss function to measure the difference between the drug nodes predicted by the model and those in the actual prescriptions. The formula is as follows: Here, Vdrug is the set of all candidate drug nodes; yi is a one-hot vector, where yi = 1 when drug node i is a drug in the actual prescription, and 0 otherwise; pi is the probability that the model predicts drug node i as a recommendation result. The smaller the recommendation loss, the higher the recommendation accuracy of the model. The path ranking loss adopts the contrastive loss function to ensure that the interpretable path from the disease node to the predicted drug node is better than other random paths. The formula is: Lpath = max(0, margin - (spos - sneg)), where spos is the score of the positive path (the real recommended path), sneg is the score of the negative path (the randomly generated non-recommended path), and margin is set to 0.5. The smaller the path ranking loss, the higher the rationality of the interpretable path. The explanation consistency loss measures the consistency between the natural language description of the explainable path and the model's recommendation logic. It uses cosine similarity loss, with the formula: Lcons = 1 - sim(embpath, embdesc), where embpath is the embedding vector of the explainable path (obtained by concatenating the embeddings of nodes in the path and averaging them), and embdesc is the embedding vector of the natural language description (converted from natural language to vectors using the BERT model). A smaller explanation consistency loss indicates higher consistency between the explainable path and the natural language description. The total loss is a weighted sum of the three losses, with weights determined using the validation set and set to Ltotal = 0.5 × Lrec + 0.3 × Lpath + 0.2 × Lcons. Model parameter optimization uses the Adam optimizer with a learning rate of 0.001 and a decay coefficient. , The batch size is set to 64. After calculating the total loss in each iteration, the gradient of each parameter is calculated through backpropagation. Then, the weight matrix of the fully connected neural network and the graph neural network and the parameters of the attention mechanism are updated to ensure that the total loss gradually decreases.
[0106] In step S450, the offline training sample set is divided into multiple batches, and batch training is used, training one batch of samples at a time, calculating the total loss, and updating the model parameters. The number of iterations is preset to 100 rounds. After each round of training, the model's accuracy (the proportion of samples where the recommended drug matches the actual prescription drug), recall (the proportion of actual prescription drugs included in the candidate set), and F1 score are calculated using the validation set as evaluation metrics for model performance. The model convergence criterion is: the change in F1 score on the validation set for 5 consecutive rounds is ≤0.001, and the total loss tends to stabilize (the decrease in total loss for 5 consecutive rounds is ≤0.0001). If the convergence criterion is met, training stops; if not, iterative training continues until the convergence criterion is met or the preset maximum number of iterations (100 rounds) is reached. During training, the training loss, validation loss, and various performance metrics for each round are recorded, and loss curves and performance curves are plotted to facilitate analysis of the model's training effect. If overfitting occurs (training loss decreases but validation loss increases), Dropout regularization (dropout rate set to 0.3) and L2 regularization (regularization coefficient set to 0.0001) are used for optimization to ensure the model's generalization ability. After training is complete, the model parameters (including the weights of fully connected neural networks and graph neural networks, and the parameters of the attention mechanism) are saved for subsequent online inference and incremental training.
[0107] Reference Figure 5 Furthermore, the training methods also include S510-S530:
[0108] S510 receives real-time desensitized prescription streams from clinics and processes the data in units of a set sliding time window. The data processing includes calculating the prescription percentage and the usage intensity growth rate.
[0109] S520 calculates a risk index based on the prescription ratio and the growth rate of usage intensity, and maps the risk index to a risk level.
[0110] S530 updates the risk index and corresponding risk level to the attributes of the corresponding regional medication intensity node in the dynamic medical knowledge graph.
[0111] Specifically, in step S510, prescription data is obtained in real time by connecting to the prescription management systems of various clinics through a data interface. This data undergoes anonymization (removing sensitive information such as patient names and ID numbers, retaining only non-sensitive information such as patient characteristics, disease diagnosis, drug information, prescription issuance time, and clinic ID) to prevent privacy leaks. The sliding time window is set to two fixed dimensions: a short-term window of 7 days and a long-term window of 30 days, with a sliding step of 1 day for both windows, meaning the relevant data for both windows is updated once every day at midnight. During data processing, the prescription percentage is calculated as follows: the number of prescriptions for a certain drug in a specific region and within a specific time window ÷ the total number of prescriptions for all drugs in that region within the same time window × 100%. For example, if the total number of prescriptions in a region within 7 days is 1000, and the number of prescriptions for amoxicillin capsules is 50, then its prescription percentage is 5%. The intensity growth rate is calculated as follows: max(0, (prescription percentage in the current time window - prescription percentage in the previous time window) ÷ prescription percentage in the previous time window × 100%). For example, if the prescription percentage for amoxicillin capsules in the current 7-day window is 5%, and the prescription percentage in the previous 7-day window was 4%, then the growth rate is (5% - 4%) ÷ 4% × 100% = 25%. Data processing is implemented using Python's Pandas library to batch calculate the prescription percentage and growth rate of each drug in different regions and time windows, and the processed data is stored in a temporary database.
[0112] In step S520, the risk index is calculated using the formula: Risk Index = Prescription Percentage × 0.4 + Growth Rate × 0.6, where both prescription percentage and growth rate are converted to decimal form (e.g., 5% is converted to 0.05, 25% to 0.25). This formula comprehensively considers both prescription percentage (reflecting the prevalence of drug use) and growth rate (reflecting the changing trend of drug use), avoiding misjudgments of risk due to a single indicator. For example, if a drug's prescription percentage is 0.05 and its growth rate is 0.25, then the risk index = 0.05 × 0.4 + 0.25 × 0.6 = 0.02 + 0.15 = 0.17. The mapping standard for risk levels is determined by statistically analyzing the correlation between the incidence of adverse drug reactions and the risk index within a region. Specifically, the risk index is as follows: Risk index < 0.1 indicates low risk, 0.1 ≤ Risk index < 0.2 indicates medium risk, and risk index ≥ 0.2 indicates high risk. For example, the risk index of the aforementioned drug is 0.17, which maps to medium risk. Drugs with abnormally high risk indices (e.g., ≥0.3) are marked as "key monitoring" to facilitate subsequent manual intervention.
[0113] In step S530, based on the drug ID, region ID, and time window, the corresponding regional drug use intensity node in the dynamic medical knowledge graph is located. Then, an update script is written using the py2neo library to write the calculated risk index and risk level into the corresponding attribute fields of the node, overwriting the original attribute values. The update frequency is consistent with the sliding step size of the sliding time window, i.e., updated once every day at midnight, ensuring that the attributes of the regional drug use intensity node can reflect the drug use risk in real time. At the same time, an attribute update log is recorded, including the update time, node ID, old attribute value, and new attribute value, to facilitate subsequent traceability and problem investigation. If a node does not exist during the update process (such as when adding a drug or a region), the corresponding regional drug use intensity node is automatically created to improve the graph structure.
[0114] Reference Figure 6 Furthermore, the training methods also include S610-S640:
[0115] S610 records the doctor's final prescription decision and determines the feedback signal;
[0116] S620 stores the feedback signal, the quadruple of this interaction, and the model-recommended drug into the online feedback log pool;
[0117] S630 periodically extracts accumulated feedback samples from the online feedback log pool, and constructs a new training target for each feedback sample based on the corresponding feedback signal.
[0118] S640 retrains the model based on the already trained parameters using the constructed incremental training sample set.
[0119] Specifically, in step S610, a feedback button is set on the model recommendation interface. After the doctor issues a prescription, they select the feedback type based on their decision: if they fully adopt the AI-recommended medication (including consistent medication name and dosage), the feedback signal is set to +1; if they reject the AI recommendation and choose a completely different medication (no recommended medication is adopted), the feedback signal is set to -1; if they partially adopt the recommendation (e.g., adopting some recommended medications, modifying the dosage, or replacing it with a similar medication), the feedback signal is set to 0. The feedback signal is recorded synchronously with the doctor's prescription decision, linked to information such as the prescription number, patient ID, model-recommended medication, and the doctor's final prescription, ensuring that each feedback signal corresponds to a specific interaction case. For example, if the model recommends medication M001 and the doctor ultimately prescribes medication M001, the feedback signal is +1; if the doctor prescribes medication M004 (unrelated to M001), the feedback signal is -1; if the doctor prescribes medication M001 (dosage adjustment), the feedback signal is 0.
[0120] In step S620, the online feedback log pool is built using a Redis database, enabling high-concurrency writes and fast queries. Each log record contains the following information: prescription number, patient ID, quadruple (patient feature vector, disease node ID, real drug node ID, context constraint set), model-recommended drug ID, feedback signal, and interaction time. The log pool is set to retain data for 6 months, and logs exceeding this period are automatically cleaned up to avoid performance impact from excessive data volume. A data backup mechanism is also implemented, backing up the log pool data daily to prevent data loss. For example, a log record might be: prescription number P0001, patient ID U0001, quadruple ([0.45, 0.5, ...], D001, M001, {inventory ≥ 20 boxes, risk ≠ high risk}), model-recommended drug M001, feedback signal +1, interaction time 2026-04-08 09:30:00.
[0121] In step S630, the extraction cycle is set to once a week, extracting the accumulated feedback samples from the past 7 days each time, and removing invalid feedback (such as samples with missing feedback signals or incomplete four-tuple information). When constructing a new training objective, if the feedback signal is +1 (complete acceptance), the model-recommended drug node is used as a positive sample, and the training objective is to maximize the recommendation score of that node; if the feedback signal is -1 (complete rejection), the model-recommended drug node is used as a negative sample, and the training objective is to minimize the recommendation score of that node, while the doctor-selected drug node is added to the training set as a positive sample; if the feedback signal is 0 (partial acceptance), both the model-recommended drug node and the doctor-selected drug node are used as positive samples, and their weights are adjusted (the doctor-selected drug node has a higher weight than the model-recommended drug node), and the training objective is to make the recommendation scores of both reach a high level. For example, if the model recommends drug M001 for a sample with a feedback signal of -1, and the doctor chooses drug M004, then when constructing the training objective, M001 is a negative sample and M004 is a positive sample. During training, the score of M001 needs to be reduced and the score of M004 needs to be increased.
[0122] In step S640, incremental training employs a fine-tuning approach, adjusting only some weight parameters of the fully connected neural network and the graph neural network without retraining the entire model, thus reducing training cost and time. The batch size for incremental training is set to 32, the learning rate to 0.0001 (lower than the initial training learning rate to avoid excessive parameter fluctuations), and the number of iterations is set to 10 rounds. After each round of training, the model performance metrics are calculated using the latest validation set (containing recent prescription data). If performance improves (F1 score improvement ≥ 0.005), the updated model parameters are saved; if performance does not improve or decreases, the incremental training is abandoned, and the original model parameters are retained. During incremental training, Dropout and L2 regularization are also used to prevent overfitting, ensuring the model can adapt to changes in doctors' prescription habits and improve the accuracy and applicability of recommendations.
[0123] Reference Figure 7 Furthermore, the training methods also include S710-S730:
[0124] S710 periodically extracts feedback signals from the online feedback log pool to represent cases of doctor refusal, and constructs a negative feedback sample set.
[0125] S720, perform attribution analysis on the negative feedback sample set, and count the frequency of different reasons for refusal. The reasons for refusal include at least side effect risk, low patient compliance, drug cost incompatibility and conflict with regional drug guidelines.
[0126] S730 performs targeted update operations on the dynamic medical knowledge graph based on the statistical results of the rejection reasons. The update operations include: adjusting the risk penalty parameters of the corresponding drug nodes for high-frequency rejection reasons, or modifying the weight coefficient of the association edge between the disease node and the drug node.
[0127] Specifically, in step S710, cases with feedback signals indicating doctor refusal are periodically extracted from the online feedback log pool to construct a negative feedback sample set. The extraction cycle is consistent with incremental training (once a week). The extraction condition is all samples with a feedback signal of -1. After removing invalid samples (such as those with incomplete prescription information or unlabeled reasons for refusal), the negative feedback sample set is formed. For example, if there are 50 samples with a feedback signal of -1 in the past 7 days, after removing 5 invalid samples, a negative feedback sample set containing 45 samples is constructed.
[0128] In step S720, attribution analysis employs a combination of manual annotation and machine classification: First, clinicians annotate a subset of negative feedback samples with reasons for rejection. Then, a text classification model (based on BERT) is trained, using textual information such as doctors' prescription notes and feedback notes as input to automatically classify the reasons for rejection. After classification, the results are manually verified to ensure the accuracy of the attribution. When calculating frequencies, the proportion of each reason for rejection in the negative feedback sample set is calculated. For example, in 45 negative feedback samples, 15 were due to side effect risks (33.3%), 10 were due to low patient compliance (22.2%), 8 were due to drug cost discrepancies (17.8%), 7 were due to conflicts with regional medication guidelines (15.6%), and 5 were due to other reasons (11.1%). A frequency distribution chart of rejection reasons is then plotted to identify the primary reasons for rejection.
[0129] In step S730, different update strategies are adopted for frequently rejected reasons: If side effect risk is a frequently rejected reason (accounting for ≥20%), the corresponding drug node is found, and its "side effect risk coefficient" is increased by 0.1 (e.g., from 0.1 to 0.2) on the original basis. At the same time, the weight of the "side effect" relationship edge between the drug node and the related disease node is increased (from 1.1 to 1.2), so that the model can pay more attention to the side effect risk of the drug when calculating the risk penalty score; if low patient compliance is a frequently rejected reason, the "compliance score" of the drug node is adjusted (set according to the frequency of drug use and dosage complexity, such as 1.0 for once-daily use and 0.7 for three-daily use), and added to the clinical utility score calculation. The weight of compliance scores is increased (e.g., from 0.4 to 0.5), and the weight of indication relationship confidence is correspondingly reduced to 0.5. If drug cost mismatch is a frequent reason for rejection, a "cost level" attribute (divided into low, medium, and high levels) is added to the drug node, and a cost matching score is added to the contextual compliance score (1.0 if the patient's affordable cost matches the drug cost level, otherwise 0.7). If regional medication guideline conflict is a frequent reason for rejection, the confidence of the "indication" relationship edge between the disease node and the drug node is modified (reduced from 0.9 to 0.7), and a "guideline compliance" attribute is added to the regional medication intensity node (1.0 for compliance with regional guidelines, 0.5 for non-compliance), and the weight of the contextual compliance score is adjusted. After the update operation is completed, a graph update log is recorded, including the update time, rejection reason, updated node and attribute, and numerical changes before and after the update, to facilitate subsequent tracking of the update effect. If the negative feedback rate of the model decreases after the update (e.g., from 10% to 8%), it indicates that the update is effective; otherwise, the update strategy is adjusted and optimized again.
[0130] Based on the above method embodiments, the second embodiment of this application discloses a training system for a medical prescription recommendation model. The training system for the medical prescription recommendation model of this application embodiment can implement any of the above-described methods for training medical prescription recommendation models, and the specific working process of each module in the training system can be referred to the corresponding process in the above method embodiments.
[0131] For ease of understanding, an example is provided below: A training system for a medical prescription recommendation model includes:
[0132] The graph construction module is used to define the node set and edge set of the graph to build a dynamic medical knowledge graph. The node set includes disease nodes, drug nodes, virtual patient nodes, inventory nodes and regional drug use intensity nodes, and the edge set includes medical relationship edges and context association edges.
[0133] The sample construction module is used to construct an offline training sample set based on historical diagnostic data. Each training sample is a quadruple, which includes the patient feature vector, the corresponding disease node, the drug node used in the real prescription, and the context constraint set when the sample occurred. The context constraint set includes inventory constraints and risk constraints.
[0134] The model training module receives the current training samples and maps the current patient feature vector to the embedding space of the dynamic medical knowledge graph through a fully connected neural network to obtain the initial embedding vector of the virtual patient node. It then performs message passing through an L-layer graph neural network on the dynamic medical knowledge graph, starting from the current disease node and the virtual patient node, to obtain the updated embedding representation set of all nodes in the dynamic medical knowledge graph. Before each layer of propagation, the module modifies the attributes or connections of relevant nodes in the dynamic medical knowledge graph according to the current context constraints, and selects a set of candidate drug nodes from the dynamic medical knowledge graph that meet the current inventory constraints based on the embedding representation set.
[0135] The third embodiment of this application provides a computer device, which may include a memory, a processor, and a computer program stored in the memory. The processor executes the computer program to implement a training method for a medical prescription recommendation model.
[0136] The memory can communicate with the processor via a communication bus, which can be an address bus, a data bus, a control bus, etc.
[0137] Additionally, the memory may include random access memory (RAM) or non-volatile memory (NVM), such as at least one disk storage device.
[0138] Furthermore, the processor can be a general-purpose processor, including a central processing unit (CPU), a network processor (NP), etc.; it can also be a digital signal processor (DSP), an application-specific integrated circuit (ASIC), a field-programmable gate array (FPGA), or other programmable logic devices, discrete gate or transistor logic devices, discrete hardware components, etc.
[0139] The fourth embodiment of this application provides a computer-readable storage medium storing a computer program that can be loaded by a processor and execute a training method for a medical prescription recommendation model.
[0140] The computer-readable storage medium can be any tangible medium that contains or stores a program that can be used by or in connection with an instruction execution system, apparatus, or device; the program code contained on the computer-readable medium can be transmitted using any suitable medium, including but not limited to wireless, wire, optical fiber, RF, etc., or any suitable combination thereof.
[0141] The above are all preferred embodiments of this application and are not intended to limit the scope of protection of this application. Any feature disclosed in this specification (including the abstract and drawings) may be replaced by other equivalent or similar features unless specifically stated otherwise. That is, unless specifically stated otherwise, each feature is only one example of a series of equivalent or similar features.
Claims
1. A training method for a medical prescription recommendation model, characterized in that, include: A set of nodes and edges is defined to construct a dynamic medical knowledge graph. The set of nodes includes disease nodes, drug nodes, virtual patient nodes, inventory nodes, and regional drug use intensity nodes. The set of edges includes medical relationship edges and contextual relationship edges. Virtual patient nodes are virtual nodes whose attributes are dynamically generated from the patient's feature vector. Medical relationship edges are constructed using triples, where indication relationships connect disease nodes and drug nodes, similar drug relationships connect drug nodes with similar mechanisms of action, and contraindication relationships connect disease nodes and contraindicated drug nodes. In contextual relationship edges, the connection between drug nodes and inventory nodes uses an inventory relationship, with attributes only indicating the relationship type. The connection between drug nodes and regional drug use intensity nodes uses a relationship with usage intensity records, with attributes indicating time windows and risk levels. This ensures that the same drug node corresponds to different regional drug use intensity nodes in different regions and time windows, and the risk level is determined comprehensively based on the usage intensity growth rate and prescription ratio. Based on historical diagnostic data, an offline training sample set is constructed, in which each training sample is a quadruple. The quadruple includes a patient feature vector, the corresponding disease node, the drug node used in the real prescription, and the context constraint set when the sample occurs. The context constraint set includes inventory constraints and risk constraints. Receive the current training sample and map the current patient feature vector to the embedding space of the dynamic medical knowledge graph through a fully connected neural network to obtain the initial embedding vector of the virtual patient node; On the dynamic medical knowledge graph, starting from the current disease node and the virtual patient node, message passing of an L-layer graph neural network is performed to obtain the updated embedding representation set of all nodes in the dynamic medical knowledge graph; wherein, before each layer of propagation, the attributes or connections of relevant nodes in the dynamic medical knowledge graph are modified according to the current context constraints. Based on the embedded representation set, a set of candidate drug nodes that meet the current inventory constraints is selected from the dynamic medical knowledge graph; The training method also includes: Record the doctor's final prescription decision and identify feedback signals; The feedback signal, the quadruple of this interaction, and the model-recommended drug are stored in the online feedback log pool; Periodically extract accumulated feedback samples from the online feedback log pool, and construct a new training target for each feedback sample based on the corresponding feedback signal; Retrain the model using the constructed incremental training sample set based on the already trained model parameters; The training method also includes: Periodically extract feedback signals representing cases of doctor refusal from the online feedback log pool to construct a negative feedback sample set; Attribution analysis was performed on the negative feedback sample set to count the frequency of different reasons for rejection. The reasons for rejection included at least side effect risk, low patient compliance, drug cost discrepancy, and conflict with regional medication guidelines. Based on the statistical results of the rejection reasons, a targeted update operation is performed on the dynamic medical knowledge graph. The update operation includes: adjusting the risk penalty parameters of the corresponding drug nodes for high-frequency rejection reasons, or modifying the weight coefficient of the association edge between the disease node and the drug node.
2. The training method for a medical prescription recommendation model according to claim 1, characterized in that, The steps following the selection of a set of candidate drug nodes that meet the current inventory constraints include: For each candidate drug node, the corresponding comprehensive score is calculated. The comprehensive score is obtained by weighted summation of clinical utility score, contextual compliance score and risk penalty score. Select the candidate drug node with the highest comprehensive score as the model's prediction output for the current sample; Based on the graph structure, an interpretable path from the current disease node to the predicted drug node is generated, and the corresponding interpretable path is converted into a natural language description. Calculate the total loss of the model, which includes recommendation loss, path ranking loss and interpretation consistency loss, and optimize the model parameters using gradient descent. Iterative training is performed by traversing the offline training sample set until the model converges.
3. The training method for a medical prescription recommendation model according to claim 1, characterized in that, The training method also includes: The system receives real-time desensitized prescription streams from clinics and processes the data in units of a set sliding time window. The data processing includes calculating the prescription percentage and the usage intensity growth rate. A risk index is calculated based on the prescription ratio and the usage intensity growth rate, and the risk index is mapped to a risk level. The risk index and corresponding risk level are updated to the attributes of the corresponding regional medication intensity node in the dynamic medical knowledge graph.
4. The training method for a medical prescription recommendation model according to claim 1, characterized in that, The specific steps for message passing in an L-layer graph neural network include: During message passing at each layer, a multi-head attention mechanism is introduced to calculate the correlation score between the current node and its neighboring nodes. An attention weight matrix is generated based on the relevance score, and differentiated weights are assigned to different types of medical relationship edges, wherein the initial weights of the corresponding side effect relationship edges and contraindication relationship edges are greater than those of ordinary relationship edges. Based on the attention weight matrix, the features of neighboring nodes are summed in a weighted manner to update the embedding representation of the current node.
5. The training method for a medical prescription recommendation model according to claim 2, characterized in that, For each candidate drug node, the steps before calculating the corresponding comprehensive score also include: Monitor whether the set of candidate drug nodes after screening is empty; If so, then in the dynamic medical knowledge graph, drug nodes that have an indication relationship with the current disease node are retrieved as target drug nodes, and then associated drug nodes that have an alternative treatment relationship with the target drug node are retrieved to construct an alternative drug subgraph; Based on the matching degree between the patient feature vector and each node in the alternative drug subgraph, an alternative recommendation score is calculated and a preset alternative discount factor is added, wherein the alternative discount factor is negatively correlated with the alternative priority; The output of the drug node with the highest alternative recommendation score is used as the model's prediction output for the current sample, and an interpretable path containing out-of-stock information is generated.
6. A training system for a medical prescription recommendation model, characterized in that, A method for training a medical prescription recommendation model as described in any one of claims 1 to 5, comprising: The graph construction module is used to define the node set and edge set of the graph to construct a dynamic medical knowledge graph. The node set includes disease nodes, drug nodes, virtual patient nodes, inventory nodes, and regional drug use intensity nodes. The edge set includes medical relationship edges and context association edges. The sample construction module is used to construct an offline training sample set based on historical diagnostic data. Each training sample is a quadruple, which includes a patient feature vector, the corresponding disease node, the drug node used in the real prescription, and a set of context constraints when the sample occurs. The set of context constraints includes inventory constraints and risk constraints. The model training module receives the current training samples and maps the current patient feature vector to the embedding space of the dynamic medical knowledge graph through a fully connected neural network to obtain the initial embedding vector of the virtual patient node. It then performs message passing through an L-layer graph neural network on the dynamic medical knowledge graph, starting from the current disease node and the virtual patient node, to obtain an updated set of embedding representations for all nodes in the dynamic medical knowledge graph. Before each layer of propagation, the module modifies the attributes or connections of relevant nodes in the dynamic medical knowledge graph according to the current context constraints, and selects a set of candidate drug nodes from the dynamic medical knowledge graph that satisfy the current inventory constraints based on the set of embedding representations.
7. A computer device, characterized in that, It includes a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the program to implement the training method of the medical prescription recommendation model as described in any one of claims 1 to 5.
8. A computer-readable storage medium, characterized in that, A computer program is stored that can be loaded by a processor and execute the training method of the medical prescription recommendation model as described in any one of claims 1 to 5.
Citation Information
Patent Citations
Prescription recommendation method and system based on machine learning and knowledge graph
CN111191020A
Intelligent prescription recommendation method and system for medicinal material shortage
CN120432075A
Clinical pharmacy knowledge graph construction method and medication conflict early warning system
CN121257678A