Decision-based code comment generation method integrating information retrieval and deep learning
Patent Information
- Application Number
- CN202111060940.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2021-09-10
- Publication Date
- 2024-09-06
- Estimated Expiration
- 2041-09-10
AI Technical Summary
Existing technologies are difficult to generate high-quality code comments, especially when code snippets evolve. Comments cannot be automatically updated, and information retrieval and deep learning-based methods have limitations and lack universality and generalization capabilities.
Propose a decision-based code annotation generation method that integrates information retrieval and deep learning. By building a model based on information retrieval and deep learning, analyzing the similarity threshold, selecting an appropriate model to generate annotations, and combining semantic, lexical and syntactic similarity. Fusion,uses a decision module to select output annotations.
It achieves better performance than the baseline method on the same corpus, generates higher-quality code comments, improves developers' code understanding efficiency and the ease of software development and maintenance.
Smart Images

Figure CN113743064B
Abstract
Description
Technical Field
[0001] The present invention relates to the field of computer technology, and in particular to a code annotation generation method based on decision-making fusion information retrieval and deep learning. Background Art
[0002] Code comment generation aims to help software developers understand the design intent and functionality of code snippets. Due to limited project development budgets or insufficient attention to the writing of code comments, the quality of code comments is difficult to ensure. In addition, code comments often cannot be automatically updated as the code snippets evolve. Therefore, there is an urgent need to design effective methods to automatically generate high-quality code comments after analyzing the semantics of the target code snippet.
[0003] Previous studies usually use information retrieval for code comment generation tasks and have achieved good performance. Since code clones are very common in software development, code clone detection techniques based on information retrieval can be used to retrieve similar code snippets from existing code repositories (such as Github) or developer Q&A websites (such as Stack Overflow). Developers can then reuse comments for similar code snippets. However, this approach lacks generality. This means that if the similarity score between the retrieved code snippet and the target code snippet is not high, it is useless to directly use the comments of the retrieved code snippet.
[0004] In recent years, more and more studies have applied deep learning methods to generate code comments, modeling the code comment generation task as a machine translation task. These studies mainly use an encoder-decoder framework with source code as input and comments as output. Experimental studies have shown that these methods can achieve good performance and have high generalization ability, but the generated comments tend to contain high-frequency words and are difficult to cover low-frequency words.
[0005] In addition to methods based on information retrieval or deep learning, recent research has also been devoted to integrating information retrieval and deep learning, and has achieved good results. Therefore, in order to improve the performance of code comment generation, it is necessary to explore more effective information retrieval-based and deep learning-based models, and analyze and propose a simple and efficient fusion method to further improve performance.
[0006] How to solve the above technical problems becomes the subject faced by the present invention. Summary of the invention
[0007] The purpose of the present invention is to provide a method for generating code annotations based on decision-making fusion information retrieval and deep learning, which can generate a code annotation based on the input code segment c and the most similar code segment c retrieved from the training set. sim The appropriate code comment generation model is selected based on the similarity between the two codes to generate high-quality code comments.
[0008] The idea of the present invention is as follows: the present invention proposes a code annotation generation method based on decision-making fusion information retrieval and deep learning. Firstly, a new model based on information retrieval and a new model based on deep learning are constructed respectively. Then, a given code segment c is analyzed on a validation set with the most similar code segment c retrieved from a training set. sim The relationship between the similarity scores between the two models and the performance of the two models is determined, and the similarity threshold is determined. Finally, when faced with a new target code, the decision module chooses to output the corresponding annotation: if the target code c is the most similar code c retrieved by the information retrieval module, sim If the similarity score is greater than the threshold, the annotation based on the output of the information retrieval model is selected, otherwise the annotation based on the output of the deep learning model is selected. The method of the present invention achieves better performance than the benchmark method in the same corpus.
[0009] The present invention is achieved by the following measures: a code annotation generation method based on decision-making fusion information retrieval and deep learning, which includes the following steps:
[0010] (1) Based on the GitHub website, we mined high-quality open source projects, collected functions and corresponding comments in the open source code to form a corpus, and further divided it into a training set and a validation set;
[0011] (2) Build a model based on information retrieval: By integrating semantic, lexical, and grammatical similarities, find the most similar code segment c in the training set for the target code segment c sim Then, the comment of the most similar code segment is reused as the comment of the target code segment, which specifically includes the following steps:
[0012] (2-1) Calculate semantic similarity: Use the pre-trained model CodeBert suitable for code to extract code semantic features, and use the BERT-whitening operation to extract key features and reduce the dimension of the code semantic features; calculate the L2 distance between the semantic vectors of the target code segment c and the code segments in the training set to determine the semantic similarity between the code segments; then select the top k most semantically similar code segments as candidate codes;
[0013] (2-2) Calculate lexical similarity: First, segment the identifiers in the code sequence according to the camel case naming rule; perform a deduplication operation on the code sequence to obtain a word set of the code fragment; calculate the lexical similarity between two code fragments using Jaccard similarity;
[0014] (2-3) Calculating grammatical similarity: First, convert the code into the corresponding abstract syntax tree; then traverse the type nodes of the code abstract syntax tree to obtain an ordered sequence; finally, calculate the grammatical similarity between the two code segments by calculating the edit distance between the ordered sequences;
[0015] (2-4) After calculating the mixed score based on the weighted sum of the proportion of lexical and grammatical similarity, find the most similar code fragment c from the candidate codes sim , reuse its code comments.
[0016] (3) Building a deep learning-based model: Consider adversarial examples and use a Transformer-based model to generate code comments. First, a general model is pre-trained and then fine-tuned on a specific corpus. The specific steps include the following:
[0017] (3-1) Pre-training stage: Identifier segmentation is performed according to the naming rules, and then sub-word segmentation is performed using the BPE algorithm to obtain the code sequence C = (c1, c2, ..., c n ), parse the code into an abstract syntax tree and traverse it to obtain an abstract syntax tree sequence A = (a1, a2, ..., a n ). Concatenate the two sequences and use the identifier <ast>To separate them, we get the input sequence X input =(c1,c2,…,c n , <ast>,a1,a2,…,a n ); through the embedding layer and position encoding, we get the vector X emb ;
[0018] (3-2) The vector is input into the bidirectional encoder for semantic learning. First, the vector is input into the multi-head attention layer, and the matrix operation dimension is made consistent by using residual connection and layer normalization, and the hidden layer in the network is normalized to the standard normal distribution, which speeds up the training and convergence of the model. Then, through the feedforward layer and two linear mapping layers, the activation function is used to generate the vector X hidden , the hidden semantic vector is obtained through residual connection and layer normalization;
[0019] (3-3) Each layer of the decoder performs additional cross-attention calculations on the final hidden layer of the encoder and is connected through cross-attention; the output of the decoder is sent to a fully connected neural network, which can predict the probability of the next token through a softmax layer;
[0020] (3-4) Finally, the beam search algorithm is used to improve the quality of the generated code comments;
[0021] (3-5) Fine-tuning stage: Do not adjust the bias and LayerNorm.weight parameters of the model, use the AdamW method to fine-tune other parameters; use the fast gradient method to obtain adversarial samples, add perturbations R adv to the embedding layer of the encoder, and use it for training after obtaining the adversarial sample.
[0022] (4) Calculating the similarity threshold: After obtaining the code annotations generated by the information retrieval model and the deep learning model respectively, the performance of these two models is analyzed on the validation set with respect to the two code segments c and c. sim The relationship between the similarity scores is determined to determine the similarity threshold, which specifically includes the following steps:
[0023] (4-1) For each code in the validation set, annotations based on information retrieval and deep learning models as well as similarity scores (mixed scores calculated based on the information retrieval module) can be obtained;
[0024] (4-2) Then divide the similarity score set into 10 subsets with an interval of 0.1, and calculate the average performance of the information retrieval model and the deep learning model on each subset. For each evaluation indicator, when the performance comparison results of the two models change, determine the threshold. Finally, take the average of the thresholds under the four evaluation indicators (i.e., BLEU, METEOR, ROUGE-L and CIDER) as the final similarity threshold.
[0025] (5) Decision module: When generating comments for a new target code, the corresponding code comments are output based on the decision-based module. If the target code c is similar to the most similar code c retrieved by the information retrieval module, sim If the similarity score of is greater than the threshold, the annotation based on the output of the information retrieval model is selected, otherwise the annotation based on the output of the deep learning model is selected.
[0026] The parameter settings of the decision-based fusion information retrieval and deep learning code comment generation method are as follows:
[0027]
[0028]
[0029] Compared with the prior art, the present invention has the following beneficial effects: the present invention proposes a code comment generation method based on decision-making fusion of information retrieval and deep learning. First, a model based on information retrieval and a model based on deep learning are respectively constructed for generating code comments. The two proposed models can achieve better performance than the corresponding types of benchmark methods. Through analysis, it is found that the performance of the two models depends on the similarity of the most similar code retrieved by the information retrieval model. Therefore, a code comment generation method based on decision-making fusion of information retrieval and deep learning is further proposed. If the target code c is similar to the most similar code c retrieved by the information retrieval module, the target code c is the most similar code c retrieved by the information retrieval module. sim If the similarity score is greater than the threshold, the annotation based on the output of the information retrieval model is selected, otherwise the annotation based on the output of the deep learning model is selected. Compared with the most advanced fusion baseline method, this decision-based fusion method can generate higher quality code annotations, which helps to improve developers' code understanding efficiency and facilitate software development and maintenance. BRIEF DESCRIPTION OF THE DRAWINGS
[0030] The accompanying drawings are used to provide further understanding of the present invention and constitute a part of the specification. They are used to explain the present invention together with the embodiments of the present invention and do not constitute a limitation of the present invention.
[0031] Figure 1 A system framework diagram of a code annotation generation method based on decision-making fusion information retrieval and deep learning provided by the present invention;
[0032] Figure 2 The present invention provides a structure of an encoder based on a deep learning model. DETAILED DESCRIPTION
[0033] In order to make the purpose, technical solution and advantages of the present invention more clearly understood, the present invention is further described in detail below in conjunction with the accompanying drawings and embodiments. Of course, the specific embodiments described here are only used to explain the present invention and are not used to limit the present invention.
[0034] Example 1
[0035] See also Figure 1 , Figure 2 As shown, the present invention provides a code annotation generation method based on decision-making fusion information retrieval and deep learning, which specifically includes the following contents:
[0036] (1) We collected two large-scale corpora, PCSD (Python Code Comment Dataset) and JCSD (Java Code Comment Dataset), as experimental objects. Both corpora are <function, comment> pairs mined from GitHub and further divided into training set, validation set and test set. The specific statistical information (such as the number of code segments, the average number of tokens in the code and the average number of tokens in the comments) is shown in Table 1.
[0037] Table 1
[0038]
[0039] (2) Build a model based on information retrieval to find the most similar code segment c in the training set for the target code segment c by integrating semantic, lexical and grammatical similarity. sim Then, the comment of the most similar code segment is reused as the comment of the target code segment, which specifically includes the following steps:
[0040] (2-1) Calculate semantic similarity: Use the pre-trained model CodeBert suitable for code to extract code semantic features, and use the BERT-whitening operation to extract key features and reduce the dimension of the code semantic features; calculate the L2 distance between the semantic vectors of the target code segment c and the code segments in the training set to determine the semantic similarity between the code segments; then select the top k most semantically similar code segments as candidate codes;
[0041] (2-2) Calculate lexical similarity: First, segment the identifiers in the code sequence according to the camel case naming rule; perform a deduplication operation on the code sequence to obtain a word set of the code fragment; calculate the lexical similarity between two code fragments using Jaccard similarity;
[0042] (2-3) Calculating grammatical similarity: First, convert the code into the corresponding abstract syntax tree; then traverse the type nodes of the code abstract syntax tree to obtain an ordered sequence; finally, calculate the grammatical similarity between the two code segments by calculating the edit distance between the ordered sequences;
[0043] (2-4) After calculating the mixed score based on the weighted sum of the proportion of lexical and grammatical similarity, find the most similar code fragment c from the candidate codes sim , reuse its code comments.
[0044] (3) Training a deep learning-based model: Consider adversarial examples and use a Transformer-based model to generate code comments. First, a general model is pre-trained and then fine-tuned on a specific corpus. The specific steps include the following:
[0045] (3-1) Pre-training stage: Identifier segmentation is performed according to the naming rules, and then sub-word segmentation is performed using the BPE algorithm to obtain the code sequence C = (c1, c2, ..., c n ), parse the code into an abstract syntax tree and traverse it to obtain an abstract syntax tree sequence A = (a1, a2, ..., a n ). Concatenate the two sequences and use the identifier <ast>To separate them, we get the input sequence X input =(c1,c2,…,c n , <ast>,a1,a2,…,a n ); through the embedding layer and position encoding, we get the vector X emb ;
[0046] (3-2) The vector is input into the bidirectional encoder for semantic learning. First, the vector is input into the multi-head attention layer, and the matrix operation dimension is made consistent by using residual connection and layer normalization, and the hidden layer in the network is normalized to the standard normal distribution, which speeds up the training and convergence of the model. Then, through the feedforward layer and two linear mapping layers, the activation function is used to generate the vector X hidden , the hidden semantic vector is obtained through residual connection and layer normalization;
[0047] (3-3) Each layer of the decoder performs additional cross-attention calculations on the final hidden layer of the encoder and is connected through cross-attention; the output of the decoder is sent to a fully connected neural network, which can predict the probability of the next token through a softmax layer;
[0048] (3-4) Finally, the beam search algorithm is used to improve the quality of the generated code comments;
[0049] (3-5) Fine-tuning stage: Do not adjust the bias and LayerNorm.weight parameters of the model, use the AdamW method to fine-tune other parameters; use the fast gradient method to obtain adversarial samples, add perturbations R adv to the embedding layer of the encoder, and use it for training after obtaining the adversarial sample.
[0050] (4) Calculating the similarity threshold: After obtaining the code annotations generated by the information retrieval model and the deep learning model respectively, the performance of these two models is analyzed on the validation set with respect to the two code segments c and c. sim The relationship between the similarity scores is determined to determine the similarity threshold, which specifically includes the following steps:
[0051] (4-1) For each code in the validation set, annotations based on information retrieval and deep learning models as well as similarity scores (mixed scores calculated based on the information retrieval module) can be obtained;
[0052] (4-2) Then divide the similarity score set into 10 subsets with an interval of 0.1, and calculate the average performance of the information retrieval model and the deep learning model on each subset. For each evaluation indicator, when the performance comparison results of the two models change, determine the threshold. Finally, take the average of the thresholds under the four evaluation indicators (i.e., BLEU, METEOR, ROUGE-L and CIDER) as the final threshold.
[0053] (5) Decision module: When generating comments for a new target code, the corresponding code comments are output based on the decision-based module. If the target code c is similar to the most similar code c retrieved by the information retrieval module, sim If the similarity score of is greater than the threshold, the annotation based on the output of the information retrieval model is selected, otherwise the annotation based on the output of the deep learning model is selected.
[0054] (6) The parameter settings of the decision-based fusion information retrieval and deep learning code comment generation method are shown in Table 2:
[0055] Table 2
[0056]
[0057]
[0058] (7) The method of the present invention and the existing code comment generation methods are evaluated on the same corpus, and four evaluation indicators (i.e., BLEU, METEOR, ROUGE-L, and CIDER) from the field of neural machine translation research are used to automatically evaluate the quality of the generated comments. Table 3 shows the comparison results between the information retrieval-based model constructed by the present invention and various information retrieval benchmark methods; Table 4 shows the comparison results between the deep learning-based model constructed by the present invention and various deep learning benchmark methods; Table 5 shows the comparison results between the decision-based fusion method proposed by the present invention and the most advanced fusion benchmark method.
[0059] Table 3 Comparison results of information retrieval-based models and benchmark methods
[0060]
[0061]
[0062] Experiments show that the code comment generation model based on information retrieval proposed in this paper can generate higher quality code comments compared with four most advanced information retrieval benchmark methods. Ablation experiments also show that using BERT-whitening operations for key feature extraction and dimensionality reduction, and considering lexical and grammatical similarities are very valuable for improving model performance.
[0063] Table 4 Comparison results of deep learning-based models and baseline methods
[0064]
[0065] Experiments show that the deep learning-based code comment generation model proposed in this paper can generate higher quality code comments compared to four state-of-the-art deep learning benchmark methods. Ablation experiments also show that considering adversarial training can further improve the performance of the model.
[0066] Table 5 Comparison results of decision-based fusion methods and state-of-the-art fusion baseline methods
[0067]
[0068] Experiments show that the code comment generation method based on decision-making fusion of information retrieval and deep learning proposed in the present invention has achieved better performance in all indicators compared with the advanced fusion benchmark method, that is, it can generate higher quality code comments. Specifically, the best result is on the JCSD corpus, where the ROUGE-L index can be improved by 3.1. In terms of evaluation indicators, the decision-based fusion method proposed in the present invention is simpler and more effective than the most advanced fusion method Rencos, which shows the competitiveness of the method proposed in the present invention.
[0069] The above description is only a preferred embodiment of the present invention and is not intended to limit the present invention. Any modifications, equivalent substitutions, improvements, etc. made within the spirit and principle of the present invention should be included in the protection scope of the present invention.< / ast> < / ast> < / ast> < / ast>
Claims
1. A code comment generation method based on decision-making integration of information retrieval and deep learning, It is characterized in that The following steps are involved: (1) Based on the GitHub website, we mined high-quality open source projects, collected functions and corresponding comments in the open source code to form a corpus, and further divided it into a training set and a validation set; (2) Build a model based on information retrieval to find the most similar code segment c in the training set for the target code segment c by integrating semantic, lexical and grammatical similarity. sim ,Then, by reusing the comments of the most similar code segment as the ,comment of the target code segment; (3) Build a deep learning-based model. Use a Transformer-based deep learning model to generate corresponding code comments. First, pre-train a general model and then fine-tune the model on a specific corpus. (4) After obtaining the code annotations generated by the information retrieval model and the deep learning model respectively, the performance of these two models is analyzed on the validation set compared with the two code segments c and c sim The relationship between the similarity scores is used to determine the similarity threshold; (5) When generating comments for a new target code, the corresponding code comments are output according to the decision-based module.
2. The code annotation generation method based on decision-making fusion information retrieval and deep learning according to claim 1, It is characterized in that In step (2), the most similar code segment c in the training set is found for the target code segment c by integrating semantic, lexical and grammatical similarities. sim And reuse its comments, including the following steps: (2-1) Calculate semantic similarity: Use the pre-trained model CodeBert suitable for code to extract code semantic features, and use the BERT-whitening operation to extract key features and reduce the dimension of the code semantic features; calculate the L2 distance between the semantic vectors of the target code segment c and the code segments in the training set to determine the semantic similarity between the code segments; then select the top k most semantically similar code segments as candidate codes; (2-2) Calculate lexical similarity: First, segment the identifiers in the code sequence according to the camel case naming rule; perform a deduplication operation on the code sequence to obtain a word set of the code fragment; calculate the lexical similarity between two code fragments using Jaccard similarity; (2-3) Calculate syntax similarity: First, convert the code into the corresponding abstract syntax tree; Then, the type nodes of the code abstract syntax tree are traversed to obtain an ordered sequence; finally, the grammatical similarity between the two code segments is calculated by calculating the edit distance between the ordered sequences; (2-4) After calculating the mixed score based on the weighted sum of the proportion of lexical and grammatical similarity, find the most similar code fragment c from the candidate codes sim , reuse its code comments.
3. The code annotation generation method based on decision-making fusion information retrieval and deep learning according to claim 1, It is characterized in that In step (3), a deep learning-based model is used to generate corresponding code comments, which specifically includes the following steps: (3-1) Pre-training stage: Identifier segmentation is performed according to the naming rules, and then sub-word segmentation is performed using the BPE algorithm to obtain the code sequence C = (c 1 ,c 2 ,…,c n ), parse the code into an abstract syntax tree and traverse it to obtain an abstract syntax tree sequence A = (a 1 ,a 2 ,…,a n ), concatenate the two sequences and use the identifier <ast>To separate them, we get the input sequence X input =(c 1 ,c 2 ,…,c n , <ast>,a 1 ,a 2 ,…,a n ); through the embedding layer and position encoding, we get the vector X emb ;< / ast> < / ast> (3-2) The vector is input into the bidirectional encoder for semantic learning. First, the vector is input into the multi-head attention layer. The residual connection and layer normalization are used to make the matrix operation dimension consistent, and the hidden layer in the network is normalized to the standard normal distribution, which speeds up the training and convergence of the model. Then, the activation function is used to generate the vector X through the feedforward layer and two linear mapping layers. hidden , the hidden semantic vector is obtained through residual connection and layer normalization; (3-3) Each layer of the decoder performs additional cross-attention calculations on the final hidden layer of the encoder and is connected through cross-attention; the output of the decoder is sent to a fully connected neural network, which can predict the probability of the next token through a softmax layer; (3-4) Finally, the beam search algorithm is used to improve the quality of the generated code comments; (3-5) Fine-tuning stage: Do not adjust the bias and LayerNorm.weight parameters of the model, use the AdamW method to fine-tune other parameters; use the fast gradient method to obtain adversarial samples, add perturbations R adv to the embedding layer of the encoder, and use it for training after obtaining the adversarial sample.
4. The code annotation generation method based on decision-making fusion information retrieval and deep learning according to claim 1, It is characterized in that In step (4), the performance of the two models is analyzed on the validation set and the two code segments c and c sim The relationship between the similarity scores and the similarity threshold are calculated, which specifically includes the following steps: (4-1) For each code in the validation set, annotations and similarity scores generated based on information retrieval and deep learning models can be obtained; (4-2) Then divide the similarity score set into 10 subsets with an interval of 0.1, and calculate the average performance of the information retrieval model and the deep learning model on each subset respectively. For each evaluation indicator, when the performance comparison result of the two models changes, determine the threshold. Finally, take the average of the thresholds under the four evaluation indicators as the final threshold.
5. The code annotation generation method based on decision-making fusion information retrieval and deep learning according to claim 1, It is characterized in that In step (5), when generating comments for a new target code, the corresponding code comments are output according to the decision-based module. If the target code c is similar to the most similar code c retrieved by the information retrieval module, sim If the similarity score of is greater than the threshold, the annotation based on the output of the information retrieval model is selected, otherwise the annotation based on the output of the deep learning model is selected.
