{'fraction_non_alphanumeric': 0.03212399863473006, 'fraction_numerical': 0.011765414499969883, 'mean_word_length': 4.857697283311772, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
On the Importance of Building High-quality Training Datasets for Neural Code Search

The performance of neural code search is significantly influenced by the quality of the training data from which the neural models are derived. A large corpus of high-quality query and code pairs is demanded to establish a precise mapping from the natural language to the programming language. Due to the limited availability, most widely-used code search datasets are established with compromise, such as using code comments as a replacement of queries. Our empirical study on a famous code search dataset reveals that over one-third of its queries contain noises that make them deviate from natural user queries. Models trained through noisy data are faced with severe performance degradation when applied in real-world scenarios. To improve the dataset quality and make the queries of its samples semantically identical to real user queries is critical for the practical usability of neural code search. In this paper, we propose a data cleaning framework consisting of two subsequent filters: a rule-based syntactic filter and a model-based semantic filter. This is the first framework that applies semantic query cleaning to code search datasets. Experimentally, we evaluated the effectiveness of our framework on two widely-used code search models and three manually-annotated code retrieval benchmarks. Training the popular DeepCS model with the filtered dataset from our framework improves its performance by 19.2% MRR and 21.3% Answer@1, on average with the three validation benchmarks.


INTRODUCTION
A semantic code search engine is a vital software development assistant, which significantly improves the development efficiency and quality. With a description of the intended code functionality in natural language, a search engine can retrieve a list of semantically best-matched code snippets from its codebase. Recently, deep learning (DL) has been widely applied in this area in view of its advantages in semantic modeling and understanding of languages. In the task of code search, DL models learn and represent the semantic mappings between the natural language and the programming language from query-code pairs. Like many other DL tasks, code search models are data-hungry and require large-scale and high-quality training datasets. Nevertheless, collecting a large set of query-code pairs is challenging, where the queries are supposed to be natural expressions from developers and the code to be a valid semantic match. Instead, considering the scale and availability, code comments are popularly used as an alternative to the queries, many of which describe the core functionalities and with the corresponding code implementation rightly available. To better understand the quality of datasets hence constructed, we investigated a Github dataset, CodeSearch-Net (Java) [19], which is popularly used in current code search research. Surprisingly, we found a considerable amount of noise and unnaturalness in the queries of its data samples, which can hinder the training of high-quality models for practical usage. As shown in Fig. 1, one-third of its queries contain text features (see Table 1 for examples of different features) that hardly exist in actual user queries. The features are summarized based on our observations of the dataset, and may not be sufficient. Comments may also be used for other purposes, such as copyright and to-do, instead of describing the core functionalities, thus shall not be seen as queries. The proportion of noise data can be higher than one-third.
Code search models trained with noisy queries will face severe performance degradation when dealing with actual user queries. The gap between the collected comment-code pairs and the natural user queries violates the basic assumption of learning algorithms that the training data and the evaluation data share a similar distribution. It is also noteworthy that evaluating the model with a noisy comment-code benchmark can hardly reflect how useful the model would be in practice, and, even worse, may bring non-negligible bias to the model design, evaluation and application. Many other researchers [7,30,44] also point out the misalignment between code comments and natural user queries, and report it as a threat to the validity of their approaches. As mentioned in [31,57], improving the quality of the training data is still a research opportunity for machine learning, including DL-based code search models. Considering that there are still plenty of comments close to actual user queries and naturally paired with high-quality code snippets, a promising solution is to filter out the noisy ones. Manual filtering can produce the most accurate results but is hardly practical for large-scale datasets. Automated data cleaning methods are of demanding needs.
Queries for code retrieval possess specific syntactic and semantic characteristics, which can be utilized as key features to distinguish genuine user queries from noise. Typical syntactic features include text attributes such as keywords, sentence length, and language type. Semantic features are related to the intention underneath the text expression, which usually describes the computational functionality of code snippets and might be influenced by the design convention of common program APIs. Compared with syntactic features, semantic features are more abstract, implicit, and hard to be matched by simple rules. Recently, some initial efforts have emerged on query quality enhancement, but primarily focusing on the regularization of syntactic features. Simple filtering heuristics are proposed, based on the appearance of verb and noun phrases [30], keywords uncommonly used in queries [7], and constraints on the query length [19,30].
However, the improvement in data quality is limited. As declared in [19], the collected dataset is still noisy despite their data cleaning efforts. The proposed rules are not sufficient to cover the various syntactic violations, let alone the semantic misalignment. For example, warning messages such as "Use of this property requires Java 6" widely exist in the code comments, but few code queries would request this way. Hence, a remaining challenge is recognizing the code comments that are syntactically valid but encode semantics rarely seen in natural user queries.
To tackle this challenge, we propose an automated and effective data cleaning framework that distills high-quality queries from Fully Remove DEPRECATED generally collected code comments on a large scale. The framework is orthogonal to the design of code search algorithms and could be integrated with any of them to improve the quality of the training dataset. Basically, it encompasses two subsequent filters: a rule-based syntactic filter and a model-based semantic filter. The rule-based filter includes a set of systematically designed heuristic rules and weeds out data with anomalous syntactic features, e.g., HTML tags and Javadoc tags. It is developed to cover a diverse range of syntactic violations, and each member inside is validated to reduce the noises effectively. It is also extensible to fulfill the specific requirements for the dataset based on the applications. The model-based semantic filter further refines the dataset produced by the rule-based filter and retains the comments that are semantically close to the natural queries. The filter relies on a bootstrap query corpus, a set of high-quality queries, which represents how semantically the queries should look. It learns the semantic features of the corpus, such as the expression style and topic, with a DL model, and leverages it to identify samples with similar semantics. The bootstrap query corpus could be constructed with any trusted sources of natural user queries, and we formulate it with question titles from StackOverflow in this work. These titles are an ideal approximation of natural queries and could be re-used by related studies. Then, a Variational Auto-Encoder [22] is trained with the bootstrap query corpus, which maps the inputs into a latent space and attempts to reconstruct the original inputs solely based on the latent features. The reconstruction loss reflects "how far away" an input is from the training data distribution, i.e., the distribution of queries in the bootstrap query corpus. The lower the reconstruction loss, the more qualified an input is as a natural query. We compute the reconstruction loss for each code comment in the raw dataset and cluster them into two groups. The group of qualified queries is retained for training, and the group of noises is discarded.
To evaluate the effectiveness of our data cleaning framework, we compare the performance of code search models trained with datasets before and after the filtering. One training dataset, two neural models, and three manually annotated validation datasets are used in the experiments, and our framework brings a significant performance improvement under all settings. In particular, the performance of the popular DeepCS [15] model is improved by 19.2% MRR and 21.3% Answer@1, on average with the three validation datasets. More importantly, with less training data used after the filtering, we also save the training time and computation resources.
Further, we carry out a comprehensive ablation study to validate the usefulness of each filter component and each rule and manually inspect the quality of the rejected and retained data. Finally, we release the implementation of our framework, NLQF, and a cleaned code search dataset, COFIC, to facilitate future research. The source code and datasets are available at https://github.com/v587su/NLQF.
To the best of our knowledge, this is the first systematic data cleaning framework for comment-based code search datasets. Our main contributions include: • A two-step data cleaning framework for code search datasets, which bridges the gap between code comments and natural user queries, both syntactically and semantically. • Implementation of the framework as a Python library for the code search task in academia and industry. • A comprehensive evaluation of our framework's effectiveness, which demonstrates significant model performance improvement on three manually-annotated validation benchmarks. • The first systematically distilled Github dataset for neural code search, containing over one million comment-code pairs.

PRELIMINARIES
We prepare readers with the primary sources for collecting querycode pairs and the Variational Auto-Encoder, a major building block of our framework.

Data Source
A query for neural code search describes, in natural language, the functionality of the code snippets desired by users, e.g., "convert string to JSON object". The ideal data source for genuine code queries is the production data from existing neural code search engines. However, these queries are not publicly accessible due to privacy and business sensitivity. In academia, researchers use texts with similar intentions (e.g., code comments) as a replacement. The primary alternative data sources for semantic code search research include GitHub and StackOverflow.
2.1.1 Github. Github [1] is an open-source community, hosting more than 100 million repositories. It is the most popular platform for developers to share and manage their projects. The large-scale well-maintained repositories on Github are a treasury for code reuse during development, thus naturally becoming the main retrieval source for code search tasks. Moreover, mature projects are usually accompanied by canonical development documents. According to Javadoc[2], a code comment style guide, the first sentence of doc comments should be a summary sentence. Therefore, it is convenient to construct a code search dataset by collecting the code snippets paired with the first sentence of comments, forming the comment-code pairs. Javadoc-generated comments have hence been widely used in practice for various software engineering purposes [25][26][27]33] due to their large scale, ease of obtaining, and being close to actual use scenarios. However, developers write comments for their software projects without considering the retrieval purposes. Not all the comments properly map to queries. As mentioned in Section 1, the Code-SearchNet collected from Github contains plenty of anomalies that rarely exist in natural user queries. It is not appropriate to include these comments in the dataset, and we call for more attention to be drawn to this problem.
2.1.2 StackOverflow. StackOverflow[4] serves as a Q&A community specialized for software developers. It is a rich resource of software-related questions and answers. When asking about codes or APIs for implementing a specific functionality, users would propose a question title to express their intention. These are natural user queries with valid syntax and semantics. Hence, researchers [52,54] also collect the titles of StackOverflow questions paired with proper answers containing sample code snippets, which also form the query-code pairs. Others also evaluate their code search models with queries manually selected from StackOverflow [7,15,32], and additional public evaluation benchmarks could be found in [24,50].
Compared with the Github data source, queries from StackOverflow have a significant advantage of being closer to natural user queries, but the quality of code samples is hard to guarantee. Hence, the dataset collected from StackOverflow is still not as desired. Nevertheless, the query corpus is valuable. It is worth investigating whether and how it could be leveraged to improve the other query-code datasets.

