A software defect prediction method based on multi-view learning
By combining source code, comments, and graph structure semantics into a multi-perspective learning approach, the problems of insufficient utilization of perspectives and semantic misalignment in existing technologies are solved, achieving more efficient software defect prediction and improving the expression and prediction performance of complex defect patterns.
Patent Information
- Application Number
- CN202611066178.5
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-17
- Publication Date
- 2026-11-24
AI Technical Summary
Existing software defect prediction methods suffer from insufficient utilization of perspectives and semantic misalignment when using multi-perspective information, resulting in inadequate prediction performance and generalization ability in complex defect scenarios.
By simultaneously utilizing source code, comments, and graph structure semantics, consistency constraints are established. An encoding method combining block-based local modeling and global relational modeling is adopted, along with contrastive learning and gating fusion mechanisms, to achieve cross-perspective semantic alignment and adaptive fusion.
It improves the expressive power and predictive performance of complex defect patterns, alleviates the noise accumulation problem caused by direct splicing of multi-view features, and improves the accuracy and stability of software defect prediction.
Smart Images

Figure CN123157579A_ABST
Abstract
Description
Technical Field
[0001] This invention belongs to the field of software engineering and relates to software defect prediction, specifically to a software defect prediction method based on multi-view learning. Background Technology
[0002] As software scales and development processes become increasingly complex, the number of potential defects in software systems increases significantly. Software defect prediction technology aims to utilize historical software artifacts and program behavior information to identify high-risk modules in code in advance, thereby providing support for test resource allocation, quality assurance, and software maintenance.
[0003] Today, deep learning excels in various machine learning tasks thanks to its ability to process large datasets and its efficient training algorithms. In the field of software defect prediction, existing methods have proposed extracting semantic features from different perspectives, including source code, comment text, abstract syntax trees, and code attribute graphs. While these methods have improved defect identification to some extent, the following problems remain: First, a single perspective is insufficient to fully reflect the formation mechanism of software defects, and modeling often lacks consideration of different perspectives, easily overlooking complementary information between code implementation logic, developer intent, and program dependencies. For example, some methods learn solely based on code metrics or source code sequences, capturing certain syntax and implementation patterns, but failing to effectively characterize developer intent and internal control and data propagation relationships. Some methods introduce additional information such as comment text or abstract syntax trees, which improves model performance to some extent, but still suffer from insufficient utilization of perspectives. Especially in complex defect scenarios, defects are often not determined by a single grammatical fragment, but are related to the combined effects of multiple factors such as developer intent bias, abnormal control dependency chains, and data dependency propagation mismatches. Relying solely on a single perspective is insufficient to comprehensively describe the defect formation mechanism. Secondly, the direct splicing of information from multiple perspectives leads to semantic misalignment between different perspectives and amplification of noise information, affecting prediction performance and generalization ability.
[0004] Against this backdrop, it is necessary to propose a software defect prediction method that can simultaneously utilize multi-perspective semantics and establish consistency constraints, so as to improve the expressive power and prediction performance of complex defect patterns. Summary of the Invention
[0005] To address the shortcomings of existing technologies, this invention proposes a software defect prediction method based on multi-view learning. It utilizes source code, comments, and graph structure semantics, and establishes consistency constraints among multi-view information to improve the expressive power and predictive performance of complex defect patterns.
[0006] A software defect prediction method based on multi-view learning, the specific steps of which are as follows:
[0007] Step 1: Obtain the software sample file to be predicted, which is divided into source code and comment text. Then, preprocess it to obtain the comment input sequence, the code input sequence, and the graph structure input representation of the code.
[0008] As a preferred method, regular expressions are used to divide the software sample file to be predicted into source code and comment text.
[0009] As a preferred approach, for source code, whitespace is cleaned up while indentation is preserved to obtain the code input sequence; simultaneously, all methods contained therein are extracted, and for each method, the Joern static analysis framework is used to generate a corresponding program dependency graph, resulting in a graph structure input representation. For comment text, whitespace is cleaned up while the original format is preserved to obtain the comment input sequence.
[0010] Step 2: Using different encoders, encode the annotation input sequence, code input sequence, and graph structure input representation of the code respectively to obtain annotation perspective representation, code perspective representation, and graph structure perspective representation. For the code input sequence, an encoding method combining block-based local modeling and global relational modeling is used. For the graph structure input representation of the code, an aggregation approach is used for encoding.
[0011] As a preferred approach, word embedding is performed on the annotation input sequence to map it into a word vector sequence, which is then input into a bidirectional long short-term memory network, and the final hidden state is selected as the annotation perspective representation.
[0012] Preferably, the code input sequence is divided into several sub-blocks with a fixed window size. For each sub-block, the encoder of the CodeT5 model is used for local modeling to extract the local semantic representation within each sub-block. Then, the attention relationship between each sub-block is calculated using a Transformer to capture the semantic association between sub-blocks and obtain the overall semantic representation of the sample. Finally, the local semantic representation within each sub-block and the overall semantic representation of the sample are weighted and fused to obtain the code perspective representation.
[0013] As a preferred approach, a graph neural network is used to embed the program dependency graph of each method in the graph structure input representation. First, the corresponding code fragment of each node is extracted and represented as a token sequence. Then, each token sequence is mapped to a low-dimensional continuous space through word embedding. An attention mechanism is used to aggregate the tokens inside the node to generate the initial representation of the node. The information of neighboring nodes is aggregated using a graph propagation mechanism. During the update process, each node simultaneously receives information from control dependency and data dependency paths, thereby forming a method-level graph representation. Finally, each method-level graph representation is weighted and aggregated to obtain the graph structure perspective representation.
[0014] Step 3: Map the code perspective representation, comment perspective representation, and graph structure perspective representation to a unified space. Perform cross-perspective semantic alignment through contrastive learning. Adaptively fuse the semantically aligned multi-perspective representations to obtain a fused representation. Finally, input the fused representation into the defect classifier and output the defect prediction results of the software samples.
[0015] As a preferred approach, after mapping the three perspective representations to a unified vector space, different perspective representations are paired into positive sample pairs within the same sample, and different perspective representations within different samples are paired into negative sample pairs. Then, a pairwise InfoNCE loss is used to construct a contrastive learning objective, and a joint InfoNCE loss is further used to impose an overall constraint on the joint representation of the three perspectives, thereby achieving cross-perspective semantic alignment.
[0016] As a preferred approach, based on the gating fusion mechanism, the contribution weights of each perspective are dynamically determined according to the information of the code perspective, annotation perspective, and graph structure perspective in a sample after semantic alignment, thereby completing the adaptive fusion of multi-perspective representations.
[0017] As a preferred approach, training is performed by jointly optimizing the supervised classification loss and the cross-view comparative learning loss.
[0018] The present invention has the following beneficial effects:
[0019] 1. Source code typically focuses on program logic and syntax structure, comments typically focus on the developer's intent, and graphs typically focus on control and data dependencies. The method of this invention integrates source code, comment text, and program dependencies. Figure 3 These complementary information sources can more comprehensively characterize the potential defect patterns of software samples.
[0020] 2. The method of this invention establishes a cross-perspective semantic alignment mechanism through comparative learning, and dynamically determines the contribution weight using information from each perspective. It adaptively fuses different defective data based on their varying degrees of dependence on information from different perspectives, effectively alleviating the semantic shift and noise accumulation problems caused by direct splicing of multi-perspective features.
[0021] 3. The method of this invention encodes the code by combining block-based local modeling and global association modeling. At the same time, it aggregates the graph structure input representation from the method-level program dependency graph into the file-level program dependency graph, which improves the modeling ability for long-distance dependencies and complex program structures, thereby improving the performance of software defect prediction. Attached Figure Description
[0022] Figure 1 This is a flowchart of the method of the present invention;
[0023] Figure 2 This is a flowchart illustrating the specific implementation of data preprocessing in this invention.
[0024] Figure 3 This is a flowchart illustrating the specific implementation of the code perspective representation in this invention.
[0025] Figure 4 This is a flowchart illustrating the specific implementation of the graph structure perspective representation in this invention.
[0026] Figure 5 This is a flowchart illustrating the specific implementation of cross-perspective semantic alignment in this invention. Detailed Implementation
[0027] The present invention will be further explained below with reference to the accompanying drawings;
[0028] As the background technology shows, current software defect prediction methods often ignore complementary information from different perspectives. Even in methods that partially utilize multi-perspective information, features from different perspectives are typically directly concatenated and fused. However, different perspectives often emphasize different information, and the model's dependence on information from different perspectives varies when predicting different defect data. Direct concatenation amplifies noise, affecting prediction performance and generalization ability.
[0029] Based on this, the present invention provides a software defect prediction method based on multi-view learning, which aims to improve the ability to express complex defect patterns and predictive performance by simultaneously utilizing source code, comments and graph structure semantics and establishing consistency constraints among multi-view information.
[0030] like Figure 1 As shown, a software defect prediction method based on multi-view learning has the following specific steps:
[0031] Step 1: Data Preprocessing
[0032] S1.1: As Figure 2 As shown, the code and comments in the software sample file are separated. Regular expressions are used to identify single-line comments, multi-line comments, and documentation comments. Single-line comments are obtained by matching text starting with " / / " to the end of the line, while multi-line comments and documentation comments are obtained by matching text between " / *" and "* / ". The identified comment fragments are extracted from the original file and concatenated according to their order of appearance to form a comment text sequence. The remaining content in the original file is used as the source code sequence. To avoid disrupting the original semantic structure during the separation process, necessary line breaks are preserved at comment removal locations to maintain code indentation and line structure as stable as possible.
[0033] S1.2: Remove comment boundary symbols, invalid spaces, and purely formatting symbols from the comment text, while retaining natural language descriptions, parameter explanations, return values, exception descriptions, and development prompts. Then, perform sentence segmentation, case consistency, and punctuation cleanup, but strive to maintain the original semantic expression of the comments to avoid diminishing the developer's intended message. Use the standardized comment text as the comment input sequence.
[0034] S1.3: Remove redundant whitespace, repeated blank lines, and trailing spaces from the source code sequence that have no actual semantic function, but retain the code's indentation level, bracket structure, keyword order, and identifier format. For excessively long literals, consecutive whitespace, and special format characters, map them uniformly to predefined placeholders to reduce noise impact. Use the normalized source code sequence as the code input sequence.
[0035] S1.4: Identify all method or function definitions contained in the source code sequence, and generate a corresponding program dependency graph for each method using the static analysis framework Joern. Nodes in the program dependency graph can represent program units such as assignment statements, conditional statements, loop statements, method call expressions, variable definition operations, variable usage operations, or return statements. Edges in the graph include at least control dependency edges and data dependency edges. Control dependency edges reflect the constraints of conditional statements, loop structures, etc., on the execution paths of other statements, while data dependency edges reflect the dependencies between variable definition, propagation, and usage. Multiple method program dependency graphs extracted from the source code sequence of a single sample are retained as a set of method-level graphs, serving as the graph structure input representation of the code.
[0036] In one embodiment, to ensure the quality of the graph structure input representation, the program-dependent graph execution node and edge filtering processes are further processed to remove redundant nodes that only have format significance but lack discriminative information, such as pure delimiter nodes or parsing noise nodes; at the same time, key nodes related to control decisions, variable propagation, function calls and exception handling are retained to improve the effectiveness of the graph representation.
[0037] Step 2: Extracting the code perspective
[0038] Since source code sequences are typically quite long, directly modeling the complete sequence in file-level prediction scenarios incurs excessive computational overhead. Conversely, truncating the input can easily lead to the loss of long-range dependency information. Therefore, a hierarchical encoding strategy combining block-based local modeling and global relational modeling is employed to encode the code input sequence and extract a code-perspective representation, such as... Figure 3 As shown:
[0039] S2.1: Divide the code input sequence into several contiguous sub-blocks according to a fixed window size. The window size can be set according to the upper limit of the input of the basic coding model. An overlapping area is set between adjacent sub-blocks to reduce information fragmentation across block boundaries. The resulting sub-blocks are sequentially input into the encoder of the pre-trained code language model CodeT5. Local semantic modeling is performed on each sub-block, and the hidden states of all tokens in the sub-block are averaged and pooled to output the local semantic representation of the sub-block.
[0040] S2.2: Arrange the local representation vectors of all sub-blocks into a local representation sequence according to the original order, input it into the Transformer module to model block-level relationships, and calculate the dependencies and contextual associations between different code sub-blocks through a multi-head self-attention mechanism, so that the model can capture long-distance semantic relationships across method calls, control structures and statement scopes, thereby obtaining a holistic semantic representation for the entire sample.
[0041] S2.3: The local semantic representation and the global semantic representation are fused. The local semantic representation of each sub-block and the global semantic representation of the whole sample are mapped to the same dimension through linear transformation. Then, the learnable weight coefficients are used to perform weighted summation to obtain the final code perspective representation.
[0042] Step 3: Extract annotation perspective representation
[0043] Compared to source code, comments are closer to natural language. They are usually shorter and better reflect the developer's concise description of the code's functionality, implementation intent, boundary conditions, and special considerations.
[0044] S3.1: Segment the input sequence of annotations. The segmentation method is set according to the annotation language type. For example, for English annotations, segmentation can be performed by spaces and punctuation marks, and identifiers named with camelCase and underscores can be further split; for Chinese annotations, a general Chinese segmentation method can be used. Then, each segmented word is mapped to a low-dimensional word vector to obtain the annotation word vector sequence.
[0045] S3.2: Input the annotation word vector sequence into a bidirectional long short-term memory network to simultaneously model forward and backward context information, thereby better understanding the semantic relationships between the preceding and following parts of the annotation. Select the final hidden state as the annotation perspective representation.
[0046] Step 4: Extract the graph structure perspective representation
[0047] S4.1: As Figure 4As shown, for each method's program dependency graph, the code snippet corresponding to each node is extracted and converted into a token sequence. Then, each token is mapped to a continuous vector space through a word embedding layer, and an attention aggregation mechanism is used to weighted aggregate the tokens within a node to obtain the initial representation of the node.
[0048] S4.2: A graph neural network is used for multi-layer message passing in the program dependency graph. In each layer of propagation, each node receives messages from its neighboring nodes and aggregates control dependency path information and data dependency path information according to the edge type. In this embodiment, two independent message transformation parameters are set: one for processing context signals propagating on control dependency edges, and the other for processing variable flow signals propagating on data dependency edges. Then, the two types of information are fused with the current node state to obtain the updated node representation. After several layers of graph propagation, each node can perceive program structure relationships over a wider range, thereby forming a method-level graph representation.
[0049] S4.3: Global average pooling is applied to each method-level graph to aggregate all node representations in the method graph into a single method-level graph representation. For file-level samples containing multiple methods, weighted aggregation of all method-level graph representations is then performed to form a file-level graph structure perspective representation. The aggregation weights of different method graphs are determined based on method length, call complexity, number of nodes, and learned attention weights, so that methods with higher defect relevance account for a larger proportion of the overall graph representation.
[0050] Step 5: Cross-perspective semantic alignment
[0051] Because code-based, annotation-based, and graph-based representations use different encoding methods, their distributions often differ significantly. Direct fusion can easily lead to inconsistencies in the representations within the same sample, affecting classification performance. Therefore, this invention introduces a contrastive learning mechanism before multi-view fusion, ensuring that different perspectives of the same sample are close to each other in a unified vector space, while cross-view representations between different samples are distinguishable. Figure 5 As shown:
[0052] S5.1: Use a multi-layer fully connected network to construct a projection head. Use independent projection heads to map the code perspective representation, comment perspective representation, and graph structure perspective representation to a contrastive learning space of the same dimension, and perform normalization processing.
[0053] S5.2: Within the same sample, different perspective representations are paired to form positive sample pairs, and different perspective representations within different samples are paired to form negative sample pairs, including code-annotation sample pairs, code-graph structure sample pairs, and annotation-graph structure sample pairs.
[0054] S5.3: Pairwise InfoNCE loss is used to establish three sets of comparison targets: code-annotation, code-graph structure, and annotation-graph structure, which increases the similarity of positive sample pairs and decreases the similarity of negative sample pairs. Furthermore, a joint InfoNCE loss is constructed to impose an overall constraint on the joint representation of the three perspectives, so as to enhance the tightness of the three perspectives corresponding to the same defective semantic entity.
[0055] Step 6: Adaptive Fusion and Defect Prediction
[0056] S6.1: Concatenate the code perspective representation, comment perspective representation, and graph structure perspective representation into a vector and input it into the gating fusion module. Output the gating weights corresponding to the three perspectives. After normalization, the contribution of each perspective is obtained.
[0057] S6.2: The three-view representations are weighted and summed according to their contributions. The fused representation is then input into the defect classifier, which outputs the defect prediction results for the software samples. In this embodiment, a fully connected layer and a Softmax layer are used to construct the defect classifier.
[0058] During the training phase, a combination of supervised classification loss and cross-view contrastive learning loss is used to jointly optimize the entire network. The supervised classification loss, which can be cross-entropy loss, is used to ensure that the model's predicted results are consistent with the true defect labels. The contrastive learning loss is used to constrain the consistency of representations from different perspectives. The total loss is chosen as a weighted sum of the classification loss and multiple contrastive losses, with the weights of each loss term set based on the validation set performance.
[0059] In the prediction phase, no comparative learning is performed. After the test samples are extracted and aligned through multi-view representation, they are directly subjected to adaptive fusion and input into the defect classifier to obtain the defect prediction results.
[0060] In addition to the embodiments described above, the present invention may have other implementations. All technical solutions formed by equivalent substitution or equivalent transformation are within the scope of protection claimed by the present invention.
[0061] The present invention has been described in detail above, but its specific implementation is not limited thereto. Various modifications or alterations can be made by those skilled in the art without departing from the spirit and scope of the claims of this application.
Claims
1. A software defect prediction method based on multi-view learning, characterized in that: The specific steps are as follows: Step 1: Obtain the sample files of the software to be predicted, which are divided into source code sequences and comment text sequences. Then, preprocess them to obtain the comment input sequence, code input sequence, and graph structure input representation of the code. Step 2: Encode the three types of input representations to obtain annotation perspective representation, code perspective representation, and graph structure perspective representation; for code input sequences, use an encoding method that combines block-based local modeling and global relational modeling; for the graph structure input representation of the code, encode it through aggregation. Step 3: Map the three perspective representations to a unified space, perform cross-perspective semantic alignment through contrastive learning, adaptively fuse the semantically aligned multi-perspective representations, and finally input them into the defect classifier to output the defect prediction results of the software samples.
2. The software defect prediction method based on multi-view learning as described in claim 1, characterized in that: Regular expressions are used to identify comment fragments in software sample files, which are then extracted from the original files and concatenated according to their order of appearance in the original files to form a sequence of comment text; the remaining content in the original files is used as the source code sequence.
3. The software defect prediction method based on multi-view learning as described in claim 1, characterized in that: The preprocessing method is as follows: for the source code sequence, symbols without actual semantic function are cleaned up, the original format is preserved, and a code input sequence is obtained; at the same time, all methods contained in the source code sequence are extracted, and a program dependency graph is generated for each method to obtain a graph structure input representation; for the comment text, symbols without actual semantic function are cleaned up, the original format is preserved, and then sentence segmentation, case uniformity, and punctuation cleaning are performed to obtain the comment input sequence.
4. The software defect prediction method based on multi-view learning as described in claim 3, characterized in that: Perform node and edge filtering on the program dependency graph to remove redundant nodes that only have formatting significance but lack discriminative information.
5. The software defect prediction method based on multi-view learning as described in claim 1, characterized in that: The preprocessing method is as follows: word embedding is performed on the annotation input sequence, which is mapped to a word vector sequence, and then the sequence is input into a bidirectional long short-term memory network. The final hidden state is selected as the annotation perspective representation.
6. The software defect prediction method based on multi-view learning as described in claim 1, characterized in that: The code input sequence is divided into several sub-blocks according to a fixed window size. For each sub-block, the encoder of the CodeT5 model is used to perform local modeling and extract the local semantic representation within each sub-block. Then, the attention relationship between each sub-block is calculated through the Transformer to capture the semantic association between the sub-blocks and obtain the overall semantic representation of the sample. Finally, the local semantic representation within each sub-block and the overall semantic representation of the sample are weighted and fused to obtain the code perspective representation.
7. The software defect prediction method based on multi-view learning as described in claim 1, characterized in that... The graph neural network embeds the program dependency graph of each method in the graph structure input representation. First, it extracts the corresponding code fragment of each node and represents it as a token sequence. Then, it maps each token sequence to a low-dimensional continuous space through word embedding and aggregates the tokens inside the node with the help of the attention mechanism to generate the initial representation of the node. The graph propagation mechanism is used to aggregate information from neighboring nodes. Each node receives information from both control dependency and data dependency paths during the update process, thus forming a method-level graph representation. Finally, each method-level graph representation is weighted and aggregated to obtain a graph structure perspective representation.
8. The software defect prediction method based on multi-view learning as described in claim 1, characterized in that: After mapping the three perspective representations to a unified vector space, different perspective representations are paired into positive sample pairs within the same sample, and different perspective representations within different samples are paired into negative sample pairs. Then, a pairwise InfoNCE loss is used to construct a contrastive learning objective, and a joint InfoNCE loss is further used to impose an overall constraint on the joint representation of the three perspectives to achieve cross-perspective semantic alignment.
9. The software defect prediction method based on multi-view learning as described in claim 8, characterized in that: Based on the gating fusion mechanism, the contribution weight of each perspective is dynamically determined according to the information of code perspective, annotation perspective and graph structure perspective in a sample after semantic alignment, so as to complete the adaptive fusion of multi-view representation. During training, the supervised classification loss and cross-view contrastive learning loss are jointly optimized to update the model parameters.
10. A computer-readable storage medium having a computer program stored thereon, which, when executed in a computer, causes the computer to perform the method of any one of claims 1 to 9.
