Code feature extraction method and system based on hierarchical contrastive learning
By using a method based on hierarchical contrastive learning, combined with the adjacency matrix and node labels of the AST tree, and using the residual self-attention network model to extract code features, the problem of information loss and gradient descent in the existing technology is solved, and a comprehensive code structure is achieved. Improvement of extraction and model expression capabilities.
Patent Information
- Application Number
- CN202110411676.X
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2021-04-16
- Publication Date
- 2024-10-15
- Estimated Expiration
- 2041-04-16
Smart Images

Figure CN113238797B_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the technical field of code feature extraction, and in particular to a code feature extraction method and system based on hierarchical contrast learning. Background Art
[0002] The statements in this section merely mention background art related to the present invention and do not necessarily constitute prior art.
[0003] In existing methods, the method of representing program syntax features often only uses the structural characteristics of the abstract syntax tree (AST) to represent a syntax structure of the source code after parsing the code snippet. However, simply modeling the program's abstract syntax tree cannot fully extract code structure information, and lacks in-depth mining of the structural characteristics of the generated AST, which will lead to information loss. In the graph embedding part, graph convolutional networks are often used to increase the receptive field through stacking to obtain local information, but global information cannot be obtained, resulting in incomplete feature information extraction. Usually, due to the problem of gradient descent or even vanishing inside the graph network, the model's expressive power will be weakened. Summary of the invention
[0004] In order to solve the deficiencies of the prior art, the present invention provides a code feature extraction method and system based on hierarchical contrastive learning;
[0005] In a first aspect, the present invention provides a code feature extraction method based on hierarchical contrastive learning;
[0006] The code feature extraction method based on hierarchical contrastive learning includes:
[0007] Get the code to be processed; parse the code snippet to be processed and generate an AST tree; embed the AST tree to obtain the feature matrix X and construct the adjacency matrix A of the AST tree;
[0008] Establish node labels based on the hierarchical number of each node in the AST tree; update the feature matrix X based on the node labels to obtain a new feature matrix X';
[0009] The new feature matrix X' and the adjacency matrix A are input into the trained residual self-attention network model to obtain the features of the code to be processed; wherein the residual self-attention network model includes: a self-attention mechanism model and a graph convolutional neural network model connected in sequence.
[0010] In a second aspect, the present invention provides a code feature extraction system based on hierarchical contrastive learning;
[0011] The code feature extraction system based on hierarchical contrastive learning includes:
[0012] The parsing module is configured to: obtain the code to be processed; parse the code fragment to be processed and generate an AST tree; embed the AST tree to obtain a feature matrix X, and construct an adjacency matrix A of the AST tree;
[0013] The matrix update module is configured to: establish a node label based on the hierarchical number of each node in the AST tree; update the feature matrix X based on the node label to obtain a new feature matrix X';
[0014] The feature extraction module is configured to: input the new feature matrix X' and the adjacency matrix A into the trained residual self-attention network model to obtain the features of the code to be processed; wherein the residual self-attention network model includes: a self-attention mechanism model and a graph convolutional neural network model connected in sequence.
[0015] In a third aspect, the present invention further provides an electronic device comprising: one or more processors, one or more memories, and one or more computer programs; wherein the processor is connected to the memory, and the one or more computer programs are stored in the memory, and when the electronic device is running, the processor executes the one or more computer programs stored in the memory so that the electronic device executes the method described in the first aspect above.
[0016] In a fourth aspect, the present invention further provides a computer-readable storage medium for storing computer instructions, wherein when the computer instructions are executed by a processor, the method described in the first aspect is completed.
[0017] Compared with the prior art, the present invention has the following beneficial effects:
[0018] The grammatical information of the program is extracted through AST, and the parsed AST is labeled and classified according to the node level, establishing a single-label multi-classification relationship, fully mining the structural information of the program, and making the expression ability of the generated model more comprehensive and accurate.
[0019] In the graph embedding part, a model combining the residual self-attention mechanism and the graph convolutional network is proposed to realize global and local feature extraction, realizing global reference while enhancing its own features. The model adds residual connections both inside and outside the self-attention module, effectively solving the gradient descent problem and enhancing the expressiveness of the model.
[0020] Advantages of additional aspects of the present invention will be given in part in the following description, and in part will become obvious from the following description, or will be learned through practice of the present invention. BRIEF DESCRIPTION OF THE DRAWINGS
[0021] The accompanying drawings in the specification, which constitute a part of the present invention, are used to provide a further understanding of the present invention. The exemplary embodiments of the present invention and their descriptions are used to explain the present invention and do not constitute improper limitations on the present invention.
[0022] Figure 1 is a method flow chart of the first embodiment;
[0023] Figure 2 This is a visualization diagram of the AST tree of the first embodiment;
[0024] Figure 3 Schematic diagram of the self-attention mechanism module of the first embodiment. DETAILED DESCRIPTION
[0025] It should be noted that the following detailed descriptions are exemplary and are intended to provide further explanation of the present invention. Unless otherwise specified, all technical and scientific terms used herein have the same meanings as those commonly understood by those skilled in the art to which the present invention belongs.
[0026] It should be noted that the terms used herein are only for describing specific embodiments, and are not intended to limit exemplary embodiments according to the present invention. As used herein, unless the context clearly indicates otherwise, the singular form is also intended to include the plural form. In addition, it should be understood that the terms "include" and "have" and any of their variations are intended to cover non-exclusive inclusions, for example, a process, method, system, product or device comprising a series of steps or units is not necessarily limited to those steps or units clearly listed, but may include other steps or units that are not clearly listed or inherent to these processes, methods, products or devices.
[0027] In the absence of conflict, the embodiments of the present invention and the features of the embodiments may be combined with each other.
[0028] Embodiment 1
[0029] This embodiment provides a code feature extraction method based on hierarchical contrast learning;
[0030] like Figure 1 As shown, the code feature extraction method based on hierarchical contrast learning includes:
[0031] S101: Obtain the code to be processed; parse the code fragment to be processed and generate an AST tree;
[0032] Embed the AST tree to obtain the feature matrix X, and construct the adjacency matrix A of the AST tree;
[0033] S102: Establish node labels based on the hierarchical number of each node in the AST tree; update the feature matrix X based on the node labels to obtain a new feature matrix X';
[0034] S103: Input the new feature matrix X' and the adjacency matrix A into the trained residual self-attention network model to obtain the features of the code to be processed;
[0035] Among them, the residual self-attention network model includes: a self-attention mechanism model and a graph convolutional neural network model connected in sequence.
[0036] Furthermore, the residual self-attention network model is abbreviated as RSGN in English, and its full English name is: Residual Self-attention Graph Network.
[0037] Furthermore, the S101: parsing the code fragment to be processed to generate an AST tree; specifically includes:
[0038] Use JavaParser to parse the code and generate its corresponding AST tree;
[0039] Among them, JavaParser is used to parse the code, and two parts of information are obtained after parsing: one is the information represented by the AST tree node; the other is the pointing relationship between nodes and the storage of edge information.
[0040] The information represented by the AST tree node includes: the specific information of a line of code corresponding to the node and the type of the line of code corresponding to the node.
[0041] The parsed AST tree can be visualized using online visualization tools. Figure 2 shown.
[0042] Furthermore, the S101: embedding the AST tree to obtain a feature matrix X; specifically includes:
[0043] Using word embedding, the string corresponding to each node of the AST tree is embedded to obtain the feature matrix X, where X = {p 1 ,p 2 ,...,p N}, p N Represents the vector representation of the Nth node.
[0044] Furthermore, the S101: constructing an adjacency matrix A of the AST tree specifically includes:
[0045] Construct the adjacency matrix A according to whether there is a pointing relationship between the nodes of the AST tree;
[0046] The adjacency matrix A is used to store the pointing relationship between nodes. If there is a pointing relationship between nodes, the corresponding element value of the adjacency matrix A is 1, otherwise the corresponding element value is 0.
[0047] Among them, the adjacency matrix A is an N*N matrix.
[0048] Furthermore, the S102: establishing node labels according to the hierarchical number of each node in the AST tree; updating the feature matrix X based on the node labels to obtain a new feature matrix X'; specifically includes:
[0049] Based on the unique ID corresponding to each node, the depth of its position in the tree is labeled accordingly. Starting from the root node, the AST tree is traversed. The root node is marked as 0, the first-level child nodes are marked as 1, the second-level child nodes are marked as 2, and so on. The M-th-level child nodes are marked as M.
[0050] Update the feature matrix X based on the node label to get a new feature matrix
[0051] Among them, the label is the level of the node, and the category is the level number of the node.
[0052] Furthermore, the S103: inputting the new feature matrix X' and the adjacency matrix A into the trained residual self-attention network model to obtain the features of the code to be processed; specifically includes:
[0053] Input the new feature matrix X' into the self-attention mechanism model of the trained residual self-attention network model to obtain the output matrix Z;
[0054] The output matrix Z and the adjacency matrix A are jointly input into the graph convolutional neural network of the trained residual self-attention network model to output the features of the code to be processed.
[0055] Furthermore, if Figure 3 As shown, the network structure of the self-attention mechanism model includes:
[0056] The first convolution layer, the second convolution layer, and the third convolution layer are arranged in parallel;
[0057] The input ends of the first convolutional layer, the second convolutional layer and the third convolutional layer are all used to input a new feature matrix X';
[0058] An output terminal of the first convolutional layer is connected to an input terminal of the first multiplier;
[0059] The output of the second convolutional layer is also connected to the input of the first multiplier;
[0060] The output end of the first multiplier is connected to the input end of the first adder through a softmax function layer;
[0061] When running for the first time, the input of the first adder is only connected to the output of the softmax function layer;
[0062] When it is not the first time to run, the input end of the first adder is also used to input the output value of the softmax function layer of the previous run;
[0063] An output terminal of the first adder is connected to an input terminal of the second multiplier;
[0064] The input end of the second multiplier is also connected to the output end of the third convolutional layer;
[0065] The output of the second multiplier is also connected to the input of the fourth convolutional layer;
[0066] The output end of the fourth convolutional layer is also connected to the input end of the second adder;
[0067] The input terminal of the second adder is used to input a new feature matrix X';
[0068] The output terminal of the second adder is used to output the matrix Z.
[0069] Furthermore, the working principle of the self-attention mechanism model includes:
[0070] The feature matrix As the input of the first convolution layer, the second convolution layer and the third convolution layer, the first convolution layer, the second convolution layer and the third convolution layer are connected. Perform linear mapping to calculate the query, key, and value, namely: Q, K, and V;
[0071] Q = GCN(X′) = X′W Q
[0072] Among them, W Q is a learnable weight matrix, and the calculation method of K and V is the same;
[0073] Then, Q and K are subjected to the matrix multiplication operation of the first multiplier to calculate the similarity between the two;
[0074] The score is calculated through the softmax function layer, and the weights of 0 to 1 are obtained. The weights are used as the attention coefficient attention, and the output of the current softmax operation is saved and recorded as attn;
[0075] When it is not the first time to run, the last softmax function layer output h_attn is added to attn through the first adder, and the addition result is matrix multiplied with V through the second multiplier;
[0076] The result of the matrix multiplication operation is then convolved through the fourth convolutional layer to extract global features;
[0077] Finally, the convolution operation result is combined with the original input Perform residual operation to obtain the output of self-attention and input it into the graph convolutional neural network.
[0078] Adding residuals inside the self-attention solves the problem of network gradient descent. In this way, not only residuals are added inside the self-attention mechanism, but also residual connections are added outside to improve the network's capabilities.
[0079] Furthermore, the graph convolutional neural network model has a network structure comprising:
[0080] The first graph convolutional layer, the first hidden layer, the second graph convolutional layer, and the second hidden layer are connected in sequence.
[0081] Furthermore, the graph convolutional neural network model has a working principle including:
[0082] The output matrix Z of the self-attention mechanism model and the matrix A(N*N) composed of the node pointing relationship are used as the input of the GCN network. The AST tree is embedded in the graph through the two-layer graph convolution layer of the GCN network to extract features. The feature vector of the last hidden layer is extracted as the feature vector of the node after hierarchical contrast learning of the node of the abstract syntax tree, which is expressed as:
[0083] GCN is a neural network layer that propagates information between layers:
[0084]
[0085] Represents the sum of the adjacency matrix A and the identity matrix I, introducing its own node, that is: for The degree matrix of (l) is the activation unit matrix of the lth layer. For the input layer, H (0) =X; σ is a nonlinear activation function, H (0) is the initial vector representation, W (l) is the weight parameter matrix of the lth graph convolutional network layer.
[0086] Construct two layers of graph convolutional layers, using ReLU and Softmax as activation functions respectively, and the overall forward propagation formula is:
[0087]
[0088] Furthermore, the training steps of the trained residual self-attention network model include:
[0089] Construct a residual self-attention network model;
[0090] Constructing a training set, wherein the training set is a known code of known extracted features;
[0091] Parse the code snippets of known code and generate AST tree;
[0092] Embed the AST tree to obtain the feature matrix X, and construct the adjacency matrix A of the AST tree;
[0093] Establish node labels based on the hierarchical number of each node in the AST tree; update the feature matrix X based on the node labels to obtain a new feature matrix X';
[0094] Use the new feature matrix X' as the input value of the self-attention mechanism model;
[0095] The output value of the self-attention mechanism model and the adjacency matrix A of the AST tree are used as the input value of the graph convolutional neural network model;
[0096] The known extracted features are used as the output values of the graph convolutional neural network, and the graph convolutional neural network is trained. When the loss function reaches the minimum value or the number of iterations meets the set requirements, the training is stopped to obtain the trained residual self-attention network model.
[0097] Among them, the loss function is:
[0098]
[0099]
[0100]
[0101] Where M represents the number of categories; y ic represents a variable 0 or 1, if the category is the same as the category of sample i, it is 1, otherwise it is 0; p icThe predicted probability that observation i belongs to category c.<a,p,n> Represents a triple, a is the anchor sample, p is the positive sample, and n is the negative sample; ||*|| is the Euclidean distance metric; α means that there is a minimum interval between the distance between x_a and x_n and the distance between x_a and x_p; + means that when the value in [] is greater than zero, the value is taken as the loss; when it is less than zero, the loss is zero; θ refers to the proportion of triple loss.
[0102] It should be understood that in order to better distinguish the input details, two loss functions are used, one is the multi-classification cross entropy loss, and the other is the triplet loss. The triplet loss can distinguish the details very well, especially in the classification task. When the two inputs are very similar, the triplet loss can learn a better representation for the two input vectors with small differences, thereby performing well in the classification task.
[0103] The residual self-attention network model combines the advantages of convolutional neural networks in obtaining local information through stacking and the characteristics of self-attention mechanisms in obtaining global information, extracting features from both local and global aspects. In order to solve the problem of gradient descent or even vanishing inside the graph network, the model also adds residual connections outside and inside the self-attention, which can effectively prevent gradient vanishing and enhance the network's expressiveness.
[0104] Embodiment 2
[0105] This embodiment provides a code feature extraction system based on hierarchical contrastive learning;
[0106] The code feature extraction system based on hierarchical contrastive learning includes:
[0107] The parsing module is configured to: obtain the code to be processed; parse the code fragment to be processed and generate an AST tree; embed the AST tree to obtain a feature matrix X, and construct an adjacency matrix A of the AST tree;
[0108] The matrix update module is configured to: establish a node label based on the hierarchical number of each node in the AST tree; update the feature matrix X based on the node label to obtain a new feature matrix X';
[0109] The feature extraction module is configured to: input the new feature matrix X' and the adjacency matrix A into the trained residual self-attention network model to obtain the features of the code to be processed; wherein the residual self-attention network model includes: a self-attention mechanism model and a graph convolutional neural network model connected in sequence.
[0110] It should be noted that the above-mentioned parsing module, matrix updating module and feature extraction module correspond to steps S101 to S103 in Embodiment 1, and the examples and application scenarios implemented by the above-mentioned modules and the corresponding steps are the same, but are not limited to the contents disclosed in the above-mentioned Embodiment 1. It should be noted that the above-mentioned modules as part of the system can be executed in a computer system such as a set of computer executable instructions.
[0111] The description of each embodiment in the above embodiments has different emphases. For parts not described in detail in a certain embodiment, reference can be made to the relevant descriptions of other embodiments.
[0112] The proposed system can be implemented in other ways. For example, the system embodiment described above is only illustrative, and the division of the modules is only a logical function division. In actual implementation, there may be other division methods, such as multiple modules can be combined or integrated into another system, or some features can be ignored or not executed.
[0113] Embodiment 3
[0114] This embodiment also provides an electronic device, including: one or more processors, one or more memories, and one or more computer programs; wherein the processor is connected to the memory, and the one or more computer programs are stored in the memory. When the electronic device is running, the processor executes the one or more computer programs stored in the memory so that the electronic device executes the method described in the above embodiment one.
[0115] It should be understood that in this embodiment, the processor may be a central processing unit CPU, and the processor may also be other general-purpose processors, digital signal processors DSP, application-specific integrated circuits ASIC, off-the-shelf programmable gate arrays FPGA or other programmable logic devices, discrete gate or transistor logic devices, discrete hardware components, etc. The general-purpose processor may be a microprocessor or the processor may also be any conventional processor, etc.
[0116] The memory may include a read-only memory and a random access memory, and provide instructions and data to the processor. A portion of the memory may also include a non-volatile random access memory. For example, the memory may also store information about the device type.
[0117] In the implementation process, each step of the above method can be completed by an integrated logic circuit of hardware in a processor or an instruction in the form of software.
[0118] The method in the first embodiment can be directly embodied as a hardware processor, or a combination of hardware and software modules in the processor. The software module can be located in a mature storage medium in the field such as a random access memory, a flash memory, a read-only memory, a programmable read-only memory, or an electrically erasable programmable memory, a register, etc. The storage medium is located in the memory, and the processor reads the information in the memory and completes the steps of the above method in combination with its hardware. To avoid repetition, it will not be described in detail here.
[0119] Those skilled in the art will appreciate that the units and algorithm steps of each example described in conjunction with this embodiment can be implemented in electronic hardware or a combination of computer software and electronic hardware. Whether these functions are performed in hardware or software depends on the specific application and design constraints of the technical solution. Professional and technical personnel can use different methods to implement the described functions for each specific application, but such implementation should not be considered to be beyond the scope of the present invention.
[0120] Embodiment 4
[0121] This embodiment further provides a computer-readable storage medium for storing computer instructions. When the computer instructions are executed by a processor, the method described in the first embodiment is completed.
[0122] The above description is only a preferred embodiment of the present invention and is not intended to limit the present invention. For those skilled in the art, the present invention may have various modifications and variations. Any modification, equivalent replacement, improvement, etc. made within the spirit and principle of the present invention shall be included in the protection scope of the present invention.
Claims
1. Code feature extraction method based on hierarchical contrastive learning, characterized by: include: Get the code to be processed; Parse the code snippet to be processed and generate an AST tree; The AST tree is embedded to obtain the feature matrix X, and the adjacency matrix A of the AST tree is constructed, which includes: Construct the adjacency matrix A according to whether there is a pointing relationship between the nodes of the AST tree; Among them, the adjacency matrix A is used to store the pointing relationship between nodes. If there is a pointing relationship between nodes, the corresponding element value of the adjacency matrix A is 1, otherwise the corresponding element value is 0; Establish node labels based on the hierarchical number of each node in the AST tree; update the feature matrix X based on the node labels to obtain a new feature matrix X'; The new feature matrix X' and adjacency matrix A are input into the trained residual self-attention network model to obtain the features of the code to be processed, including: Input the new feature matrix X' into the self-attention mechanism model of the trained residual self-attention network model to obtain the output matrix Z; The output matrix Z and the adjacency matrix A are input into the graph convolutional neural network of the trained residual self-attention network model to output the features of the code to be processed; Among them, the residual self-attention network model includes: a self-attention mechanism model and a graph convolutional neural network model connected in sequence.
2. The code feature extraction method based on hierarchical contrastive learning as claimed in claim 1, characterized in that: Parse the code snippet to be processed and generate an AST tree; Specifically include: Use JavaParser to parse the code and generate its corresponding AST tree; Among them, JavaParser is used to parse the code, and two parts of information are obtained after parsing: one is the information represented by the AST tree node; the other is the pointing relationship between nodes and the storage of edge information.
3. The code feature extraction method based on hierarchical contrastive learning as claimed in claim 1, characterized in that: The AST tree is embedded to obtain the feature matrix X; specifically, it includes: Using word embedding, the string corresponding to each node of the AST tree is embedded to obtain the feature matrix X, where X = {p1, p2, ..., p N }, p N Represents the vector representation of the Nth node.
4. The code feature extraction method based on hierarchical contrastive learning as claimed in claim 1, characterized in that: Establish node labels based on the hierarchical number of each node in the AST tree; update the feature matrix X based on the node labels to obtain a new feature matrix X'; Specifically include: Based on the unique ID corresponding to each node, the depth of its position in the tree is labeled accordingly. Starting from the root node, the AST tree is traversed. The root node is marked as 0, the first-level child nodes are marked as 1, the second-level child nodes are marked as 2, and so on. The M-th-level child nodes are marked as M. Update the feature matrix X based on the node label to get a new feature matrix 5. The code feature extraction method based on hierarchical contrastive learning as claimed in claim 1, characterized in that: The working principle of the self-attention mechanism model includes: The feature matrix As the input of the first convolution layer, the second convolution layer and the third convolution layer, the first convolution layer, the second convolution layer and the third convolution layer are connected. Perform linear mapping to calculate the query, key, and value, namely: Q, K, and V; Q=GCN(X′)=X′W Q Among them, W Q is a learnable weight matrix, and the calculation method of K and V is the same; Then, Q and K are subjected to the matrix multiplication operation of the first multiplier to calculate the similarity between the two; The score is calculated through the softmax function layer, and the weights of 0 to 1 are obtained. The weights are used as the attention coefficient attention, and the output of the current softmax operation is saved and recorded as attn; When it is not the first time to run, the last softmax function layer output h_attn is added to attn through the first adder, and the addition result is matrix multiplied with V through the second multiplier; The result of the matrix multiplication operation is then convolved through the fourth convolutional layer to extract global features; Finally, the convolution operation result is combined with the original input Perform residual operation to obtain the output of self-attention and input it into the graph convolutional neural network; or, The graph convolutional neural network model has the following working principles: The output matrix Z of the self-attention mechanism model and the matrix A composed of the node pointing relationship are used as the input of the GCN network. The AST tree is embedded in the graph through the two-layer graph convolution layer of the GCN network to extract features. The feature vector of the last hidden layer is extracted as the feature vector of the node after hierarchical contrast learning of the node of the abstract syntax tree, which is expressed as:
6. A code feature extraction system based on hierarchical contrastive learning, characterized by: include: The parsing module is configured to: obtain the code to be processed; Parse the code snippet to be processed and generate an AST tree; The AST tree is embedded to obtain the feature matrix X, and the adjacency matrix A of the AST tree is constructed, which includes: Construct the adjacency matrix A according to whether there is a pointing relationship between the nodes of the AST tree; Among them, the adjacency matrix A is used to store the pointing relationship between nodes. If there is a pointing relationship between nodes, the corresponding element value of the adjacency matrix A is 1, otherwise the corresponding element value is 0; The matrix update module is configured to: establish a node label based on the hierarchical number of each node in the AST tree; update the feature matrix X based on the node label to obtain a new feature matrix X'; The feature extraction module is configured to: input the new feature matrix X' and the adjacency matrix A into the trained residual self-attention network model to obtain the features of the code to be processed, specifically: Input the new feature matrix X' into the self-attention mechanism model of the trained residual self-attention network model to obtain the output matrix Z; The output matrix Z and the adjacency matrix A are input into the graph convolutional neural network of the trained residual self-attention network model to output the features of the code to be processed; Among them, the residual self-attention network model includes: a self-attention mechanism model and a graph convolutional neural network model connected in sequence.
7. An electronic device, characterized in that: include: One or more processors, one or more memories, and one or more computer programs; wherein the processor is connected to the memory, and the one or more computer programs are stored in the memory, and when the electronic device is running, the processor executes the one or more computer programs stored in the memory to enable the electronic device to execute the method described in any one of claims 1 to 5.
8. A computer-readable storage medium, characterized in that: Used to store computer instructions, which, when executed by a processor, complete the method described in any one of claims 1 to 5.