Variational Auto-Encoder
Variational Auto-Encoder (VAE) [5] is a neural model that learns the distribution of a set of data. A VAE model consists of an encoder and a decoder. The encoder learns to map an input data into a prior distribution ( ), from which a latent variable is sampled, and the decoder maps back toˆ, a reconstruction of . It is expensive to calculate ( ) directly, so VAE introduces an approximate posterior ( | ). and are parameters of the prior and the approximate posterior.
The loss function, Evidence Lower Bound (ELBO), which seeks to maximize the likelihood of reconstructing the original data and minimize the Kullback-Leibler (KL) divergence between the actual and estimated posterior distributions, is represented as: where represents the KL divergence. Theoretically, the distributions of ( | ) and ( ) can be arbitrary. In practice, the Gaussian distribution is mostly adopted.

THE DATA CLEANING FRAMEWORK
This section introduces our automated and effective data cleaning framework for code search datasets, mainly to filter out query-code pairs with inappropriate queries. The framework consists of two subsequent filters, the rule-based syntactic filter and model-based semantic filter. An overview of the framework, when applied to clean the comment-code pairs collected from Github, is shown in Fig. 2. The raw comment-code pairs are firstly cleaned by the rule-based filter, where a ruleset is applied to detect the existence of invalid query syntax. Next, for the model-based filter, leveraging a small bootstrap query corpus as the semantics reference, a VAE model is trained to model its characteristics and further used to reject comments violating the natural query semantics. Here we collect the bootstrap query corpus (no need of the paired code snippets) from StackOverflow, and more details can be found in Section 4.1. Such, we take advantage of both the Github

