scieee AI-readable full text Open interactive document viewer

Natural language processing for textual process descriptions

Cilleruelo Calderón, Gustavo

Abstract

Textual descriptions of processes are ubiquitous in organizations as a way to store, maintain and manage procedures. Formal notations for processes exist in fields like business process management, for example BPMN. With the rise of Natural Language Processing there is a growing interest on using these techniques to bridge the gap between textual processes and formal tools to analyze them. Nevertheless, an overview of the literature reveals that often the process datasets used are either small or too simplistic. We compile processes from three different sources to train classifiers with self-learning techniques, in order to leverage readily available unlabeled data. We train the Universal Sentence Encoder on these datasets, where bootstrapping greatly outperforms fully-supervised training. Furthermore, we build a framework to train and use these classifiers to detect processes on PDF sources.

Full text

Title: Natural Language Processing for Textual Process Descriptions Author: Gustavo Cilleruelo Calderón Advisor: Lluís Padró & Josep Carmona Department: Computer Science Academic year: 2021 Master of Science in Advanced Mathematics and Mathematical Engineering Natural Language Processing for Textual Process Descriptions Universitat Polit`ecnica de Catalunya Gustavo Cilleruelo Advisors: Llu´ıs Padr´o & Josep Carmona 2021 Abstract Textual descriptions of processes are ubiquitous in organizations as a way to store, maintain and manage procedures. Formal notations for processes exist in fields like business process management, for example BPMN. With the rise of Natural Language Processing there is a growing interest on using these techniques to bridge the gap between textual processes and formal tools to analyze them. Nevertheless, an overview of the literature reveals that often the process datasets used are either small or too simplistic. We compile processes from three different sources to train classifiers with self-learning techniques, in order to leverage readily available unlabeled data. We train the Universal Sentence Encoder on these datasets, where bootstrapping greatly outperforms fully-supervised training. Furthermore, we build a framework to train and use these classifiers to detect processes on PDF sources. Keywords— Natural Language Processing, process modeling, Universal Sentence Encoder, semi-supervised learning Contents 1 Introduction 3 1.1 Motivation .............................................. 3 1.2 Objectives&Structure........................................ 3 2 Theoretical Background 5 2.1 ProcessModels............................................ 5 2.2 ClassificationforNLP ........................................ 6 2.3 NaiveBayes.............................................. 6 2.4 Semi-SupervisedLearning...................................... 7 2.4.1 Bootstrapping ........................................ 8 2.4.2 EMalgorithms ........................................ 9 2.4.3 Probabilistic Formulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 2.5 Deep Learning techniques for NLP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2.5.1 Embeddings.......................................... 13 2.5.2 Universal Sentence Encoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.5.3 Using embeddings for downstream tasks . . . . . . . . . . . . . . . . . . . . . . . . . . 14 3 Methods & Framework 16 3.1 Self-Learning Experiments Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 3.2 Framework for pre-processing & process extraction . . . . . . . . . . . . . . . . . . . . . . . . 19 3.3 Classifierevaluationmetrics..................................... 21 3.4 Datasources ............................................. 22 3.4.1 Business Process Modelling Literature (BPM) . . . . . . . . . . . . . . . . . . . . . . . 22 3.4.2 Plymouth’s Hospital Standard Operating Procedures (MED) . . . . . . . . . . . . . . 23 3.4.3 WikiHow Finance & Business Category (WKH) . . . . . . . . . . . . . . . . . . . . . . 23 3.4.4 UK Government Procedures (UKG) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 4 Experiments 25 4.1 Fully-Supervised ........................................... 25 4.2 Self-Supervised: Bootstrapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 4.3 Self-Supervised:EM ......................................... 27 4.4 FindingprocessesinUKG...................................... 28 5 Conclusions & Future Work 33 Bibliography 35 A Code Appendix 38 A.1 TokenizerClass............................................ 38 A.2 DatasetClass............................................. 40 A.3 ModelClass.............................................. 45 A.4 UniversalSentenceEncoder Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 A.5 NaiveBayesClass........................................... 52 1 A.6 ExperimenterClass.......................................... 53 A.7 ExplorerClass ............................................ 57 2 Chapter 1 Introduction The objective of this master thesis is to build a dataset of textual descriptions of processes, and, in doing so, exploring different NLP and self-supervised algorithms. In this Section we contextualise and motivate the choice of topic and give an overview of the structure of the work. 1.1 Motivation The initial idea for the thesis, was to do research around a paper titled Process Extraction from Texts via Multi-Task Architecture [16], which featured a complex and interesting neural network architecture (with encoders, decoders, convolutions, shared layers, etc.) to extract information from textual descriptions of processes, with an elegant yet simple modelling approach. I was particularly excited about the underlying theme of the paper, extracting and structuring knowledge from natural language through an algorithm. As I accessed their code and datasets on github, I was in for a big disappointment: the dataset they had used for their experiments was very simple. For example, there were no sentences in passive tense, a linguistic marker for processes, and almost, if not all, sentences on each sentence classification sub-task had the same structure, to the point were a conditional random fields algorithm could reach 100% accuracy on 6k datapoints training from just 10 examples. Other literature about process model extraction also run into problems with their data, even if their data quality was high, quantity was still an issue. For example in [17], their process dataset consists of 25 examples. Both of these papers require a dataset with complex labels to correctly identify roles, events and other moving pieces in a process, which justifies their simplicity or small size. Manually labeling data is a time-consuming task, especially if the labels are non-trivial for a human to annotate. It is surprisingly hard to find examples of processes online, probably due to being a critical and internal element in any organization, often containing sensible information and therefore not fit for online distribution. Precisely because of these reasons, of how capital is for any enterprise to have control over their processes, a dataset of textual descriptions would be a useful tool for researchers in the field, as it would allow for new techniques which benefit from vast amounts of data, even if this data is unlabeled for that specific task. Instead of spending countless hours manually tagging documents, we tried building this dataset by researching machine learning techniques that, with a bit of luck and patience, could complete the task. As labeled process data is hard to come by, we explore so-called semi-supervised or self-learning machine learning algorithms, which focus on utilizing unlabeled data to increase performance when fully-supervised learning does not have enough labeled training data to succeed. 1.2 Objectives & Structure We have three main objectives for this thesis: ·Give a literature review and theoretical justification for self-supervised techniques applied to natural language processing. 3 ·Experiment with different self-supervised algorithms in combination with different classifiers. ·Build a process dataset from online scrapped data. In Section 2, we will go over all the theoretical background needed. We will start with an introduction to Naive Bayes as one of the cornerstone algorithms for NLP classification as well as different self-learning techniques. We explore the theoretical justification for using unlabeled data to improve classifier performance, and try to understand -on an idealized settingwhen this would and would not work. Finally we discuss the deep learning approach to text classification, giving a historical overview of techniques such as embeddings and introducing the Universal Sentence Encoder, which we will use for our experiments. In Section 3 we go over the python code necessary to set up experiments with the algorithms discussed in Section 2 and use them to classify raw data from different internet sources. We consider several issues, from the scrapping of websites to the implementation of our classifiers in a framework that we can use end-to-end. Our modular code allows for the pre-processing of datasets, training models and using those models to find processes in an arbitrary corpus. Here we also briefly describe the datasets we use to train classifiers with semi-supervised methods, which try to cover different sub-domains where textual descriptions of processes are present, such as business or medical. In Section 4 we go over the results of the experiments and the different design choices, providing pseudocode for our implementations and F-1 scores for a variety of algorithms and datasets. In this Section we also describe our attempt to find processes with our trained classifiers in documents found in the UK government website. Finally, in Section 5 we give an overview of the project and highlight some future lines of work in this field. 4 Chapter 2 Theoretical Background 2.1 Process Models The Cambridge dictionary defines process as a series of actions that you take in order to achieve a result. Everything that happens around us is a process of some sort, whether we are cooking a pumpkin risotto or performing a life-saving surgery. Therefore, humans have the need to document, store, learn and maintain the processes that drive everything in their society, from tradition to business. Natural language is the most prominent tool we have to share knowledge, and this case is no exception, as most organizations rely on textual descriptions to document their main processes [18]. Natural language poses some problems, because although it is extremely useful for punctual human-to- human exchanges, its unstructured and complex nature goes against scalabilty and difficult communication with machines. The field of business process modelling (BPM) attempts to solve these problems by formalising processes, making them verifiable, flexible, systematic and easily visualised. Languages like business process model notation (BPMN) appear during the early 2000s and give explicit symbols to represent the elements of a process: activities, roles, events, etc. [1] Through logical rules, we are now able to go from the text describing a process to diagrams with internal logic, that both can be used to visualise and formalise it. Figure 2.1: BPMN 2.0 representation of a returns & refund process, courtesy of Aina Centelles. In [8] we can find an attempt to bridge the gap between text and process model using linguistic information extracted through NLP part-of-speech/syntactic parsers like Standfrod CoreNLP [11] or the lexical database 5 WordNet for semantic information. Exploiting arising patterns, a set of heuristics is layed out to bring the distilled information to the human-readable BPMN representation. Again, the dataset of this paper consists of only 47 text-model pairs, where they generate 77% of models correctly. In a similar fashion, in [18] an algorithm combining NLP extraction of linguistic information with heuristics is developed. This time the aim is to annotate the text in a structured way, called Annotations from Textual Descriptions of Processes (ATDP), that allows for formal reasoning or simulation in the underlying process. Their technique relies on matching the dependency trees to known patterns, thus identifying entities, activities and relations present in the text. Here the results of their algorithm are compared to other state-of-the-art tools in a set of 21 processes. Natural language is very complex, and processes are far from being an exception. Some of the difficulty comes from the ambiguity in these descriptions, for example an anaphora resolution mechanism is usually a focus in this text-to-model algorithms. These ambiguities also make it hard for a human to label words in a process, as usually it is up to interpretation where an action ends or how the steps are performed. In the ATDP framework, this is dealt with by considering the set of possible annotations, accounting for different types of ambiguity. Another problem is that processes occur in many different domains, and in each domain they take specific characteristics. A recipe and a loan procedure are hardly comparable, yet they are still both processes, encoded in natural language in a way that we can understand the steps and the order in which they should be executed. 2.2 Classification for NLP Natural language processing (NLP) is an umbrella term that refers to the ecosystem of models, algorithms, etc. that explore and are applied to written human language. Classification in natural language processing usually involves a set of documents d∈Dsuch as words, sentences or fragments of text that need to be given a label or class, according to its characteristics. Some common examples are deciding whether a review is positive or negative (sentiment analysis, binary classification) or whether a news snippet is talking about sports, politics or health (multivariate classification). Definition 2.2.1. Given a discrete set of classes Cand a set of documents x∈X⊂ X in a given domain, the classification problem deals with finding a classifier fsuch that f:X −→ C it maps each document to its corresponding class. In binary classification,|C|= 2. In statistical learning, there are two main paradigms. Given a collection (xi, yi)∈X×Y, where Xis a feature space and Ya label space, the generative paradigm models the conditional probability p(x|y), which, by building a model for each class, allows to classify new data at test time using Bayes’ theorem: p(y|x) = p(x|y)p(y) p(x)(2.1) The joint probability of the data, p(x, y) = p(x|y)p(y) is modeled and new pairs (ˆx, ˆy) could be generated, hence the name. Discriminative models focus on the much easier task of estimating directly p(y|x), that is, the probability of a class given a sample, disregarding how that sample is generated (p(x)). 2.3 Naive Bayes The naive bayes is one of the most flexible algorithms in statistical learning, being used for a variety of tasks. One of the well-known uses of the naive bayes in the context of NLP, and in particular that of text classification, is in spam-detection systems [23]. For the spam problem, we have to classify emails as spam or non-spam given their content. 6 world examples, as labeled data has more information. If the number of labeled examples is large compared to unlabeled ones, the error will be close to e(θ∗ l). As we add more unlabeled samples to the experiment, we move the error towards e(θ∗ u), worsening the performance of the model. The continuity of θ∗ πon πcan be derived from 2.4.1 and the implicit function theorem [4]. In conclusion, although in some cases unlabeled data can degrade performance because of a variety of reasons [4], semi-supervised techniques can outperform fully-supervised classifiers for some tasks similar to process-description extraction [25], because we can leverage the information on p(X) that bulk unlabeled data gives us for generative models. Whilst not as widely used as supervised or unsupervised methods, we have both theoretical and empirical evidence that techniques such as bootstrapping will be useful to work in a context were labeled data is hard to come by, but unlabeled data can easily be obtained. 2.5 Deep Learning techniques for NLP In this Section we will briefly introduce some key concepts and tools commonly used when experimenting with deep learning in the field of natural language processing. 2.5.1 Embeddings When examining the semantics of a word, linguists in the 1950s formulated the distributional hypothesis, which states that words that occur in similar contexts will tend to have similar meanings. A good example of this behaviour are homonyms, words with different meanings but same spelling and pronunciation such as lead or bear, where the context is what makes us able to differentiate between definitions. In order to study language from a mathematical standpoint, one of the tools we rely on is the transformation of words into vectors with well defined operations. Yet the value of this approach is only as good as the semantic information these vectors are able to convey. On [20], in 1971, a term-document matrix is introduced. Here, for a set of documents, each word has associated a vector with its count in each of those documents. That is, we are embedding words in a vector space, and we can already use tools as cosine similarity, even though the vectors are sparse and highdimensional. The tf-idf (term-frequency-inverse document frequency) algorithm follows as a weighted version of this approach, to solve the problem of words like the or good skewing counts due to being common. A modern algorithm to create vector word representations as we know them today is introduced in the socalled word2vec paper [12]. Here they use two different strategies to generate word embeddings from neural networks. The continuous skip-gram model aims to predict words on the context of an input word. On the other hand, the continuous bag-of-words model predicts the current word given a window of context around it. Both of these tasks involve projecting the one-hot-encoded input words to dense vector representations (encoding) and taking those to generate a softmax prediction for the task (decoding). These dense vector representations we indirectly get for each word through training each task is the word embedding. One of the most cited property of these embeddings, which is described as somewhat surprising in the paper itself, is the good behaviour they have under algebraic operations. To find a word similar to small in the same sense as big is similar to biggest, the operations in the vector space shown in 2.16 yield a vector which is close (by cosine similarity) to smallest, which is the expected semantic result. vector(biggest) −vector(big) + vector(small) ≈vector(smallest) (2.16) To achieve this level of semantic subtlety and understanding, embeddings require massive amounts of data and computational power to be trained on. This, which is a big weakness in the approach, is overcome by the fact that they have to be only trained once and then be slightly modified to perform on a variety of tasks. Since they already encode a huge complexity and richness, very little task-specific data can be necessary. We discuss further how to exploit the flexibility of embeddings in section 2.5.3. One of the problems with the word2vec approach is dealing with homonyms, as the architecture only yields a vector per spelling of a word, and will fail to successfully convey the semantics of words with same spelling but with distinct meanings. 13 Nowadays there are a variety of architectures used to generate embeddings, most notably BERT [6], introduced by Google in 2018. BERT provides contextualized embeddings, which will produce different embeddings for a word even with homonyms, and has state-of-the-art performance in many NLP benchmarks. Embeddings are not limited to words, for example in the next section we will be introducing sentence embeddings to get a deep-learning angle on the binary classification problem of process finding at hand. 2.5.2 Universal Sentence Encoder In [3], the team at Google Research present models for encoding sentences into embedding vectors that specifically target transfer learning to other NLP tasks. To do so, they propose two architectures for the encoder block. The first one, based on transformers just as BERT, targets high accuracy at the cost of being computationally expensive and having greater model complexity. Their second encoder architecture is based on deep averaging networks (DAN), which seeks a compromise between performance and compute time, especially since the latter is linear on the length of the input sentence. In [9], deep averaging neural networks are introduced as an unordered model, that is, a model which ignores syntactic information just as Naive Bayes, that is nonetheless able to get near state-of-the-art results competing against syntactic models. The authors highlight the fact that their architecture is extremely easy to train and more robust to datasets with syntactic variability. When processing a sentence, the composite function is the mathematical process for combining the multiple word embeddings into a single vector. Concatenation would be an example, which would keep syntactic information by preserving the order of the words in the input of the algorithm. As its name suggest, the DAN architecture averages the word vector embeddings into one, which is then fed to several feed-forward layers. This allows for computational complexity to scale on the depth of the network rather on the length of the input sentence. In this thesis we will be using the DAN-based architecture, as it allows to run experiments comfortably in a local machine, without running into any memory or time issues. Figure 1 of the original universal sentence encoder paper [3] is a heatmap depicting the similarity between the embeddings of different sentences, although these are quite simple. As an experiment to push the capabilities of this encoder, in Figure 2.2 we build a pairwise similarity matrix between 9 sentences, also with different 3 semantic fields, but giving difficult example sentences with no intersecting keywords and a less obvious relation. 2.5.3 Using embeddings for downstream tasks Once we have a system that understands language, tailoring it to a specific task is easy. For example, if we know that good is opposite from bad, learning sentiment analysis can be done with fewer examples than if we have to learn those relationships from scratch, even if the association of good is positive and bad is negative is unknown for us. This is the most common way to proceed for modern NLP techniques, where very large models are trained on massive corpus of text (using extensive time and computing resources not available to most researchers or organizations), and then those can be used as starting point for different downstream tasks, such as classification, question answering, summarizing, just by adapting them with very little resources (like task-specific data or computing power). These embeddings trained on general data (usually Wikipedia or a book corpus), are called pre-trained, and aim to understand language so that appending some layers on top of them to learn specific tasks, which is called fine-tuning, yields better results than training just on the data for those tasks altogether. Sometimes this is done across domains, which is often called transfer learning. For this project, we use a pre-trained universal sentence encoder, with the weights downloaded online. On top of the pre-trained model with non-trainable weights, we add additional layers with trainable weights to learn our specific classification task. This is a standard fine-tuning procedure, where only the last fullyconnected layers are updated during training. 14 Figure 2.2: Heatmap showing pairwise semantic similarity between sentences. 15 Chapter 3 Methods & Framework In this Section we go over the structure of the code used to perform the experiments in Section 4, the implementation of the self-learning algorithms described in Section 2.4 and discuss the libraries used for the naive bayes and universal sentence encoder. We also discuss the infrastructure wrapping datasets and models to handle pre-processing, tokenization, training and evaluation in a streamlined manner. The objectives was to develop the tools to facilitate the following two tasks: ·Explore self-learning algorithms. ·Extract process data from a massive and ”difficult” online corpus. After some time exploring processes and different self-supervised learning and NLP algorithms, I found myself lost in a sea of caothic jupyter notebooks and reusing the same code snippets over and over again in a way that did not allow me to keep track of the changes I was making. Therefore, I decided to organize my code as a group of interdependent python classes whose methods would allow me to generate high-level readable scripts to handle the practical challenges for this thesis. These classes’ methods are then called from notebooks to plan experiments or scrape documents, but all complexity stays within the classes themselves. Using <and a gitlab repository also helped to organize the coding process. All code is written in Python *. The code for the classes introduced in this section can be found in the Appendix A. I have not included the scrapping scripts, as they are quite standard, nor the auxiliary jupyter notebooks as they are caothic. 3.1 Self-Learning Experiments Framework The input for the learning pipeline is a semi-labeled dataset, which is a csv with sentences, some manually labeled as process (1) or non-process (0) and most of them unlabeled (2). We also have the core algorithm we want to use, in our case naive bayes or the universal sentence encoder. The Dataset class (A.2) wraps around the semi-labeled csv and pre-processes according with the necessities for each algorithm, its methods return pre-processed and split data ready to be utilized for training. For the sklearn implementation of naive bayes, for example, we need to tokenize the sentences and save the counts of their words in sparse matrices. This tokenization is handled by the Tokenizer class (A.1), which uses a BERT tokenizer and vocabulary. For the USE we need to wrap the strings in a tensorflow tensor object. The Model (A.3) abstract class implements self-learning algorithms without depending on a particular classifier or implementation, by using two abstract methods: trainer and labeler. These are defined in the classifier-specific child classes, which are different from each other, but return the objects (whether it is a trained model or labels for data) in a way that they both work in the implementation of the parent class. This means that the bootstrapping and EM algorithms are independent from the underlying classifier, which us better control the hyperparameters, maintain the code and get comparable experiments. 16 Dataset + max length + split + mode + get labeled() + get test() + get train() + get unlabeled() + pre process dataset() + set max length(max length) + set split(split) + get labeled blocks() - load data() Tokenizer + mode + tokenize() + get bert vocabulary() - to bert as string(sentence) - to token words(sentence) - to bert(sentence) Model + bootstrap train() + em train() + train() + classification report() - load from dataset(dataset,total unlb,split) - load from csv(csv name, total unlb, split) - score to confidence(x) - bt unlabeled at iteration() - model probability(all labels, confidence) - initialize data(total unlabeled) - block classification report() -length(data) -concatenate(data1, data2, case) -labeler(data, model, verbose) -trainer(data, labels, verbose) -weighted trainer(data, labels, sample weights) -save model(model, model path) -load model(model path) UniversalSentenceEncoder - length(data) - concatenate(data1, data2, case) - labeler(data, model, verbose) - trainer(data, labels, verbose) - weighted trainer(data, labels, sample weights) - save model(model, model path) - load model(model path) - initialize embedding(model dir) NaiveBayes - length(data) - concatenate(data1, data2, case) - labeler(data, model, verbose) - trainer(data, labels, verbose) - weighted trainer(data, labels, sample weights) - save model(model, model path) - load model(model path) Experimenter + run experiment(parameters) - load parameters to self(parameters) - load gold(verbose) - initialize model() - print log() - run fully supervised(target file) Figure 3.1: UML class diagram of the framework used. In Figure 3.2 we have the trainer method for the UniversalSentenceEncoder class (A.4). Note how takes data and its corresponding labels and returns a trained model, making it a modular piece which could be substituted by a naive bayes implementation, granted the other model-specific methods are also implemented. 17 def trainer(self,data,labels, verbose =False): model =self.build_model() history =model.fit(x=data,y=labels, epochs=3, verbose =verbose) return model Figure 3.2: Code snippet of the trainer method for the UniversalSentenceEncoder class. Model also uses these abstract methods to evaluate the models, generating classification reports that are based on the metrics.classification report function from the sklearn python library. We also use the sklearn library for the the naive bayes implementation that powers the NaiveBayes class (A.5): naive bayes.MultinomialNB. Although there are other libraries with implementations such as nltk.NaiveBayesClassifier (which is omitted in the UML diagram but for which tokenization and bootstrap training is also supported), sklearn’s naive bayes offered the best API in terms of flexibility and reliability. In particular, it was easy to implement training with weighted samples, necessary for the EM (Algorithm 4). For the UniversalSentenceEncoder, we download their pre-trained model from tensorflow hub [21], which also includes an explanation on how to use their embedding on python. We use the embedding in a Lambda layer and append two fully connected layers on top to allow for fine-tuning of our specific task. Building and compiling the model is handled by the build model method, using the keras Model class, Figure 3.3. Since our task is a binary classification problem, we use the binary cross-entropy loss. We also compile the model with additional metrics as precision and recall, as accuracy does not give us a good sense of the performance of our classifier for our problem, as will be discussed in Section 3.3. def build_model(self): def UniversalEmbedding(x): return self.embed(tf.squeeze(tf.cast(x, tf.string))) input_text =tf.keras.layers.Input( shape=(1,), dtype=tf.string, name='string_input' ) embedding =tf.keras.layers.Lambda( UniversalEmbedding,output_shape=(512,),name='embedding' )(input_text) dense =tf.keras.layers.Dense(256, activation='relu',name='hidden')(embedding) pred =tf.keras.layers.Dense(1, activation='sigmoid', name='sigmoid')(dense) model =tf.keras.Model(inputs=[input_text], outputs=pred) #model.summary() model.compile(loss='binary_crossentropy',optimizer='adam', metrics=self.METRICS) return model Figure 3.3: Method that builds the USE embedding with Dense layers for fine-tuning. Finally, the Experimenter class (A.6) takes a dictionary of parameters and runs an experiment accordingly, managing calls to the different methods of the Model class to handle training and evaluation. Parametrizing experiments in a json allows for a very easy to use high-level api, as seen in Figure 3.4. 18 import experimenter experiment =experimenter.Experimenter() parameters ={ "base_model" :"naive_bayes", "learning_algorithm" :"fully_supervised", "training_parameters" : { "TRAINING_DATASET" : [ 'wikihow_structured.csv', 'bpml_structured.csv', 'med_structured.csv' ], "TESTING_DATASET" : ['wikihow_structured.csv', 'bpml_structured.csv', 'med_structured.csv' ] } } experiment.run_experiment(parameters) experiment.print_log("log_results.txt") Figure 3.4: Code snippet to generate classification reports for fully-supervised naive bayes. 3.2 Framework for pre-processing & process extraction We also need the tools to automate the pre-processing of the raw data and the scrapping and classification of unlabeled data from the web. To restrict the scope of the project, we will only use data from PDF documents. The objective is to extract the text from the original PDF to a list of sentences as strings, ready to feed to the Dataset class and then to a learning algorithm. Additionally this extraction is done in a structured manner, with document, sentence and block/paragraph ids. The first element needed is a parser, which takes a PDF file and extracts the text contents. After trying some of the multiples libraries and options available, we decided to use the PyMuPDF. Other than an allaround good performance, both with speed and consistency of the parsing, PyMuPDF already extracts the text in terms of blocks, that is, paragraphs or elements in the PDF. We also considered the Amazon Web Services textract tool, as it offered similar capabilities. In the end, we decided to use the library, as keeping the code local seemed the better option for this kind of project. Once the text is extracted in blocks, the next step is to break apart these paragraphs by their sentences. We started by using the .split(’.’) method for python strings, but it resulted on degenerate splits due to abbreviations and failed on lists where items had no period. We end up using the SentenceSplitter class of the sentence splitter package, which uses heuristics to split text by sentences. At first, we tried to clean as much as possible the training datasets, but since real-world data in bulk quantities will yield noisy examples (different PDF templates can mess with text extraction algorithms), we decided to leave these sentences, such as ISBNs, headers, indices, isolated text from figures, that were not sentences but still commonly appear in PDFs. When trying to pick only the actual sentences in a text, we observed that, for example, naive bayes classifiers had a tendency to confuse these erratic texts as processes. The only element of cleaning up the data we include is a regex (using the python library re) for e-mail adresses and website links, which we substituted by ’email’ and ’url’ respectively. 19 Explorer + classifier + labeler + pre processor + splitter + explore pdfs() + save pdf from url() + clean text() - text to sentences() + pdf to block sentences() + pdf to blocks() + label doc blocks() + block list to block sentences() + explore doc list() Figure 3.5: Class for exploring and finding processes in PDFs. The class Explorer (A.7) takes as input a classifier, such as a USE model, a labeler and pre-processor functions that work with that model and can use it to label and format text data to the adequate input format respectively. The splitter handles the splitting of the raw text into sentences. We scrape the text data at two levels: sentences and blocks, which are paragraphs or other blocks of text present in the structure of the PDF. This will allow us to later play with ensemble methods to decide whether a paragraph contains a process or not. In Figure 3.6 we find an example of how to use the methods in Explorer to label and extract processes from a list of urls containing PDFs, just by calling the explore pdfs method. This method will download the PDF to a temporal file, scrape it and split it by blocks of sentences, label such sentences with the given classifier/labeler and return a dataframe with the structured data containing the scores and labels found. An outline of how the Explorer class works is found in Figure 4.1 in Section 4.4, were we discuss the results of using this framework to find processes in a corpus. When we have a PDF we want to parse into the block-sentence granularity but we want to manually label, we can use some of the methods of Explorer but without passing it any classifier, which will set all labels to 2, as unlabeled samples. Afterwards, some of the samples can be manually labeled to create a semi-labeled dataset. Having the individual sentences grouped by paragraph is very useful, since we understand and use them as units of information, if some sentences of a paragraph describe a process, chances are the whole paragraph is doing so. 20 import keras.backend as K def labeler_use_with_placeholder(data,model): labels =model.predict(data) K.clear_session() # to fix the memory leak of .predict smh return labels[1:] # data has a placeholder def pre_processor_use(data): processed_data =tf.convert_to_tensor( [tf.convert_to_tensor('placeholder')] + [tf.convert_to_tensor(s.lower()) for sin data] ) return processed_data # classifier = trained USE urls =['url_to_pdf_1.pdf','url_to_pdf_2.pdf'] exp =explorer.Explorer( classifier =model, labeler =labeler_use_with_placeholder, pre_processor =pre_processor_use ) results_df =exp.explore_pdfs(urls) Figure 3.6: Code snippet to explore urls of pdfs with a trained universal sentence encoder classifier. 3.3 Classifier evaluation metrics How do I know how good is my trained classifier? is more often than not a non-trivial question to answer. In our setting, it becomes harder, as we have a very limited amount of labeled data, that we have to leverage as training, validation and testing. Moreover, in most domains processes appear scattered and isolated, being most of the corpus non-process. Unbalanced datasets pose a characteristic problem, where accuracy (3.1), the usual metric to evaluate the performance of a classifier, fails to do so in a meaningful way. The scarcity of labeled data justifies that when presenting the results of classifiers on our datasets in the following Sections, we forego the validation split and use only a train-test scheme. It could be justified that our true test set is the corpus in which we want to use classifiers to find processes. Given our binary classification task, we will refer to samples that are a process as positive and nonprocesses as negative. Therefore, given a classifier and a set of samples, the accuracy of the classifier is defined as: accuracy = samples correctly labeled total samples (3.1) If our dataset is unbalanced, we will get high accuracy values close to 1 by just labeling as negative all the observations, as the positive observations only make up a small proportion of the set. Therefore we should not rely solely on accuracy to asses the performance of the classifiers. Let true positives be the positive datapoints correctly labeled by the classifier and false positives the negative datapoints identified as positive by the classifier, similarly for the negative case, with true negatives and false negatives. By counting these, we can give metrics which are more suitable for classification, such as precision and recall. Precision (3.2) informs us on how good are the classifier’s predictions, that is, the proportion of the examples labeled positive by the classifier that were actually positive. We want a classifier to show high precision scores, as this gives us confidence that if a datapoint is labeled as positive, it will be so. precision = true positives true positives + false positives (3.2) Recall (3.3), on the other hand, gives a measure of how many of the positive examples does the classifier actually manage to find. A classifier with a high precision score is not good if it misses most of the examples in the data. recall = true positives true positives + false negatives (3.3) 21 Definition 3.3.1. The F-βscore combines both metrics with a real factor β, where the recall is weighted as βtimes more important than precision, given by the following formula: Fβ= (1 + β2)·precision ·recall β2·precision + recall Usually we set β= 1, getting the well-known F-1 score. As we aim to build a model capable of detecting processes, rather than a more general binary classifier, the metric we are more interested on is the F-1 score for the process class. In fact, the global F-1 score on processes and non-processes is not interesting for our task, as some of our datasets are unbalanced and our focus is process extraction. 3.4 Data sources Finding sources of textual descriptions of processes turned out to be a challenging part of this thesis. As exposed in Section 2.1, although vital for organizations, processes rarely are publicly available. We ended up using three different sources of process descriptions, to experiment with how different domains with its own characteristics would affect the learning algorithms. 3.4.1 Business Process Modelling Literature (BPM) There is extensive literature on the field of business process management (BPM) and business process model notation (BPMN), mostly focused on helping businesses build, structure, store and analyze their processes with efficiency. Often, these texts contain process examples, although they are less common than what one would expect. For example, in scientific papers they are mostly omitted and only books or articles with a longer format and broader audience tend to include them. This results on a very unbalanced distribution, where less than 1% of the sentences are actually proper process descriptions. 0 | The Terminate End Event causes the immediate cessation of the Process on its current level (and below) even if there is still ongoing activity. 0 | Effectively, it kills off the reminder loop. 0 | More details on the elements introduced are available in the BPMN Reference Section: 0 | •Timer Intermediate Events on page 103. •Terminate End Event on page 128. •Parallel Gateways on page 143. •Text Annotations on page 167. 0 | Exercise One Try modeling this process. it will help ensure that the techniques discussed so far sink in: 1 | Every weekday morning, the database is backed up and then it is checked to see whether the "Account Defaulter" table has new re-cords. 1 | If no new records are found, then the process should check the CRM system to see whether new returns have been filed. 1 | If new re-turns exist, then register all defaulting accounts and customers. 1 | If the defaulting client codes have not been previously advised, produce an-other table of defaulting accounts and send to account management. 1 | All of this must be completed by 2:30 pm, if it is not, then an alert should be sent to the supervisor. Figure 3.7: Example of manually labeled sentences for the BPM dataset, note how the process is introduced as an exercise. There are also fragments where processes are being discussed but not described, where it is hard to decide whether a sentence belongs to a process or not, even for a human. Sentences have rich and complex syntactic elements, both in processes and in the surrounding text. We manually labeled one of the four books that make up this dataset: [24], [10], [7] and [19]. 22 We find a classifier with 0.84 F-1 for processes, with very good precision of 0.82 and a recall of 0.86. With this classifier giving us a good performance on our data, we expect it to also work well for the processextraction task from the UK government procedures dataset. We scrape all PDFs returned from querying for procedure the gov.uk website as detailed in 3.4.4. Both the list and the classifier are fed to the Explorer class, which will handle the labeling as detailed in Figure 4.1. We impose some post-processing to the labeled UKG sentences to increase precision, even if the cost is losing some recall. This is because we are interested in finding some text we know is describing a process rather than capturing all processes in UKG. A non-process sentence will get scores close to 0 and a process close to 1. We label a sentence with 1 if the score is greater or equal than 0.5 and 0 otherwise, and the confidence in this prediction is derived from the score as follows: confidence(s) = sif s≥0.5 (process) 1−sotherwise. (non-process) (4.1) Instead of considering sentences as processes, we treat the PDFs as a union of blocks or paragraphs, which are labeled as with a majority vote of their respective sentence scores. Let P={p1, .., pn}be a paragraph, pithe sentences that make it up and C(pi) = sithe score from 0 (non-process) to 1 (process) the classifier gives each sentence. Then, we compute the label of a paragraph label(P) by weighted majority score as follows: label(P) = (1Pisi |P|≥0.5 0 otherwise. (4.2) We do this by sentence scores instead of by sentence labels to take into account the confidence information the classifier gives us. 2classifier /Explorer Class scraped PDF urls Idownload PDF from url Cparse contents into paragraphs split pragraphs into sentences 3score each sentence with classifier ²label paragraph from sentence vote save results to dataframe/csv ∀PDF url Figure 4.1: Outline of how the explorer class finds processes from a set of PDF urls. In a first draft of the experiment, we execute the explore pdfs method of the Explorer class with only 1000 of the more than 61000 PDFs. From those only 855 are actually processed, as some links can become outdated, only contain images or cannot be parsed by the library. Those 855 PDFs account for 270369 blocks labeled, and a total of 348558 sentences. These proportions imply most blocks of texts detected by the PDF-parsing library contain a single sentence, this is due to most official documents having double spacing between lines of text and other formatting issues. We find 28434 blocks of text labeled as 1 or process by the algorithm, which makes about a 10% of the total blocks. If we take into account how noisy and hard to control the search results can be for our purpose, as well as the 1% of processes that we found in specialized literature, this gives a lot of promise for the UKG data source as a corpus where to find textual descriptions of processes. Once we have a dataframe with hundreds of thousands of texts labeled with a classifier we barely had a couple thousand examples to train, in a domain where no standardized benchmark exists, it is very hard to asses how good is this labeling beyond visual observation of the results. We will now go over different examples of fragments of text labeled as process to see the weaknesses and strengths of our approach and inspire changes to make it more robust. 29 0.99 | A. First take the throat swab. 0.98 | Open the swab packet which contains the small bottle and pull out the swab.B. Wipe the soft tip of the swab around the back of your throat as shown in the diagram. 0.95 | Stand in front of a mirror. 0.08 | Open your mouth wide and stick out your tongue - you will see an arch at the back of your mouth. 0.14 | Try to swipe the soft tip of the swab across the five areas in the picture as below. Figure 4.2: Paragraph containing part of a textual description of the swabbing test for Covid-19. Source: https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment data/file/880999/Combined throat nose swab instruction sheet postal.pdf In Figure 4.2 we can see a paragraph that was successfully identified as so by the PDF parser, describing part of the swab testing process for the coronavirus. The scores for each sentence are to the left, and by the majority vote in (4.2) the paragraph as a whole gets labeled as process. In the second sentence, we can see that because of formatting issues in the original text, where it was probably written as a list with A and B as cardinals, the sentence splitter fails to detect the two sentences. The classifier does not identify as processes the last two sentences of the block, which is compensated by the majority vote to get the correct labeling as process. Although the rest of the process is extracted as isolated sentences by the parser, not paragraphs as we would like, the classifier performs very good on it and detects all the sentences that make it up. In Figure 4.3 the whole fragment is shown, with the sentences classified as non-process greyed out. If we consider the two misclassified sentences in 4.2 would be labeled as process in the block-majority vote strategy, the labeling of the process is near perfect. Let’s now take a look at a less straight-forward example. The main issue we find in this administrative corpus is that the processes are often written for a user who is not the one executing it. The citizen makes petitions, and the document explains how these are handled by the administration, yet what we would love to have are the internal documents detailing to the public workers in such administration how to handle the procedures. Instead, we often get descriptions of such procedures for an outsider to understand the general workflow, and they end up not being as concise as we would like. 30 0.98 | How to take a combined throat and nose swab | Postal version 0 | Public Health England gateway number: 2020042 Version 1. 0.99 | If at any stage your condition worsens, or if you are more worried about your health contact NHS 111 urgently 0.76 | To test for coronavirus (SARS-CoV-2) we need two samples, one from the back of your throat and then from inside the nose with the same swab. 0 | Both tests are commonly used by doctors and nurses but you can take both samples safely yourself. 0.66 | Prepare to take throat sample 0.99 | A. First take the throat swab. 0.98 | Open the swab packet which contains the small bottle and pull out the swab.B. Wipe the soft tip of the swab around the back of your throat as shown in the diagram. 0.95 | Stand in front of a mirror. 0.08 (1) | Open your mouth wide and stick out your tongue - you will see an arch at the back of your mouth. 0.14 (1) | Try to swipe the soft tip of the swab across the five areas in the picture as below. 0.99 | Rub the swab several times across the very back of your throat, behind the arch. 0 | This may make you gag but should not be painful. 0.99 | Ensure you also swab the sides of the arch where your tonsils protrude. 0.46 | Try to avoid swabbing your tongue and teeth. 0.99 | A. Place the tip of the cotton bud gently JUST inside one of your nostrils and gently wipe the cotton bud around the inside of your nose. 0.95 | Please repeat this for your other nostril using the same swab. 0.80 | No force is needed and you do not have to push far into your nostril. 0.65 | B. Once you have taken the swab, place the soft tip of the swab into the collection tube and break off the plastic end (at the breaking off point where the swab stick is thinner). 0.96 | Replace the lid on the bottle. 0.55 | Next, take the nose sample 0.99 | A. Wash your hands again.B. Write your name, date of birth and today’s date on the outside of the small collection tube with the swab. 0 | Your GP may include sticky labels. 0.99 | D. Make sure the request form details are correct and place inside the box. 0.91 | C. Place the small tube inside the large white screw topped lid contained and close the lid tightly. 0.99 | Place the white top container into the cardboard box. 0.26 | The testing kit you have received contains everything you need to take the samples. 0 | Please write clearly in dark ink Figure 4.3: Complete fragment describing the covid testing procedure. Sentences classified as non-process are in light gray. In parenthesis next to the score the block label of the sentence, if it was different from the sentence-level classification (non-process sentence in a majority process paragraph, for example) Another problem we encounter is that our main datasets, especially the WikiHow and SOP ones, focus on processes described for the user to execute some actions, where the average sentence will be DO X. Often times, especially in administrative environments, processes may be presented as X IS DONE, with passive sentences and a different syntactic distribution overall. Although the classifier can detect passive sentences in processes, it struggles a bit more with those. This problem would be solved by finding more examples of process descriptions with that structure to (self-)train a more domain-specific classifier. 0.94 | ANNEX A - TENANT FEES BILL Q&A .................................................. 0.77 | TENANCY CHECK-OUT FEES........................................................... 0.98 | RENT ............................................................................ Figure 4.4: The algorithm seemed to confuse elements in the table of contents of the documents as processes. As can be seen in figure 4.4, some of the noise from the PDF structure can confuse the network, as the points from the table of contents can get labeled as a process with high confidence. This is again is an issue of finding a better parsing algorithm for the documents, where we can clean table of contents, headers, 31 figure descriptions and such and just get the interesting and grouped paragraphs with (or without) textual descriptions. 0.99 | If they decide that you are not eligible and you think that they did not take account of all the facts, you can ask them to consider your application again. 0.99 | What you need to apply for a Blue Badge You will need to provide: •proof of identity • proof of address •a recent head and shoulders digital photo •your national insurance number (if you have one) •contact details (phone number, email and postal address) To prove your identity, you can provide a copy of either: •birth or adoption certificate •passport •driving licence •marriage or civil partnership certificate •divorce or dissolution certificate To prove your address, you can provide a copy of either: •a recent council tax bill •a recent letter from a government department such as Department for Work and Pensions (DWP) •driving licence •a recent letter from a school (if you are under 16) -- 0.01 | Providing proof of benefits Personal Independence Payment (PIP) You’ll need to know the scores from the mobility assessment and the award end date (if applicable). 0.0 | You’ll also be asked to provide proof of the PIP award. 0.62 | This would be the 3 pages from the letter from DWP, which clearly shows: •entitlement to PIP (front page) •assessment scores (second to last page) •mobility scores (last page) Disability Living Allowance (DLA) You’ll need to know which rate of the mobility component you receive and the award end date (if applicable). 0.92 | You’ll also be asked to provide proof of the DLA award. 0.98 | This should be the most recent letter from DWP, which clearly shows: •mobility rating • certificate of entitlement to DLA •the date of the letter Figure 4.5: Example of two paragraphs labeled as a process. This example tries to highlight the ambiguosity in the tone used in some of these documents as the adress the reader and not the executor of the process. Source: https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment data/file/856310/who-can-get-blue-badge-large-type.pdf Overall, in this section we have demonstrated that exploring vast corpus of text for processes is a viable strategy that can yield good results. Surprisingly, the bottleneck of the method seems to be the parsing of the PDFs, to reduce noise and structure the data in ways that post-processing can improve and support the classifier itself. 32 Chapter 5 Conclusions & Future Work In this thesis we have aimed to explore some aspects of Natural Language Processing through the use-case of a domain where labeled data is hard to come by. To do so we delved into the theoretical aspects of classifiers for NLP as well as semi-supervised techniques to try to leverage unlabeled data. At the end of the project, we have successfully fulfilled the following: 1. Work on an open problem in the NLP literature where datasets of processes are hard to come by and have problems both in terms of quantity and quality. 2. Give an overview of classification and semi-supervised methods, in particular focusing on Natural Language Processing; from classical arguments around the naive bayes classifier to an outline of the evolution of embeddings and apparition of deep neural networks in the field. 3. Build a framework to work end-to-end in an NLP problem, from tokenization to training and usage of a model with real-world scraped data. Here the word framework is important as the code is modular (within its limitations) and is not dependant on our NLP task at hand. In this process I had to learn many new skills, both directly related to python and programming as well as supporting tools such as git and gitlab ß. 4. Run experiments with different algorithms in a comparable setting, choosing adequate metrics and interpreting the results. For some datasets we find that by using the bootstrapping self-learning algorithm we improve in over 20 points the F-1 score for the same classifier in the fully-supervised case. 5. Find processes in an arbitrary corpus with a classifier we had designed and fine-tuned on our own datasets. Although far from perfect, the labeling of the scraped UK government data is a promising source of high quality textual descriptions of processes. The results of the experiments made it clear that leveraging unlabeled data is not easy, but can be done by refining algorithms and hyperparameter selection. Having developed a framework to perform such experiments allows for an efficient exploration of new implementations and design choices. We also found some new processes in the UKG corpus that can be added to datasets of the kind. As with any open research topic, there are many ways in which to continue with the investigation. Some future lines of work that could be followed are: 1. A more thorough study of semi-supervised techniques, as they fail to boost the performance with naive bayes in our experiments. More refined algorithms can be implemented to solve some of the problems we encountered. 2. Use of semi-supervised techniques on the target corpus to scrape (UKG). Instead of training a classifier and trying to classify sentences or paragraphs in another corpus, use some labeled process from other sources as a starting point for a semi-supervised algorithm. Here we would be interested on the labeled examples, rather than the trained classifier. 33 3. More advanced techniques for PDF parsing, in particular for proper paragraph detection, to allow for a better increase of accuracy in post-processing. Better ways to manage sentence splitting, maybe machine-learning based, especially for fragments of noisy parsed text. 4. Creation of a benchmark dataset for processes to have a better sense of how good classifiers on this domain are. 5. Run experiments with a transformer-based embedding (such as BERT or the transformers version of USE), which could increase the performance of the classifier. 6. In relation with the last point, running a bigger (transformer) model would require the experiments to be in a cloud-computing environment, whether it be a university computing cluster or a private provider such as AWS. This would highly increase the speed and open an array of possibilities for those bigger models that are hard to run in a limited local machine. 34 Bibliography [1] Laden Aldin and Sergio de Cesare. “A literature review on business process modelling: new frontiers of reusability”. In: Enterprise Information Systems 5.3 (2011), pp. 359–383. doi:10.1080/17517575. 2011.557443. eprint: https://doi.org/10.1080/17517575.2011.557443.url:https://doi.org/ 10.1080/17517575.2011.557443. [2] C. Byrne and P. P. B. Eggermont. “EM algorithms”. In: Handbook of Mathematical Methods in Imaging, edited by Otmar Scherzer. Vol. 54. Feb. 2013, pp. 306–384. doi:10.1080/00107514.2012.756938. [3] Daniel Cer et al. “Universal Sentence Encoder”. In: CoRR abs/1803.11175 (2018). arXiv: 1803.11175. url:http://arxiv.org/abs/1803.11175. [4] O. Chapelle, B. Sch¨olkopf, and A. Zien. “Risks of Semi-Supervised Learning: How Unlabeled Data Can Degrade Performance of Generative Classifiers”. In: Semi-Supervised Learning. 2006, pp. 57–72. [5] Ira Cohen et al. “Semisupervised Learning of Classifiers: Theory, Algorithms, and Their Application to Human-Computer Interaction”. In: IEEE transactions on pattern analysis and machine intelligence 26 (Jan. 2005), pp. 1553–67. doi:10.1109/TPAMI.2004.127. [6] Jacob Devlin et al. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. 2019. arXiv: 1810.04805 [cs.CL]. [7] Marlon Dumas et al. Fundamentals of Business Process Management. Mar. 2018. isbn: 978-3-662- 56508-7. doi:10.1007/978-3-662-56509-4. [8] Fabian Friedrich, Jan Mendling, and Frank Puhlmann. “Process Model Generation from Natural Language Text”. In: Advanced Information Systems Engineering. Ed. by Haralambos Mouratidis and Colette Rolland. Berlin, Heidelberg: Springer Berlin Heidelberg, 2011, pp. 482–496. isbn: 978-3-642-21640- 4. [9] Mohit Iyyer et al. “Deep Unordered Composition Rivals Syntactic Methods for Text Classification”. In: Jan. 2015, pp. 1681–1691. doi:10.3115/v1/P15-1162. [10] J.M. Jacka and P.J. Keller. Business Process Mapping: Improving Customer Satisfaction. Wiley, 2009. isbn: 9780470496053. url:https://books.google.co.uk/books?id=wcJ%5C_J7muLj0C. [11] Christopher Manning et al. “The Stanford CoreNLP Natural Language Processing Toolkit”. In: Proceedings of 52nd Annual Meeting of the Association for Computational Linguistics: System Demonstrations. Baltimore, Maryland: Association for Computational Linguistics, June 2014, pp. 55–60. doi: 10.3115/v1/P14-5010.url:https://www.aclweb.org/anthology/P14-5010. [12] Tomas Mikolov et al. Efficient Estimation of Word Representations in Vector Space. 2013. url:http: //arxiv.org/abs/1301.3781. [13] Kamal Nigam, Andrew Mccallum, and Tom Mitchell. “Text Classification from Labeled and Unlabeled Documents using EM”. In: Machine Learning 39 (May 2000), pp. 103–134. doi:10.1023/A: 1007692713085. [14] Yassine Ouali, C´eline Hudelot, and Myriam Tami. An Overview of Deep Semi-Supervised Learning. 2020. arXiv: 2006.05278 [cs.LG]. [15] Plymouth Hospital Standard Operating Procedures.url:https://www.plymouthhospitals.nhs.uk/ sop. 35 [16] Chen Qian et al. “Process Extraction from Texts via Multi-Task Architecture”. In: CoRR abs/1906.02127 (2019). arXiv: 1906.02127.url:http://arxiv.org/abs/1906.02127. [17] Luis Quishpi, Josep Carmona, and Llu´ıs Padr´o. “Extracting Annotations from Textual Descriptions of Processes”. In: Sept. 2020. doi:10.1007/978-3-030-58666-9_11. [18] Luis Quishpi, Josep Carmona, and Llu´ıs Padr´o. “Extracting Annotations from Textual Descriptions of Processes”. In: Business Process Management. Ed. by Dirk Fahland et al. Cham: Springer International Publishing, 2020, pp. 184–201. isbn: 978-3-030-58666-9. [19] Manfred Reichert and Barbara Weber. Enabling Flexibility in Process-Aware Information Systems: Challenges, Methods, Technologies. Oct. 2012. isbn: 978-3-642-30409-5. doi:10.1007/978-3-642- 30409-5. [20] G. Salton. The SMART Retrieval System—Experiments in Automatic Document Processing. USA: Prentice-Hall, Inc., 1971. [21] TensorFlow Hub.url:https://tfhub.dev/google/universal-sentence-encoder/4. [22] Philippe Thomas. “Semi-Supervised Learning by Olivier Chapelle, Bernhard Sch¨olkopf, and Alexander Zien (Review)”. In: IEEE Transactions on Neural Networks 20 (Jan. 2009), p. 542. [23] Qijia Wei. “Understanding of the naive Bayes classifier in spam filtering”. In: AIP Conference Proceedings 1967.1 (2018), p. 020007. doi:10.1063/1.5038979. [24] S.A. White and D. Miers. BPMN Modeling and Reference Guide: Understanding and Using BPMN. Business Process Management Process Modeling. Future Strategies Incorporated, 2008. isbn: 9780977752720. url:https://books.google.co.uk/books?id=0Z2Td3bCYW8C. [25] YuNing. “Domain Adaptation for Opinion Classification: A Self- Training Approach”. In: Journal of Information Science Theory and Practice 1.1 (Mar. 2013), pp. 10–26. [26] Xiaojin Zhu. “Semi-Supervised Learning Literature Survey”. In: Comput Sci, University of Wisconsin- Madison 2 (July 2008). 36 Acknowledgements I have many people to be thankful of. To my advisors Llu´ıs and Josep for proposing and guiding me through this project. To my parents Jos´e ´ Angel & Marisol, and to Pacu and Yaya, for taking care of me in the distance. To my love, Aina, who is correcting the thesis as I write. To my (flat)mates, Dome, Bernat, (Miquel) and Dami`a for putting up with me. To Rami, for being my fms buddy. To Charis, for inspiring me and giving me some tools I needed to finish this thesis. I hereby swear to myself this is the last soul-less thing I do in my life. 37 Appendix A Code Appendix A.1 Tokenizer Class import os from transformers import BertTokenizer from transformers import AutoTokenizer from nltk.tokenize import word_tokenize ''' This class wraps around different implementations and tokenization requirements for different classifiers. Three tokenization modes: > bert: bert dictionary (for bert-like networks) > bert_as_string: string with bert tokens split by whitespace (for sklearn naive bayes) > word: dictionary with word frequencies (for nltk naive bayes) ''' class Tokenizer: def __init__(self,mode): self.mode =mode if self.mode == 'bert': self.tokenizer =AutoTokenizer.from_pretrained('bert-base-uncased') elif self.mode == 'bert_as_string': self.tokenizer =BertTokenizer.from_pretrained('bert-base-uncased') def tokenize(self,sentence): ''' Input: string sentence Output: tokenization in the selected mode ''' if self.mode == 'word': return self.to_token_words(sentence) elif self.mode == 'bert': return self.to_bert(sentence) elif self.mode == 'bert_as_string': return self.to_bert_as_string(sentence) def to_bert_as_string(self, sentence): ''' Input: sentence string 38 A.3 Model Class import re import sys import nltk import random import logging import numpy as np np.random.seed(619) import pandas as pd import tensorflow as tf tf.random.set_seed(619) import keras.backend as K import tensorflow_hub as hub # https://docs.python.org/3/library/abc.html from abc import ABC, abstractmethod from scipy.sparse import csr_matrix from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import classification_report sys.path.insert(1,'../utils/') import dataset from scipy.sparse import vstack class Model(ABC): ''' Model wraps around some tailored methods for a binary classifier to provide a high-level api to training it with supervised and semi-supervised techniques. ''' def __init__(self): self.self_labeled_labels =(None,None) def load_from_dataset(self, dataset, total_unlb = 0, split = 1): ''' Loads dataset from an instance of a Dataset. ''' self.dataset =dataset self.dataset.set_split(split) self.dataset.pre_process_dataset() self.initialize_data(total_unlb) def load_from_csv(self,csv_name, total_unlb = 0, split = 1): ''' Loads dataset from csv path into a Dataset. ''' self.dataset =dataset.Dataset(csv_name,self.dataset_mode) self.dataset.set_split(split) self.dataset.pre_process_dataset() self.initialize_data(total_unlb) def score_to_confidence(self,x): ''' Returns confidence = max(score,1-score), score goes from 0 to 1. ''' 45 return max(x,1-x) def bootstrap_train(self,lab_method ='top200', stop_condition = 3000, gold =None): ''' Trains a classifier by bootstrapping, in time labeling the unlabeled loaded data. ''' logging.info('Start Bootstrapping!') logging.info('Label choice algorithm: %s', lab_method) bt_labels =self.labels bt_labeled =self.labeled bt_unlabeled =self.unlabeled num_training_labels =len(self.labels) iteration_count = 0 while len(self.labels)-num_training_labels <stop_condition: # train new classifier on labeled data try: model =self.trainer(self.labeled,self.labels) except Exception as e: print('Error at iteration_count: '+str(iteration_count)) print(e) model =self.classifier # label some unlabeled data with the trained classifier unlb =self.bt_unlabeled_at_iteration() new_labels, scores =self.labeler(unlb,model) confidence =np.vectorize(self.score_to_confidence)(scores) if lab_method == 'top200': topx =min(self.length(unlb),200) top_idx =np.argsort(np.array([x[0]for xin confidence]))[-topx:] if lab_method == 'top20': topx =min(self.length(unlb),20) top_idx =np.argsort(np.array([x[0]for xin confidence]))[-topx:] elif re.search('relaxed_thresh',lab_method): threshold =max(0.8, int(re.search('relaxed_thresh(\d+)',lab_method).group(1)) /100-iteration_count/100 ) top_idx =[] for iin range(len(confidence)): if confidence[i] >= threshold: top_idx.append(i) if not top_idx: # if no samples over the threshold: top 20 eamples topx =min(self.length(unlb),20) top_idx =np.argsort(np.array([x[0]for xin confidence]))[-topx:] # add top results back to labeled & take out of unlabeled new_top_labels =[] for tin top_idx: self.labeled =self.concatenate(self.labeled,unlb[t],'labeled') new_top_labels.append(new_labels[t]) self.unlabeled =self.concatenate( self.unlabeled[:t],self.unlabeled[t+1:],'unlabeled') self.labels =self.concatenate(self.labels,new_top_labels,'labels') #self.train_log.append(history.history) logging.info( '\nLabeled: %s\nUnlabeled: %s',self.length(self.labeled),self.length(self.unlabeled) 46 ) self.classifier =model self.self_labeled_labels =(bt_labeled, bt_labels) iteration_count += 1 return self.classifier def bt_unlabeled_at_iteration(self): ''' Serves unlabeled data to be labeled at each bootstrapping iteration. ''' return self.unlabeled[:2000] def em_train(self, MAX_EM_ITERATIONS): # train on labeled examples model =self.trainer(self.labeled,self.labels) self.classifier =model # while stopping condition is not met, do EM iteration_count = 1 while iteration_count <= MAX_EM_ITERATIONS: # get scores and labels for unlabeled data new_labels, scores =self.labeler(self.unlabeled,model) # samples weights 1 for training labeled sample_weights =list(np.ones_like(self.labels)) +list(np.vectorize(self.score_to_confidence)(scores)) all_labels =self.concatenate(self.labels, new_labels, 'labels') # retrain model model =self.weighted_trainer( self.concatenate( self.labeled,self.unlabeled,'unlabeled'), all_labels, sample_weights) model_prob =self.model_probability(all_labels,sample_weights) logging.info( 'EM iteration %s: model log-probability is %s',iteration_count, model_prob) self.classifier =model self.em_labels =all_labels iteration_count += 1 return self.classifier def model_probability(self, all_labels, confidence): log_model_prob =np.log(np.prod(confidence)[0]) #print(log_model_prob) prob_1 =sum(all_labels)/len(all_labels) prob_0 =1-prob_1 #prob_class = [prob_0,prob_1] #print(prob_1) model_prob =log_model_prob for l,c in zip(all_labels,confidence): if l== 0: model_prob += np.log(prob_0*c+prob_1*(1-c)) #aux = c*prob_0 else: model_prob += np.log(prob_0*(1-c) +prob_1*c) #aux = c*prob_1 return model_prob 47 def initialize_data(self, total_unlabeled): ''' Initialize labeled and unlabeled data for training. ''' self.labeled, self.labels =self.dataset.get_train() self.unlabeled =self.dataset.get_unlabeled() #random.shuffle(self.unlabeled) #aux = list(zip(self.labeled, self.labels)) #random.shuffle(aux) #self.labeled, self.labels = zip(*aux) if total_unlabeled: self.unlabeled =self.unlabeled[:total_unlabeled] def classification_report(self, model, test_data, gold, verbose =True): labels, _ =self.labeler(test_data, model) # sklearn classification report class_report =classification_report(gold, labels) if verbose: print(class_report) return class_report def block_classification_report(self, model, test_data, gold, verbose): ''' Classification report for blocks. ''' block_labels =[] clean_gold =[] for block, g in zip(test_data,gold): try: labels, scores =self.labeler(block, model) except: continue clean_gold.append(g) block_labels.append(int(scores[0].mean().round(0))) class_report =classification_report(clean_gold, block_labels) if verbose: print(class_report) return class_report def get_self_labeled(self, algorithm): if algorithm == 'em': return self.concatenate(self.labeled, self.unlabeled, 'unlabeled'), self.all_labels if algorithm == 'bt': return self.labeled, self.labels print('Please choose the algorithm you just run ("em" or "bt").') def train(self): ''' Fully supervised training, saves resulting classifier.''' train_data, train_labels =self.dataset.get_train() self.classifier =self.trainer(train_data, train_labels, False) return self.classifier @abstractmethod def length(self,data): 48 pass @abstractmethod def concatenate(self,data1,data2,case): ''' Abstract Method: Concatenates data in different ways depending of underlying model's data requirements. ''' pass @abstractmethod def labeler(self, data, model, verbose): ''' Abstract Method: Returns scores and labels for data given a trained classifier. ''' pass @abstractmethod def trainer(self,data,labels, verbose): ''' Abstract Method: Returns trained classifier with given data and labels. ''' pass @abstractmethod def weighted_trainer(self,data,labels,sample_weights): ''' Abstract Method: Returns trained classifier with given data, labels and weights. ''' pass @abstractmethod def save_model(self,model,model_path): ''' Abstract Method: Saves model. ''' pass @abstractmethod def load_model(self,model_path): ''' Abstract Method: Loads saved model. ''' pass 49 A.4 UniversalSentenceEncoder Class class UniversalSentenceEncoder(Model): ''' Universal Sentence Encoder by GOOGLE ''' def __init__(self): Model.__init__(self) self.classifier =None self.dataset_mode ='string' self.METRICS =[ tf.keras.metrics.TruePositives(name='tp'), tf.keras.metrics.FalsePositives(name='fp'), tf.keras.metrics.TrueNegatives(name='tn'), tf.keras.metrics.FalseNegatives(name='fn'), tf.keras.metrics.BinaryAccuracy(name='accuracy'), tf.keras.metrics.Precision(name='precision'), tf.keras.metrics.Recall(name='recall'), tf.keras.metrics.AUC(name='auc') ] self.initialize_embedding() def concatenate(self,data1,data2,case): #tf.concat([self.labeled,[unlb[t]]],axis=0) 'labeled' if case == 'labeled': return tf.concat([data1,[data2]],axis=0) #tf.concat([self.unlabeled[:t],self.unlabeled[t+1:]],axis=0) 'unlabeled' if case == 'unlabeled': return tf.concat([data1,data2],axis=0) #tf.concat([self.labels,tf.squeeze(tf.cast(new_top_labels,'int32'))],axis=0) 'labels' if case == 'labels': return tf.concat([data1,tf.squeeze(tf.cast(data2,'int32'))],axis=0) def length(self,data): return len(data) def labeler(self, data, model, verbose =False): scores =model.predict(data, verbose =verbose) labels =scores.round(0) K.clear_session() return labels, scores def trainer(self,data,labels, verbose =False): model =self.build_model() history =model.fit(x=data,y=labels, epochs=3, verbose =verbose) return model def weighted_trainer(self,data,labels,sample_weights): model =self.build_model() sample_weights =np.asarray(sample_weights).astype('float32') history =model.fit(x=data, y=labels, epochs=3, sample_weight =sample_weights) return model def initialize_embedding(self,model_dir ='../models/universal-sentence-encoder_4'): try: 50 self.embed =hub.load(model_dir) except: self.embed =hub.load('https://tfhub.dev/google/universal-sentence-encoder/4') def build_model(self): def UniversalEmbedding(x): return self.embed(tf.squeeze(tf.cast(x, tf.string))) #signature="default" input_text =tf.keras.layers.Input(shape=(1,), dtype=tf.string, name='string_input') embedding =tf.keras.layers.Lambda( UniversalEmbedding,output_shape=(512,),name='embedding')(input_text) dense =tf.keras.layers.Dense(256, activation='relu',name='hidden')(embedding) pred =tf.keras.layers.Dense(1, activation='sigmoid', name='sigmoid')(dense) model =tf.keras.Model(inputs=[input_text], outputs=pred) #model.summary() model.compile(loss='binary_crossentropy',optimizer='adam', metrics=self.METRICS) return model def save_model(self, model, model_path ='use/ckpt'): model.save_weights(model_path) def load_model(self, model_path ='use/ckpt'): model =self.build_model() model.load_weights(model_path) return model 51 A.5 NaiveBayes Class class NaiveBayes(Model): ''' sklearn implementation of Naive Bayes ''' def __init__(self): Model.__init__(self) self.dataset_mode ='counts' def length(self,data): return data.shape[0] def concatenate(self,data1,data2,case): if case in ['labeled','unlabeled']: return vstack((data1,data2)) if case == 'labels': return data1 +data2 def labeler(self, data, model, verbose =False): labels, scores =[], [] for pin model.predict_proba(data): labels.append(p.argmax()) scores.append([p.max()]) return labels, scores def trainer(self, data, labels, verbose =False): model =MultinomialNB().fit(data,y=labels) return model def weighted_trainer(self, data, labels, sample_weights): model =MultinomialNB().fit(data,y=labels, sample_weight=sample_weights) return model def save_model(model, model_path ='nb'): pickle.dump(model,open(model_path,'wb')) def load_model(model_path ='nb'): return pickle.load(open(model_path,'rb')) 52 A.6 Experimenter Class import sys import json sys.path.insert(1,'../utils/') import dataset import model class Experimenter: def __init__(self): pass def load_parameters_to_self(self,parameters): ''' Takes parameter dictionary and initializes self. parameters = { "base_model" : "use"/"naive_bayes", "learning_algorithm" : "fully_supervised"/"bootstrapping"/"em", "training_parameters" : { "TRAINING_DATASET" : [...], "TESTING_DATASET" : [...] } } ''' self.parameters =parameters self.base_model =parameters['base_model'] self.learning_algorithm =parameters['learning_algorithm'] train_params =parameters['training_parameters'] self.TRAINING_DATASET =train_params['TRAINING_DATASET'] self.TESTING_DATASET =train_params['TESTING_DATASET'] if self.learning_algorithm == 'bootstrapping': self.NEW_LABELS_AT_ITERATION =train_params['NEW_LABELS_AT_ITERATION'] self.TOTAL_UNLABELED_DATA =train_params['TOTAL_UNLABELED_DATA'] elif self.learning_algorithm == 'em': self.MAX_EM_ITERATIONS =train_params['MAX_EM_ITERATIONS'] self.TOTAL_UNLABELED_DATA =train_params['TOTAL_UNLABELED_DATA'] def load_gold(self, verbose =False): if self.base_model == 'use': mode ='string' elif self.base_model == 'naive_bayes': mode ='counts' self.gold ={} for dataset_csv in self.TESTING_DATASET: if verbose: print(dataset_csv) dt =dataset.Dataset(dataset_csv,mode) dt.set_split(0) dt.pre_process_dataset() test, label =dt.get_test() self.gold[dataset_csv] ={ 'data':test, 'labels':label } 53 return self.gold def run_experiment(self,parameters): ''' Takes parameter dictionary and runs experiments accordingly. ''' self.load_parameters_to_self(parameters) self.load_gold() print('Starting experiment...') if self.learning_algorithm == 'fully_supervised': self.run_fully_supervised() elif self.learning_algorithm == 'bootstrapping': self.run_bootstrapping() elif self.learning_algorithm == 'em': self.run_em() print('Experiment finished!') def initizalize_model(self): if self.base_model == 'use': return model.UniversalSentenceEncoder() return model.NaiveBayes() def run_fully_supervised(self): classifier_model =self.initizalize_model() self.experiment_log ={ "parameters" :self.parameters, "experiments" : [] } for train_csv in self.TRAINING_DATASET: classifier_model.load_from_csv(csv_name =train_csv, split = 0.85) self.classifier =classifier_model.train() experiment ={ "params" : [train_csv], "reports" : [] } self.generate_reports_and_log(train_csv, classifier_model, experiment, self.classifier) return self.experiment_log def generate_reports_and_log(self, train_csv, classifier_model, experiment, classifier): for test_csv in self.TESTING_DATASET: if test_csv == train_csv: test_data, test_labels =classifier_model.dataset.get_test() else: test_data =self.gold[test_csv]['data'] test_labels =self.gold[test_csv]['labels'] class_report =classifier_model.classification_report( classifier, test_data, test_labels, False ) experiment["reports"].append({"test":test_csv, "report":class_report}) self.experiment_log["experiments"].append(experiment) def run_bootstrapping(self): classifier_model =self.initizalize_model() self.experiment_log ={ 54