diff --git a/docs/report/report-en.pdf b/docs/report/report-en.pdf index 9f75d7a..137930e 100644 Binary files a/docs/report/report-en.pdf and b/docs/report/report-en.pdf differ diff --git a/docs/report/report-en.tex b/docs/report/report-en.tex index b993565..7e810bb 100644 --- a/docs/report/report-en.tex +++ b/docs/report/report-en.tex @@ -1,190 +1,267 @@ \documentclass[a4paper,12pt]{article} \usepackage[english]{babel} \usepackage[parfill]{parskip} \usepackage{graphicx} \usepackage{amssymb} \usepackage{amsmath} \usepackage{amsthm} \usepackage{xunicode} -\usepackage[T1]{fontenc} -\usepackage{charter} +\usepackage[charter]{mathdesign} \usepackage{url} \usepackage{hyperref} +\DeclareTextCommand{\nobreakspace}{T1}{\leavevmode\nobreak\ } + \title{Large-scale Programming Language Detection} \author{Yuan YIN} \date{} \begin{document} \maketitle \begin{abstract} (to be completed) \end{abstract} \section{Introduction} Programming Language Detection is a problem of identifying which programming language is a piece of source code written in. We here define the piece of source code as a textual sequential representation of an artefact, which is normally in the form of character sequence or, more generally, byte sequence. More precisely, the objective is to build a model which could predict the language of a given byte sequence. The formal definition of the problem as follows: on the input, given an byte sequence $d$ and the number of languages $n$, \[l_d = \underset{l_i\in \{l_1, ..., l_n\}}{\arg \max}\ m(d, l_i),\] where $l_d$ is the projected language, model $m$ calculates a value indicating the likelihood of a document written in language $l_i$ and the most likely one is chosen as the language of the document. In general, Programming Language Detection could be utilised in different situations, here are several example applications: language composition of software project in version control systems. For example, GitHub team is developing the project Linguist to return which languages are the project written in; code searching in plain text, in order to track the popularity of a language; language detection helps also IDEs to choose the language whose support functionalities, like syntax highlighting, are implemented. We dive into this problem in the context of \emph{Software Heritage}. \emph{Software Heritage}, initiated by Inria, is an archive in which 4 billions source code files from 80 millions projects are stored. The reason why the language detection is requested by \emph{Software Heritage} is that the language of a file could not be found in its filename extension. In \emph{Software Heritage}, every source code file is a blob which contains raw content of the file, that means a sequence of bytes without any extra information, such as filename (including filename extension), metadata, \emph{etc}. Since each blob could be represented by an intrinsic identifier generated from the blob itself, the duplication of files is avoided. For this reason, all existing tools depending on filenames fail in our context, and the methods for recognising the language from a sequence of bytes is strongly demanded. In this report, we introduce briefly the state-of-the-art methods in Section 2. In Section 3, the procedure of making a feasible dataset is related. In Section 4, we explain the methods that we took in account for the evaluation. \section{State of the Art} The existing approaches could be divided into two groups: practical methods and machine learning methods. Practical methods are mostly based on several empirical or external information, basic ideas are presented as follows: \begin{itemize} \item Judging from filename extension. Ohcount\cite{ohcount} and Linguist\cite{linguist} practice the detection by hashing filename extension. The problem from this straightforward method is that some extensions are related to different languages, \emph{e.g.} \texttt{*.m} refers to a file written in Objective-C or MATLAB, \texttt{*.pl} points to Python or Prolog. \item Grammar-based approaches. The principal is to parse through all languages, which is complex in modelling and demand an heavy consumption of calculation time. \item Heuristics approaches. Most of them, such as SLOCCount\cite{sloccount}, use predefined regular expressions to capture empirically discovered features, \emph{e.g.} a file start with ``\texttt{\#include}'' is probably written in C. Some other looks for hints in the file, such as shebang lines, Vim modelines, Emacs modelines, \emph{etc}. \end{itemize} In Machine learning, the problem is regarded as a sub-problem of \emph{text categorisation} or \emph{text classification}, which means that given a piece of text, we find a function that predicts which category the text belongs to. The state-of-the-art methods build such function based on example input-output pairs, which are categorised as \emph{supervised learning}. Ugurel \emph{et al.} \cite{Ugurel02} selects firstly the features by Expected Entropy Loss for each language, then vectorise the tested document into a vector representing the presence of a selected feature. Since Support Vector Machine (SVM) is binary classifier, the $n$-class classification is resolved by training $n \choose 2$ SVMs in the form of decision tree. Van Dam and Zaytsev \cite{vanDam16} test several popular and performant methods in Natural Language Processing. Multi-nominal Naïve Bayes (MNB), one of the variants of Naïve Bayes Classifiers, utilises unified frequency of a word or a sequence of words in a byte-sequence to decide the most possibly corresponding programming language. $N$-gram model and skip-gram model calculate for each gram the possibility of its appearance after $N$ grams. Normalised Compression Distance compares a piece of compressed code to the examples in the training set, then chooses the nearest language on as projection. MNB and $N$-gram model outperform others according to the experimental results. Gilda\cite{Gilda17} adopts a general setup of Convolutional Neurone Network (ConvNet) in NLP and proofs its performance. In this report, we will test several NLP methods on a larger dataset. \section{Dataset} Supervised learning methods require a dataset containing labeled inputs to train and to evaluate the model. Nowadays, since Programming Language Detection is not seriously considered as an important subject in machine learning, for the reason that it could be resolved by adopting existing classifiers of ML, the articles are rarely accompanied by a publicly available dataset. Therefore, we natively build a novel dataset for our experiments. GitHub is one of the most popular web-based hosting service for Git version control system, reporting having more than 57 million repositories. We decide to build the dataset using GitHub. \paragraph{Ground Truth Supposition} In the context of \emph{Software Heritage}, our aim is to cover as many languages as possible for classification, thus the dataset we build possesses inevitably a large amount of files, which is unaffordable to be labeled manually. We thus seek help from automatic labelling tools. Linguist\cite{linguist} is the tool of language detection developed by the GitHub team for unveiling the language composition in git repository, service provided on GitHub through API. There exists a command line version Linguist producing list of files by language for repository. Given that filename extensions are visible for Linguist and such features boost enormously on accuracy of classification (we will show this claim in later experiment), we suppose that the language recognised by Linguist is the ground truth language attributed to it. \paragraph{Repository Fetching} For each language, we fetch the first 75 repositories which top on the list ordered by number of stars, which shows the popularity of the repository. To avoid huge repositories, we ignore all repositories whose size is superior to 150 MiB. All lists We initially took the entire language list of Linguist (version 6.0.1) into account for repository fetching, then we eliminated some languages, \emph{i.e.} data description languages, which we could not fetch any repository. \paragraph{Imbalance Among Classes} Despite of our efforts on balancing the number of repositories for each class, a significant imbalance is eventually observed among language classes. For example, C++ has 180,093 files, but Omgrofl has only 16 files. (Graph needed) \paragraph{Training Set And Test Set} Files of the training set are randomly picked at first, then the test set is built from the remaining samples. To avoid the imbalance of the training set that impacts the performance of several methods in Section 4, for each language, we restrain the maximum number of training files to 500 and the maximum number of test files to 1000. \section{Methods for Evaluation} In this section, we describe several NLP methods here tested on our dataset: \begin{itemize} \item $n$-gram-based frequency distance model, \item $n$-gram model, \item Multinominal Naïve Bayes (MNB), and \item Convolutional Neurone Networks (ConvNet). \end{itemize} The first approach is regarded as a baseline method for the evaluation of the accuracy and the efficiency of the model. \subsection{Baseline: $n$-gram-based frequency distance} -Cavnar and Trenkle \cite{Cavnar94} introduce an early NLP method using the distance between two $n$-gram frequency profiles. - \paragraph{$n$-gram} An $n$-gram is a slice of a larger sequence with $n$ units. In NLP, the sequence is naturally the string. Depending on different problems, an unit represents a character or a word. For example, the string ``print(n)'' with 8 characters could generate following character based $n$-grams: \begin{itemize} \item unigrams: \texttt{, p, r, ..., ), } \item bigrams: \texttt{ p, p r, r i, ..., n ), ) } \item trigrams: \texttt{ p r, p r i, r i t, ..., ( n ), n ) } \item ... \end{itemize} or word-based $n$-grams: \begin{itemize} \item unigrams: \texttt{, print, (, n, ), } \item bigrams: \texttt{ print, print (, ( n, n ), ) } \item trigrams: \texttt{ print (, print ( n, ( n ), n ) } \item ... \end{itemize} Strings are often padded with \texttt{} and \texttt{} around to mark its start and end. In general, a $k$-unity sequence generates exactly $k-(n-1)$ n-grams. +Cavnar and Trenkle \cite{Cavnar94} introduce an early NLP method using the distance between two $n$-gram frequency profiles. + According to Zipf's law, an empirical observation expressing that the $n$-th most common word in a human language occurs with a frequency inversely proportional to $n$. By retaining the most common words, it is possible to obtain a list describing the characteristics of the language. Given a training set, at the training phase, a bag of $n$-grams is generated for each document in the training set. By gathering all bags of a language and counting the occurrences of each $n$-gram, a list of $n$-grams ordered by number of occurrences is created as the \emph{category profile} of the class. Only the most frequent 300 $n$-grams are kept, since they are highly correlated to the language. The \emph{distance} between category profile and document profile is defined as follows: Given trained category profiles $p_{l_1}, ..., p_{l_k}$ for $k$ languages, and document profile $p_{d}$ of test document $d$, \[ distance(p_{l_i}, p_{d}) = \sum_{w\in p_{d}} | rankdist(w, p_d, p_{l_i})| \] \[ rankdist(w, p_d, p_{l_i})= \begin{cases} |rank(w, p_d) - rank(w, p_{l_i})| & \text{if }rank(w, p_{l_i}) \text{ exists,} \\ |p_d| & \text{else} \end{cases} \] where $p$ containing an ordered list of word, $rank(w, p)$ returns the rank of $w$ in list $p$. $rankdist(w, p_d, p_{l_i})$ returns the out-of-place distance between two profiles if $w$ appears in $p_{l_i}$. If $w$ is an out-of-vocabulary word, the distance is the length of document profile $p_d$. We then categorise the document as language with minimum distance. +\subsection{Multinominal Naïve Bayes} + +This approach is introduced by van Dam and Zaytsev \cite{vanDam16}. + +We assume in Naïve Bayes model that each word of the document is independent from each other. According to Bayes' Theorem, +\begin{eqnarray*} + P(l|w_1w_2...w_n) & = & \frac{P(w_1w_2...w_n|l)P(l)}{P(w_1w_2...w_n)} \\ + & = & c\cdot P(l) P(w_1w_2...w_n|l)\\ + & = & c\cdot P(l) \prod_{i = 1}^n P(w_i|l) +\end{eqnarray*} + +Probability of $w_i$ in language $l$ is estimated by its occurrences in language with bag-of-word assumption: +\[ +P(w_i|l) = \frac{C_l(w_i) + 1}{\sum_{w\in V}C_l(w) + |V|} +\] +where $C_l$ gives frequency of a word, $V$ is the vocabulary all languages. + +Assumption of independence of words is quite limited for classification because it ignores the context of words, in practice we actually use unigrams to 5-grams as (words) in the original method. + \subsection{$n$-gram model} -As the precedent method, $n$-gram model utilises also statistical properties of $n$-grams but in another way. +The approach is introduced by van Dam and Zaytsev\cite{vanDam16}. As the precedent method, $n$-gram model utilises also statistical properties of $n$-grams but in another way. -\subsection{Multinominal Naïve Bayes} +Originally, $n$-gram model aims at predicting the possibility of an unit after knowing $n-1$ units occurred before. Given an unit $w_i$, the probability of its occurrence in a sequence is defined as: +\[ +P(w_i | w_1...w_{i-1}) +\] + +According to Markov assumption, we omit older context in the sequence, +\[ +P(w_i | w_1...w_{i-1}) \approx P(w_i | w_{i-(n-1)}...w_{i-1}) +\] + +In reality, the probability could be estimated by maximum likelihood estimation (MLE): +\[ +P(w_i | w_{i-(n-1)}...w_{i-1}) = \frac{C(w_{i-(n-1)}...w_{i-1}w_{i})}{C(w_{i-(n-1)}...w_{i-1})} +\] +where $C$ gives the count of given $n$-gram. + +By chain rule of probability and precedent estimation, +\[ + P(w_1w_2...w_n)\approx \prod_{i = 1}^n P(w_i|w_{i-(n-1)}...w_{i-1}) +\] + +Now we transform such model into a classifier. Given a sequence $w_1w_2...w_n$, we assume that each language $l$ appears with the same probability and the probability of a given sequence is fixed. + +According to Bayes' Theorem, +\begin{eqnarray*} + P(l|w_1w_2...w_n) & = & \frac{P(w_1w_2...w_n|l)P(l)}{P(w_1w_2...w_n)} \\ + & = & c\cdot P(w_1w_2...w_n|l)\\ + & = & c\cdot \prod_{i = 1}^n P(w_i|w_{i-(n-1)}...w_{i-1}, l) +\end{eqnarray*} +Rather than counting $n$-grams in the document, the probability of $n$-gram is estimated from the $n$-gram frequency of language, obtained from training set. +\[ +P(w_i | w_{i-(n-1)}...w_{i-1}, l) = \frac{C_l(w_{i-(n-1)}...w_{i-1}w_{i})}{C_l(w_{i-(n-1)}...w_{i-1})} +\] +where $l$ is $C_l$ gives the count of language $l$ in training set. + +While estimating the probability of $n$-grams, the smoothing techniques are required because of possible occurrence of \emph{out-of-vocabulary (OOV)} $n$-gram. In our case, Modified Kneser-Ney is applied since it is one of the methods that gives better experimental results in \cite{vanDam16}. -\subsection{Convolutional Neurone Network} +\subsection{Convolutional Neurone Network (ConvNet)} + +Convolutional Neurone Network is one of the most popular machine learning branch. \subsubsection{Word-level Approach} \subsubsection{Byte-level Approach} \section{Experimental Results} -\subsection{Evaluation des modeles} +In this section, we present several questions that we are willing to answer by experiments on our customised dataset. + +\subsection{Filename Extension Is Important} + +We know empirically that filename extension is a critical feature of classification. However, we hope to figure out how important it is. Knowing that ConvNet is good at choosing features distinguishing inputs, we test the performance using Byte-level ConvNet. For convenience, we test only for 20 languages in the list. + +\begin{table} + \centering + \begin{tabular}{|c|c|c|} + \hline + & With Extension & Without Extension \\ + \hline + Accuracy & 91.27\% & 97.39\% \\ + \hline + \end{tabular} + \caption{\label{dsa} Comparison of accuracy with extension and accuracy without extension with Bytelevel ConvNet Classification on 20 classes} +\end{table} + +\subsection{Generality of Dataset} + +\subsection{Evaluation of Models} \subsubsection{Impact de nombre de classes} \subsubsection{Confusion d'inter-classes} \subsection{Benchmark} \section{Défis à grande échelle} \subsection{Déployabilité des approches dans les systèmes distribués} \subsection{Découverte de nouvelles classes} \subsubsection{Regroupement hiérarchique agglomératif} \subsection{Apprentissage incrémental (partie optionelle)} \section{Conclusion} \bibliography{bib-rapport} \bibliographystyle{unsrt} %Rapport % %Il doit faire de 15 à 30 pages et, dans la mesure du possible, doit être en grande part lisible par des non-spécialistes. Son plan peut être par exemple : %présentation du domaine de recherche (le jury n'est pas constitué seulement de spécialistes du domaine, tenez-en compte !) ; %énoncé et motivation du sujet ; %résultats existants s'y rapportant (état de l'art, commentaire d'article, ...) ; %vos résultats personnels (clairement identifiés comme tels). %Le rapport devra être assorti d'un résumé d'une page compréhensible par quiconque. \tableofcontents \end{document} \ No newline at end of file