Comment-Code Pairs
Query-Code Pairs

Rule-based Syntactic Filter
Figure 2: An overview of our data cleaning framework.
data sources and produce a large set of high-quality query-code pairs. In the following, we elaborate on the design of the two filters.

The Rule-based Syntactic Filter
Code comments contain richer information than just descriptions on code functionalities and manifest various syntactic features rarely existing in actual code search quires. For example, URLs are used for external references, and HTML tags are used in comments for documentation autogeneration. To reduce such deviations from natural queries, we sampled 1% code comments from CodeSearch-Net, manually inspected and summarized noises in these 3,949 instances. We establish a black list of invalid syntax features to reject unqualified code comments. If a comment matches any of these features, we remove the invalid parts if they are detachable; otherwise, we abandon this comment-code pair. Based on a comparative observation of code comments and user queries, we develop a set of rules to precisely identify synthetically inappropriate queries and leave the fine-grained semantic check to the model-based filter. To facilitate the management, we define three criteria that the ruleset must comply with: 1) any rule should define a unique and specific construction pattern, 2) the rules should be conservative and limit the preclusion of valid queries within an acceptable range, and 3) any rule is not a subrule of other rules in the set. As a plug-in framework, the ruleset is extensible, and any rules that meet these criteria can be appended to the set.
We introduce the syntax features covered by our ruleset in the following, and their examples can be found in Table 1. We empirically decide whether to keep the content enclosed by a feature structure or not and validate the decisions with experiments (see our website [3] for more details) and manual inspection (see Section 5.2). From the results, our decisions help improve the naturalness and bring greater improvement to the model performance. HTML tags HTML tags are used for documentation autogeneration in comments and should not appear in user queries. However, the content wrapped by the tags can still be informative. Therefore, we remove the HTML tags from the comments but keep the wrapped content. Parentheses Parentheses in comments are for adding supplementary information and do not appear in user queries. Due to such purpose, the removal of the content inside the parentheses does not have much influence on the completeness of the comments. We only retain the content outside of the parentheses. Javadoc tags Javadoc tags starting with an "@" sign are special tags indicating a Javadoc comment. Such comments are only consumed by the Javadoc project for autogenerating well-formatted documentation. Considering that the special syntax of the tags may mislead code search models on natural language understanding, we reject all comments containing Javadoc tags. URLs URLs in comments provide external references to relevant code snippets, but natural language queries do not contain any URLs. We reject all comments containing URLs. Non-English Languages Non-English expressions exist as developers from different countries may write comments in their first languages. However, current code search models are not designed to handle multi-languages. We reject all non-English comments. Punctuation Sometimes, punctuation symbols are used for section partitioning in the comments. For example, developers use a row of equal signs (=) or asterisks signs ( * ) (see examples in Table 1) to indicate a new section. For effectiveness, we reject comments containing no English letters in our implementation. Interrogation Based on our observation, some of the comments in the dataset are interrogative. Developers seem to use comments to communicate with their collaborators during the code review process. There may be some sparse information about the code functionality, but the quality is hard to control. We reject comments ending with a question mark. Short Sentence The sentence length is a commonly used criterion for comment filtering. Extremely short comments are not informative enough for code search models to establish their mapping to the corresponding code snippets. We reject comments containing no more than two words.

