code2vec: Learning Distributed Representations of Code
0x00 前言
读完这篇paper,第一感觉是:写得太详细(啰嗦)。好多东西翻来覆去讲了好几遍,最后总长度30页,确定不是水字数的?
但是不得不承认,论文里提到的方法很好。
0x01 Introduction
这篇paper提供了一种学习code的 Distributed Representation 的方法,借鉴了 word2vec 和 Attention 的方法。
它使用代码的抽象语法树结构,对代码片段在树上的路径(包括Terminal在内)进行 embedding ,这样得到的 code 的 embedding 可以用来做一些 downstream 的任务,原文做的任务是给出方法的代码,预测方法名。
0x02 AST Paths
对于代码片段
一条 AST Path 就是语法树上从一个终结符到另一个终结符之间的路径,中间会经过两终结符的LCA,可以被表示为一个三元组 $
如语句
1 | x = 7 |
就可以被表示为
0x03 Embedding Model
AST Path Embedding
一条 AST Path 的 embedding 由它所对应的三元组(两个终结符的值 + 中间路径)所对应的 embedding 连接起来,再经过一个全连接层得到。对于终结符的值和路径的 embedding ,采用 word2vec 的方法,即用 one-hot 向量和 embedding 矩阵作乘法,即可得到对应的 embedding 向量。
具体来说,有
将这三个向量连接起来,得到
Code Snippet Embedding
在得到代码片段中所有 AST Path 的 embedding 之后,对每条 AST Path 进行 Attention 操作,得到 attention weight ,将所有 AST Path 的 embedding 按照这个 attention weight 进行加权求和,得到整个代码段的 embedding 。
具体来说,我们有一个全局的 attention 向量
softmax 是指,对于得到的 AST Path 的 embedding 们
$\alphai=\frac{exp(c^T_i\cdot a)}{\sum{j=1}^n exp(c^T_j\cdot a)}$
,这个值满足
我们将每条 AST Path 对应的 embedding
。
Label Embedding
对于每个代码段的标签(在这里就是这个方法对应的方法名),也采用 word2vec 的方法对其进行 embedding ,即有
0x04 Prediction Model
在得到代码段和各个标签的 embedding 以后,我们需要预测这个代码段是每个标签的概率。我们这样计算代码段
$q(yi) = \frac{exp(v^T\cdot tags_vocab_i)}{\sum{y_j\in Y}exp(v^T\cdot tags_vocab_j)}$
,其中
0x05 Training
使用交叉熵损失(Cross Entropy Loss)作为损失函数。
使用反向传播机制+梯度下降算法,即可完成模型训练。
- Post title:code2vec: Learning Distributed Representations of Code
- Post author:Franky
- Create time:2023-03-22 15:45:08
- Post link:https://franky.pro/2023/03/22/code2vec-Learning-Distributed-Representations-of-Code/
- Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.