Klebsiella pneumoniae drug resistance detection method, system, device and medium
By using topological persistence-based feature detection and interpretable contrastive learning networks, this study addresses the issues of insufficient feature extraction and weak model generalization ability in existing technologies for Klebsiella pneumoniae drug resistance detection, achieving high-precision and clinically reliable drug resistance detection.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- BEIJING UNIV OF CHEM TECH
- Filing Date
- 2026-04-13
- Publication Date
- 2026-07-10
AI Technical Summary
Existing mass spectrometry-based Klebsiella pneumoniae drug resistance detection technologies suffer from insufficient feature extraction resolution and noise resistance, high dependence on large-scale labeled samples, and a lack of interpretability in the prediction process. As a result, the generalization performance of the models is limited when dealing with complex variant strains, and they are difficult to gain trust in clinical decision-making.
A feature detection mechanism based on topological persistence is used to screen feature peaks. The feature mapping of position encoding tensor and intensity embedding tensor is combined. An interpretable contrastive learning network is used to model the spatial dependence and co-expression association between feature peaks. The parameters of the feature extractor are optimized through self-supervised learning. After freezing, the parameters are connected to the classification head for supervised adjustment to output the detection results.
It significantly improves the noise resistance and robustness of feature extraction, enhances the identification accuracy of complex variant strains, reduces the dependence on large-scale labeled samples, and achieves highly accurate and clinically reliable drug resistance detection.
Smart Images