The Model-based Semantic Filter
This section introduces the model-based semantic filter, which takes the initially cleaned comment-code pairs from the rule-based filter as input and further selects the pairs with comments semantically close to the queries in a pre-collected bootstrap query corpus. We present the detailed design of the VAE model and discuss how it is used for filtering.

3.2.1
The VAE Model. The two main components of a VAE model are the encoder and decoder, which are generally composed of deep neural networks. Here, we use Gated Recurrent Unit (GRU) [11] for both the encoder and decoder in our VAE model. GRU is a variant of Recurrent Neural Network (RNN), which enables the model to capture information from sequential texts. Fig. 3 illustrates an overview of the design of the model structure. Details about each layer are as follows.
Embedding Given a query 0 1 . . . of length , the -th token is . The embedding layer is responsible for mapping each token into an embedding vector. It consists of an embedding matrix E ∈ R × , where is the vocabulary size of the query language and is the dimension of embedding vectors. The matrix is initialized with random values and updated during training.
GRU Encoder We design the encoder of VAE as a bi-directional GRU. Sequentially, it deals with the input tokens, and propagates the upstream and downstream context through the hidden states, respectively in the forward and backward directions, as shown in Eq.
(2) and Eq. (3). maps a token to its embedding vector. Finally, we sum up the last hidden states of both directions to get the final hidden state, as in Eq. (4), and pass it to the next layer.
Latent Variable Based on the hidden state h from the encoder, we estimate the parameters of a Gaussian distribution with a fullyconnected layer, which are the mean vector and variance vector 2 . The latent variable z is randomly sampled from this distribution. The equations are as follows: where is a fully-connected layer and r is a random vector from the standard normal distribution.
GRU Decoder The latent variable represents the key features of the original input in a highly abstract and compact way. The decoder works to reconstruct the input solely based on the latent variable. Iteratively, the decoder computes the hidden state at each step and reconstructs token ′ , based on the previous state −1 (or z at step 0) and ′ −1 generated in the previous step. The equations are as follows: where is a special token indicating the start of a sentence, and ∈ R represents the probability of -th token to be generated. Loss We measure the likelihood of reconstructing the original input with the Cross-Entropy (CE) loss. Hence, the ELBO loss introduced in Section 2.2 can be computed as: best dividing point where and represents the calculation of the CE loss and KL divergence.

The Filtering Algorithm.
We train the VAE model with a set of high-quality code search queries collected from near-real scenarios, which we call the bootstrap query corpus. After the training, the VAE model is able to recognize whether a query semantically resembles those in the corpus. We measure the reconstruction loss, i.e., the CE loss, of an input when fed to the VAE model, which just reflects how well it is within the training set distribution. Intuitively, the loss value is the anomaly score gauging how far an input stays away from the queries in bootstrap query corpus. Comments with smaller losses are more likely to be query-appropriate.
To select comments resembling queries in bootstrap query corpus, we sort the comments based on their reconstruction losses, in ascending order, and retain the top-ranked ones. It is tricky to decide an appropriate dividing point for retaining the portion with better quality and discarding the remaining. The less data we keep from the top, the higher the dataset quality. However, a sharp reduction in the data size hinders the performance of the trained code search model. Fig. 4 shows a theoretical model illustrating the relation between the dividing point and the model performance. As the amount of retained data increases, the model performance firstly increases and then decreases after reaching the peak. There is a trade-off between the quality and quantity of the dataset.
We leverage an unsupervised clustering algorithm, EM-GMM (Expectation-Maximization for Gaussian Mixture Model) [14], to decide the partition automatically. It is widely used to model the mixed distributions of a dataset. For our task, EM-GMM divides a set of comments into the qualified and the unqualified groups based on the reconstruction loss. For each group, GMM fits a Gaussian probability density function and mixes them together as the distribution of the whole dataset, which can be represented as: where is the mixture coefficient for the qualified group, ( , ) and ( , ) are the parameters for the Gaussian probability density functions of the qualified and unqualified groups, respectively. Finally, the EM algorithm [14] is applied to estimate a set of optimal values for all the parameters.
Note that, to establish a high-quality code search dataset, all comments are processed together with their paired code snippets.
Hence, we obtain a set of comment-code pairs after applying this semantic filter, where the comments are syntactically and semantically close to natural user queries.

EXPERIMENT SETUP
We introduce the research questions, the basic experimental setup about the datasets and models, and the evaluation metrics used throughout the evaluation. The research questions we aim to answer include: RQ1: How effective is our data cleaning framework? RQ2: What is the impact of each filter component and each rule on the effectiveness of our framework? RQ3: How is the dividing point determined by the clustering algorithm during the model-based filtering?

Datasets
Three types of datasets are involved in our evaluation, including the training and validation datasets used to train and assess the performance of code search models and the bootstrap query corpus used to develop our model-based filter. To make the best use of existing resources, we focus on the Java programming language in this work, for which there have been the most public datasets and models in the field of neural code search. Theoretically, our framework is language-independent and applicable to other programming languages with a proper adaptation of the filtering rules.

Training Datasets.
We use the popular CodeSearchNet (CSN) [19] dataset to train all the code search models. CSN is a collection of datasets and benchmarks for semantic code retrieval. It extracts functions and their paired comments from Github repositories. It covers six programming languages, and we take the training dataset for Java, which contains 394,471 data points. We took the first sentence of each comment. In what follows, we denote it as CSN-t. Another widely used dataset in DeepCS [15] is not included because the authors only released the processed data, but our framework cannot work without accessing the raw data.

Validation Datasets.
We utilize human-annotated validation datasets to evaluate how well a code search model performs in a real-world scenario, and three widely used datasets are adopted. It is noteworthy that the validation datasets are never filtered by our framework in order to ensure the fairness of our experiments. They are listed as follows: • CSN-v CSN also offers a validation benchmark for Java, containing query-code pairs collected from Bing and StackOverflow. Human annotators are hired to rate the relevance between the query and the code. Pairs with a score greater than 0 are deemed as relevant, and there are 434 relevant pairs in total. In the dataset, each pair is accompanied by 999 distractor code snippets. It means, given a query, the code search model needs to retrieve the ground truth among 1000 candidates. • CB CosBench (CB) [50] is a validation dataset consisting of 52 selective queries from StackOverflow. For each query, the authors prepared around ten paring code snippets as its ground truths, including its best answer on StackOverflow and several other matched code snippets selected from GitHub. Additionally, there is a pool of 4,199,769 distractor code snippets. The model needs to search the ground truths from a mixture with the complete code pool given a query. • NCSED Proposed in [24], the NCSED dataset contains 287 question queries manually collected from StackOverflow. For each query, there are around three pairing code snippets selected from GitHub. The ground truths are mixed with other 4,716,814 distractor code snippets collected from GitHub. The search model is required to retrieve the ground truths from the large corpus for a query.
The extremely large search space in NCSED and CB makes it extremely hard for code search models to achieve a good performance, and the performances variations brought by data cleaning can also be too marginal to compare. Without loss of generality, for each query in NCSED and CB, we construct 999 distractor snippets, following a similar fashion as CSN-v.

Bootstrap Query Corpus.
StackOverflow is an ideal source for collecting resemblers of actual user queries, though the quality of the pairing code snippets is hard to guarantee. It becomes an optimal choice to establish the bootstrap query corpus. We surveyed existing StackOverflow datasets in the code search field, and found that they were of severely limited size. With their aim to collect high-quality question-code pairs, numerous questions were discarded due to the lack of qualified code answers. Hence, to better facilitate the training of our VAE model, we determined to construct a questiononly corpus from StackOverflow instead of using existing ones.
According to a study [36], the StackOverflow questions can be divided into four types: "Debug/Corrective", "Need-To-Know", "How-To-Do-It" and "Seeking-Different-Solution". Among them, questions of the "How-To-Do-It" type are most relevant to queries for the code search task. Aiming to select the most qualified resemblers, we require the question titles to 1) start with "how to", 2) be tagged with "Java", and 3) pass the rule-based syntactic filter proposed in Section 3.1 (except for the Interrogation rule). In the end, 168,779 out of 1,709,703 Java-related question titles were retained. Afterwards, we transformed them into declarative sentences by removing the starting "how to" and the question marks if any, thus forming the bootstrap query corpus, which is used to train the VAE model later.

Code Search Model
Two code search models, DeepCS [15] and CARLCS [41], are used in our experiments. They are designed with representative architectures among most neural code search models. DeepCS is based on the Siamese architecture, and CARLCS is an Interaction-based network [35]. The Siamese architecture consists of two DL models to represent the query and code, respectively, with independent embedding vectors, and the similarity between these vectors is used to measure the relevance between query and code. The Interactionbased network compares the query and code directly by generating an interaction matrix to reflect their relevance.
When training the models with our training dataset, we adopted the recommended settings for all the hyper-parameters, except for the training epoch of the DeepCS model. In order to save some time and computation resources, we set the maximum training epoch of DeepCS to 100 instead of the recommended 500. Without loss of fairness, the same setting has been used for training with the dataset either before or after the data cleaning. This change should

Evaluation Metrics
Two widely used metrics are adopted in our experiments to evaluate the code retrieval performance.

RESULTS
In this section, we show the experimental results and answer the research questions. Measures for both evaluation metrics are reported as the medium over five independent runs.