Figure CN122024859B_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of computer information processing technology, and in particular to a method, system, device and medium for detecting drug resistance in Klebsiella pneumoniae. Background Technology
[0002] Klebsiella pneumoniae (KP) is an important Gram-negative pathogen that can cause serious infections such as pneumonia and sepsis. With the global prevalence of carbapenem-resistant Klebsiella pneumoniae (CRKP), clinical treatment faces significant challenges. Due to the extremely high mortality rate following CRKP infection, rapid and accurate identification of strain resistance is crucial for guiding rational clinical drug use.
[0003] Currently, matrix-assisted laser desorption / ionization time-of-flight mass spectrometry (MALDI-TOF MS) has become the mainstream method for microbial identification due to its fast detection speed and low cost. However, existing technologies still have significant shortcomings when using mass spectrometry data to build deep learning classification models. Traditional feature extraction often uses uniform binning or cluster-based feature center extraction, which has limited resolution, leading to the easy merging of key adjacent peaks. Furthermore, mass spectrometry instruments are susceptible to noise disturbances, causing peak positions to drift. Since cluster centers are highly dependent on the training set distribution, when new strains or variants appear in the test set, the model struggles to effectively capture their unique mass spectrometry characteristics, resulting in feature information loss, decreased classification performance, and weak generalization ability.
[0004] Furthermore, traditional supervised learning models heavily rely on high-quality sample sets labeled with standard drug sensitivity tests. However, acquiring such large-scale labeled data in clinical settings is costly and time-consuming. Therefore, with small sample sizes, existing models are often insufficiently trained and struggle to learn robust feature representations from massive amounts of unlabeled data. In addition, existing deep learning classification models are often considered "black boxes," their decision-making processes are not transparent, and they fail to reveal key biomarkers related to drug resistance. This lack of clinical interpretability limits the reliability and depth of application of these models in medical decision support. Summary of the Invention
[0005] (a) Technical problems to be solved
[0006] In view of the above-mentioned shortcomings and deficiencies of the prior art, the present invention provides a method, system, device and medium for detecting Klebsiella pneumoniae drug resistance. It solves the technical problems of existing Klebsiella pneumoniae drug resistance detection technology based on mass spectrometry data, which has limited generalization performance when dealing with complex variant strains and is difficult to gain trust in clinical decision-making due to insufficient feature extraction resolution and noise resistance, high dependence on large-scale labeled samples and lack of interpretability in the prediction process.
[0007] (II) Technical Solution
[0008] To achieve the above objectives, the main technical solutions adopted by the present invention include:
[0009] In a first aspect, embodiments of the present invention provide a method for detecting drug resistance in Klebsiella pneumoniae, comprising: acquiring and preprocessing the raw mass spectrometry data of the test strain to obtain a mass spectrometry signal sequence; determining topological durability based on the difference between the local maximum point in the mass spectrometry signal sequence and the higher of the adjacent local minimum points on both sides, and screening feature peaks according to the topological durability to construct an ordered feature sequence; performing enhancement processing on the ordered feature sequence to obtain enhanced view pairs, mapping each enhanced view to a position encoding tensor and an intensity embedding tensor respectively, and constructing an input sequence by combining embedding labels; inputting the input sequence into an interpretable contrastive learning network containing a feature extractor and a projection head, modeling the spatial dependence and co-expression association between feature peaks using an attention mechanism, performing mapping on the association information obtained by globally aggregating the embedding labels through the projection head to obtain a contrastive representation vector, optimizing the consistency of the contrastive representation vector using contrastive learning to update the feature extractor parameters; freezing the feature extractor parameters, removing the projection head and connecting a classification head, performing supervised adjustment using labeled samples, performing mapping on the association information obtained by re-aggregating the embedding labels through the classification head to obtain a co-representation vector, and performing discrimination on the co-representation vector to output the drug resistance detection result.
[0010] Optionally, the raw mass spectrometry data of the test strain is acquired and preprocessed to obtain a mass spectrometry signal sequence, including: acquiring the protein fingerprint spectrum of the strain using a mass spectrometer, and resampling the protein fingerprint spectra of different samples to align all samples to a mass-to-charge ratio axis to generate raw mass spectrometry data; performing local polynomial least squares fitting on the raw mass spectrometry data within a preset sliding window using a polynomial smoothing filtering algorithm, updating the amplitude of each data point in the raw mass spectrometry data through convolution mapping to generate smoothed mass spectrometry data; performing background estimation on the smoothed mass spectrometry data using an asymmetric reweighted penalized least squares algorithm, calculating the residual distribution using the initially established estimated baseline and the amplitude of the smoothed mass spectrometry data during the iterative calculation of background estimation to allocate asymmetric weights, and using the asymmetric weights to perform weighted penalty on the smoothed mass spectrometry data to construct a background baseline, subtracting the background baseline from the smoothed mass spectrometry data to extract the true ion intensity signal; and performing normalization and feature scaling processing on the true ion intensity signal after background subtraction to obtain a mass spectrometry signal sequence composed of data labels, mass-to-charge ratios, and corresponding ion intensities.
[0011] Optionally, topological durability is determined based on the difference between a local maximum point in the mass spectrometry signal sequence and the higher of the two adjacent local minimum points. This includes: traversing each data sampling point in the mass spectrometry signal sequence, comparing the ion intensity of the current sampling point with its previous and next neighbor points, identifying local maximum points with ion intensities greater than those of the two neighbor points, and recording the corresponding sampling position indices to construct a candidate peak set; for each candidate peak in the candidate peak set, performing bidirectional gradient probing along the mass-to-charge ratio axis starting from the corresponding sampling position index until the first sampling point with an ion intensity less than that of the two neighbor points is obtained on both sides, which are then identified as the left and right local minimum points closest to the candidate peak point; obtaining the intensity values of the left and right local minimum points and comparing their amplitudes, selecting the intensity of the side with the higher amplitude as the intensity of the topographic reference boundary characterizing the local waveform envelope; and quantifying the topological height of the candidate peak point relative to the local waveform envelope by calculating the intensity difference between the candidate peak point and the topographic reference boundary, thereby obtaining the topological durability corresponding to each candidate peak point.
[0012] Optionally, feature peaks are selected based on topological persistence to construct an ordered feature sequence, including: extracting candidate peaks with topological persistence greater than zero as effective feature peaks reflecting the heterogeneity of Klebsiella pneumoniae discrete drug resistance protein fingerprints, and rearranging the effective feature peaks in descending order of topological persistence values; truncating the first preset number of effective feature peaks according to the rearranged order to form a fixed-length feature set; when the total number of effective feature peaks does not reach the preset input number, performing zero-value padding mapping on the fixed-length feature set using virtual zero-peak nodes composed of zero mass-to-charge ratio and zero topological persistence, until the fixed-length feature set meets the preset input number; extracting the mass-to-charge ratio and topological persistence of each effective feature peak in the fixed-length feature set that meets the preset input number, and assembling them according to the rearranged sequence positions to generate an ordered feature sequence characterized by numerical pairs corresponding to the mass-to-charge ratio and topological persistence.
[0013] Optionally, enhancement processing is performed on the ordered feature sequence to obtain enhanced view pairs. Each enhanced view is mapped to a position encoding tensor and an intensity embedding tensor, respectively, and an input sequence is constructed by combining the embedding labels. This includes: performing random peak loss processing on the ordered feature sequence, determining the number of removals according to a preset masking ratio, and performing random sampling without replacement to remove feature peaks of the corresponding position order, generating a masked feature sequence; performing amplitude perturbation processing on the topological durability component in the masked feature sequence, by superimposing random noise with a mean of zero and a standard deviation positively correlated with the average topological durability, and performing numerical correction based on the zero-value lower limit discrimination, to obtain semantically consistent enhanced view pairs; and extracting enhancements. The topological persistence components of each feature peak in the view pair are transformed into feature intensity scalars representing the peak response amplitude. By performing a linear spatial dimension transformation, the feature intensity scalars are mapped to a feature representation space with multi-dimensional components, generating an intensity embedding tensor. The mass-to-charge ratio of each feature peak in the enhanced view pair is extracted and a periodic coordinate mapping based on sine and cosine logic is performed. The periodic dimensional components generated by the mapping are used to synthesize a position space vector with multi-dimensional components, generating a position encoding tensor that reflects the spatial distribution characteristics of the mass-to-charge ratio. Embedding tags representing global correlation information of the entire spectrum are initialized and concatenated at the beginning and end of the combined sequence of the intensity embedding tensor and the position encoding tensor. The input sequence is constructed by dimension concatenation.
[0014] Optionally, the input sequence is input into an interpretable contrastive learning network containing a feature extractor and a projection head. An attention mechanism is used to model the spatial dependencies and co-representation associations between feature peaks. The projection head maps the association information obtained from the global aggregation of embedded labels to obtain contrastive representation vectors. Contrastive learning is used to optimize the consistency of the contrastive representation vectors to update the feature extractor parameters. This includes: using a multi-head attention mechanism in the feature extractor to perform parallel interactive mapping of feature vectors containing mass-to-charge ratio location information and response intensity information in the input sequence; calculating the association weights between different feature vectors and performing weighted summation to model the spatial dependencies and co-representation associations between feature peaks; and using a positional feedforward network in the feature extractor to perform position-by-position nonlinear processing on the sequence obtained from the weighted summation. The algorithm transforms and normalizes layers to extract the embedding label vector from the last layer of the feature extractor as the global feature vector for aggregating global association information. It then uses a linear adapter layer in the projector to adjust the dimensionality of the global feature vector and inputs it into a multilayer perceptron for nonlinear mapping to obtain contrast representation vectors corresponding to different augmented views in the feature space. The cosine similarity between augmented view pairs is calculated using these contrast representation vectors, and a temperature hyperparameter is introduced to scale the similarity distribution, constructing a normalized consistency loss metric to measure the distribution consistency between augmented views. Finally, it performs representation consistency optimization with the loss metric as the target, using backpropagation to calculate the gradient of the loss metric with respect to the network model parameters, and synchronously updates the weight parameters of the feature extractor and the projector.
[0015] Optionally, the feature extractor parameters are frozen, the projection head is removed and a classification head is connected, supervised adjustment is performed using labeled samples, and the association information of the embedded labels is mapped again through the classification head to obtain a co-representation vector. The co-representation vector is then discriminated to output the drug resistance detection result. This includes: setting the model parameters of the feature extractor to a non-updateable state to lock the co-relation modeling capability between the feature peaks obtained from contrastive learning; removing the projection head and connecting a classification head containing a linear layer to the output of the feature extractor; inputting Klebsiella pneumoniae drug resistance sample sequences with data labels into the feature extractor; performing parallel mapping on the feature vector using a multi-head attention mechanism; and then having the embedded labels... Global aggregation is performed on the feature components reflecting global correlation information to obtain a feature vector of aggregated global correlation information. The feature vector of aggregated global correlation information is mapped to a collaborative representation vector for drug resistance discrimination using a classification head. A classification loss index is constructed to measure the discrimination accuracy based on the difference between the collaborative representation vector and the drug resistance category in the data label. Keeping the feature extractor parameters fixed, backpropagation is used to optimize the model parameters of the classification head only according to the classification loss index to achieve supervised adjustment of the discrimination ability of the collaborative representation vector. The class probability mapping is performed on the collaborative representation vector using the classification head after supervised adjustment to output the drug resistance detection results of Klebsiella pneumoniae.
[0016] Secondly, embodiments of the present invention provide a Klebsiella pneumoniae drug resistance detection system, comprising: a preprocessing module for acquiring and preprocessing the raw mass spectrometry data of the test strain to obtain a mass spectrometry signal sequence; a feature selection module for determining topological persistence based on the difference between the local maximum point in the mass spectrometry signal sequence and the higher of the adjacent local minimum points on both sides, and selecting feature peaks according to the topological persistence to construct an ordered feature sequence; an input construction module for performing enhancement processing on the ordered feature sequence to obtain enhanced view pairs, mapping each enhanced view to a position encoding tensor and an intensity embedding tensor respectively, and constructing an input sequence by combining embedding tags; and a model training module. The network is designed to accept input sequences into an interpretable contrastive learning network containing a feature extractor and a projection head. It utilizes an attention mechanism to model spatial dependencies and co-representation associations between feature peaks. The projection head maps the association information obtained from the global aggregation of embedded labels to obtain a contrastive representation vector. Contrastive learning optimizes the consistency of the contrastive representation vector to update the feature extractor parameters. A classification module freezes the feature extractor parameters, removes the projection head and connects a classification head, performs supervised adjustments using labeled samples, maps the association information from the re-aggregated embedded labels using the classification head to obtain a co-representation vector, and performs discrimination on the co-representation vector to output the drug resistance detection result.
[0017] Thirdly, embodiments of the present invention provide a Klebsiella pneumoniae drug resistance detection system device, comprising: at least one processor; and a memory communicatively connected to the at least one processor; wherein the memory stores instructions executable by the at least one processor, the instructions being executed by the at least one processor to enable the at least one processor to perform the Klebsiella pneumoniae drug resistance detection method as described above.
[0018] Fourthly, embodiments of the present invention provide a computer-readable storage medium storing computer-executable instructions, which, when executed by a processor, implement the method for detecting Klebsiella pneumoniae drug resistance as described above.
[0019] (III) Beneficial Effects
[0020] The beneficial effects of this invention are as follows: First, this invention uses a feature detection mechanism based on topological durability to screen core feature peaks by utilizing the difference in durability between local maxima and adjacent minima, rather than relying on binning processing based on absolute intensity or fixed frequency. Since topological durability reflects the structural saliency of a signal, it can effectively identify highly robust feature components in the spectrum, thereby fundamentally overcoming the peak position drift problem caused by noise interference and environmental fluctuations in mass spectrometry instruments, and greatly improving the noise resistance and robustness of feature extraction.
[0021] Secondly, this invention introduces position-encoding tensors and intensity embedding tensors in the feature mapping stage, and utilizes the attention mechanism in the feature extractor to model the spatial dependencies and co-expression associations between feature peaks. This modeling approach breaks through the limitations of traditional methods that isolate and process single peaks, enabling the deep capture of complex interaction patterns and potential co-expression rules between peaks with different mass-to-charge ratios. Through this refined characterization of the intrinsic connections of the full spectrum features, the model can uncover more specific drug resistance signals, significantly enhancing the system's accuracy in identifying complex variant strains.
[0022] Furthermore, the contrastive learning framework with a projection head constructed in this invention, by optimizing and enhancing the representation consistency between view pairs, endows the feature extractor with powerful self-supervised learning capabilities. Since the model can spontaneously learn high-quality feature representations with invariance from unlabeled large-scale samples, it significantly reduces the dependence on large-scale labeled samples, improving generalization performance and convergence speed in small-sample scenarios.
[0023] Meanwhile, by freezing the pre-trained feature extractor parameters and connecting them to the classification head, this invention achieves a smooth transfer from general spectral pattern learning to specific drug resistance discrimination tasks. Since the classification process directly operates on the feature vector obtained from global aggregation of embedded labels, and the feature extractor retains the feature associations obtained from modeling, it can output highly robust and accurate drug resistance detection results.
[0024] Therefore, by combining topological persistent feature extraction with interpretable contrastive learning networks, this invention significantly improves the robustness of mass spectrometry signal representation and reduces the dependence on labeled samples. It also utilizes attention mechanisms and aggregation logic to eliminate the black-box nature of the decision-making process, achieving highly accurate and clinically reliable detection of Klebsiella pneumoniae drug resistance. Attached Figure Description
[0025] Figure 1 This is a schematic diagram of the overall process of the method provided in the embodiments of the present invention;
[0026] Figure 2 This is a schematic diagram illustrating the specific process of step S1 of the method provided in this embodiment of the invention;
[0027] Figure 3 A visual schematic diagram of the mass spectrometry signal sequence preprocessing workflow provided in an embodiment of the present invention;
[0028] Figure 4 This is a schematic diagram of a portion of step S2 of the method provided in the embodiments of the present invention;
[0029] Figure 5 This is a schematic diagram illustrating the principle of topology persistence peak detection provided in an embodiment of the present invention;
[0030] Figure 6 This is a schematic diagram illustrating another part of the specific process of step S2 of the method provided in the embodiments of the present invention;
[0031] Figure 7 This is a detailed flowchart illustrating step S3 of the method provided in this embodiment of the invention;
[0032] Figure 8 This is a detailed flowchart illustrating step S4 of the method provided in this embodiment of the invention;
[0033] Figure 9 This is a detailed flowchart illustrating step S4 of the method provided in this embodiment of the invention;
[0034] Figure 10 Attention diagram of CRKP strain provided in an embodiment of the present invention;
[0035] Figure 11 Attention to the CSKP strain provided in the embodiments of the present invention;
[0036] Figure 12 This is a general framework diagram of the method provided in the embodiments of the present invention. Detailed Implementation
[0037] To better explain and facilitate understanding of the present invention, the present invention will be described in detail below with reference to the accompanying drawings and specific embodiments.
[0038] like Figure 1 As shown in the embodiment of the present invention, a method for detecting drug resistance in Klebsiella pneumoniae includes: acquiring and preprocessing the raw mass spectrometry data of the test strain to obtain a mass spectrometry signal sequence; determining the topological persistence based on the difference between the local maximum point in the mass spectrometry signal sequence and the higher of the two adjacent local minimum points, and screening feature peaks according to the topological persistence to construct an ordered feature sequence; performing enhancement processing on the ordered feature sequence to obtain enhanced view pairs, mapping each enhanced view to a position encoding tensor and an intensity embedding tensor respectively, and constructing an input sequence by combining embedding labels; inputting the input sequence into an interpretable contrastive learning network containing a feature extractor and a projection head, using an attention mechanism to model the spatial dependence and co-expression association between feature peaks, performing mapping on the association information obtained by global aggregation of embedding labels through the projection head to obtain a contrastive representation vector, using contrastive learning to optimize the consistency of the contrastive representation vector to update the feature extractor parameters; freezing the feature extractor parameters, removing the projection head and connecting a classification head, using labeled samples for supervised adjustment, performing mapping on the association information obtained by re-aggregating embedding labels through the classification head to obtain a co-representation vector, and performing discrimination on the co-representation vector to output the drug resistance detection result.
[0039] First, this invention employs a topological durability-based feature detection mechanism, utilizing the durability difference between local maxima and adjacent minima to screen core feature peaks, rather than relying on absolute intensity or fixed-frequency binning. Since topological durability reflects the structural saliency of a signal, it can effectively identify highly robust feature components in the spectrum, fundamentally overcoming the peak position drift problem caused by noise interference and environmental fluctuations in mass spectrometry instruments, and greatly improving the noise resistance and robustness of feature extraction.
[0040] Secondly, this invention introduces position-encoding tensors and intensity embedding tensors in the feature mapping stage, and utilizes the attention mechanism in the feature extractor to model the spatial dependencies and co-expression associations between feature peaks. This modeling approach breaks through the limitations of traditional methods that isolate and process single peaks, enabling the deep capture of complex interaction patterns and potential co-expression rules between peaks with different mass-to-charge ratios. Through this refined characterization of the intrinsic connections of the full spectrum features, the model can uncover more specific drug resistance signals, significantly enhancing the system's accuracy in identifying complex variant strains.
[0041] Furthermore, the contrastive learning framework with a projection head constructed in this invention, by optimizing and enhancing the representation consistency between view pairs, endows the feature extractor with powerful self-supervised learning capabilities. Since the model can spontaneously learn high-quality feature representations with invariance from unlabeled large-scale samples, it significantly reduces the dependence on large-scale labeled samples, improving generalization performance and convergence speed in small-sample scenarios.
[0042] Meanwhile, by freezing the pre-trained feature extractor parameters and connecting them to the classification head, this invention achieves a smooth transfer from general spectral pattern learning to specific drug resistance discrimination tasks. Since the classification process directly operates on the feature vector obtained from global aggregation of embedded labels, and the feature extractor retains the feature associations obtained from modeling, it can output highly robust and accurate drug resistance detection results.
[0043] Therefore, by combining topological persistent feature extraction with interpretable contrastive learning networks, this invention significantly improves the robustness of mass spectrometry signal representation and reduces the dependence on labeled samples. It also utilizes attention mechanisms and aggregation logic to eliminate the black-box nature of the decision-making process, achieving highly accurate and clinically reliable detection of Klebsiella pneumoniae drug resistance.
[0044] To better understand the above technical solutions, exemplary embodiments of the present invention will be described in more detail below with reference to the accompanying drawings. Although exemplary embodiments of the present invention are shown in the drawings, it should be understood that the present invention can be implemented in various forms and should not be limited to the embodiments set forth herein. Rather, these embodiments are provided so that the present invention can be understood more clearly and thoroughly, and that the scope of the present invention can be fully conveyed to those skilled in the art.
[0045] Specifically, embodiments of the present invention provide a method for detecting drug resistance in Klebsiella pneumoniae, comprising:
[0046] S1. Obtain and preprocess the raw mass spectrometry data of the test strain to obtain the mass spectrometry signal sequence.
[0047] Furthermore, such as Figure 2 As shown, step S1 includes:
[0048] S11. Obtain the protein fingerprint of the strain using a mass spectrometer, and resample the protein fingerprints of different samples to align all samples to a mass-to-charge ratio axis to generate raw mass spectrometry data.
[0049] The data for this study came from 61 patients diagnosed with Klebsiella pneumoniae infection during their hospitalization at the Second Hospital of Tianjin Medical University from October 2023 to May 2025. The patients ranged in age from 44 to 95 years, with a mean age of 69 years. A total of 61 clinical isolates of Klebsiella pneumoniae were collected from sputum, urine, blood, or pus samples, including 50 carbapenem-resistant strains (CRKP) and 11 carbapenem-sensitive strains (CSKP). This test was approved by the Ethics Committee of the Second Hospital of Tianjin Medical University (Approval No.: KY2025K281), and all participants signed informed consent forms. Inclusion criteria were patients diagnosed with Klebsiella pneumoniae infection (including lung, urinary tract, bloodstream, or other site infections) based on symptoms, imaging, and laboratory examinations. Exclusion criteria included improper specimen collection, potential environmental microbial contamination, or the presence of colonizing bacteria. The determination of bacterial resistance was based on the drug susceptibility test of the VITEK2-Compact system (specifically, the blood agar plates for culture were purchased from Beijing Luqiao Technology Co., Ltd.; the turbidimeter, VITEK MS microbial mass spectrometry identification and analysis system, VITEK 2-Compact identification / drug susceptibility analysis system and matching target plates, matrix solutions, drug susceptibility plates and other consumables were all products of bioMérieux, France). Based on the drug susceptibility results, fully sensitive strains and carbapenem-resistant strains (resistant to two or more of the three antibiotics meropenem, imipenem and ertapenem) were selected.
[0050] First, prepare for bacterial strain identification and testing: Step 1, pick a single colony and prepare a 0.5 McFarland turbidity bacterial suspension using 3 mL of 0.45% NaCl solution (pH 4.5-7.2); Step 2, remove the Gram-negative (GN) identification card and allow it to warm to room temperature for 15-20 minutes; Step 3, place the test cards in sequence on the card holder and insert the sample delivery tube into the bacterial suspension tube (0.5 McFarland turbidity). Place the antimicrobial susceptibility test card after the paired identification card and insert the sample delivery tube into the bacterial suspension tube (0.5 McFarland turbidity, then diluted 20 times); Step 4, access the VITEK2COMPACT application software main interface. Scan the barcode on the card holder. Perform the instrument test and view the results after all instrument operations are complete.
[0051] Subsequently, after purification by blood agar plates, single colonies were picked and evenly spread onto a mass spectrometry target plate. A sterile pipette tip was used to apply 1 μl of matrix solution to each well on the target plate containing the sample. The plates were then air-dried at room temperature. After drying, the samples were analyzed using Vitek-MS RUO mode to acquire protein spectra. The raw spectra were converted to mzXML format using MSConvert software. A custom Python script was then used to perform resampling, aligning all individual mass spectra to a uniform mass-to-charge ratio (m / z) axis, generating the desired result. Figure 3 The raw mass spectrometry data in (a).
[0052] S12. A polynomial smoothing filter algorithm is used to perform local polynomial least squares fitting on the original mass spectrometry data within a preset sliding window. The amplitude of each data point in the original mass spectrometry data is updated through convolution mapping to generate smoothed mass spectrometry data. For initial data containing noise and background signals, this step uses a Savitzky-Golay filter. The window length is set to 11, and a third-order polynomial is used to perform local polynomial least squares fitting on the original mass spectrometry data. Convolution mapping effectively suppresses high-frequency noise, thus achieving spectral smoothing while preserving the true characteristic signals, generating smoothed mass spectrometry data as shown below. Figure 3 Smoothed mass spectrometry data in (b).
[0053] S13. An asymmetric reweighted penalized least squares algorithm is used to perform background estimation on the smoothed mass spectrometry data. During the iterative calculation of background estimation, the residual distribution is calculated using the initially established estimated baseline and the amplitude of the smoothed mass spectrometry data to allocate asymmetric weights. These asymmetric weights are then used to weight and penalize the smoothed mass spectrometry data to construct a background baseline. The background baseline is then subtracted from the smoothed mass spectrometry data to extract the true ion intensity signal. During the iterative calculation, asymmetric weights are allocated by comparing the relative positions of the smoothed mass spectrometry data amplitude and the initially estimated baseline: when the smoothed mass spectrometry data amplitude is higher than the estimated baseline (i.e., the residual is positive), the region is identified as a potential characteristic peak signal, and a very low weight coefficient close to 0 is assigned to this point to greatly reduce the interference of the characteristic peak on the baseline fitting; when the smoothed mass spectrometry data amplitude is lower than or close to the estimated baseline (i.e., the residual is negative or tends to zero), the region is identified as background noise, and a high weight coefficient tending to 1 is assigned to this point. A second-order difference penalty term is introduced to constrain the smoothness of the baseline, and asymmetric weights are used to perform asymmetric weighted penalties on the residuals of different regions. After multiple iterations until the weight distribution stabilizes, a background baseline capable of accurately tracking the bottom of the waveform is finally constructed. Figure 3 As shown in (c), the instrument background and chemical noise are removed by subtracting the obtained background baseline from the smoothed mass spectrometry data, and the true ion intensity signal is extracted.
[0054] S14. The true ion intensity signal after background subtraction is normalized and feature-scaled to obtain a mass spectrometry signal sequence consisting of data tags, mass-to-charge ratios, and corresponding ion intensities. To eliminate the differences in bacterial density during target plate application, uneven thickness during matrix drying, and random fluctuations in ionization efficiency during instrument detection among the 61 samples, this embodiment performs total ion intensity normalization on the extracted true ion intensity signal. This process uses the sum of ion intensities of each sample across the entire spectrum as a benchmark, and divides the intensity value of each data point in the sequence by this sum to ensure that the response intensities of different strains are compared at the same order of magnitude. Subsequently, feature scaling is used to linearly map the normalized intensity values to a preset numerical range (e.g., [0,1]). Finally, using a Python script, the processed data is correlated with the drug resistance tags (CRKP for resistance, CSKP for sensitivity) determined by drug susceptibility testing to generate a mass spectrometry signal sequence containing data tags, mass-to-charge ratio positions, and ion intensity values. Among them, ion intensity provides the original dimensional basis for subsequent calculation of topological durability; data labels are mapped to mass spectrometry signal sequences and used as true labels to calculate cross-entropy loss when fine-tuning model parameters, so as to supervise and optimize the model's classification network.
[0055] To meet the input requirements of deep learning models for large-scale structured data, this step uses a Python script to convert the above mass spectrometry signal sequence into the standard mzML format, and further extracts and generates the final dataset in CSV format. In this CSV file, each row represents an independent Klebsiella pneumoniae sample, and the column features fully cover the mass-to-charge ratio axis (m / z) and the corresponding ion intensity after resampling and alignment.
[0056] S2. The topological durability is determined based on the difference between the local maximum point in the mass spectrometry signal sequence and the higher of the two adjacent local minimum points, and the characteristic peaks are selected based on the topological durability to construct an ordered characteristic sequence.
[0057] Furthermore, such as Figure 4 As shown, step S2, which determines topological durability based on the difference between a local maximum point in the mass spectrum signal sequence and the higher of its two adjacent local minimum points, includes:
[0058] S21. Traverse each data sampling point in the mass spectrometry signal sequence, compare the ion intensity of the current sampling point with its previous and next neighboring points, identify the local maximum point where the ion intensity is greater than the two neighboring points, and record the corresponding sampling position index to construct a candidate peak set.
[0059] In this step, the mass spectrometry signal sequence is first defined as a set of discrete data points acquired by the mass spectrometer, denoted as: Where N* is the total number of discrete data points, m i I represents the mass-to-charge ratio (m / z) of the i-th data point in the data point set. i I(m) represents the ion intensity of the i-th data point. i ) represents m i Ion intensity at a given location. To identify local maxima, this embodiment focuses on a data point p in the mass spectrometry signal sequence S. j =(m j ,I(m j Perform a logical judgment: if its ionic strength satisfies the local maximum judgment condition I(m) j )>I(m j-1 )∩I j >I(m j+1 If p is a given point, then p is a given point. j A point identified as a local maximum is denoted by its index j. All points satisfying this condition constitute the set of candidate peaks: Peaks = {p1, p2, ..., p...} k ,……,p l}, where p k Let p be the k-th peak, and l be the number of local maxima. For any candidate peak p in the set... k Its coordinates are recorded as (m k ,I(m k )), m k It is the mass-to-charge ratio at the peak, I(m) k ) is the ionic strength corresponding to the mass-to-charge ratio.
[0060] S22. For each candidate peak in the candidate peak set, starting from the corresponding sampling position index, perform bidirectional gradient detection along the mass-to-charge ratio axis until the first sampling point with an ion intensity less than the intensity of the adjacent points on both sides is obtained on both sides. These points are then identified as the left local minimum point and the right local minimum point closest to the candidate peak point.
[0061] This step uses iterative search to precisely locate the topological boundary of each candidate peak. Referring to the minimum ion intensity search algorithm, let p... k The position index is j peak The step size is 1 data point: During the search on the right, starting from position index j peak+1 Starting from the nearest point, iterate in the direction of increasing mass-to-charge ratio, using the local minimum criterion I(m) to determine the value. j )<I(m j-1 )∩I j <I(m) j+1 The comparison is performed point by point. Once the first point that meets the conditions is found, it is determined as the nearest local minimum point p on the right. minR (m minR ,I(mminR Similarly, in the left-hand search, a completely symmetric logic is used from index j. peak-1 Traverse in the direction of decreasing mass-to-charge ratio until the first sampling point that satisfies the local minimum criterion is found, and determine it as the nearest local minimum point p on the left. minL (m minL ,I(m minL Through this bidirectional detection logic, a topological closed-loop interval consisting of adjacent local minima is determined for each candidate peak.
[0062] S23. Obtain the intensity values of the local minimum points on the left and right sides and compare their amplitudes. Select the intensity of the side with the higher amplitude as the terrain reference boundary intensity characterizing the local waveform envelope. By comparing I(m minL ) and I(m minR The size of ) is taken as its maximum value max(I(m) minL ),I(m minR This serves as a reference benchmark for quantifying the significance of the peak. Since mass spectrometry signals are often accompanied by baseline drift or overlapping of adjacent peaks, this step uses amplitude comparison logic to select the valley intensity value on the higher side as the topographic reference boundary intensity. This selection strategy effectively filters out spurious significance caused by unilateral background noise fluctuations, ensuring the robustness of the reference benchmark.
[0063] S24. The topological height of each candidate peak point relative to the local waveform envelope is quantified by calculating the intensity difference between the candidate peak point and the terrain reference boundary, thus obtaining the topological durability corresponding to each candidate peak point. This step introduces the topological durability P(p k The significance of a peak is quantified by the formula: P(p) k )=I(m k )-max(I(m minL ),I(m minR )).like Figure 5 As shown, the calculation process details the difference between the peak intensity and the intensity of the valley on the higher side on both sides. By performing this calculation on each local maximum point in the signal (such as the peaks at m / z≈17 and m / z≈75), the topological height value of each candidate peak relative to the local waveform envelope can be obtained, mapping the traditional absolute intensity to the topological height, thereby eliminating the interference of the background baseline on peak identification in subsequent screening.
[0064] Furthermore, such as Figure 6 As shown, step S2, which involves filtering feature peaks based on topological persistence to construct an ordered feature sequence, includes:
[0065] S25. Extract candidate peaks with topological persistence greater than zero as effective feature peaks reflecting the heterogeneity of Klebsiella pneumoniae discrete drug resistance protein fingerprints, and rearrange the effective feature peaks in descending order of topological persistence value. To accurately capture the fingerprint characteristics of Klebsiella pneumoniae drug resistance proteins, this step implements an effective peak selection strategy: a candidate peak is selected if and only if p... k Topological durability P(p k When the peak duration is greater than or equal to 0, it is defined as a valid peak. This criterion ensures that only peaks that are truly higher than their local counterparts are retained, while "shoulder peaks" or noise fluctuations with a duration less than or equal to zero are filtered out. The final output set of initial valid peaks is as follows: , where M is the total number of valid peaks. Subsequently, all valid peaks in the initial valid peak set D are sorted in descending order of their persistence.
[0066] S26. Based on the rearranged positional order, the first preset number of effective feature peaks are truncated to form a fixed-length feature set. To construct a regular input suitable for deep learning models and achieve feature dimensionality reduction, this embodiment selects the most significant top N peaks (N=50 in this embodiment) from the initial effective peak set D to obtain the fixed-length feature set. ,in This represents the j-th peak after sorting. Through this Top-N selection mechanism, the variable-length original mass spectrometry data is compressed into a fixed-length feature vector, achieving effective feature dimensionality reduction and noise filtering while preserving the core protein fingerprint information.
[0067] S27. When the total number of valid feature peaks does not reach the preset input quantity, zero-value padding is performed on the fixed-length feature set using virtual zero-peak nodes synthesized from zero mass-to-charge ratio and zero topological durability, until the fixed-length feature set meets the preset input quantity. Considering that the number of peaks M detected by different samples may be less than the preset value N, if the total number of valid peaks of the samples is insufficient, "virtual zero-peaks" (m / z=0, P=0) are used for padding until the dimension of the feature set reaches a fixed N. This ensures that all input samples are consistent in spatial dimension. This padding mapping ensures tensor alignment of the model during batch processing, while not introducing spurious technical features.
[0068] S28. Extract the mass-to-charge ratio and topological durability of each effective feature peak in a fixed-length feature set that meets the preset input quantity. Assemble these peaks according to their rearranged positions to generate an ordered feature sequence characterized by numerical pairs corresponding to the mass-to-charge ratio and topological durability. Ultimately, each sample is represented as a structured peak list of fixed length N. To adapt to the subsequent Transformer model, extract the mass-to-charge ratio information of each peak to construct the m / z tensor T. mz This is used to generate positional codes; simultaneously, the extracted topological durability is encapsulated in an intensity tensor, mapped to an intensity embedding tensor T in a high-dimensional space.I This transforms discrete physical intensity features into a deep representation that can be understood by a neural network, enabling the feature extractor to focus on signal components with biophysical significance.
[0069] S3. Enhancement processing is performed on the ordered feature sequence to obtain enhanced view pairs. Each enhanced view is mapped to a position encoding tensor and an intensity embedding tensor, respectively, and the input sequence is constructed by combining the embedding labels. In the framework of contrastive learning, data augmentation is not only a means to expand the dataset, but also a fundamental mechanism for constructing a self-supervised learning paradigm and providing core supervisory signals. In this embodiment, by preprocessing the topological features extracted from the original mass spectrometry data and applying strategies such as random peak loss and peak intensity perturbation, two "enhanced views" that are both different and retain core information are generated, thereby constructing positive sample pairs for contrastive learning.
[0070] Furthermore, such as Figure 7 As shown, step S3 includes:
[0071] S31. Perform random peak loss processing on the ordered feature sequence. Determine the number of peaks to remove based on a preset masking ratio and perform random sampling without replacement to remove feature peaks in the corresponding positions, generating a masked feature sequence. This step aims to force the subsequent model to learn a more distributed feature representation by randomly deleting some feature peaks, thereby reducing the risk of overfitting and improving generalization ability. The specific method is as follows: The goal is to make the ordered feature sequence F peaks Transformed into the masked sequence F masks First, determine the number of covers, k, calculated as follows: (in This is the floor function. (For the preset masking ratio). Then, random sampling without replacement is performed from the index set {1,2,...,N} of all peaks to select k indices to form the masking index set M, satisfying... Finally, from the ordered feature sequence F peaks Remove all peaks whose indices are in set M to obtain the masked feature sequence. P i This refers to the topological durability of the i-th retained characteristic peak, m i Let N' be the mass-to-charge ratio corresponding to the i-th retained characteristic peak, at which point the number of peaks is reduced to N'=Nk.
[0072] S32. Perform amplitude perturbation processing on the topological durability component in the masked feature sequence, and obtain semantically consistent enhanced view pairs by superimposing random noise with a mean of zero and a standard deviation positively correlated with the average topological durability, and performing numerical correction based on the zero lower limit discrimination.
[0073] After removing some peaks, a small, random variation is added to the height (intensity) of each remaining peak. This step aims to simulate real-world errors and improve model stability. Specifically, this step involves applying a masked feature sequence... The above steps aim to add reasonable noise to the persistence values of the retained peaks. Specifically, noise is first sampled from a zero-mean normal distribution, with a standard deviation σ... noise It is proportional to the average persistence of the original spectrum, i.e. To ensure that the noise level is reasonable, among which, It is the original spectrum. Average durability strength, This is a control coefficient defining the percentage of noise fluctuation amplitude relative to the average ion intensity of the entire spectrum, determined by historical data. For F... masks Each peak (m') j ,P' j Independent sampling noise value The intensity is then arithmetically added to the original intensity. Since the ion intensity may become negative after adding noise, a ReLU function (taking the maximum value between 0 and the new intensity) is used for numerical correction to ensure that the physically meaningful intensity is not negative. The final enhanced ion intensity is... I j ' The strength before the j-th perturbation. The resulting enhanced sample. This constitutes the enhanced view.
[0074] S33. Extract the topological persistence components of each feature peak in the enhanced view pair and transform them into feature intensity scalars that characterize the peak response amplitude. Map the feature intensity scalars to a feature representation space with multidimensional components by performing a linear spatial dimension transformation to generate an intensity embedding tensor.
[0075] This step corresponds to the intensity embedding tensor T in the mathematical description of the feature. I The construction. For those containing For each batch of samples, the peak persistence information (intensity) retained in each enhanced view is transformed into a tensor:
[0076] ;
[0077] In the formula, this tensor contains the durability information of each peak, where, Represents the intensity embedding tensor. This represents the scalar value representing the single-peaked durability feature after data augmentation. This indicates the fixed sequence length of the input model. R represents the batch size of the model. B×NThis represents the dimension definition of the real-valued feature space in which the tensor resides. It is used to generate the feature embeddings for the Transformer model.
[0078] S34. Extract the mass-to-charge ratio of each feature peak in the enhanced view pair and perform periodic coordinate mapping based on sine and cosine logic. Use the periodic dimensional components generated by the mapping to synthesize a position space vector with multi-dimensional components, generating a position encoding tensor reflecting the spatial distribution characteristics of the mass-to-charge ratio. This step corresponds to the position encoding tensor T of the mass-to-charge ratio. mz The model is constructed by extracting the mass-to-charge ratio information of each peak to generate the model's positional encoding, thus preserving the spatial relationship of the peaks along the mass spectrum axis. Its mathematical expression is as follows:
[0079] .
[0080] In the formula, the tensor It includes mass-to-charge ratio information for each peak. Among them, This represents the unimodal mass-to-charge ratio coordinate scalar after data augmentation, where B represents the batch size, N represents the fixed sequence length of the input model, and R... B×N This represents the dimension definition of the real-valued feature space in which the tensor resides.
[0081] S35. Initialize the embedding token representing the global correlation information of the entire spectrum, and concatenate the embedding token to the beginning of the combined sequence of the intensity embedding tensor and the position encoding tensor, constructing the input sequence through dimensional concatenation. Through the above steps, this embodiment transforms the raw, variable-length, high-dimensional mass spectrometry data into a structured, fixed-dimensional model input. Based on this, a learnable embedding token (such as the [CLS] token) is initialized and dimensionally concatenated with the intensity embedding tensor and the position encoding tensor. This construction method provides a high-quality feature foundation for the subsequent Transformer model to accurately capture the complex nonlinear correlations between peaks, realizing the transformation from discrete data points to global semantic representation.
[0082] S4. The input sequence is fed into an interpretable contrastive learning network containing a feature extractor and a projection head. An attention mechanism is used to model the spatial dependencies and co-expression associations between feature peaks. The projection head maps the association information obtained from the global aggregation of embedded labels to obtain contrastive representation vectors. Contrastive learning is used to optimize the consistency of the contrastive representation vectors to update the feature extractor parameters. This stage is the self-supervised contrastive learning pre-training stage. This embodiment also implements a deep learning framework called ICon-Trans KPnet, designed for accurate classification of CRKP and CSKP. This framework innovatively integrates contrastive learning and a Transformer structure: the former is used to extract discriminative characterizations of bacterial strains from MALDI-TOF mass spectrometry, while the latter serves as a powerful classification backbone network.
[0083] Furthermore, such as Figure 8 As shown, step S4 includes:
[0084] S41. Utilizing the multi-head attention mechanism in the feature extractor, feature vectors containing mass-to-charge ratio location information and response intensity information in the input sequence are mapped in parallel. By calculating the correlation weights between different feature vectors and performing weighted summation, the spatial dependence and co-expression correlation between each feature peak are modeled.
[0085] The feature extractor consists of four Transformer blocks stacked sequentially. In this feature extractor, each layer receives the output of the previous layer as input and produces the output of the current layer. Each Transformer block integrates two core sub-layers: a multi-head self-attention network and a positional feedforward network, and is combined with layer normalization technology. This layer normalization technology effectively improves the standardization of feature representation by forcing the input and output data of each neural network layer to a standard distribution, thereby ensuring the stability of deep networks during model training.
[0086] Transformers require vector representations of uniform dimension as input, therefore they need to map the original low-dimensional features to... The embedding space of dimension T. Specifically, the intensity embedding tensor T I First, project the linear mapping Linear(·) onto the target object. The feature space is 3D, while the position encoding tensor T mz The corresponding position encoding function PE(·) is used to generate the corresponding position encoding function. A position vector. The final sum of these two vectors forms the peak's representation vector: In this context, Linear(·) is used to embed and map the intensity features, while PE(·) is used to inject the position information of the mass spectrum peaks, thus together forming the input representation of the Transformer.
[0087] Furthermore, the core mechanism of multi-head self-attention (MHSA) captures the dependencies between spectral peaks through h=8 parallel attention heads. For each head j, query Q is computed. j Key K j Sum V j Interaction: .in It is the dimension of each head; the output of a single attention head is... The result is calculated by a function. The core process of this function is: first, by querying the matrix... AND key matrix The original relevance score is calculated using matrix multiplication and then scaled; then, using... The function normalizes these scores into a probability distribution that sums to 1, known as the "attention weights"; finally, these weights are applied to the value matrix. A weighted summation is performed to generate an output representation rich in contextual information. Next, the output vectors of all h=8 attention heads are concatenated to link the vectors from multiple independent perspectives, and then linearly projected again to obtain the final MHSA output. ,in, Its function is to concatenate multiple independent vectors end-to-end. This mechanism effectively captures the combination patterns between multiple feature peaks in the mass spectrum by calculating the association weights and weighted summation of each feature vector in the input sequence that contains mass-to-charge ratio position information and response intensity information, thereby achieving accurate modeling of the spatial dependence and co-expression association between feature peaks.
[0088] S42. The position-wise nonlinear transformation of the sequence obtained by weighted summation is performed using the position feedforward network in the feature extractor, and combined with layer normalization processing, the embedding label corresponding vector of the last layer output of the feature extractor is extracted as the global feature vector for aggregating global association information.
[0089] For each layer output X'(l), a nonlinear transformation is performed through a position feedforward network (FFN): FFN(x) = ReLU(xW1 + b1)W2 + b2, where, It is a non-linear activation function, and its calculation formula is: By combining normalization techniques to ensure the standardization of data distribution, W1 and b1 are used as the first-layer weights and biases to map the input features to a higher-dimensional intermediate space. W2 and b2 are used as the second-layer weights and biases to project the high-dimensional intermediate features back to the original dimension. After four layers of processing, the first output vector corresponding to the [CLS] embedding label is extracted as the global feature representation of the entire mass spectrum. .
[0090] S43. The linear adapter layer in the projection head is used to adjust the dimensionality of the global feature vector and input into the multilayer perceptron to perform nonlinear mapping, so as to obtain the contrast representation vectors corresponding to different augmented views in the feature space.
[0091] Extracted global feature vector h enc Then, after two consecutive modules: first, the encoder adapter reduces the dimension from d through a linear layer. out (64) Adjusted to d model (128), we get h adapted =W adapter •h enc +b adapter W adapter and b adapterLet h represent the learnable weight matrix and bias vector of the encoder adapter, respectively. adapted h enc The transitional feature vector obtained after the adapter linear transformation is then fed into the projection head (a multilayer perceptron (MLP) consisting of Linear→ReLU→Linear), which maps the features to the low-dimensional embedding space used for the final contrastive loss calculation, resulting in the final representation vector: z=g(h adapted =W2ReLU(W1•h adapted +b1)+b 2, Where g(·) represents the mapping function of the projector, W1 and b1 represent the learnable weight matrix and bias vector of the first layer of the projector MLP, respectively, ReLU represents the modified linear unit activation function, and W2 and b2 represent the learnable weight matrix and bias vector of the second layer of the projector, respectively. This final vector This is the core representation used to calculate the loss function in the contrastive learning framework.
[0092] For positive sample pairs (S) generated by data augmentation a ,S b ), respectively output the representation vector z a With z b The shared Transformer encoder outputs global feature vectors for each of them. These two vectors are then fed into a non-linear projection head. In your implementation, the projection head consists of a multilayer perceptron (MLP): ,in These are the learnable parameters of the projection head. This step maps the features from the encoder space to a lower-dimensional embedding space that is more suitable for calculating the contrastive loss, resulting in the final vector representation. .
[0093] S44. Calculate the cosine similarity between enhanced view pairs using the contrast representation vector, and introduce a temperature hyperparameter to perform scaling processing on the similarity distribution, so as to construct a normalized consistency loss index for measuring the distribution consistency between enhanced views.
[0094] In this embodiment, normalized temperature-scaled cross-entropy loss (NT-Xent) is used. In a batch containing B original samples, a total of 2B enhanced representation vectors are obtained. For positive sample pairs (z) i ,z j The enhanced view pair, whose loss function Defined as:
[0095] ;
[0096] in, Let be the cosine similarity between two vectors. Indicates that the batch excluding z i Other sample feature vectors, The temperature hyperparameter is used to adjust the sharpness of the distribution, controlling the sharpness of the softmax function distribution. The numerator of this formula aims to maximize the positive sample pairs. The similarity between them, while the denominator includes the similarity with all other items in the batch. One sample (including one positive sample and...) The similarity to (a negative sample) is calculated, with the aim of minimizing the similarity to the negative sample.
[0097] S45. Perform representation consistency optimization with the loss metric as the target. Calculate the gradient of the loss metric with respect to the network model parameters using backpropagation, and simultaneously update the weight parameters of the feature extractor and projector. The final loss for the entire batch. It is the mean of the loss for all positive sample pairs. Let the th... The number of positive sample pairs is ,but: , The comparison loss term, with (2k-1, 2k) and (2k, 2k-1) summed in the formula, signifies that the model needs to simultaneously optimize "augmented view A is closer to augmented view B" and "augmented view B is closer to augmented view A" to ensure symmetry. The loss function is calculated using the backpropagation algorithm. For model parameter vectors (Includes Transformer encoder parameters) and projector head gradient of ) Then, the optimizer is used to update the parameters: ,in, It is the learning rate. By iterating this process across the entire dataset, the model is driven to learn a powerful encoder capable of generating high-quality, invariant features.
[0098] S5. Freeze the feature extractor parameters, remove the projection head and connect the classification head, perform supervised adjustment using labeled samples, map the association information re-aggregated by the embedded labels through the classification head to obtain the co-representation vector, and perform discrimination on the co-representation vector to output the drug resistance detection result. This stage is the supervised fine-tuning stage for the downstream classification task. Using the pre-trained feature extractor, the final drug resistance identification is completed with a small amount of labeled data.
[0099] Furthermore, such as Figure 9 As shown, step S5 includes:
[0100] S51. Set the model parameters of the feature extractor to a non-updateable state to lock the collaborative correlation modeling capability between the feature peaks obtained from contrastive learning. Remove the projection head and connect a classification head containing a linear layer to the output of the feature extractor. Load the Transformer encoder parameters obtained in the pre-training stage and set them to a frozen state. Remove the non-linear projection head used for self-supervised learning and connect a new lightweight classification head.
[0101] S52. Input the labeled Klebsiella pneumoniae drug-resistant sample sequences into the feature extractor. A multi-head attention mechanism is used to perform parallel mapping on the feature vectors. Embedded tags then perform global aggregation on the feature components reflecting the full spectrum of correlation information to obtain a feature vector aggregating the full spectrum information. The labeled samples, after preprocessing, are input into the frozen encoder, which uses its learned information to perform parallel mapping on the complex dependencies between feature peaks. The [CLS] embedded tags, through multi-layer attention weight allocation, aggregate the drug resistance fingerprint features in the full spectrum and output a global feature vector.
[0102] S53. Using a classification head, the feature vector aggregating full-spectrum information is mapped into a collaborative representation vector for drug resistance discrimination. Based on the difference between the collaborative representation vector and the drug resistance label, a classification loss metric is constructed to measure discrimination accuracy. The classification head will... enc The mapping is used to construct a collaborative representation vector for CRKP or CSKP discrimination. A classification loss metric for supervised learning is built by calculating the cross-entropy between the predicted class probability and the true drug resistance label.
[0103] S54. Keeping the feature extractor parameters fixed, backpropagation is used to iteratively optimize only the model parameters of the classification head based on the classification loss metric, thereby achieving supervised adjustment of the discriminative ability of the co-representation vector. In this process, the feature extractor acts only as a static feature extraction module. By updating only the parameters of the classification head through backpropagation, the model can efficiently transfer deep knowledge learned on large-scale unlabeled data to a limited number of specific classification tasks.
[0104] S55. Using the supervised adjustment of the classification head, class probability mapping is performed on the collaborative representation vector to output the drug resistance detection results of Klebsiella pneumoniae. After adjustment, the model outputs the probability score of whether a sample belongs to CRKP or CSKP through the classification head, thereby achieving accurate drug resistance detection. This "pre-training-fine-tuning" mode significantly reduces the dependence on expensive labeled data while ensuring extremely high detection accuracy.
[0105] This invention validates the superiority of the proposed scheme through a series of comparative experiments, focusing on three dimensions: feature effectiveness, model advancement, and clinical generalization ability. First, the topological feature extraction method is validated. Comparative experiments show that, under various machine learning models such as Random Forest, SVM, and XGBoost, both topological features and fused features significantly outperform the original features based on basic processing. Particularly in ensemble learning algorithms, topological features, due to their robustness to noise-induced positional drift, achieve classification accuracy close to or exceeding 0.98, demonstrating that the peak detection method based on topological persistence can effectively capture significant peak signals with discriminative power.
[0106] Subsequently, addressing the practical scenario of scarce labeled data in clinical settings, this study compared the performance of ICon-TransKPnet with traditional models on a dataset containing only 30% labeled samples. As shown in Table 1 below, our method effectively mined the latent information in 70% of the unlabeled samples through a self-training mechanism, achieving an accuracy of 95.13% and a Macro F1 score as high as 0.9152. This significantly outperforms traditional fully supervised machine learning models and CNN baselines limited by sample size, demonstrating the powerful representation capabilities of the Transformer architecture in a semi-supervised setting.
[0107] Table 1. Accuracy and F1 score of the model in this paper compared with different machine learning models on the dataset (5-fold cross-validation).
[0108]
[0109] To further verify that the performance improvement stems from a customized "topology-aware" strategy rather than a general paradigm, experiments were conducted with a fixed backbone network to compare with different contrastive learning frameworks. As shown in Table 2, our proposed method outperforms general frameworks such as SimCLR, MoCo, and DINOv2 under the same 30% annotation ratio, confirming that the random peak loss and intensity perturbation strategy designed for mass spectrometry characteristics can learn more robust topology-invariant features. Furthermore, satisfactory results were achieved in the generalization test on the public dataset DRIAMS-A (as shown in Table 3), demonstrating the model's adaptability to different bacterial and drug-resistant types.
[0110] Table 2. Accuracy and F1 score of the model in this paper compared with different contrastive learning frameworks (5-fold cross-validation) on the dataset.
[0111]
[0112] Table 3. Comparison of the proposed model with different machine learning models on the publicly available dataset DRIAMS-A against Staphylococcus aureus.
[0113]
[0114] Furthermore, to gain a deeper understanding of the internal decision-making mechanism of the ICon-Trans KPnet model of this invention and to uncover the key biomarkers it identifies, the interpretability analysis of the model's classification criteria was conducted using the inherent self-attention mechanism of its Transformer architecture. By visualizing the attention scores of each mass spectrometry peak in a single sample, the core features upon which the model relies in distinguishing between drug-resistant strains (CRKP) and susceptible strains (CSKP) can be clearly identified.
[0115] like Figure 10 As shown, this analysis reveals clear and highly differentiated decision-making patterns. For the classification of drug-resistant strains (CRKP, labeled 0), the model assigned the highest attention weight (Attention Score ≈ 0.166) to the mass spectrometry peak at m / z 306.0 Da, while also showing high attention to peaks in regions such as 1763.0 Da and 1955.0 Da. This indicates that the peak at m / z 306.0 Da is a key biomarker for the model to identify CRKP strains. Conversely, when identifying susceptible strains (CSKP, labeled 1)... Figure 11 The model's decision focus shifted significantly. At this point, the mass spectrometry peak with m / z of 411.0 Da received the highest attention score (Attention Score≈0.169), becoming the most important basis for determining that the strain was CSKP, while multiple peaks such as m / z of 1639.0 Da and 1830.0 Da served as auxiliary features.
[0116] Therefore, the model constructed in this invention not only performs excellently in classification tasks, but its interpretability analysis further demonstrates that it can automatically learn discriminative features with clear biological significance. Mass spectrometric peaks at approximately 306.0 Da and 411.0 Da were identified by the model as the most important differential peaks distinguishing CRKP and CSKP strains. This finding not only verifies the effectiveness and reliability of the model, but also provides clear and reliable data-driven clues for subsequent mass spectrometry validation and in-depth research on carbapenem resistance mechanisms.
[0117] Furthermore, this invention provides a Klebsiella pneumoniae drug resistance detection system, comprising: a preprocessing module for acquiring and preprocessing the raw mass spectrometry data of the test strain to obtain a mass spectrometry signal sequence; a feature selection module for determining topological persistence based on the difference between the local maximum point in the mass spectrometry signal sequence and the higher of the two adjacent local minimum points, and selecting feature peaks according to the topological persistence to construct an ordered feature sequence; an input construction module for performing enhancement processing on the ordered feature sequence to obtain enhanced view pairs, mapping each enhanced view to a position encoding tensor and an intensity embedding tensor respectively, and constructing an input sequence by combining embedding tags; and a model training module for using... The input sequence is fed into an interpretable contrastive learning network containing a feature extractor and a projection head. An attention mechanism is used to model the spatial dependence and co-expression associations between feature peaks. The projection head maps the association information obtained from the global aggregation of embedded labels to obtain a contrastive representation vector. Contrastive learning is used to optimize the consistency of the contrastive representation vector to update the feature extractor parameters. A classification module is used to freeze the feature extractor parameters, remove the projection head and connect a classification head, perform supervised adjustment using labeled samples, and map the association information from the re-aggregated embedded labels using the classification head to obtain a co-representation vector. The co-representation vector is then used for discrimination to output the drug resistance detection result.
[0118] Meanwhile, embodiments of the present invention provide a Klebsiella pneumoniae drug resistance detection system device, including: at least one processor; and a memory communicatively connected to the at least one processor; wherein the memory stores instructions executable by the at least one processor, the instructions being executed by the at least one processor to enable the at least one processor to perform the Klebsiella pneumoniae drug resistance detection method as described above.
[0119] Furthermore, embodiments of the present invention provide a computer-readable storage medium storing computer-executable instructions, which, when executed by a processor, implement the method for detecting drug resistance of Klebsiella pneumoniae as described above.
[0120] In summary, this invention provides a method, system, device, and medium for detecting Klebsiella pneumoniae drug resistance based on topological persistence and interpretable contrastive learning networks. Firstly, this invention proposes a topological feature extraction method by evaluating the topological persistence of each characteristic peak in a mass spectrometry signal relative to its local environment. This method directly operates on the peak position with the densest information, effectively overcoming the peak position drift problem caused by insufficient resolution in traditional binning or clustering methods. It transforms the variable-length unstructured spectrum into a high-quality, stable, ordered feature sequence, providing a robust input foundation for subsequent models.
[0121] Subsequently, as Figure 12As shown in sections (a) and (c), this invention constructs a self-supervised contrastive learning framework that utilizes data augmentation strategies involving random peak loss and peak intensity perturbation to create different view representations for ordered feature sequences. A feature extractor incorporating a multi-layer multi-head attention mechanism is used to map the augmented views. By optimizing the consistency of representation vectors across different views, the model can learn robust feature representations from massive amounts of unlabeled mass spectrometry data. This mechanism significantly reduces the reliance on expensive and time-consuming manually labeled data, ensuring excellent model performance even in low-resource scenarios.
[0122] Furthermore, such as Figure 12 As shown in the input embedding section of (b), the model combines sinusoidal position encoding based on mass-to-charge ratio and linear embedding tensor based on intensity during the mapping stage, thereby enabling it to deeply capture long-range dependencies and complex dependency patterns among mass spectral peaks. Furthermore, this study draws on the Physical Information Neural Networks (PINNs) paradigm, constructing a multi-objective loss function driven by a physico-phenotypic synergy by introducing biological consistency loss. This mechanism explicitly embeds the topological physical constraints of mass spectral peaks into the optimization objective, guiding the model from simple data fitting to biophysical mechanism alignment, effectively preventing the model's dependence on spurious correlations, and significantly enhancing its biological rationality and robustness in different clinical settings.
[0123] Ultimately, as Figure 12 As shown in (d), this invention freezes the pre-trained feature extractor parameters and connects them to the classification head, using labeled drug-resistant samples to complete supervised fine-tuning, thus achieving accurate differentiation between drug-resistant and sensitive strains. By leveraging the attention map mechanism, this invention not only achieves excellent classification performance and generalization ability but also successfully reveals key biomarker features of the model's decision-making, opening the "black box" of deep learning at a microscopic level and improving the model's transparency and reliability in clinical auxiliary diagnosis.
[0124] This invention is described with reference to flowchart illustrations and / or block diagrams of methods, apparatus (systems), and computer program products according to embodiments of the invention. It will be understood that each block of the flowchart illustrations and / or block diagrams, as well as combinations of blocks in the flowchart illustrations and / or block diagrams, can be implemented by computer program instructions.
[0125] Although preferred embodiments of the invention have been described, those skilled in the art, upon learning the basic inventive concept, can make other changes and modifications to these embodiments. Therefore, the claims should be interpreted to include both the preferred embodiments and all changes and modifications falling within the scope of the invention.
[0126] Obviously, those skilled in the art can make various modifications and variations to this invention without departing from its spirit and scope. Therefore, if these modifications and variations fall within the scope of the claims of this invention and their equivalents, then this invention should also include these modifications and variations.
Claims
1. A method for detecting drug resistance in Klebsiella pneumoniae, characterized in that, include: The raw mass spectrometry data of the test strain were acquired and preprocessed to obtain a mass spectrometry signal sequence consisting of data tags, mass-to-charge ratio and corresponding ion intensities; The topological durability is determined based on the difference between a local maximum point in a mass spectrometry signal sequence and the higher of its two adjacent local minimum points. Characteristic peaks are then selected based on this topological durability to construct an ordered feature sequence. This process includes: traversing each data sampling point in the mass spectrometry signal sequence, comparing the ion intensity of the current sampling point with its previous and next neighbors, identifying local maximum points with ion intensities greater than those of its two neighbors, and recording the corresponding sampling position indices to construct a candidate peak set; for each candidate peak in the candidate peak set, performing bidirectional gradient probing along the mass-to-charge ratio axis, starting from the corresponding sampling position index, until the first sampling point with an ion intensity less than that of its two neighbors is obtained on both sides, which are then identified as the left and right local minimum points closest to the candidate peak; obtaining the intensity values of the left and right local minimum points and comparing their amplitudes, selecting the side with the higher amplitude as the topographic reference boundary intensity characterizing the local waveform envelope; and quantifying the topological height of the candidate peak point relative to the local waveform envelope by calculating the intensity difference between the candidate peak point and the topographic reference boundary, thus obtaining the topological durability corresponding to each candidate peak point. Enhancement processing is performed on ordered feature sequences to obtain enhanced view pairs. Each enhanced view is mapped to a position encoding tensor and an intensity embedding tensor, and an input sequence is constructed by combining the embedding labels. The enhancement processing includes: performing random peak loss processing on ordered feature sequences, determining the number of removals according to a preset masking ratio and performing random sampling without replacement to remove feature peaks of the corresponding position order, generating a masked feature sequence; performing amplitude perturbation processing on the topological durability components in the masked feature sequence, by superimposing random noise with a mean of zero and a standard deviation positively correlated with the average topological durability, and performing numerical correction based on the zero-value lower limit discrimination, to obtain semantically consistent enhanced view pairs. The input sequence is fed into an interpretable contrastive learning network containing a feature extractor and a projector head. Utilizing the multi-head attention mechanism in the feature extractor, feature vectors containing mass-to-charge ratio location information and response intensity information in the input sequence are interactively mapped in parallel. By calculating the correlation weights between different feature vectors and performing weighted summation, the spatial dependence and co-representation correlation between feature peaks are modeled. The projector head then maps the correlation information obtained from the global aggregation of embedded labels to obtain contrastive representation vectors. Contrastive learning is used to optimize the consistency of the contrastive representation vectors to update the feature extractor parameters. The feature extractor consists of four Transformer blocks stacked sequentially. In the feature extractor, each layer receives the output of the previous layer as input and produces the output of the current layer. Each Transformer block integrates a multi-head self-attention and position feedforward network and applies layer normalization techniques. The feature extractor parameters are frozen, the projection head is removed and the classification head is connected, and supervised adjustment is performed using labeled samples. The association information of the embedded labels is re-aggregated through the classification head to obtain the co-representation vector, and the co-representation vector is discriminated to output the drug resistance detection result.
2. The method for detecting Klebsiella pneumoniae drug resistance as described in claim 1, characterized in that, The raw mass spectrometry data of the test strain were acquired and preprocessed to obtain a mass spectrometry signal sequence consisting of data tags, mass-to-charge ratios, and corresponding ion intensities, including: Protein fingerprints of the strains were obtained using a mass spectrometer, and the protein fingerprints of different samples were resampled to align all samples to a mass-to-charge ratio axis to generate raw mass spectrometry data. A polynomial smoothing filter algorithm is used to perform local polynomial least squares fitting on the original mass spectrometry data within a preset sliding window. The amplitude of each data point in the original mass spectrometry data is updated by convolution mapping to generate smooth mass spectrometry data. An asymmetric reweighted penalized least squares algorithm is used to perform background estimation on smoothed mass spectrometry data. During the iterative calculation of background estimation, the residual distribution is calculated using the initially established estimation baseline and the amplitude of smoothed mass spectrometry data to allocate asymmetric weights. The asymmetric weights are then used to weight and penalize the smoothed mass spectrometry data to construct a background baseline. The background baseline is then subtracted from the smoothed mass spectrometry data to extract the true ion intensity signal. The true ion intensity signal after background subtraction is normalized and feature-scaled to obtain a mass spectrometry signal sequence consisting of data labels, mass-to-charge ratio and corresponding ion intensity.
3. The method for detecting Klebsiella pneumoniae drug resistance as described in claim 1, characterized in that, Feature peaks are selected based on topological persistence to construct an ordered feature sequence, including: Candidate peaks with topological persistence greater than zero are extracted as effective feature peaks reflecting the heterogeneity of discrete drug resistance protein fingerprints of Klebsiella pneumoniae, and the effective feature peaks are rearranged in descending order of topological persistence value. Based on the rearranged positional order, a predetermined number of effective feature peaks are extracted to form a fixed-length feature set; When the total number of effective feature peaks does not reach the preset number of inputs, a virtual zero-peak node composed of zero mass-to-charge ratio and zero topological durability is used to perform zero-value padding mapping on the fixed-length feature set until the fixed-length feature set meets the preset number of inputs. Extract the mass-to-charge ratio and topological durability of each effective feature peak in a fixed-length feature set that meets the preset input quantity, and assemble them according to the position of the rearranged sequence to generate an ordered feature sequence characterized by numerical pairs corresponding to the mass-to-charge ratio and topological durability.
4. The method for detecting Klebsiella pneumoniae drug resistance as described in any one of claims 1-3, characterized in that, Each augmented view is mapped to a position encoding tensor and an intensity embedding tensor, respectively, and the input sequence is constructed by combining the embedding tags, including: The topological persistence components of each feature peak in the enhanced view pair are extracted and transformed into feature intensity scalars that characterize the peak response amplitude. The feature intensity scalars are then mapped to a feature representation space with multidimensional components by performing a linear spatial dimension transformation, generating an intensity embedding tensor. Extract the mass-to-charge ratio of each feature peak in the enhanced view pair and perform periodic coordinate mapping based on sine and cosine logic. Use the periodic dimensional components generated by the mapping to synthesize a position space vector with multi-dimensional components, and generate a position encoding tensor that reflects the spatial distribution characteristics of the mass-to-charge ratio. Initialize the embedding tags that represent the global correlation information of the whole spectrum, and concatenate the embedding tags to the beginning of the combined sequence of intensity embedding tensor and position encoding tensor, and construct the input sequence by dimension concatenation.
5. The method for detecting drug resistance in Klebsiella pneumoniae as described in any one of claims 1-3, characterized in that, The input sequence is fed into an interpretable contrastive learning network containing a feature extractor and a projection head. Utilizing the multi-head attention mechanism in the feature extractor, feature vectors containing mass-to-charge ratio location information and response intensity information in the input sequence are interactively mapped in parallel. By calculating the correlation weights between different feature vectors and performing weighted summation, the spatial dependence and co-representation correlations among feature peaks are modeled. The projection head then maps the correlation information obtained from the global aggregation of embedded labels to obtain contrastive representation vectors. Contrastive learning is used to optimize the consistency of the contrastive representation vectors to update the feature extractor parameters, including: By utilizing the multi-head attention mechanism in the feature extractor, feature vectors containing mass-to-charge ratio location information and response intensity information in the input sequence are mapped in parallel. By calculating the correlation weights between different feature vectors and performing weighted summation, the spatial dependence and co-expression correlation between each feature peak are modeled. The position-wise nonlinear transformation of the weighted summed sequence is performed by the position feedforward network in the feature extractor, and combined with layer normalization, the embedding label corresponding vector of the last layer output of the feature extractor is extracted as the global feature vector for aggregating global association information. The linear adapter layer in the projection head is used to perform dimensionality scaling on the global feature vector and input into the multilayer perceptron to perform nonlinear mapping, so as to obtain the contrast representation vectors corresponding to different augmented views in the feature space; The cosine similarity between augmented view pairs is calculated using contrastive representation vectors, and a temperature hyperparameter is introduced to perform scaling processing on the similarity distribution, so as to construct a normalized consistency loss index for measuring the distribution consistency between augmented views. The representation consistency optimization is performed with the loss metric as the target. Backpropagation is used to calculate the gradient of the loss metric with respect to the network model parameters, and the weight parameters of the feature extractor and the projector are updated synchronously.
6. The method for detecting drug resistance in Klebsiella pneumoniae as described in claim 1, characterized in that, The feature extractor parameters are frozen, the projection head is removed and a classification head is connected, supervised adjustment is performed using labeled samples, the association information of the embedded labels is re-aggregated through the classification head to obtain a co-representation vector, and the co-representation vector is discriminated to output the drug resistance detection result, including: The model parameters of the feature extractor are set to a non-updateable state to lock the collaborative correlation modeling capability between the feature peaks obtained by contrastive learning, the projection head is removed, and a classification head containing a linear layer is connected to the output of the feature extractor. The Klebsiella pneumoniae drug-resistant sample sequences with data tags are input into the feature extractor. The feature vectors are mapped in parallel using a multi-head attention mechanism. The feature components reflecting global correlation information are aggregated by the embedding tags to obtain the feature vectors that aggregate global correlation information. The feature vectors that aggregate global association information are mapped to a collaborative representation vector for drug resistance discrimination using a classification head, and a classification loss index for measuring discrimination accuracy is constructed based on the difference between the collaborative representation vector and the drug resistance category in the data label. Keeping the feature extractor parameters fixed, backpropagation is used to optimize the model parameters of the classification head only based on the classification loss metric, so as to achieve supervised adjustment of the discriminative ability of the collaborative representation vector; The classifier head, after supervision adjustment, is used to perform class probability mapping on the collaborative representation vector, and the drug resistance detection results of Klebsiella pneumoniae are output.
7. A Klebsiella pneumoniae drug resistance detection system, using the method described in any one of claims 1-6, characterized in that, include: The preprocessing module is used to acquire and preprocess the raw mass spectrometry data of the test strain to obtain the mass spectrometry signal sequence; The feature filtering module is used to determine the topological durability based on the difference between the local maximum point in the mass spectrometry signal sequence and the higher of the two adjacent local minimum points, and to filter feature peaks based on the topological durability in order to construct an ordered feature sequence. The input building module is used to perform enhancement processing on the ordered feature sequence to obtain enhanced view pairs, map each enhanced view to a position encoding tensor and an intensity embedding tensor respectively, and construct the input sequence by combining the embedding tags; The model training module is used to input the input sequence into an interpretable contrastive learning network containing a feature extractor and a projection head. It uses an attention mechanism to model the spatial dependence and co-representation association between feature peaks, performs mapping on the association information obtained by the global aggregation of embedded labels through the projection head to obtain the contrastive representation vector, and uses contrastive learning to optimize the consistency of the contrastive representation vector to update the feature extractor parameters. The classification and recognition module is used to freeze the feature extractor parameters, remove the projection head and connect the classification head, perform supervised adjustment using labeled samples, perform mapping on the association information of the embedded labels again through the classification head to obtain the co-representation vector, and perform discrimination on the co-representation vector to output the drug resistance detection result.
8. A system for detecting drug resistance in Klebsiella pneumoniae, characterized in that, include: At least one processor; and memory that is communicatively connected to at least one processor; The memory stores instructions that can be executed by at least one processor, which enables the at least one processor to perform the method for detecting Klebsiella pneumoniae resistance as described in any one of claims 1-6.
9. A computer-readable storage medium storing computer-executable instructions thereon, characterized in that, When the executable instructions are executed by the processor, they implement the method for detecting drug resistance in Klebsiella pneumoniae as described in any one of claims 1-6.