RQ1: Effectiveness
This experiment evaluates the effectiveness of our data cleaning solution as a pre-processing step when training neural code search models. Specifically, one training dataset (CSN-t), two code search models (DeepCS and CARLCS), and three validation datasets (CSNv, CB, and NCSED) are used in the evaluation. Thus, we have six (1 × 2 × 3) experimental settings in total. During experiments, a relatively smaller filtered training set will be derived from CSNt after our framework is applied for the data cleaning. To also benchmark the performance variation brought by the size shrinking, we further derive a controlled training set by randomly selecting from CSN-t an equivalent number of data as the filtered set. We observe the model performance resulted from training with these three datasets respectively. The model performance is measured with four evaluation metrics, namely, A@1, A@5, A@10, and MRR, and the results are shown in Table 2. Under all the six experimental settings, our data cleaning framework demonstrates a positive influence on the model's searching ability and helps it hit the best score. On average of the three validation datasets, DeepCS trained over the filtered data outperforms the one trained over original data by 21.3% A@1, 17.4% A@5, 7.8% A@10, and 19.2% MRR. Correspondingly, the improvements of CARLCS are 63.3% A@1, 58.6% A@5, 16.0% A@10, and 38.6% MRR. Regarding the MRR on the three validation datasets, CSN-v,CB, and NCSED, DeepCS achieves 0.512, 0.644 and 0.271, and CARLCS achieves 0.302, 0.056 and 0.168, respectively. Basically, DeepCS and CARLCS are boosted to their new best records, and CARLCS sees a greater improvement. Note that the A@1 score of CARLCS over NCSED is increased by 75.0% (from 20 to 35), which is an extraordinary improvement.
Overall, with around half of the data quantity and half of the training time, models trained over the filtered data achieve a significant improvement on the number of answered queries and the rank of ground truth in search results.
Answer to RQ1: Our filtering framework produces a highquality query-code dataset, which shortens the training time by reducing the training data and effectively improves the performance of the code search model under a real-world application scenario.

RQ2: The impact of each filter component and each rule
We evaluate the effectiveness of each filter component with ablation experiments and conduct manual inspection on the queries accepted/rejected by each syntactic rule and the model-based filter to study their precision in identifying noises. Each time, one of the two filter components is muted for the ablation experiments. We observe the model performance after training with such derived filtered dataset and compare it with their previous performance (in Section 5.1). If the performance declines compared with when both filters are enabled, we can infer a positive impact of the muted component on the framework effectiveness. We evaluate the performance of DeepCS and CARLCS trained under ablation and report the results in Table 3. The removal of any filter leads to worse performance scores. Without the model-based filter, the A@1, A@5, A@10, and MRR scores of DeepCS on the three validation sets reduce by 5.4%, 5.6%, 3.6%, and 4.6% on average. CARLCS sees a much more severe deduction, and on average, A@1, A@5, A@10, and MRR decrease by 35.5%, 18.7%, 10.4%, and 20.6%. After removing the rule-based filter, the performance of DeepCS averagely drops by 8.4% A@1, 6.4% A@5, 5.2% A@10, and 7.6% MRR. Meanwhile, the average reduction percentages of CARLCS on all the validation sets are 32.7% A@1, 15.5% A@5, 9.9% A@10, and 14.3% MRR. It is noteworthy that the A@1 score of CARLCS on NCSED drops from 35 to 18 when the rule filter is muted, indicating that the ruleset plays a very influential part during the data cleaning.
For the manual inspection, two annotators, with over two years' development experience, are hired to rate how likely a sentence is to be used as a code search query. The rating score ranges from 0 to 2, where 0 means worst and 2 best. There are 11 groups of data to annotate, including eight groups of comments rejected by each rule, the group of comments discarded by the model filer, the original CSN-t dataset, and the filtered dataset after the two-filter cleaning. The last two groups are for comparison purposes. For rules focusing on detachable features, i.e., the Parentheses and HTML tags, we let the annotators judge how well the removed part can help with a query expression. We sample a subset of data from its full set for each group. The sample size of each group is computed by a statistical formula which is extracted from [12] where is the size of the entire dataset, is the standard deviation of the population, is the confidence interval (margin of error), is the Z-Score determined by the confidence level. In this experiment, we choose to work with a 95% confidence level (i.e., 1.96 Z-Score according to [20]), a standard deviation of 0.5 (0.5 is the maximum standard deviation, and a safe choice given the exact figure unknown), and a confidence interval of 5%. We also measure the agreement between the two annotators with Cohen's Kappa [13], which is 0.69 and within the range of fair to good.
For each data, we finalize its score as the average of scores from the two annotators and display the statistics in Table 4. We report the number of data examined in each group, the respective portion of data scored as 0 or no less than 1, and the group's average score, in the last four columns. In general, the comments rejected by either the rule-based filter or the model-based filter poorly resemble real user queries, with 96.9% and 85.9% of them receiving a score of 0 and the average scores being as low as 0.04 and 0.20, respectively. Still, it comes at an acceptable cost of losing a small set of good quality data, where 3.1% and 14.1% of the discarded data by the two filters score at least 1. Each of the eight rules rejects code comments in an effective way, with four of them rejecting non-query-like data at 100% precision. The precision of the Parentheses rule is relatively low, where 11% of the discarded data is of high quality. In the future, when deciding whether the content inside the parentheses should be removed, a more refined rule can be derived. Also, the modelbased semantic filter is accompanied by a larger sacrifice, indicating it as a more challenging task.
Overall, through the two-phase filtering, the average likeness score increases from 0.27 to 0.61. In particular, the portion of nonquery-like data drops from 79.0% to 59.2%, and the portion of highly query-like data scoring at least 1 improves from 21% to 40.8%. There are still many comments inappropriate to be seen as code search queries, but our data cleaning framework makes a substantial contribution to alleviating the situation. We call for more attention to be drawn to overcoming related challenges.
Answer to RQ2: Each filter and rule in our framework demonstrates a positive contribution to the effectiveness. The full setting boosts it to the best performance. However, there remain many unqualified comments even after the filtering, and it calls for more attention to be paid from the community.

RQ3: Quality of dividing point determined in the model-based filtering
In the model-based filter, we use EM-GMM to decide the dividing point between the qualified and the unqualified groups. To assess the quality of the dividing point, we observe the model performance resulting from alternative dividing points, including fix proportions and the one decided by K-means, another widely used clustering algorithm. For the fixed proportions, we set a 25% step and select 25%, 50%, 75%, and 100% top-ranked comments, respectively. The results on DeepCS and CARLCS are reported in Table 5. For DeepCS, EM-GMM outperforms K-means and the fixed proportions on all the validation sets. Compared with the second-best partition, 75%, EM-GMM still achieves higher average performances by 4.3% A@1, 4.2% A@5, 4.3% A@10, and 3.3% MRR. The superiority is also observed on CARLCS at every metric, and EM-GMM outperforms K-means on average of CSN-v and NCSED by 30.4% A@1, 5.9% A@5, 2.8% A@10, and 15.0% MRR.
EM-GMM ultimately retains 192,031 data points, accounting for 67.3% of the original dataset, which locates between 57.5%, the dividing point set by K-means and 75%. As discussed in Section 3.2.2, the relation between the data quantity and the model performance should be a convex function. According to the property of the convex function, if there exists another optimal dividing point, it would locate between 57.5% and 75.0%. Therefore, EM-GMM successfully identifies an optimal solution of the dividing point with an error less than 9.8% (calculated by 67.3% − 57.5%).
Answer to RQ3: EM-GMM produces a better approximation of the best dividing point for the datasets and is adequate to be used in the framework.

APPLICATION
This section presents the applications of our filtering framework, including a proof-of-concept data cleaning toolbox and a highquality code search dataset.

NLQF : Natural Language Query Filter
We release the implementation of our filtering framework as a thirdparty Python library, Natural Language Query Filter (NLQF), which is designed to systemically filter queries for neural code search models. As a lightweight library with convenient APIs, NLQF can be easily integrated into the development pipeline of any code search model. Besides, NLQF is extensible at several features to ensure its applicability in a wide range of contexts: Extensible Ruleset The ruleset in NLQF is configurable, which enables users to specify the rules based on the characteristics of their own data. Besides, NLQF accepts user-defined functions as a part of rule-based filtering. One can easily extend the filter implementation by creating the filtering function for any new rule. Open-source Filtering Model NLQF requires a trained VAE model in the model-based filter. We release the source code for training the VAE model used in this paper. Following the instructions, users can easily train a new model with their own bootstrap query corpus, which may boost the filtering performance further. Tunable Dividing Proportion Besides the recommended clustering method, EM-GMM, NLQF also provides an interface accepting user-defined dividing points. Users can create their own method for finding the dividing point and configure NLQF to adopt it easily.

COFIC: Codebase Paired with Filtered Comments
We build and release a Codebase paired with Filtered Comments (COFIC) for Java programming language.
6.2.1 Dataset Building. We collect the source code of Java repositories from Github according to the list maintained by Libraries.io [37], From these files, we extract the methods and corresponding comments using the scripts provided by CodeSearchNet [19]. In the end, 2,475,692 raw comment-code pairs are obtained. Through the processing with NLQF, there are 1,048,519 data points left in the cleaned query-code dataset. Detailed statistics of the dataset during filtering are reported in Table 6.

Dataset Comparison.
We compare COFIC, on the query quality, with several other datasets currently used in neural code search research. Following the same manual inspection convention as    Table 7. Again, we measure the agreement level between the two annotators with Cohen's Kappa, which is 0.73 and within the range of fair to good. Among all the datasets collected from Github, COFIC receives the highest score on data quality, but there is still a gap compared with the StackOverflow dataset, StaQC. Indeed, the datasets collected from StackOverflow have high-quality queries, but they suffer from the unstable code quality in answers [45,55]. With our filtering framework, a Github dataset with better quality is established. Besides the user study, we also experimentally compare COFIC with CSN-t. We train the DeepCS and CARLCS models with three datasets: CSN-t, COFIC, and a controlled COFIC (same size as CSNt). The model trained with COFIC outperforms other experimental settings on the three validation datasets (CSV-v, CB, and NCSED). The detailed results are reported in Table 8.

THREATS TO VALIDITY
Rule Design Though our experiments have evaluated the usefulness of each rule in the ruleset; the rule-based filter may still introduce a few false positives or false negatives due to its design and implementation. For example, the widely used query "quick sort" can be filtered out by the rule Short Sentences. Besides, some rules are tricky to be implemented exactly in line with our aim. For example, non-English letters in the comments are identified based on ASCII encoding. It may leave out several other languages also using English letters. But no English sentences will be falsely filtered out. Overall, it requires further exploration on balancing the trade-off between precision and recall better. Bootstrap Query Corpus The bootstrap query corpus in this work is built based on the questions on StackOverflow. Only titles starting with "how to" are collected into the corpus, which limits the sentence pattern. The VAE model trained over this corpus may not have a good tolerance to other patterns. Besides, StackOverflow titles are also not fully query-appropriate. Although we filter the titles by rules, there are still semantically irrelevant texts left. Generalization Limited by the accessibility of models and evaluation benchmarks for code search tasks, we evaluate our solution only on Java datasets. In theory, our approach is capable of any comment-based code search dataset. Yet, the generalization of our filtering framework in different programming languages has not been experimentally verified. Besides, we only evaluate our filtering framework on two code search models, DeepCS and CARLCS, which is also a threat to the generalizability of our approach.

RELATED WORK
Code Search Dataset Recent years have witnessed a growing interest in the semantic search for code snippets [21]. DL models are applied to establish links between natural language and programming language. To train these models [7, 9, 15-17, 28, 30, 40, 41, 46, [6,15,18,19,46]. According to a manual investigation [39], there are 16 categories of comments in source code, most of which, e.g., TODO, License, and Exception, are not appropriate to serve as queries. However, to the best of our knowledge, the comments in code search datasets have never been fully cleaned. For example, Barone et al. [6] remove empty or non-alphanumeric lines from the docstrings. CodeSearchNet [19] filters each comment-code pair with its comment length. Ling et al. [30] use heuristic rules (e.g., the existence of verb and noun phrases) to filter comments. Cambronero et al. [7] filter out queries that contain specific keywords. These simple and scattered efforts are not enough to filter out the various noises, especially the texts that are semantically unrelated to real queries. Liu et al. [31] also mention that improving the data quality is still a research opportunity for deep-learning-based code search models, which well motivates our work. There are two evaluation methods for neural code search research: train-test split and actual user query evaluation. A lot of works [7,41,47,53] split their datasets into train and test sets. The queries of their test set contain the same defects as the train set so that the results fail to reflect the model performance in an actual environment. Manually reviewed queries [19,24,50] can overcome this problem but they are usually on a small scale and cannot serve as the training dataset. Unsupervised Anomaly Detection Comments cleaning is an application of the unsupervised anomaly detection algorithm as labeled comments are non-trivial to obtain. Unsupervised anomaly detection algorithms identify the outliers solely based on the intrinsic properties of the data instances. Various techniques can be applied, such as Principal Component Analysis [48], Generative Adversarial Network [23], Spatio Temporal Networks [10] and LSTM [42]. Among them, Auto-Encoder (AE) is the fundamental architecture for unsupervised anomaly detection [38]. It has been applied in many tasks. For example, Zhang et al. [56] detect the rumors in social media using multi-layer AE. Castellini et al. [8] apply AE to detect false followers on Twitter. Luo and Nagarajan [34] use AE to identify the error events of interest such as equipment faults and undiscovered phenomena in wireless sensor networks.
The encoder of AE maps an input to a point in the latent space, while VAE maps an input to a region. In this way, VAE can extract more abstract semantic features. It has been applied to unsupervised anomaly detection with promising evaluation scores [5,29,43,49].

CONCLUSION
We propose the first data cleaning framework for code search tasks, which improves the quality and naturalness of the queries. The framework leverages two subsequent filters, the rule-based syntactic filter, and the model-based semantic filter. The rule-based filter uses configurable heuristics rules to filter out comments with syntactic anomalies. The model-based filter aims to refine the dataset semantically. It trains a VAE model over a pre-collected bootstrap query corpus, and exploits it to select comments with smaller reconstruction losses. Experiments show that our filtering framework can significantly save computing resources and improve the model accuracy. Finally, we release our framework as a Python library NLQF and make public a high-quality cleaned code search dataset COFIC, to facilitate relevant research in academia and industry.