<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Nwamaka Imasogie’s Machine Learning and Artificial Intelligence Projects - Medium]]></title>
        <description><![CDATA[My machine learning and artificial intelligence projects. The ability to communicate is very important for a ML/AI engineer. I focus on communicating the what, why, when, where, and who of the insights in the simplest way possible. - Medium]]></description>
        <link>https://medium.com/nwamaka-imasogie?source=rss----c1856a20555a---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Nwamaka Imasogie’s Machine Learning and Artificial Intelligence Projects - Medium</title>
            <link>https://medium.com/nwamaka-imasogie?source=rss----c1856a20555a---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:59:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/nwamaka-imasogie" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ClinicalBERT: Using Deep Learning Transformer Model to Predict Hospital Readmission]]></title>
            <link>https://medium.com/nwamaka-imasogie/clinicalbert-using-deep-learning-transformer-model-to-predict-hospital-readmission-c82ff0e4bb03?source=rss----c1856a20555a---4</link>
            <guid isPermaLink="false">https://medium.com/p/c82ff0e4bb03</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[predictive-modeling]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Nwamaka Imasogie]]></dc:creator>
            <pubDate>Tue, 14 Jan 2020 20:07:59 GMT</pubDate>
            <atom:updated>2024-03-29T13:35:39.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yReOxUMOUb0u6fvh3xxcVQ.png" /></figure><h3>ClinicalBERT: Using a Deep Learning Transformer Model to Predict Hospital Readmission</h3><p><strong><em>Before we begin, let me point you to my </em></strong><a href="https://github.com/nwams/ClinicalBERT-Deep-Learning--Predicting-Hospital-Readmission-Using-Transformer"><strong><em>GitHub repo</em></strong></a><strong><em> [or</em></strong><a href="https://nbviewer.jupyter.org/github/nwams/ClinicalBERT-Deep-Learning--Predicting-Hospital-Readmission-Using-Transformer/blob/master/ClinicalBERT%20Deep%20Learning%20-%20Predicting%20Hospital%20Readmission.ipynb"><strong><em> Jupyter Notebook</em></strong></a><strong><em>] containing all the code used in this guide. Feel free to use the code to follow along with the guide. You can use </em></strong><a href="https://drive.google.com/drive/folders/0BzzQzSMWf9-1fktRSUR0S3M5TXRzemE1ZmdaVnlLb0d0eVl3eVdOSHpDalp1a0lXblNmZE0?resourcekey=0-roF9gkEnGRZtKfjr42ud7w&amp;usp=sharing"><strong><em>this google link</em></strong></a><strong><em> (439MB) to download the early readmission model (this is all you will need to follow along). Alternatively, you can use </em></strong><a href="https://drive.google.com/drive/folders/0BzzQzSMWf9-1fnFvdkVrRURoVHVXQU15QWd2NjhlMnkybjdQV1BvbU1BNHZRamQyZjFKbjQ?resourcekey=0-FbKZD3pNJZMg2wry-FGmHg&amp;usp=sharing"><strong><em>this google link</em></strong></a><strong><em> (1.32GB) to download the pretrained ClinicalBERT model + the readmission task fine-tuned model weights + the early readmission model.</em></strong></p><h3>Preface</h3><p>If you came here from my earlier work <a href="https://medium.com/nwamaka-imasogie/predicting-hospital-readmission-using-nlp-5f0fe6f1a705">Predicting Hospital Readmission using NLP</a>, this deep learning work won’t serve as a direct comparison for the AUROC metric because my approach is completely different in this paper. The more I dug into it, the more I discovered that the most beneficial application for clinicians is to be able to use these predictions to make adjustments <strong>while a patient is still in the hospital</strong> in order for Doctors to intervene and prevent them from being readmitted in the future. Therefore, instead of using discharge summaries (written after a patient’s stay is over) it’s best to just feed in the early notes into the model that were gathered from within 2 or 3 days of a patient’s stay.</p><p>In this tutorial, I will use ClinicalBERT to train a readmission classifier. Specifically, I will take the pre-trained ClinicalBERT model, add an untrained layer of neurons on the end, and train the new model (fine-tuning). A.k.a. <strong>Transfer Learning</strong>.</p><h3>TLDR</h3><p>My results for predicting readmission <strong>using only the first few days of notes in the intensive care unit (not discharge summaries) </strong>are:</p><ul><li>For 2days AUROC=0.748 and for 3days AUROC=0.758.</li><li>For 2days RP80=38.69% and for 3days RP80=38.02%.</li></ul><p>See the bottom of this article for full details.</p><h3>Introduction</h3><p>I recently read this great paper “ClinicalBert: Modeling Clinical Notes and Predicting Hospital Readmission” by Huang et al (<a href="https://arxiv.org/pdf/1904.05342.pdf"><em>Paper</em></a><em> &amp; </em><a href="https://github.com/kexinhuang12345/clinicalBERT"><em>GitHub</em></a>).</p><p>They develop ClinicalBert by applying BERT (bidirectional encoder representations from transformers) to clinical notes.</p><p>I wanted to dissect the work and expound upon the deep learning concepts. My work will serve as a detailed annotation. I also walk through implementation, code explanations and interpretation of the contents of this academic paper. I will also create visualizations to enhance explanations. And I put my work into a convenient Jupyter Notebook format.</p><h4>How my work differs from the author:</h4><ol><li>I am only working with <strong>early</strong> clinical notes (first 24–48 hrs and 48–72 hrs, a.k.a. 2day and 3day, respectively) because although discharge summaries have predictive power for readmission, “discharge summaries might be written after a patient has left the hospital. Therefore, discharge summaries are <strong>not actionable</strong> since doctors cannot intervene when a patient has left the hospital. Models that dynamically predict readmission in the early stages of a patient’s admission are relevant to clinicians…a maximum of the first 48 or 72 hours of a patient’s notes are concatenated. These concatenated notes are used to predict readmission.”[<a href="https://arxiv.org/pdf/1904.05342.pdf">pg 12</a>]. The ClinicalBERT model can predict readmission dynamically. <strong>Making a prediction using a discharge summary at the end of a stay means that there are fewer opportunities to reduce the chance of readmission. To build a clinically-relevant model, we define a task for predicting readmission at any timepoint since a patient was admitted.</strong></li><li>My code is presented in a Jupyter Notebook.</li><li>It’s important to note that my code differs from Huang’s because I <a href="https://huggingface.co/transformers/migration.html">migrated</a> to using <a href="https://huggingface.co/transformers/index.html">HuggingFace’s</a> new transformer module instead of the formerly known as pytorch_pretrained_bert that the author used.</li><li>I do not conduct pre-training for ClinicalBERT because the author already performed pre-training on Clinical words and the model’s weights are already available <a href="http://bit.ly/clinicalbert_weights">here</a>. This is exactly the same concept for original BERT since it is pre-trained on Wikipedia/the Book Corpus and can be used for other downstream tasks. *Note: This is a very expensive process (hundreds of GPU hours!) that Google has already undertaken and then provided the output vectors for public-use :) <strong>Transfer Learning!</strong></li></ol><h3>About the Dataset</h3><p>I will utilize the MIMIC-III (Medical Information Mart for Intensive Care III), an amazing free hospital database.</p><p>The database includes information such as demographics, vital sign measurements made at the bedside (~1 data point per hour), laboratory test results, procedures, medications, caregiver notes, imaging reports, and mortality (including post-hospital discharge).</p><p>MIMIC-III is an open-access relational database containing tables of data relating to patients who stayed within the intensive care units (ICU) at Beth Israel Deaconess Medical Center. This public database of Electronic Health Records contains data points on about 41,000 patients from intensive care units between 2001 and 2012, including notes on close to 53,000 admissions.</p><p>Due to the sensitive nature of medical data, I cannot include the data openly in this repository. If you’d like to get access to the data for this project, you will need to request access at this link (<a href="https://mimic.physionet.org/gettingstarted/access/">https://mimic.physionet.org/gettingstarted/access/</a>).</p><h3>Brief BERT Intro</h3><p><strong>BERT</strong> (Bidirectional Encoder Representations from Transformers) is a recent <a href="https://arxiv.org/pdf/1810.04805.pdf">model</a> published in Oct 2018 by researchers at Google AI Language. It has caused a stir in the Machine Learning community by presenting state-of-the-art results in a wide variety of NLP tasks, including Question Answering (SQuAD v1.1), Natural Language Inference (MNLI), and others.</p><h3>What is ClinicalBERT?</h3><p>ClinicalBERT is a Bidirectional Transformer.</p><p>ClinicalBERT is a modified BERT model: Specifically, the representations are learned using medical notes and further processed for downstream clinical tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XnuR87i5muEN59h_M_fYHg.png" /><figcaption>ClinicalBERT is pretrained on patient clinical notes/EHR and then can be used for downstream predictive tasks.</figcaption></figure><p>The diagram below illustrates how care providers add notes to an electronic health record during a patient’s admission, and the model dynamically updates the patient’s risk of being readmitted within a 30-day window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xPVPG0QeVugnOK6mMBnI1A.png" /><figcaption>Every day, more data gets added to an EHR. Notes like Radiology, Nursing, ECG, Physician, Discharge summary, Echo, Respiratory, Nutrition, General, Rehab Services, Social Work, Case Management, Pharmacy and Consult.</figcaption></figure><h3>Why is ClinicalBERT needed?</h3><p>Before the author even evaluated ClinicalBERT’s performance as a model of readmission, <strong>his initial experiment showed that the original BERT suffered in performance on the masked language modeling task on the MIMIC-III data as well as the next sentence prediction tasks. This proves the need develop models tailored to clinical data such as ClinicalBERT!</strong></p><p>Medicine suffers from alarm fatigue. This means useful classification rules for medicine need to have high precision (positive predictive value).</p><p>The quality of learned representations of text depends on the text the model was trained on. <strong>Regular BERT is pretrained on BooksCorpus and Wikipedia</strong>. However, these two datasets are distinct from clinical notes. Clinical notes have jargon, abbreviations and different syntax and grammar than common language in books or encyclopedias. <strong>ClinicalBERT is trained on clinical notes/Electronic Health Records (EHR)</strong>.</p><p>Clinical notes require capturing interactions between distant words and ClinicalBert captures qualitative relationships among clinical concepts in a database of medical terms.</p><p>Compared to the popular word2vec model, ClinicalBert more accurately captures clinical word similarity.</p><h3>BERT Basics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9PjJt3EkZS85Hy3H4UKeLg.png" /><figcaption>[<a href="https://arxiv.org/abs/1904.05342">Source</a>]</figcaption></figure><p>Just like BERT, Clinical BERT is a trained Transformer Encoder stack.</p><p>Here’s a quick refresher on the basics of how BERT works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*rAAdyehB3uXuDkrjB3Mzog.png" /><figcaption>[<a href="http://jalammar.github.io/illustrated-bert/">Source</a>]</figcaption></figure><p>BERT base has 12 encoder layers.</p><p>In my code I am using <strong><em>BERT base uncased</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j9R9I4taW5P4qxaCW-7liw.png" /><figcaption>[<a href="http://jalammar.github.io/illustrated-bert/">Source</a>]</figcaption></figure><p>Pretrained BERT has a max of <strong>512 input tokens</strong> (position embeddings). The output would be a vector for each input token. Each vector is made up of <strong>768</strong> float numbers (<strong>hidden units</strong>).</p><h3>Pre-training ClinicalBERT</h3><p>Training the BERT baseline model is typically done with AdamW, a variant of the Adam optimizer with weight decay as the optimizer.</p><p>At its heart, Adam is a simple and intuitive idea: why use the same learning rate for every parameter, when we know that some surely need to be moved further and faster than others? Since the square of recent gradients tells us how much signal we’re getting for each weight, we can just divide by that to ensure even the most sluggish weights get their chance to shine. Adam takes that idea, adds on the standard approach to momentum, and (with a little tweak to keep early batches from being biased) that’s it!…We should use <strong>weight decay</strong> with Adam, and not the L2 regularization that classic deep learning libraries implement [<a href="https://www.fast.ai/2018/07/02/adam-weight-decay/#understanding-adamw-weight-decay-or-l2-regularization">fast.ai</a>].</p><p>ClinicalBERT outperforms BERT on two unsupervised language modeling tasks evaluated on a large corpus of clinical text. In <em>masked language modeling</em> (where you mask 15% of the input tokens and using the model to predict the next tokens) and <em>next-sentence prediction</em> tasks ClinicalBERT outperforms BERT by 30 points and 18.75 points respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QAGvhTGhTPA0DTZms19o7g.png" /><figcaption>Source: <a href="https://arxiv.org/abs/1904.05342">https://arxiv.org/abs/1904.05342</a></figcaption></figure><h3>Fine-tuning ClinicalBERT</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z4u4ibxWw09VFI-csMWNcw.png" /><figcaption>ClinicalBERT can be readily adapted to downstream clinical tasks e.g. Predicting 30-Day Readmission.</figcaption></figure><p>In this tutorial, we will use ClinicalBERT to train a readmission classifier. Specifically, I will take the pre-trained ClinicalBERT model, add an untrained layer of neurons on the end, and train the new model.</p><h4>Advantages to Fine-Tuning</h4><p>You might be wondering <a href="https://mccormickml.com/2019/07/22/BERT-fine-tuning/">why</a> we should do fine-tuning rather than train a specific deep learning model (BiLSTM, Word2Vec, etc.) that is well suited for the specific NLP task you need?</p><ul><li><strong>Quicker Development: </strong>The pre-trained ClinicalBERT model weights already encode a lot of information about our language. As a result, it takes much less time to train our fine-tuned model — it is as if we have already trained the bottom layers of our network extensively and only need to gently tune them while using their output as features for our classification task. For example in the original BERT paper the authors recommend only 2–4 epochs of training for fine-tuning BERT on a specific NLP task, compared to the hundreds of GPU hours needed to train the original BERT model or a LSTM from scratch!</li><li><strong>Less Data: </strong>Because of the pretrained weights this method allows us to fine-tune our task on a much smaller dataset than would be required in a model that is built from scratch. A major drawback of NLP models built from scratch is that we often need a prohibitively large dataset in order to train our network to reasonable accuracy, meaning a lot of time and energy had to be put into dataset creation. By fine-tuning BERT, we are now able to get away with training a model to good performance on a much smaller amount of training data.</li><li><strong>Better Results: </strong>Fine-tuning is shown to achieve state of the art results with minimal task-specific adjustments for a wide variety of tasks: classification, language inference, semantic similarity, question answering, etc. Rather than implementing custom and sometimes-obscure architectures shown to work well on a specific task, fine-tuning is shown to be a better (or at least equal) alternative.</li></ul><h4>Fine-tuning Details</h4><p>ClinicalBert is fine-tuned on a task specific to clinical data: <strong>readmission prediction</strong>.</p><p>The model is fed a patient’s clinical notes, and the patient’s risk of readmission within a 30-day window is predicted using a linear layer applied to the classification representation, hcls, learned by ClinicalBert.</p><p>The model parameters are fine-tuned to <strong>maximize the log-likelihood</strong> of this binary classifier.</p><p>Here is the probability of readmission formula:</p><pre>P (readmit = 1 | hcls) = σ(W hcls)</pre><ul><li><strong>readmit</strong> is a binary indicator of readmission (0 or 1).</li><li><strong>σ</strong> is the sigmoid function</li><li><strong>hcls</strong> is a linear layer operating on the final representation for the CLS token. In other words <strong>hcls</strong> is the output of the model associated with the classification token.</li><li><strong>W</strong> is a parameter matrix</li></ul><figure><a href="https://www.buymeacoffee.com/nwamakai"><img alt="" src="https://cdn-images-1.medium.com/max/327/1*plPoTREcTv6_c3lZm2iBBA.png" /></a></figure><h3>Setting Up</h3><p>Before starting you must create the following directories and files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*CrnzPXD7N642_eSNs5uzng.png" /></figure><h4>Installation</h4><p>Run this command to install the HuggingFace transformer module:</p><p>conda install -c conda-forge transformers</p><h3>MIMIC-III Dataset on AWS S3 Bucket</h3><p>I used the MIMIC-III dataset that they host in the cloud in an <a href="https://physionet.org/content/mimiciii/1.4/">S3 bucket</a>. I found it was easiest to simply <a href="https://mimic.physionet.org/gettingstarted/cloud/">add my AWS account number to my MIMIC-III account</a> and use this link s3://mimic-iii-physionet to pull the ADMISSIONS and NOTEEVENTS table into my Notebook.</p><h3>Preprocessing</h3><p>ClinicalBert requires minimal preprocessing:</p><ol><li>First, words are converted to lowercase</li><li>Line breaks are removed</li><li>Carriage returns are removed</li><li>De-identified the personally identifiable info inside the brackets</li><li>Remove special characters like ==, −−</li><li>The <a href="https://spacy.io/">SpaCy</a> sentence segmentation package is used to segment each note (Honnibal and Montani, 2017).</li></ol><p>Since clinical notes don’t follow rigid standard language grammar, we find rule-based segmentation has better results than dependency parsing-based segmentation. Various segmentation signs that misguide rule-based segmentators are removed or replaced.</p><ul><li>For example 1.2 would be removed.</li><li>M.D., dr. would be replaced with with MD, Dr</li><li>Clinical notes can include various lab results and medications that also contain numerous rule-based separators, such as 20mg, p.o., q.d.. (where q.d. means one a day and q.o. means to take by mouth. To address this, segmentations that have less than 20 words are fused into the previous segmentation so that they are not singled out as different sentences.</li></ul><h3>AWS SageMaker — Training on a GPU</h3><p>I used a Notebook in AWS <a href="https://aws.amazon.com/sagemaker/">Sagemaker</a> and trained on a single p2.xlarge K80 GPU (in SageMaker choose the ml.p2.xlarge). You will have to request a limit increase from AWS support before you can use a GPU. It is a manual request that’s ultimately granted by a human being and could take several hours or 1-day.</p><p>Create a new Notebook in SageMaker. Then open a new Terminal (see picture below):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*ZQdFLr0P02ep2WDwmR2KHw.png" /></figure><p>Copy/paste and run the script below to cd into the SageMaker directory and create the necessary folders and files:</p><pre>cd SageMaker/</pre><pre>mkdir -p ./data/discharge</pre><pre>mkdir -p ./data/3days</pre><pre>mkdir -p ./data/2days</pre><pre>touch ./data/discharge/train.csv</pre><pre>touch ./data/discharge/val.csv</pre><pre>touch ./data/discharge/test.csv</pre><pre>touch ./data/3days/train.csv</pre><pre>touch ./data/3days/val.csv</pre><pre>touch ./data/3days/test.csv</pre><pre>touch ./data/2days/test.csv</pre><p>Upload your Notebook that you’ve been working in on your local computer.</p><p>When creating an IAM role, choose the Any S3 bucket option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/0*e__mo25HXzWWmTvv" /></figure><p>Create a /pickle directory and upload the 3 pickled files: df_discharge.pkl, df_less_2.pkl and df_less_3.pkl. This may take a few minutes because the files are 398MB, 517MB, and 733MB respectively.</p><p>Then upload the modeling_readmission.py and file_utils.py files into the Jupyter home directory.</p><p>Then upload the <a href="https://drive.google.com/open?id=1t8L9w-r88Q5-sfC993x2Tjt1pu--A900">model</a> directory to the Jupyter home directory. You can create the directory structure using the following command: mkdir -p ./model/early_readmission. Then you can upload the 2 files pytorch_model.bin and bert_config.json into that folder. This may take a few minutes because pytorch_mode.bin is 438MB.</p><p>Ultimately your Jupyter directory structure should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*39g9-D-7Votj4WYaS9tUuw.png" /><figcaption>Note that the <strong>result_early</strong> folder will be created by the code (not you).</figcaption></figure><p>Now you can run the entire notebook.</p><p>Running the entire notebook took about 8 minutes on a K80 GPU.</p><p>If you’d like to save all of the files (including output) to your local computer run this line in your Jupyter Notebook: !zip -r -X ClinicalBERT_results.zip &#39;./&#39; then you can download it manually from your Notebook.</p><h3>Code Breakdown</h3><p>There’s quite a bit of code so let’s walk through the important bits. I’ll skip a lot of the preprocessing parts like cleaning, splitting training/val/test sets and subsampling that I already covered in-depth <a href="https://medium.com/nwamaka-imasogie/predicting-hospital-readmission-using-nlp-5f0fe6f1a705">here</a>.</p><h4>Model Configuration for Readmission</h4><p>Here are the parameters used for the model:</p><pre>{<br>  &quot;attention_probs_dropout_prob&quot;: 0.1,<br>  &quot;hidden_act&quot;: &quot;gelu&quot;,<br>  &quot;hidden_dropout_prob&quot;: 0.1,<br>  &quot;hidden_size&quot;: 768,<br>  &quot;initializer_range&quot;: 0.02,<br>  &quot;intermediate_size&quot;: 3072,<br>  &quot;max_position_embeddings&quot;: 512,<br>  &quot;num_attention_heads&quot;: 12,<br>  &quot;num_hidden_layers&quot;: 12,<br>  &quot;type_vocab_size&quot;: 2,<br>  &quot;vocab_size&quot;: 30522<br>}</pre><h4>Split into 318 word chunks</h4><pre># to get 318 words chunks for readmission tasks<br>    df_len = len(df_less_n)<br>    want = pd.DataFrame({&#39;ID&#39;: [], &#39;TEXT&#39;: [], &#39;Label&#39;: []})<br>    for i in tqdm(range(df_len)):<br>        x = df_less_n.TEXT.iloc[i].split()<br>        n = int(len(x) / 318)<br>        for j in range(n):<br>            want = want.append({&#39;TEXT&#39;: &#39; &#39;.join(x[j * 318:(j + 1) * 318]), &#39;Label&#39;: df_less_n.OUTPUT_LABEL.iloc[i],<br>                                &#39;ID&#39;: df_less_n.HADM_ID.iloc[i]}, ignore_index=True)<br>        if len(x) % 318 &gt; 10:<br>            want = want.append({&#39;TEXT&#39;: &#39; &#39;.join(x[-(len(x) % 318):]), &#39;Label&#39;: df_less_n.OUTPUT_LABEL.iloc[i],<br>                                &#39;ID&#39;: df_less_n.HADM_ID.iloc[i]}, ignore_index=True)</pre><p>A patient will usually have a lot of different notes, however, the ClinicalBert model has a fixed maximum length of input sequence. We split notes into subsequences (each subsequence is the maximum length supported by the model), and define how ClinicalBert makes predictions on long sequences by binning the predictions on each subsequence.</p><p>You might be wondering why we split into 318 word pieces? Because with BERT there’s a <strong>512 maximum</strong> sequence number of sub word unit tokens (average ~318 words). In other words, BERT uses sub word units (WordPieces) instead of the entire word as the input unit. So instead of “I am having lunch” as 4 individual words, conceptually, it might do something like “I am hav ing lun ch”.</p><p>If you’d like to know more about it this academic <a href="https://arxiv.org/abs/1508.07909">paper</a> was originally written to tackle the “out of vocab” problem but it turns out to have stronger predictive values.</p><h4>Readmission Prediction</h4><p>The probability of readmission for a patient is computed as follows. Assume the patient’s clinical notes are represented as <em>n</em> subsequences and fed to the model separately; the model outputs a probability for each subsequence. The <strong>probability of readmission</strong> is computed using the probabilities output for each of these subsequences:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Gb6Mg8YSigxCJgTPFPaQA.png" /><figcaption>Equation for Probability of Readmission where <strong>c</strong> is a scaling factor that controls the amount of influence of the number of subsequences <strong>n</strong>, and <strong>hpatient</strong> is the implicit representation ClinicalBert computes from the entirety of a patient’s notes. <strong>Pnmax</strong> is the maximum of probability of readmission across the <strong>n</strong> subsequences, and <strong>Pnmean</strong> is the mean of the probability of readmission across the <strong>n</strong> subsequences a patient’s notes have been split into.</figcaption></figure><p>Huang finds that computing readmission probability using the equation above consistently outperforms predictions on each subsequence individually by 3-8%. This is because:</p><ol><li>Some subsequences, n, (such as tokens corresponding to progress reports) do NOT contain information about readmission, whereas others do. The risk of readmission should be computed using subsequences that correlate with readmission risk, and <strong>the effect of unimportant subsequences should be minimized</strong>. This is accomplished by using the maximum probability over subsequences (Pnmax).</li><li>Also noisy subsequences mislead the model and decrease performance. So they also include the average probability of readmission across subsequences (Pnmean). This leads to a trade-off between the mean and maximum probabilities of readmission.</li><li>If there are a large number of subsequences for a patient with many clinical notes, there is a higher probability of having a noisy maximum probability of readmission. This means longer sequences may need to have a larger weight on the mean prediction. We include this weight as the n/c scaling factor, with c adjusting for patients with many clinical notes. Empirically, Huang found that c=2 performs best on validation data.</li></ol><p>The formula can be found in the vote_score function in the <strong>temp</strong> variable Remember that the 2 is from c=2:</p><pre>def vote_score(df, score, readmission_mode, output_dir):<br>    df[&#39;pred_score&#39;] = score<br>    df_sort = df.sort_values(by=[&#39;ID&#39;])<br>    #score <br>    <strong>temp = (df_sort.groupby([&#39;ID&#39;])[&#39;pred_score&#39;].agg(max)+df_sort.groupby([&#39;ID&#39;])[&#39;pred_score&#39;].agg(sum)/2)/(1+df_sort.groupby([&#39;ID&#39;])[&#39;pred_score&#39;].agg(len)/2)</strong><br>    x = df_sort.groupby([&#39;ID&#39;])[&#39;Label&#39;].agg(np.min).values<br>    df_out = pd.DataFrame({&#39;logits&#39;: temp.values, &#39;ID&#39;: x})</pre><pre>fpr, tpr, thresholds = roc_curve(x, temp.values)<br>    auc_score = auc(fpr, tpr)</pre><pre>plt.figure(1)<br>    plt.plot([0, 1], [0, 1], &#39;k--&#39;)<br>    plt.plot(fpr, tpr, label=&#39;Val (area = {:.3f})&#39;.format(auc_score))<br>    plt.xlabel(&#39;False positive rate&#39;)<br>    plt.ylabel(&#39;True positive rate&#39;)<br>    plt.title(&#39;ROC curve&#39;)<br>    plt.legend(loc=&#39;best&#39;)<br>    plt.show()<br>    string = &#39;auroc_clinicalbert_&#39;+readmission_mode+&#39;.png&#39;<br>    plt.savefig(os.path.join(output_dir, string))</pre><pre>return fpr, tpr, df_out</pre><h4>Results</h4><p>For validation 10% of the data is held out, for testing 10% of the data is held out.</p><p>Each model is evaluated using three metrics:</p><ol><li>Area under the ROC curve (AUROC)</li><li>Area under the precision-recall curve (AUPRC)</li><li>Recall at precision of 80% (RP80): For the readmission task, false positives are important. To minimize the number of false positives and thus minimize the risk of alarm fatigue, we set the precision to 80%. In other words we set a 20% false positive rate out of the predicted positive class and use the corresponding threshold to calculate recall. This leads to a clinically-relevant metric that enables us to build models that control the false positive rate.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86995103ba26b36e6898be1b58ccb058/href">https://medium.com/media/86995103ba26b36e6898be1b58ccb058/href</a></iframe><p>Here are the results output from Predicting Readmission on the Early Notes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Im6GTZQBdKEnX4l01QnoQ.png" /></figure><h3>Interpreting Results</h3><h4>Quick Review of Precision, Recall and AUROC</h4><p>I recommend reading Jason Brownlee’s <a href="https://machinelearningmastery.com/roc-curves-and-precision-recall-curves-for-classification-in-python/">article</a>.</p><ul><li><a href="https://machinelearningmastery.com/roc-curves-and-precision-recall-curves-for-classification-in-python/"><strong>Precision</strong></a> is a ratio of the number of true positives divided by the sum of the true positives and false positives. <strong>It describes how good a model is at predicting the positive class</strong>. It is also referred to as the positive predictive value.</li><li><strong>Recall</strong>, a.k.a. sensitivity, is calculated as the ratio of the number of true positives divided by the sum of the true positives and the false negatives.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XZvqxpV4yyfOg-vd.png" /></figure><p><strong>It’s important to look at both precision and recall in cases where there is an imbalance</strong> in the observations between the two classes. Specifically, when there are many examples of no event (class 0) and only a few examples of an event (class 1). Because usually the large number of class 0 examples means we are less interested in the skill of the model at predicting class 0 correctly, e.g. high true negatives.</p><blockquote>The important thing to note in the calculation of precision and recall is that the calculations do not make use of the true negatives. It is only concerned with the correct prediction of the minority class, class 1.</blockquote><h4>When to Use ROC vs. Precision-Recall Curves?</h4><p>The recommendations are:</p><ul><li>ROC curves should be used when there are roughly equal numbers of observations for each class.</li><li>Precision-Recall curves should be used when there is a moderate to large class imbalance.</li></ul><p>Why? Because <strong>ROC curves present an overly optimistic picture of the model on datasets with a class imbalance</strong>. It’s optimistic because of the use of true negatives in the False Positive rate in the ROC Curve; however remember that the False Positive rate is carefully avoided in the Precision-Recall.</p><h4>Now back to interpreting our results</h4><p>Since we balanced the data I’ll focus on reporting the AUROC curve as the most appropriate metric instead of the AUPRC.</p><p>I’ll also focus on reporting the Recall at 80% Precision metric due to the fact that it is clinically relevant (remember that alarm fatigue is a real problem in healthcare that we are intentionally trying to avoid/reduce).</p><blockquote>For 2days AUROC=0.748 and for 3days AUROC=0.758.</blockquote><blockquote>For 2days RP80=38.69% and for 3days RP80=38.02%.</blockquote><p>Unfortunately, I didn’t find any other papers/studies that focused specifically on applying deep learning to early notes (which could’ve been a nice additional comparison point).</p><p>However, as a light reference point, according to Huang’s experimentation, he found that ClinicalBERT outperformed Bag-Of-Words and BILSTM baselines “up to” the following:</p><h4>2days compared to other models:</h4><ul><li><strong>Up to 9.5% AUROC</strong> compared to Bag-of-Words and <strong>up to</strong> <strong>6.5% AUROC</strong> when compared to BILSTM.</li><li><strong>Up to</strong> <strong>20.7% RP80</strong> compared to Bag-of-words and <strong>up to</strong> <strong>19.4% RP80</strong> when compared to BILSTM.</li></ul><h4>3days compared to other models:</h4><ul><li><strong>Up to 9.8% AUROC</strong> compared to Bag-of-Words and <strong>up to</strong> <strong>9.6% AUROC</strong> when compared to BILSTM.</li><li><strong>Up to</strong> <strong>26.2% RP80</strong> compared to Bag-of-words and <strong>up to</strong> <strong>20.9% RP80</strong> when compared to BILSTM.</li><li>I’d like to emphasize that the above metrics only gives the upper bound on the delta on Huang’s experimentation.</li></ul><p>ClinicalBERT has more confidence compared to the other models. And at a fixed rate of false alarms, ClinicalBert recalls more patients that have been readmitted.</p><h3>Self-Attention Maps — Visualizing the Results</h3><p><strong><em>The code I used for creating the self-attention map in this section is </em></strong><a href="https://github.com/nwams/ClinicalBERT-Deep-Learning--Predicting-Hospital-Readmission-Using-Transformer/blob/master/attention/attention_visualization.ipynb"><strong><em>here</em></strong></a><strong><em>.</em></strong></p><p>It’s very difficult for a human to understand why a neural network made a certain prediction, and what parts of the input data did the model find most informative. Therefore Doctors may not trust output from a data-driven method.</p><p>Well, visualizing the self-attention mechanism is a way to solve that problem because it allows you to see the terms correlated with predictions of hospital readmission.</p><p>You might already be familiar with the popular “<a href="https://papers.nips.cc/paper/7181-attention-is-all-you-need.pdf">Attention is All You Need</a>” paper that was submitted at the 2017 arXiv by the Google machine translation team. If not, check out this <a href="https://towardsdatascience.com/attn-illustrated-attention-5ec4ad276ee3">animation</a> that explains attention. More intuitively, we can think <strong>“self-attention”</strong> as the sentence will <strong>look at itself to determine how to represent each token.</strong></p><blockquote>As the model processes each word (each position in the input sequence), self attention allows it to look at other positions in the input sequence for clues that can help lead to a better encoding for this word.</blockquote><p>— <a href="http://jalammar.github.io/illustrated-transformer/">The Illustrated Transformer</a> by Jay Alammar</p><p>For every clinical note input to ClinicalBert, each self-attention mechanism computes a distribution over every term in a sentence, given a query. The <strong>self-attention equation</strong> is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XR3cVEY3y4c6h_CeHgsHfg.png" /><figcaption>Where q is query vector, K is the key vector, d is the dimensionality of the queries and keys.</figcaption></figure><p>Intuitively, we can think of it like this: the query, q, represents what kind of information we are looking for, and the key, K, represent the relevance to the query.</p><p>A high attention weight between a query and key token means the interaction between these tokens is predictive of readmission. In the ClinicalBert encoder, there are 144 heads (which is 12 multi-head attention mechanisms for each of the 12 encoder layers). There will be diversity in the different heads, which is what we should expect because different heads learn <a href="https://docs.dgl.ai/en/latest/tutorials/models/4_old_wines/7_transformer.html">different relations</a> between word pairs. Although each head receives the same input embedding, through random initialization, each learns different focuses [<a href="https://www.researchgate.net/publication/328627493_Parallel_Attention_Mechanisms_in_Neural_Machine_Translation/figures?lo=1">img</a>].</p><p>The self-attention map below is just one of the self-attention heads in ClinicalBERT — it reveals which terms in clinical notes are predictive of patient readmission. The sentence he has experienced acute on chronic diastolic heart failure in the setting of volume overload due to his sepsis . is used as input that is fed into the model. This sentence is <strong>representative</strong> of a clinical note found in MIMIC-III. The Self-Attention equation is used to compute a distribution over tokens in this sentence, where every query token, q, is also a token in the same input sentence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m8fSW29_qmke-qDf6na8LQ.png" /><figcaption>ClinicalBERT Self-Attention Map. The darker colors stand for greater weights.</figcaption></figure><p>Notice that the self-attention map shows a higher attention weight between the the word chronic and acute…or chronic and ###load .</p><p>Intuitively, the presence of the token associated with the word “chronic” is a predictor of readmission.</p><p>Remember though, there are 12 heads at each layer (144 total heads for this model). And each head is looking at different things. The diverse representations it captures is what makes BERT so intelligent! So looking at each head’s attention graph separately will give you an understanding of <strong>how</strong> the model makes predictions — but it won’t make it super easy to interpret the entire system as a “one-stop shop”. Instead, you could do some aggregation (summing up or averaging all the attention head’s weights).</p><p>So if you’re a clinician looking for a “one-stop shop” understanding of the help with interpretation <a href="http://exbert.net/">exBERT</a> is an interactive software tool that provides insights into the meaning of the contextual representations by matching a human-specified input to similar contexts in a large annotated dataset. By aggregating the annotations of the matching similar contexts, exBERT helps intuitively explain what each attention-head has learned [<a href="https://arxiv.org/pdf/1910.05276.pdf">Paper</a>]. Although this was created for BERT, this type of tool could also be adapted to ClinicalBERT as well!</p><blockquote><em>As an aside, if you’re interested in learning more about the heads, and self-attention weights as it pertains to several BERT NLP tasks, I highly, highly, recommend this academic paper, </em><a href="https://arxiv.org/pdf/1908.08593.pdf"><em>Revealing the Dark Secrets of BERT</em></a><em> — it does a great job at dissecting and investigating the self-attention mechanism behind BERT-based architectures.</em></blockquote><h3>References</h3><pre>@article{clinicalbert,<br>author = {Kexin Huang and Jaan Altosaar and Rajesh Ranganath},<br>title = {ClinicalBERT: Modeling Clinical Notes and Predicting Hospital Readmission},<br>year = {2019},<br>journal = {arXiv:1904.05342},<br>}</pre><p>MIMIC-III, a freely accessible critical care database. Johnson AEW, Pollard TJ, Shen L, Lehman L, Feng M, Ghassemi M, Moody B, Szolovits P, Celi LA, and Mark RG. Scientific Data (2016). DOI: 10.1038/sdata.2016.35. Available at: <a href="http://www.nature.com/articles/sdata201635">http://www.nature.com/articles/sdata201635</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c82ff0e4bb03" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nwamaka-imasogie/clinicalbert-using-deep-learning-transformer-model-to-predict-hospital-readmission-c82ff0e4bb03">ClinicalBERT: Using Deep Learning Transformer Model to Predict Hospital Readmission</a> was originally published in <a href="https://medium.com/nwamaka-imasogie">Nwamaka Imasogie’s Machine Learning and Artificial Intelligence Projects</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Sequence Modeling]]></title>
            <link>https://medium.com/nwamaka-imasogie/deep-sequence-modeling-bdd9d26a5d6e?source=rss----c1856a20555a---4</link>
            <guid isPermaLink="false">https://medium.com/p/bdd9d26a5d6e</guid>
            <category><![CDATA[recurrent-neural-network]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[sequence-model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Nwamaka Imasogie]]></dc:creator>
            <pubDate>Thu, 17 Oct 2019 20:00:49 GMT</pubDate>
            <atom:updated>2019-10-24T17:56:05.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*eNizA1E8EFCxtPsS0CE0yA.png" /></figure><p>Whether it’s an audio waveform of your voice or a sentence we can think of this type of data as sequential because it consists of related data points that occur sequentially; like words or waves. When we feed a sequence into a model and output a new sequence (e.g. input words and output a new sentence of words) we consider that sequence to sequence modeling.</p><p>Machine translation, summarization, question answering are all sequence to sequence. And the <strong>Encoder-Decoder</strong> model has been the go-to model for sequence to sequence models.</p><p>I follow this <a href="https://www.coursera.org/learn/nlp-sequence-models/home/welcome">Sequence Models Coursera course</a> taught by Andrew Ng on Sequence models. In this course I learned about different types of RNNs, language model and sequence generation, Gated Recurrent Units, LSTMs, Bidirectional RNNs, Deep RNNs, Word Embeddings, Beam Search, Attention Models and Speech recognition.</p><h3>Why Sequence Models?</h3><ul><li>Speech recognition — Input audio clip, output text transcript.</li><li>Music Generation — Input nothing (or genre), output a sequence of notes.</li><li>Sentiment classification — Input phrase, output number of stars this review could be.</li><li>DNA sequence analysis — Input your DNA sequence, output which part of sequence belongs to a protein.</li><li>Machine translation — Input French, output English.</li><li>Named Entity Recognition — Input a sentence, output who the people in the sentence are.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IxFm_18Nj-JinFtouoqGMg.png" /><figcaption>Examples of sequence data: <a href="https://www.coursera.org/learn/nlp-sequence-models/lecture/0h7gT/why-sequence-models">https://www.coursera.org/learn/nlp-sequence-models/lecture/0h7gT/why-sequence-models</a></figcaption></figure><h3>Coursera Week 1</h3><h3>Recurrent Neural Networks</h3><p>Why not use a standard neural network?</p><ol><li>Inputs and outputs can be different lengths in different examples.</li><li>Doesn’t share features learned across different positions of text.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VJfOfWQjuaA_82C0NjUrGA.png" /><figcaption>Forward Propagation of a RNN</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4FDaCE4RoSjYx7bdGpAlwA.png" /><figcaption>RNN Forward Propagation Equations</figcaption></figure><p>In the notation, W<strong>ax</strong>, the subscript <strong>x</strong> in the second index means W<strong>ax</strong> will be multiplied by an <strong>x</strong> like quantity. And the subscript <strong>a</strong> means it will be used to compute an <strong>a</strong> like quantity.</p><p>However we can compress the two weight matrices down to just one matrix, W<strong>a</strong>. The advantage is that we don’t have to carry around two separate parameter matrices W<strong>aa</strong> and W<strong>ax</strong>, we can compress them into just one parameter matrix W<strong>a</strong>. Here’s the new notation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*lGhcr2JDof50qEB6PJSb8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*_yzFj4AIbYDSCCkPWa8zhA.png" /></figure><ul><li>One downfall in RNN is that they only take into consideration information that happened earlier in the sequence, but not later. So if for example you’re trying to determine whether Teddy is a name in the sentence He said, “Teddy Roosevelt was a great president.” Knowing only the first 3 words He said “Teddy” isn’t helpful. However, <strong>Bidirectional Recurrent Neural Networks</strong> address this problem.</li><li><strong>Tanh</strong> is the most common activation function used in RNN, sometimes <strong>ReLU</strong> is also used.</li><li>The choice of activation function for your output y will depend on your classification problem: binary classification(<strong>sigmoid</strong> function) , k-way classification (<strong>softmax</strong> function).</li></ul><p>Suppose that y&lt;t&gt; is a person’s name. And y hat is what your neural net output as the probability of a word being the person’s name. In order to compute backpropagation you need a loss function. Here’s the standard element-wise Cross-entropy loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*87dODlXfb4t6hXQjQOxYgg.png" /><figcaption>Element-wise Cross-entropy loss at a single time step, t, for a single word</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*KHC6pltQPMmrsPO7FEpyFA.png" /><figcaption>Loss for the entire sequence. Notice the L has no time stamp, t.</figcaption></figure><h3>Examples of RNN Architecture</h3><ol><li>Many-to-many — Used in Machine Translation (Encoder-Decoder).</li><li>Many-to-one — Text reviews to star ratings</li><li>One-to-many — Used in music generation</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jb-ziqz6nzywo1-2XTK3-w.png" /><figcaption>The first many-to-many can be used for Named Entity Recognition. The second Many-to-many can be used for Machine Translation Encoder-Decoder (Tx and Ty are not the same).</figcaption></figure><h3>Language Modeling &amp; Sequence Generation with RNN</h3><p>A Speech recognition system would choose “The apple and pear salad” instead of “The apple and pair salad”. So the language model will estimate the probability of a sequence of words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FYH1kmMvKpY-q4BZu0tAZA.png" /></figure><p>Below is an RNN language model for predicting the next upcoming word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zNw8tUgTQCSBk3oC_SUXNg.png" /></figure><p>a<strong>&lt;1&gt;</strong> is a softmax activation function that outputs the probability of what the first word is. For step 2 we will tell is that the correct word was “cat” and will pass that to the input of the next neural layer. We will continue passing the previous (correct) words forward as inputs into the next steps. Essentially, this RNN learns one word at a time going from left to right.</p><h3>Vanishing Gradients with RNNs</h3><h4><strong>Disadvantage</strong>:</h4><p>The sentence The cat, which already ate.......was full has a term that was that is dependent on cat but it’s located far away from cat. Was should be singular because cat is singular; rather than the plural cats and were. Basic RNNs above are not very good at capturing long term dependencies. This is due to the problem of vanishing gradients in very deep neural networks (because the gradients have a hard time propagating from the outputs of the errors from the later time steps to affect the computations of the earlier time steps).</p><h4>Gated Recurrent Unit (GRU)</h4><p>GRUs solve the vanishing gradient problem. GRUs provide a memory cell c.</p><p>At every time step we are going to consider overwriting the memory cell with a value č, the <strong>candidate</strong> new value.</p><p>Gamma with subscript u, Γ<strong>u</strong> , is an <strong>update</strong> <strong>gate</strong> value that’s always either 0 or 1. And <strong>u</strong> stands for update. It decides whether we will update the memory cell c with č.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*E8U0-m2uKoqpIbeHw_EFHw.png" /><figcaption>Simplified GRU <a href="https://www.coursera.org/learn/nlp-sequence-models/lecture/agZiL/gated-recurrent-unit-gru">https://www.coursera.org/learn/nlp-sequence-models/lecture/agZiL/gated-recurrent-unit-gru</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*7heFd3dSDxFwybkvnFgxgg.png" /><figcaption>Full GRU with relevance gamma, Γr.</figcaption></figure><p>For full GRU. Gamma with subscript u, Γ<strong>r</strong> , is a <strong>relevance gate</strong> value that’s always either 0 or 1. And <strong>r</strong> stands for relevance.</p><p>LSTM is also another common version. But there isn’t a consensus on when to use LSTM vs GRU. GRU is simpler and computationally faster. LSTM is more powerful and flexible since it has more gates.</p><h3>LSTM Unit — Long Short Term Memory</h3><p>Even more powerful than the GRU. It has 3 gates total.</p><p>Γ<strong>u</strong> is the update gate.</p><p>Γ<strong>f</strong> is the forget gate.</p><p>Γ<strong>o</strong> is the output gate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*kaU1WE5gxBR-IKlmDaFcbg.png" /></figure><h3>Bidirectional RNN</h3><p>BRNN allow you to take information from both earlier and later in the sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLaLQDwBzLLGV-ovZhAUIg.png" /><figcaption>The green blocks with backward arrows represent the Backward Recurrent layer. These backwards blocks will be connected to each other. First the forward sequence will compute all the way to the end. Then the (green) backward network activations will compute backwards all the way to the beginning. Then you can make your predictions.</figcaption></figure><p>For example, to make a prediction for y_hat at time step 3, information from x<strong>&lt;1&gt;</strong> flows through forward a<strong>&lt;1&gt;</strong> to forward a<strong>&lt;2&gt;</strong> to forward a<strong>&lt;3&gt;</strong> to y_hat<strong>&lt;3&gt;</strong> therefore information from x<strong>&lt;1&gt;</strong>, x<strong>&lt;2&gt;</strong> and x<strong>&lt; 3&gt;</strong> are all taken into account. And information from x4 flows in through a backward a<strong>&lt;4&gt;</strong> to a backward a<strong>&lt;3&gt;</strong> to y_hat<strong>&lt;3&gt;</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*np_L2UFpIHfbtxyAb2Suqw.png" /><figcaption>Follow the yellow lines to see how the data flows from the example we described above when trying to predict y_hat<strong>&lt;3&gt;</strong>.</figcaption></figure><p>NOTE: These blocks don’t have to be just RNN blocks, they can also be LSTM or GRU blocks as well!</p><p>A BRNN with an LSTM, seems to be used a lot in NLP. If you have an NLP problem where you have a complete sentence and want to label things in the sentence a <strong>Bidirectional Recurrent Neural Network with an LSTM</strong> blocks would be a reasonable first thing to try.</p><h4>Disadvantage</h4><p>The disadvantage to BRNN is that you need the entire sequence of data before you can make predictions anywhere. So in speech recognition you’d need to wait for a person to stop talking before processing it.</p><h3><a href="https://www.coursera.org/learn/nlp-sequence-models/lecture/v2pRn/picking-the-most-likely-sentence">Coursera Week 3</a></h3><h3>Machine Translation</h3><p>The motivating example here is translating a French sentence (x) to an English sentence (y_hat). Let’s assume we have an English dictionary/vocabulary of 10,000 different words.</p><blockquote>Jane visite l’Afrique en Septembre.</blockquote><p>should translate to</p><blockquote>Jane is visiting Africa in September.</blockquote><p>Machine Translation (MT) can be posed as a “conditional language modeling problem” where the encoder’s output is fed as the input into a language model, instead of the usual zero vector initialization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XERfaNtoN7lyPK9VAekSIg.png" /><figcaption>Notice how the Decoder portion looks just like the Language model above it.</figcaption></figure><p>But the major difference between MT and the earlier language model is rather than wanting to generate a sentence at random, we want to, instead, find the best or <strong>most likely</strong> English translation.</p><p>And because the set of all set of English sentences are too large to enumerate one-by-one, we’ll look into the <strong>Beam Search</strong> algorithm next.</p><h4>Beam Search</h4><p>Given an input French sentence, we don’t want to output a random English translation, we want to output the best/most likely translation. Beam Search is the most widely used algorithm to do this.</p><p><strong>Step 1</strong></p><p>The first thing Beam Search does is it tries to pick the first word of the English translation that it’s going to output, P(y_hat<strong>&lt;1&gt;</strong>|x).</p><p>It can consider multiple alternatives. There’s a parameter, <strong>B</strong> the <strong>beam width</strong>, that determines how many different choices it will consider. Let’s set <strong>B</strong>=3, so it will pick 3 top words and keep them in memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pHSDOLGsQOgxWsHa1Rzzgg.png" /><figcaption>Let’s say in step 1 of the Beam Search algorithm the beam width B=3. Run the input sentence into the Encoder network (green). The first step of the Decoder network (purple) has a Softmax output over all 10,000 Englishvocab words, it would keep the top 3 of the 10,000 outputs in memory.</figcaption></figure><p>Let’s assume that it picked “in”, “jane” and “september” as the top 3 most likely words.</p><p><strong>Step 2</strong></p><p>It will iterate over each of the 3 words “in”, “jane” and “september”. First it will look at “in”. It will try to pick the best second word, from the English disctionary, that should come after “in”.</p><p>It will assess all 10,000 vocabulary words again, however, this time it is trying to maximize the likelihood of y<strong>&lt;1&gt;</strong> and y<strong>&lt;2&gt;</strong> given y<strong>&lt;1&gt;</strong>. It will assess probabilities of pairs starting with (“in”, “a”), then (“in”, “aaron”), etc until the end of the vocabulary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1rbHZdUkvrlNFbuCvgkzA.png" /><figcaption>Notice that y_hat<strong>&lt;1&gt;</strong> is hardset to “in” and fed into the next block which will try to pick the most likely y_hat<strong>&lt;2&gt;</strong> which is P(y<strong>&lt;2&gt; </strong>| x, “in”). <a href="https://www.coursera.org/learn/nlp-sequence-models/lecture/4EtHZ/beam-search">Source</a>.</figcaption></figure><p>We ultimately care about finding the <strong>pair</strong> of the first and second word that are most likely (<strong>not just the first word alone</strong>). Remember from the rules of conditional probability, we can express this as the probability of the first word multiplied by the probability of the second word, ∴P(y<strong>&lt;1&gt;</strong>, y<strong>&lt;2&gt;</strong>|x) = P(y<strong>&lt;1&gt;</strong>|x)·P(y<strong>&lt;2&gt;</strong>|x, y<strong>&lt;1&gt;</strong>).</p><p>It will repeat these exact steps for “jane” and then “september”.</p><p>This will consider 30,000 possibilities because (beam width )(vocabulary) = (3)(10,000) = 30,000.</p><p>You only need to instantiate 3 copies of the network to efficiently compare “in”, “jane” and “september”. No need to instantiate 30,000 copies of the network.</p><p><strong>Step 3</strong></p><p>It selected the top 3 most probable pairs and stored the probabilities in memory:</p><ul><li>in september</li><li>jane is</li><li>jane visits</li></ul><p>In step 3 it will keep going to try to pick the 3rd most likely word combinations. See the image below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QeM4LOAJs_hyMpGgEECDSA.png" /></figure><p><strong>NOTE </strong>that if you set the <strong>beam width = 1</strong> this will just be the <strong>Greedy</strong> algo which does not work as demonstrated in this <a href="https://www.coursera.org/learn/nlp-sequence-models/lecture/v2pRn/picking-the-most-likely-sentence">previous</a> video.</p><p>Watch <a href="https://www.coursera.org/learn/nlp-sequence-models/lecture/AkjG2/refinements-to-beam-search">here</a>, at 7:20, for tips on how to choose <strong>B</strong>.</p><p>Length normalization is a refinement you can apply to improve Beam search which involved using log probabilities and normalizing with alpha=0.7 [source: <a href="https://www.coursera.org/learn/nlp-sequence-models/lecture/AkjG2/refinements-to-beam-search">video</a>].</p><p><strong>NOTE</strong> that Beam Search it is an approximate (heuristic) search algorithm. So it doesn’t always output the most likely. It can make a mistake.</p><h4>Error Analysis in Beam Search</h4><p>Let’s look at error analysis that help us determine if beam search made a mistake or is it just our RNN that is to blame.</p><p>The short version explanation is:</p><ul><li>Have a human translate the sentence, y*.</li><li>Case 1: If P(y*|x) &gt; P(y_hat|x) then beam search is at fault.</li><li>Case 2: If P(y*|x) ≤ P(y_hat|x) then the RNN model is at fault.</li></ul><p>For more detailed explanation watch this <a href="https://www.coursera.org/learn/nlp-sequence-models/lecture/UfvRl/error-analysis-in-beam-search">video</a>.</p><h3>Bleu Score — Bilingual Evaluation Understudy</h3><p>One of the challenges of machine translation is that, given a French sentence, there could be multiple English translations that are equally good translations of that French sentence. So how do you evaluate a machine translation system if there are multiple equally good answers?</p><p>If there are multiple great answers, how do you measure accuracy?</p><p>The way this is done conventionally is through something called the BLEU score.</p><p>The <strong>BLEU score</strong> is a popular automatic evaluation technique.</p><p>First you count the n-gram scores (ratio of n-grams that occur over the number of n-grams).</p><p>Then calculate the <strong>Brevity score </strong>(or brevity penalty)<strong> </strong>by dividing the length of the output by the length of the reference. Then take the min(1, brevity).</p><p>Finally, calculate the BLEU score by multiplying the n-gram scores and taking the 4th root, then multiplying by the brevity.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jd1SWagbFUiyuxKun8T8GA.png" /><figcaption>Calculating the BLEU score. [<a href="https://www.coursera.org/learn/language-processing/lecture/nv7Cr/introduction-to-machine-translation">Source</a>]</figcaption></figure><h3>Attention Model</h3><p>It is very difficult for a MT system to memorize a very long sentence. The BLEU score drops significantly. So the Attention model looks at part of a sentence at a time which helps stabilize the BLEU score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESG9lm5IpzAWWOPRJmkNzA.png" /><figcaption>The green line is what the Attention model achieves.</figcaption></figure><p>The question we’re trying to answer is, when you’re trying to generate an (output) English translation, how much <strong>context</strong> should <strong>each</strong> word of the sentence pay attention to in respect to the input? It uses <a href="https://www.coursera.org/learn/nlp-sequence-models/lecture/lSwVa/attention-model">attention weights</a> (<strong>α</strong>)to achieve this.</p><h3>Speech Recognition — Audio Data</h3><p>One of the most exciting developments with sequence to sequence models has been the rise of very accurate speech recognition.</p><p>A common pre-processing step for audio data is to run your raw audio clip and generate a spectrogram (plot audio intensity frequencies over time). Which is pretty similar to what the human ear does.</p><p>In this example we want to transform audio data to a text transcript. We have an audio clip where someone is saying: “the quick brown fox”. The number of inputs being fed into the model is usually very large with audio data, especially compared to the much smaller output of words.</p><p>Let’s image that this is a 10 second audio clip at a frequency of 100Hz, that would be <strong>1000</strong> inputs being fed into the model (BRNN, either LSTM or GRU).</p><h4>Connectionist temporal classification (<a href="https://www.coursera.org/learn/nlp-sequence-models/lecture/sjiUm/speech-recognition">CTC</a>)</h4><p>The CTC cost function’s basic rule is to collapse repeated characters that are not separated by a “blank” which I’ll denote as an underscore _. So the CTC cost function allows the RNN to generate an output like:</p><pre>t t t _ h _ e e e _ _ _ q q q_ _ …</pre><p>Which will ultimately end up as “the quick brown fox” which is only 19 characters long (including spaces). So the neural network was able to force upwards of 1000 characters by allowing the network to insert blanks and repeated characters to represent a 19 character output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lYZ3jAa5mIczGmb8qCcQIw.png" /><figcaption><a href="https://www.coursera.org/learn/nlp-sequence-models/lecture/sjiUm/speech-recognition">https://www.coursera.org/learn/nlp-sequence-models/lecture/sjiUm/speech-recognition</a></figcaption></figure><h3>Google Neural Machine Translation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*6OssCqpmuYcpDcwXnoq7Mg.png" /><figcaption><a href="https://www.inf.ed.ac.uk/teaching/courses/anlp/lectures/30/">https://www.inf.ed.ac.uk/teaching/courses/anlp/lectures/30/</a></figcaption></figure><p>Google Neural Machine Translation is an example of <strong>Interlingual</strong> translation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*x-_zOdeTMBWV2cjAvQO9Gg.png" /><figcaption><a href="https://research.googleblog.com/2016/11/zero-shot-translation-with-googles.html">https://research.googleblog.com/2016/11/zero-shot-translation-with-googles.html</a></figcaption></figure><p>Here’s how it works:</p><p>Train a system on a few pairs of languages like English, Japanese and Korean on the encoder, decoder architecture.</p><p>The encoder encodes your sentence to some hidden representation. And the decoder takes that hidden representation and decides it to the target sentence.</p><p>The amazing thing is if, for example, you just take your encoder for Japanese, and your decoder for Korean, it somehow works! Even though the system has never seen Japanese to Korean translations. This is a <strong>zero-shot translation</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdd9d26a5d6e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nwamaka-imasogie/deep-sequence-modeling-bdd9d26a5d6e">Deep Sequence Modeling</a> was originally published in <a href="https://medium.com/nwamaka-imasogie">Nwamaka Imasogie’s Machine Learning and Artificial Intelligence Projects</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Networks & Word Embeddings]]></title>
            <link>https://medium.com/nwamaka-imasogie/neural-networks-word-embeddings-8ec8b3845b2e?source=rss----c1856a20555a---4</link>
            <guid isPermaLink="false">https://medium.com/p/8ec8b3845b2e</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[stanford]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Nwamaka Imasogie]]></dc:creator>
            <pubDate>Fri, 11 Oct 2019 17:26:54 GMT</pubDate>
            <atom:updated>2019-10-15T18:35:26.731Z</atom:updated>
            <content:encoded><![CDATA[<p>All modern NLP techniques use neural networks as a statistical architecture. Word embeddings are mathematical representations of words, sentences and (sometimes) whole documents. Embeddings allow us to compare text, visualize it, and improve the accuracy of newer models. Stanford’s <a href="http://web.stanford.edu/class/cs224n/index.html#schedule"><strong>Natural Language Processing with Deep Learning Course</strong></a> is a great course that I’ll follow to get started [video’s 1–5 and the associated readings]. For assignment 2, I’ll complete the coding and written parts Implementing Word2vec in PyTorch.</p><h3>Representing words by their context</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8rXD5-xhemo%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8rXD5-xhemo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8rXD5-xhemo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/be8b70bb8c5a9a1734c80bd84c79783b/href">https://medium.com/media/be8b70bb8c5a9a1734c80bd84c79783b/href</a></iframe><h3>Distributional semantics</h3><p>Distributional semantics: A word’s meaning is given by the words that frequently appear close-by. In other words “<em>You shall know a word by the company it keeps</em>”.</p><h3>Word Embeddings (a.k.a. Word vectors)</h3><p>We will build a dense vector for each word, chosen so that it is similar to vectors of words that appear in similar contexts [<a href="https://www.youtube.com/watch?v=8rXD5-xhemo&amp;feature=youtu.be&amp;t=2091">here’s a visual video snippet</a>]. They are a <strong>distributed</strong> representation. In practice the minimum dimensionality is 50, 300 (on laptop), 1000, 2000, or 4000 are common vector sizes used.</p><h3>Word2vec</h3><p>Word2vec is a framework for learning word vectors. It’s a very simple and scalable way of learning vector representations of words. Ultimately, <strong>we want a model that gives a reasonably high probability estimate to all words that occur in the context (fairly often)</strong>.</p><h4>Main Idea/Summary:</h4><ol><li>Iterate through each word of the whole corpus</li><li>Predict surrounding words using word vectors</li><li>Update vectors so you can predict well</li></ol><h4>More Detailed Steps:</h4><ul><li>Start with a large corpus of text (with actual sentences).</li><li>Every word in a fixed vocabulary is represented by a <strong>vector</strong>. Start with a <strong>random</strong> vector for each word.</li><li>Go through each position t in the text, which has a center word c and outside context words o.</li><li>Use the <strong>similarity of the word vectors</strong> for c and o to calculate the probability of o given <em>c</em> (or vice versa).</li><li><strong>Keep adjusting the word vectors</strong> to maximize this probability.</li></ul><p>The question now is how do we calculate the probability of the center word and the context given the center word? [<a href="https://youtu.be/8rXD5-xhemo?t=2844">Video Snippet</a>]</p><p>We will use two vector representations per word, w. So we will use one vector for a word when it’s the center word and we are predicting other words (v). Then we have a second vector for the word when it’s a context word (u).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*LaqwlqOfZ096LrKPM7CwIA.png" /><figcaption><a href="https://youtu.be/8rXD5-xhemo?t=2871">https://youtu.be/8rXD5-xhemo?t=2871</a></figcaption></figure><p><strong>NOTE</strong>: Generally we may be using Word2vec to get the context of, let’s say, 10 words or so. So it will be a “loose” model where we might get a 5% chance to one of those 10 words being guessed correctly. So while we should not expect to get 97%, the goal is, for example, we hope to capture that the word “withdrawal” is likely to occur with “bank” instead of “football” a non-related word.</p><h3>Word2vec the Skip-Gram Model</h3><blockquote>Here’s <a href="http://mccormickml.com/2016/04/19/word2vec-tutorial-the-skip-gram-model/">an excellent article</a> that covers the skip gram neural network architecture for Word2Vec.</blockquote><p>The skip-gram model proposes a simple <strong>single-layer</strong> architecture based on the inner product between two word vectors. The objective is to predict a word’s context given the word itself.</p><p>The intuition of skip-gram is:</p><ol><li>Treat the target word and a neighboring context word as positive examples.</li><li>Randomly sample other words in the lexicon to get negative samples.</li><li>Use logistic regression to train a classifier to distinguish those two cases.</li><li>Use the regression weights as the embeddings.</li></ol><p>[Source: <a href="https://web.stanford.edu/~jurafsky/slp3/6.pdf#page=17">Jurafsky, SLP, Ch 6.8</a>]</p><p>Imagine a sentence like the following, with a target word apricot, and assume we’re using a window of ±2 context words:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CX8og2npUwrVVCwub42jRg.png" /></figure><p>Our goal is to train a classifier such that, given a tuple (t, c) of a target word t paired with a candidate context word c (for example (apricot, jam), or perhaps (apricot, aardvark)) it will return the probability that c is a real context word (true for jam, false for aardvark):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*RFHrtF2U068UUNKeIEHHqg.png" /><figcaption>The probability that c is a real context word.</figcaption></figure><p>How does the classifier compute the probability P? The intuition of the skip-gram model is to base this probability on similarity: a word is likely to occur near the target if its embedding is similar to the target embedding. How can we compute similarity between embeddings? Recall that two vectors are similar if they have a high dot product (cosine, the most popular similarity metric, is just a normalized dot product).</p><p>Of course, the dot product t·c is not a probability. Cosine isn’t a probability either.</p><p>To turn the dot product into a probability, we’ll use the logistic or sigmoid function σ(x), the fundamental core of logistic regression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TsX7tCa0zQ_L63VrdaEhow.png" /></figure><p>The probability that word c is a real context word for target word t is thus computed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kuEjYoT8HFWR7mpF7R9DwQ.png" /></figure><p>The sigmoid function just returns a number between 0 and 1, so to make it a probability we’ll need to make sure that the total probability of the two possible events (c being a context word, and c not being a context word) sums to 1.</p><p>The probability that word c is not a real context word for t is thus:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hZzXeZtU9Os-R882tUD_1g.png" /></figure><p>The equation above gives us the probability for one word, but we need to take account of the multiple context words in the window. Skip-gram makes the strong but very useful simplifying assumption that all context words are independent, allowing us to just multiply their probabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMbHfP5Us_VIGTf3zmYalA.png" /></figure><p><strong>In summary, skip-gram trains a probabilistic classifier that, given a test target word t and its context window of k words c1:k , assigns a probability based on how similar this context window is to the target word.</strong> The probability is based on applying the logistic (sigmoid) function to the dot product of the embeddings of the target word with each context word. We could thus compute this probability if only we had embeddings for each target word and context word in the vocabulary. Let’s now turn to learning these embeddings (which is the real goal of training this classifier in the first place).</p><h4>Learning skip-gram embeddings</h4><p>Read <a href="https://web.stanford.edu/~jurafsky/slp3/6.pdf#page=20">chapter 6.8, page 20</a> of Jurafsky’s Vector Semantics and Embeddings book for a great explanation of how Word2vec learns embeddings.</p><h3>Efficient Estimation of Word Representation in Vector Space [Paper]</h3><p>In this Google paper, <a href="https://arxiv.org/pdf/1301.3781.pdf">Efficient Estimation of Word Representation in Vector Space</a>, it was observed that it is possible to train high quality word vectors using very simple model architectures, compared to the popular neural network models (both feedforward and recurrent). Because of the much lower computational complexity, it is possible to compute very accurate high dimensional word vectors from a much larger data set. Using the <a href="http://papers.nips.cc/paper/4687-large-scale-distributed-deep-networks"><strong>DistBelief</strong></a> distributed framework, it should be possible to train the CBOW (Continuous Bag-of-Words) and Skip-gram models even on corpora with one trillion words, for basically unlimited size of the vocabulary.</p><h3>Distributed Representations of Words and Phrases and their Compositionality [Paper]</h3><p><a href="http://papers.nips.cc/paper/5021-distributed-representations-of-words-and-phrases-and-their-compositionality.pdf">http://papers.nips.cc/paper/5021-distributed-representations-of-words-and-phrases-and-their-compositionality.pdf</a></p><p>In this Google paper they found that by subsampling of the frequent words we obtain significant speedup and also learn more regular word representations. We also describe a simple alternative to the hierarchical softmax called negative sampling. Also because the meanings of “Canada” and “Air” cannot be easily combined to obtain “Air Canada” they present a simple method for finding phrases in text. Top highlights from the paper are:</p><ul><li>The training objective of the Skip-gram model is to find word representations that are useful for predicting the surrounding words in a sentence or a document.</li><li>While NCE can be shown to approximately maximize the log probability of the softmax, the Skipgram model is only concerned with learning high-quality vector representations, so we are free to simplify NCE as long as the vector representations retain their quality.</li><li>The results show that <strong>Negative Sampling</strong> outperforms the Hierarchical Softmax on the analogical reasoning task, and has even slightly better performance than the Noise Contrastive Estimation</li><li>10⁻⁵ subsampling can result in faster training and can also improve accuracy, at least in some cases</li><li>The <strong>Negative sampling</strong> algorithm, which is an extremely simple training method that learns accurate representations especially for frequent words.</li></ul><h3><strong>Assignment 1 —Explore Word2Vec [</strong><a href="https://github.com/nwams/Explore-Word2Vec/blob/master/Exploring%20Word%20Vectors.ipynb"><strong>GitHub</strong></a><strong>][</strong><a href="https://nbviewer.jupyter.org/github/nwams/Explore-Word2Vec/blob/master/Exploring%20Word%20Vectors.ipynb"><strong>Code</strong></a><strong>]</strong></h3><p>I completed <a href="http://web.stanford.edu/class/cs224n/assignments/a1_preview/exploring_word_vectors.html">Assignment 1</a>that was issued from Stanford CS224N course.<br>In this assignment I explore two types of word vectors: those derived from <strong>co-occurrence matrices</strong>, and those derived via <strong>word2vec</strong>.</p><p>Below is my Jupyter Notebook:</p><p><a href="https://nbviewer.jupyter.org/github/nwams/Word2Vec-Visualize-Implement/blob/master/Exploring%20Word%20Vectors.ipynb">Notebook on nbviewer</a></p><h4>Word Vectors</h4><p>Word Vectors are often used as a fundamental component for downstream NLP tasks, e.g. question answering, text generation, translation, etc., so it is important to build some intuitions as to their strengths and weaknesses. Here, you will explore two types of word vectors: those derived from co-occurrence matrices, and those derived via word2vec.</p><p><strong>Note on Terminology</strong>: The terms “word vectors” and “word embeddings” are often used interchangeably. The term “embedding” refers to the fact that we are encoding aspects of a word’s meaning in a lower dimensional space.</p><h4><strong>Part 1: Count-Based Word vectors</strong></h4><p>Many word vector implementations are driven by the idea that similar words, i.e., (near) synonyms, will be used in similar contexts. As a result, similar words will often be spoken or written along with a shared subset of words, i.e., contexts. By examining these contexts, we can try to develop embeddings for our words.</p><ul><li><strong>Create a Co-occurrence Matrix</strong>: I create a co-occurrence matrix. A co-occurrence matrix counts how often things co-occur in some environment.</li><li><strong>Dimensionality Reduction</strong>: Use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.TruncatedSVD.html">sklearn.decomposition.TruncatedSVD</a> and construct a method that performs dimensionality reduction on the matrix to produce k-dimensional embeddings. Use SVD to take the top _k_ components and produce a new matrix of k-dimensional embeddings.</li></ul><h4>Part 2: Prediction-Based Word Vectors</h4><p>Here I explore the embeddings produced by word2vec.</p><ul><li><strong>Dimensionality Reduction</strong>: Reduce dimensionality of Word2Vec Word Embeddings using truncated SVD.</li><li><strong>Synonyms &amp; Antonyms</strong>: Demonstrate counter-intuitive examples and explore why they happen.</li><li><strong>Solving Analogies with Word Vectors:</strong> I use gensim to solve analogies. For example, for the analogy “man:king :: woman:x”, what is x?</li><li><strong>Finding Analogies</strong>: Use <a href="https://radimrehurek.com/gensim/models/keyedvectors.html#gensim.models.keyedvectors.FastTextKeyedVectors.most_similar">GenSim’s</a> most_similar function to find analogies, e.g. Austin is the capital of Texas, and Atlanta is the capital of Georgia.</li><li><strong>Explore Incorrect Analogies</strong>: Gensim doesn’t always produce correct results. Here I explore that.</li><li><strong>Analyze Bias in Word Vectors</strong>: Use the most_similar function to find another case where some bias is exhibited by the vectors. E.g. I discovered that there’s a bias which results in the correlation of mothers and doctors to nurse. While father and doctors is correlated to physician.</li></ul><blockquote>NOTE: In machine learning, the ideal algorithm has <strong>low bias</strong> and can accurately model the true relationship. And it has <strong>low variability</strong>, by producing consistent predictions across different datasets. [<a href="https://www.youtube.com/watch?v=EuBBz3bI-aA">This video explains it clearly</a>].</blockquote><h3>Word Vectors “2&quot; and Word Senses</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FkEMJRjEdNzM%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DkEMJRjEdNzM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkEMJRjEdNzM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/82bb8a86a3b2fe6a393bf4add969a1db/href">https://medium.com/media/82bb8a86a3b2fe6a393bf4add969a1db/href</a></iframe><ul><li>Don’t over trust PCA 2-dimensional displays. We took 100D to 2D projections. It captures some of the major geometry of the space but it loses a huge amount of information. So if it looks close together in the 2D space, it might have been close in the original space, or they might have been that some words were lost in the 2D projection because there were other patterns that were dominant and chosen as the first 2 principal components.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B6s1DhrWjN1iqBvFSS-WyQ.png" /><figcaption>We have 2 matrices. For the center words, we have a matrix, V, where for each word in our vocabulary we have a vector (represented as rows). So the V matrix has 6 words. For the outside matrix, U, we have a 2nd vector for each word. So if the center word is word 4, we take are taking a dot product of v4 and each row of U. Which gives us a vector of dot products between U and V4. After that we run softmax’s on each of those numbers (element-wise), which gives us a probability distribution over words in the context.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9NXeoJvw8VY3l0eia-8yPg.png" /><figcaption>CAUTION: These 2-dimensional pictures are exceedingly misleading. For example, “Nokia” is next to “Samsung” so let’s say you expect it to be far away from words in the bottom side. Or you might actually want the effect that Nokia is close to Finland, for some reason. But you cannot do that in 2D vector spaces. <strong>Most properties of high dimensional vector spaces are very unintuitive, because in a high-dimensional vector space a word can be close to lots of other words in different directions</strong>.</figcaption></figure><h3><strong>Skip-grams (SG) versus Continuous Bag of Words (CBOW)</strong></h3><p>In this lecture he presents the skip-grams model. However, there are two different Word2vec model variants:</p><ol><li><strong>Skip-grams</strong> — Predict the context (“outside”) words (position independent) given center word.</li><li><strong>Continuous Bag of Words (CBOW)</strong> — Predict the center word from the (bag of) context words.</li></ol><p><strong>Disadvantage</strong>: Both SG and CBOW do not operate directly on the co-occurrence statistics of the corpus. Instead, these models scan context windows across the entire corpus, which fails to take advantage of the vast amount of repetition in the data.</p><p>For additional efficiency in training use <strong>negative sampling</strong> because in practice naive sampling is way too slow.</p><h4>Negative Sampling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*u9_5d1gmI1m-v0kMqSHaFw.png" /><figcaption>Probability of a word in the context (o), given a center word ( c ).</figcaption></figure><p>The idea of negative sampling is that we are going to train binary logistic regressions. <strong>We want to give a high probability to the word that was actually observed (center word)</strong>. So we will do one binary logistic regression for the actual word observed (in the numerator). Then we will randomly sample a bunch of other words (the negative samples) and try to give them as low of a probability as possible because it wasn’t the words that were actually seen. So in other words:</p><blockquote>Main idea: train binary logistic regressions for a true paid (center word and word in its context window) versus several noise pairs (the center word paired with a random word).</blockquote><h3>GloVe — Global Vectors for Word Representations. Combining the best of both worlds.</h3><p>GloVe is a new global log-bilinear regression model that combines the advantages of the two major model families: global matrix factorization (like LSA) and local context window methods (like skip-gram). <strong>Why?</strong></p><blockquote>Currently, both families suffer significant drawbacks. While methods like LSA efficiently leverage statistical information, they do relatively poorly on the word analogy task, indicating a sub-optimal vector space structure. Methods like skip-gram may do better on the analogy task, but they poorly utilize the statistics of the corpus since they train on separate local context windows instead of on global co-occurrence counts. <em>[Source: </em><a href="https://nlp.stanford.edu/pubs/glove.pdf"><em>GloVe paper</em></a><em>]</em></blockquote><ul><li><strong>NOTE</strong>: The main problem with word-word co-occurrence matrices is that the number of times two words co-occur with “the” or “and”, for example, will have a large effect on their similarity despite conveying little about semantic relatedness!</li></ul><p>Crucial insight!: We can use ratios of co-occurrence probabilities can encode meaning components. The goal is: How can we keep the benefits of the neural net methods while trying to do things with a count matrix?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*La5Bp7DKr07dwEtR3hs5HQ.png" /><figcaption>Co-occurrence probabilities for target words <strong>ice</strong> and <strong>steam</strong> with selected context words from a 6 billion token corpus. Only in the ratio does noise from non-discriminative words like water and fashion cancel out, so that large values (much greater than 1) correlate well with properties specific to ice, and small values (much less than 1) correlate well with properties specific of steam.</figcaption></figure><p>If we have a word like “ice” how often are things going to co-occur with it? Solids should co-occur a lot and “gas” shouldn’t. “Water” should occur a lot while another random word won’t occur much. <strong>The interesting thing lies in the difference between the two co-occurrence probabilities P(x|ice) versus P(x|steam).</strong> The ratio is a “<em>dimension of meaning”</em>. Notice how in “water” and “fashion”, they cancel out to ~1. However, there is a “dimension of meaning” for “solid” and “gas”. The ratio is better able to distinguish relevant words (solid and gas) from irrelevant words (water and fashion) and it is also better able to discriminate between the two relevant words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2trRE1pQX0er4_L49z_UqA.png" /><figcaption><strong>Question</strong>: How can we capture rations of co-occurrence probabilities as linear meaning components in a word vector space? <strong>Answer</strong>: Make the dot products equal to the log of the co-occurrence probability. Which yields the fact that a vector difference leads to a log of the co-occurrence probabilities.</figcaption></figure><h4>The GloVe model:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*noSAG_dtxyhq_vVPWL4HMA.png" /><figcaption>GloVe model: <strong>J</strong> is the objective function with a squared loss. The dot product of <strong>wi</strong> and <strong>wj</strong> should be as similar as possible to the log of the co-occurrence probability so they will be “lost” to the extent that they are not the same! Then bias terms, <strong>bi</strong> and <strong>bj</strong>, are added because maybe the word is very common or very uncommon. The <strong>f-function</strong> in front caps the effect that very common word-pairs can have on the performance of the system.</figcaption></figure><h3><strong>GloVe: Global Vectors for Word Representation [Paper]</strong></h3><p><a href="http://nlp.stanford.edu/pubs/glove.pdf">GloVe: Global Vectors for Word Representation</a></p><h3>Improving Distributional Similarity with Lessons Learned from Word Embeddings [Paper]</h3><p><a href="https://www.aclweb.org/anthology/Q15-1016.pdf">https://www.aclweb.org/anthology/Q15-1016.pdf</a></p><p>In this paper they reveal that much of the <strong>performance gains of word embeddings are due to certain system design choices and hyperparameter optimizations</strong>, rather than the embedding algorithms themselves. Furthermore, they show that these modifications can be transferred to <strong>traditional distributional models</strong>, yielding similar gains. In contrast to prior reports, they observe mostly local or insignificant performance differences between the methods, with no global advantage to any single approach over the others.</p><p>They tuned the following hyperparameters:</p><pre>window size (win)</pre><pre>dynamic context window (dyn)</pre><pre>subsampling (sub)</pre><pre>deleting rare words (del)</pre><pre>shifted PMI (neg)</pre><pre>context distribution smoothing (cds)</pre><pre>adding context vectors (w+c)</pre><pre>eigen weighting (eig)</pre><pre>vector normalization (nrm)</pre><h3>Evaluation methods for unsupervised word embeddings [Paper]</h3><p><a href="https://www.aclweb.org/anthology/D15-1036.pdf">https://www.aclweb.org/anthology/D15-1036.pdf</a></p><p>We present a comprehensive study of evaluation methods for unsupervised embedding techniques that obtain meaningful representations of words from text. Different evaluations result in different orderings of embedding methods, calling into question the common assumption that there is one single optimal vector representation. We present new evaluation techniques that directly compare embeddings with respect to specific queries. These methods reduce bias, provide greater insight, and allow us to solicit data-driven relevance judgments rapidly and accurately through crowdsourcing.</p><h4>Intrinsic Evaluations</h4><p>Intrinsic evaluations directly test for syntactic or semantic relationships between words. There are 4 broad categories: Relatedness, analogy, categorization and selectional preference.</p><p>Intrinsic evaluations measure the quality of word vectors by directly measuring correlation between semantic relatedness and geometric relatedness</p><h4>Extrinsic Tasks</h4><p>Extrinsic evaluations measure the contribution of a word embedding model to a specific task.</p><ul><li>We find that extrinsic evaluations, although useful for highlighting specific aspects of embedding performance, should not be used as a proxy for generic quality.</li><li>Different tasks favor different embeddings.</li></ul><h3>Word Window Classification, Neural Networks, and Matrix Calculus</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8CWyBNX6eDo%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8CWyBNX6eDo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8CWyBNX6eDo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b2dc3aefbcdc45b7a142fe3796adfb6/href">https://medium.com/media/2b2dc3aefbcdc45b7a142fe3796adfb6/href</a></iframe><p>This lecture covers:</p><ul><li>Classification</li><li>Neural networks introduction</li><li>Named Entity Recognition</li><li>(Model) Binary true vs. corrupted word window classification model</li><li>Matrix calculus</li></ul><h4>Cross entropy loss</h4><ul><li>We are assuming there’s a true probability distribution <strong>p</strong>.</li><li>Let’s say we computed a distribution probability <strong>q</strong> from our softmax regression, for example.</li><li>And we’d like to have a measure of whether our estimate probability distribution is a good one.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_P3RzOZph6HgOnZ0dGJgA.png" /><figcaption>Cross entropy loss formula</figcaption></figure><ul><li>We go through the classes, and say what’s the probability of the class according to the true model. Using that weighting, we then work out the log of the probability according to our estimated model. We sum those up and negate it and that gives our cross entropy measure.</li><li>In general this gives us a measure of estimation between distributions.</li><li>But in our particular binary text classification case, in each example, we have a piece of labeled training data. So in our example, where p = [0,…,0,1,0,…,0] the correct answer is class 7. Therefore our true distribution is class 7 has probability of 1 and probability 0 over everything else.</li><li>In the cross entropy formula above, the summation of p(c) will then be 1 when c=7 and 0 everywhere else. Which will basically leave only the negative log of the true class q(7).</li><li><strong>Because of one-hot </strong><strong>p, the only term left is the negative log probability of the true class.</strong></li></ul><h3>Classification difference with word vectors</h3><p>Compared to conventional machine learning classification, classification with word vectors is a weird idea. Rather than saying we just have the parameters W we are also saying that all of the word representations, x, are also parameters of our model. So in NLP deep learning we are actually going to change the representations of words to allow our classifiers to do better! (In other words, we simultaneously change (learn) both the <strong>weights</strong> and <strong>word representations</strong>). The word vectors re-represent one-hot vectors — move them around in an intermediate layer vector space — for easy classification with a (linear) softmax classifier via later x = Le. L is a lexicon matrix comprised of different one-hot vectors for each word in your corpus. e is a one-hot vector which, when multiplied by L, the effect is to bring out one column of L.</p><p>Really you can think of word vector embedding as having a model with one more neural network layer. See below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BU97jKd77pGbKmnPo0Bpzg.png" /></figure><h4>Non-linear activation functions and why they’re needed</h4><p>Without non-linearities, deep neural networks can’t do anything more than a linear transform. With more layers, they can approximate more complex functions! For example, in the classification problem below, non-linearities allow for better decision boundaries in more complex scenarios resulting in the second graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4aNoXkmZ_yqriBNkuxM27A.png" /><figcaption><strong>Left</strong>: Linear decision boundaries. <strong>Right:</strong> Non-linear decision boundaries.</figcaption></figure><h4>Maximum margin objective function</h4><p>Like most machine learning models, neural networks also need an optimization objective, a measure of error or goodness which we want to minimize or maximize respectively.</p><p>The maximum margin objective is a popular error metric (commonly associated with SVMs).</p><p>Let’s look at this example where we want to perform Named Entity Recognition on this sentence:</p><blockquote>“Museums in Paris are amazing”</blockquote><p>The maximum margin formula is:</p><pre>minimize <strong>J = max(∆ + sc − s, 0)</strong></pre><ul><li>The intuition behind doing this is that we only care the the “true” data point have a higher score than the “false” data point and that the rest does not matter. Thus, we want our error to be (sc − s) if sc &gt; s else 0.</li><li>Each window with an NER location at its center should have a score +1 higher than any window without a location at its center</li><li>∆ is a safety margin. We would want the “true” labeled data point to score higher than the “false” labeled data point by some positive margin ∆.</li><li>s is the score computed for “true” labeled data points. <strong>s = score(museums in Paris are amazing)</strong></li><li>sc is the score of the “corrupt” window. s = score(museums in Paris are amazing). <strong>sc = score(Not all museums in Paris)</strong></li><li>[source: <a href="http://web.stanford.edu/class/cs224n/slides/cs224n-2019-lecture03-neuralnets.pdf">cs224class slides</a>]</li></ul><h3>Assignment 2: Implementing Word2Vec [<a href="https://nbviewer.jupyter.org/github/nwams/Implementing-word2vec/blob/master/Implementing%20word2vec.ipynb">Jupyter Notebook</a>][<a href="https://github.com/nwams/Implementing-word2vec">Github</a>]</h3><p>In the coding part I implement the word2vec model and train my own word vectors with stochastic gradient descent (SGD).</p><ul><li>(a) Implement the <strong>sigmoid</strong> function to apply the sigmoid function to an input vector. In the same file, fill in the implementation for the <strong>softmax</strong> and <strong>negative sampling loss</strong> and <strong>gradient</strong> functions: naiveSoftmaxLossAndGradient and getNegativeSamples. Then, fill in the implementation of the loss and gradient functions for the skip-gram model: negSamplingLossAndGradient and skipgram.</li><li>(b) Complete the implementation for your <strong>SGD</strong> optimizer: sgd.</li><li>(c) Show time! Now we are going to load some real data and train word vectors with everything you just implemented! We are going to use the <a href="https://nlp.stanford.edu/sentiment/treebank.html">Stanford Sentiment Treebank (SST)</a> dataset to train word vectors, and later apply them to a simple sentiment analysis task. The script will finish and a visualization for your word vectors will appear.</li></ul><p><strong>Written part of CS224n Assignment 2</strong></p><p>Here are <a href="https://nbviewer.jupyter.org/github/nwams/word2vec-written-solutions/blob/master/Written%20Solutions%20for%20word2vec%20from%20Stanford%20CS224n%20course.ipynb">my solutions</a> to the written part, from the first half of Assignment 2. The goal of the written portion is to ensure that you understand word2vec. Here I do compute <strong>partial derivatives</strong> of the Naive Softmax loss function as well as the Negative Sampling loss (which is an alternative to the Naive Softmax loss).</p><h3>Backpropogation &amp; Computation Graphs + Stuff You Should Know: Regularization, Vectorization, Nonlinearities, Learning Rates, Initialization, Optimizers</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FyLYHDSv-288%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DyLYHDSv-288&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FyLYHDSv-288%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/59d7ed759166c7be899157fe1fca4e13/href">https://medium.com/media/59d7ed759166c7be899157fe1fca4e13/href</a></iframe><p>Backpropagation is recursively applying the chain rule along a computation graph. Be clever to minimize computation by re-using shared stuff.</p><p>What’s great is the big O() complexity is the same as Forward Propagation!</p><p>Here’s a <a href="http://web.stanford.edu/class/cs224n/slides/cs224n-2019-lecture04-backprop.pdf#page=16">visual</a> of how backpropagation works in a neural network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*-GBiA7_U0WzDfP1JO60hnQ.png" /><figcaption>A node receives an <strong>upstream gradient</strong>.</figcaption></figure><p>A node receives an <strong>upstream gradient</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*24E3CS4DlUSmzSCNHmRkeQ.png" /><figcaption>This is a single node example. The goal is to pass on the correct <strong>downstream gradient</strong>. Each node has a<strong> local gradient</strong>. <strong>Downstream gradient = (upstream gradient) x (local gradient).</strong></figcaption></figure><blockquote><strong>Downstream gradient = (upstream gradient) x (local gradient)</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*eev569PJp0dkSTGuxO9hNg.png" /><figcaption>Multiple inputs example</figcaption></figure><p><strong>Algorithm</strong>:</p><ol><li>Do Forward Propagation: compute results of operations and save intermediate values.</li><li>Backprop: Initialize output gradient = 1.</li><li>Visit nodes in reverse order: Compute gradient with respect to each node using gradient with respect to successors.</li></ol><h3>Things You Should Know about Deep Learning — Regularization, Vectorization, Nonlinearities, Learning Rates, Initialization, Optimizers</h3><h4>Regularization</h4><p>The general idea is if you have a lot of parameters in your model, those parameters can memorize what’s in the data that you trained it with. The model becomes very good at predicting the answers to the data that you trained it on (overfitting) but might not perform well on different examples in the real world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*clbZA2LnEsmiXMTR-WXNgg.png" /><figcaption>The training error loss will keep going down until it approaches zero due to so many parameters. To the right of the grey line, the training model is just learning to memorize whatever is in the training data, but not in a way that it will perform well on other data.</figcaption></figure><p>This problem is especially bad for deep learning because typically DL has vast vast number of parameters.</p><h4>Non-linearities</h4><p><strong>Logistic</strong> is no longer the defaults for making deep networks. Logistic has been found to work quite poorly for neural networks (disclaimer: unless in the specific case when you want an output of actually want a value between 0 and 1 as your output.</p><p><strong>Tanh</strong> is still reasonably widely used in neural networks. But the downside is the expensive calculations of exponentials on your computer tends to slow things down.</p><p><strong>Hard tanh</strong> was birthed from the desire for cheaper computation. Hard tanh works pretty well in neural networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ExZneouOMVJ5VUrOW0NDiA.png" /></figure><p><strong>ReLU</strong> (rectified linear unit) is hard tanh rect(z) = max(z,0) is essentially the simplest nonlinearity you can have. Turns out that it works brilliantly! It’s by far <strong>the default</strong> when people are building <strong>feed-forward neural networks</strong>. They train very quickly. So try ReLU first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*Jd5r6jb1Hukg3_lszvwtkA.png" /><figcaption>ReLU has slope 0 when you’re in the negatives, while slope = 1 when in the positive regime so it acts like an identity function.</figcaption></figure><h4><strong>Parameter Initialization</strong></h4><p>When we have matrices of parameters in our model, it’s very very very important that you initialize the parameter weights with small values. Because we are trying to avoid symmetry where everything moves the same and is calculating the same (prevents learning/specialization). <strong>Xavier</strong> is a common initialization equation. It aims to tamper down the initialization based on the inputs and outputs so that the numbers don’t get to big (within the middle of tanh for example we want the values to be small within the line).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*ScAbN6B8JkyKd2iRX7ypvg.png" /></figure><h4>Optimizers</h4><p>With SGD you will have to hand tune the learning rate. But there are other sophisticated “<strong>adaptive</strong>” optimizers which can determine which parameters to move more or less depending on the sensitivities of the parameter. So where things are flat you can move fairly quickly but if things are bouncing around a lot you can move just a little so that you don’t overshoot. Adam is a fairly reliable one that many people use. See below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*5w8x6DOv8oK2bFgDTQNtWw.png" /></figure><h4>Learning Rates</h4><p>Start around 10^-3 (0.0001). Try powers of 10. In general you want to use the fastest learning rate that isn’t making things unstable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*gzFhoFwlVdCRjXuKdAzT6A.png" /></figure><h3>Dependency Parsing</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FnC9_RfjYwqA%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DnC9_RfjYwqA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FnC9_RfjYwqA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/56cdc34769d708190ff7790c3e77bd6d/href">https://medium.com/media/56cdc34769d708190ff7790c3e77bd6d/href</a></iframe><p><strong>Why do we need sentence structure?</strong> Machines need to know what is connected to each other to understand meaning.</p><p>Turns out you can use a simple neural to control the decision of what to do next part which could get greater accuracy and speed than Nivre’s MaltParser. The neural net is a very simple classifier. We extract a set of tokens based on the stack/buffer positions. The neural networks include distributed representations of the <strong>word</strong>, <strong>part of speech tag</strong>, and <strong>dependency labels</strong>. We convert them to vector embeddings and concatenate them!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*Q-GAWZPoowxknfVbimCwRg.png" /><figcaption><a href="http://web.stanford.edu/class/cs224n/slides/cs224n-2019-lecture05-dep-parsing.pdf#page=39">http://web.stanford.edu/class/cs224n/slides/cs224n-2019-lecture05-dep-parsing.pdf#page=39</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ec8b3845b2e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nwamaka-imasogie/neural-networks-word-embeddings-8ec8b3845b2e">Neural Networks &amp; Word Embeddings</a> was originally published in <a href="https://medium.com/nwamaka-imasogie">Nwamaka Imasogie’s Machine Learning and Artificial Intelligence Projects</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Language Models & Lexicons]]></title>
            <link>https://medium.com/nwamaka-imasogie/language-models-lexicons-259bc6665df9?source=rss----c1856a20555a---4</link>
            <guid isPermaLink="false">https://medium.com/p/259bc6665df9</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[hidden-markov-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[text-classification]]></category>
            <category><![CDATA[dependency-parsing]]></category>
            <dc:creator><![CDATA[Nwamaka Imasogie]]></dc:creator>
            <pubDate>Thu, 26 Sep 2019 21:26:40 GMT</pubDate>
            <atom:updated>2019-10-29T19:28:51.313Z</atom:updated>
            <content:encoded><![CDATA[<p>A statistical language model is a probability distribution over a sequence of words. If we can create a language model from a text corpus, we can use it to perform tasks like text classification or text generation in the style of that corpus because it captures the essence of it. In this post I cover:</p><ul><li>Generative vs Discriminative Text Classifiers: Naive Bayes, Logistic Regression, Linear SVM</li><li>Dependency Parsing, Context-Free Grammar (Phrase Structure)</li><li>Hidden Markov Models (HMM) and I use PyTorch to build a HMM and implemented with Viterbi, Forward-Backward and Baum Welch algorithms.</li><li>Text Classification, Precision, Recall, Cross-validation, comparing classifiers (hypothesis testing), TF-IDF</li></ul><blockquote>Lecture videos 2–6 from the University of Washington’s NLP course are <a href="https://courses.cs.washington.edu/courses/csep517/17sp/video/">here</a>.</blockquote><h3>Language Models (<a href="https://www.youtube.com/watch?v=CMwgR4JnBAI&amp;t=86s">Video lecture 2</a>)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZR6xU19SlKgUcw_3hQ0DKg.png" /></figure><p>Language models are a predictive theory of what word will come next.</p><h4>Log-Linear Models</h4><p>Log-Linear models are a feature vector representation of the <strong>word’s history</strong> and the <strong>word</strong>. Usually the features are things we’ve engineered (found to work well). Usually in NLP the features tend to be binary but don’t have to be. Estimation/learning is carried out by an iterative algorithm like Stochastic Gradient Descent. We really focus on using linguistic patterns to come up with features!</p><p>There are several estimation/learning algorithms but here are the 2 most popular today. Here are some convex optimization algorithms for calculating maximum likelihood:</p><ul><li>Batch methods (L-BFGs is popular). It calculates the whole function, over all of the data. Calculates its data and takes a step. Except it does some things more cleverly than Gradient Descent. In addition to calculating the gradient, it keeps an approximation to the 2nd derivative in its memory.</li><li>Stochastic Gradient Descent/Ascent is <strong>most widely used</strong>. The nice thing about SGD, that’s different than the Batch method, is that we start making progress right away. Every time I look at an example I immediately make an update. In practice, SGD gets to a pretty good solution faster than Batch (in a relatively small amount of passes). It’s a good choice when you have a budget/deadline.</li></ul><p>I’ll summarize the most important take-aways to remember:</p><ol><li>We probably aren’t going to implement a log-linear model. But will definitely run into them again in life.</li><li>We have to use an iterative method like Stochastic Gradient Descent because there is no closed form; we can’t set the <strong>weights</strong> by simply implementing a function that counts, normalizes or does a transformation on the data.</li><li>Log-linear models are expensive but it never really took off because the computation of the summation is just too expensive so it’s unrealistic to use in real-time (because it incorporates the vocabulary size per calculation).</li><li>Regularization is very important! Subtract a quadratic term at the end of our objective function and suffer a penalty when the weights get big. We don’t actually do maximum likelihood.</li></ol><h3>Text Classification (<a href="https://www.youtube.com/watch?v=x03zpuvfCx0&amp;t=112s">Video lecture 3</a>)</h3><p>Before jumping directly into text classification lets first look at how to measure performance.</p><p>There are some issues with Test-Set <strong>accuracy</strong>. For example:</p><ol><li>Class imbalance: You could get 99% accuracy by simple labelling all emails as “not spam”.</li><li>Variance due to the test data: Your test data is really just an “approximation” to the true distribution to the universe of data. And changing your test data a little bit might lead to some variance. So it’s easy to get lucky or unlucky.</li></ol><p>Let’s look at a different way to do evaluate performance.</p><h4><strong>Evaluation</strong>, in a Two-Class Case</h4><blockquote>Side note:</blockquote><blockquote>If you’d like deeper explanations on performance metrics (with <strong>visualizations</strong>) Andrew Long wrote a very helpful <a href="https://towardsdatascience.com/data-science-performance-metrics-for-everyone-4d68f4859eef">blog</a> on Recall, Specificity, Accuracy and Precision.</blockquote><blockquote>If you would like to read an article that uses <strong>equations</strong> for performance metrics, check out this <a href="https://towardsdatascience.com/beyond-accuracy-precision-and-recall-3da06bea9f6c">article</a> by William Koehrsen.</blockquote><p>Suppose we have two classes, and one of them is the “target” class and the other is the non-target class. If we use a <strong>search engine</strong> as an example you can think of someone entering a query, and the target class is a set of relevant documents to that query. Let’s look at two complimentary measures of performance called <strong>precision</strong> and <strong>recall</strong>.</p><p><strong>Precision — </strong>Using the search engine as an example, precision measures the fraction of the documents that the classifier returns versus how many of them are actually relevant. Precision measures the goal of returning a “pure” set of target instances.</p><p><strong>Recall</strong> — Out of every document that I should have returned, how many did I actually return correctly? Recall measures the goal of capturing <em>all</em> of the targeted instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8VRdBteom9Zyvl0McW4ZQ.png" /><figcaption>Venn Diagram for Precision and Recall</figcaption></figure><p>Every document on the web will be either inside our outside of these circles.</p><p>Instances outside of the circle are not relevant to the query, so we won’t see them and don’t care about them.</p><p>The documents labeled in circle A are the documents that are actually in the “target” class. These are the set of relevant documents that you <strong>want</strong> to have be returned.</p><p>Circle B contains the set of documents that your classifier believes to be a relevant document. A.k.a. what your classifier will show you.</p><p>And circle C contains all of the documents that are correct. In other words, its the set of documents that are both in the target class and what your classifier returned.</p><p><strong>F-measure a.k.a. Harmonic Mean </strong>— F1 is a single number that balances, combines, and considers both precision and recall.</p><p><strong>Formulas</strong></p><pre>P(classify) = |C|/|B|</pre><pre>R(classify) = |C|/|A|</pre><pre>F1(classify) = 2 * [(P * R)/(P + R)]</pre><p>It’s important to know that often times in NLP there will be more than 2 classes. For example, maybe we want to classify an article as sports, another as news, and another as business, etc. We can still use precision and recall as either <strong>macroaveraged</strong> or <strong>microaveraged</strong>.</p><h4>Evaluation with &gt; 2 Classes</h4><p>Macroaveraged precision and recall — Let each class be the target and report the the average precision and recall across all classes. Basically this treats every class as having an equal weight.</p><p>Microaveraged precision and recall — pull all one-vs.-rest decisions into a single contingency table, calculate precision and recall from that. Basically this will weight the classes that are more dominant, heavier.</p><h3>Cross-Validation</h3><p>It’s important to remember that accuracy, precision, recall and F1 are just estimates of how the classifier’s would perform under a true data distribution. But the estimates are noisy! Because we only have a finite sample.</p><h4><strong>K-fold cross-validation</strong></h4><p>Partition the training set into K non-overlapping “folds” (10 is most commonly used, but it can be another value). Then do a series of training runs on all of the data except for one fold. So hold out one fold on each turn and use it as the development set. Then you estimate the quality on the <em>i</em>th development set. And you repeat this K times. So now we’ll either have 10 measures of accuracy, 10 measures of precision, 10 measures of recall, etc and finally you report the average. You might also want to report the <strong>standard error</strong> which gives us a sense of how much does it wobble around based on splits of the data.</p><h3>Hypothesis Testing — Statistical Significance</h3><p>Supposed we have two classifiers and want to know if classifier1 is significantly better than classifier 2. If classifier1 has a better accuracy, we can’t automatically assume it’s really better. It might have just gotten lucky.</p><p>In our experiment, we can think of the “null hypothesis (H0)” as your skeptical friend who says no, classifier1 is not better.</p><p>But if accuracy1 &gt;&gt; accuracy2 we are tempted to believe otherwise. So that brings us to a great question, how much larger must accuracy1 be than accuracy2 to reject the null hypothesis?</p><h4>McNemar’s (1947) Hypothesis Test for Text Classifiers</h4><p>McNemar’s is one test that’s clean and simple, transparent statistical test related to NLP.</p><ol><li>The null hypothesis: true accuracy1 = true accuracy2</li><li>Pick a significance level alpha, an “acceptably” high probability of incorrectly rejecting the null hypothesis. — It’s like how bad would it be to retract your statement later if you decide that the null hypthesis is. Then set your alpha as low as possible so that you’re comfortable with this risk. Usually in scientific literature, its common to set alpha = 5%. Meaning 1 experiment in 20 is going to incorrectly reject the null hypothesis. This is subjective.</li><li>Calculate the test statistic, k (explained below)</li><li>Calculate the probability of an as extreme or more extreme value of k, assuming the null hypothesis is true; this is the p-value. In other words, how probable is it that we would observe k or something more extreme if the null hypothesis is true. How surprising is what we’ve seen?</li><li>Reject the null hypothesis if the p-value is less than alpha.</li></ol><p>Be careful. The p-value is the probability of this observation (or one more extreme) given that the null hypothesis is true.</p><blockquote>The p-value is p(this observation | H0 is true), not the other way around!</blockquote><h4>Details of the McNemar Test</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z9slB5_qGND5QLyRxgnpKg.png" /><figcaption>McNemar’s Test Details</figcaption></figure><p>Contingency table is shows whether a classifier got it right or wrong. We are interested in the cells where a classifier is right, and a classifier is wrong, so c01 and c10.</p><p>We want to know how surprising is the smaller of either c01 or c10. So k is the minimum of the two.</p><p>Here’s how to think about it: If we had a binomial distribution where we draw coins from a bucket. In other words, if we were to toss c01+c10 amount of coins, what’s the probability of getting k, or fewer, heads.</p><h3>Features in Text Classification</h3><p>Often times features are simply term frequencies. For example, from the sentence: the vodka was great, but don’t touch the hamburger, the term frequencies would be a vector containing counts:</p><pre>hamburger = 1<br>the = 2<br>delicious= 0<br>don’t touch = 1<br>...</pre><h4>Transformations on Word Frequencies</h4><p><strong>Logarithm — </strong>When the frequencies of a word count get really really big it starts to have a disproportionate influence on the category. So it’s better to damp down the frequencies. So taking the log will tune it down. So the difference between 1000 and 10,000 becomes less significant.</p><p><strong>Idf weighting, a.k.a. TF-IDF —</strong>Document frequency is a different way of counting. It checks how many documents a word occurred in. If a word like “the” occurs in every single document, it’s not very helpful. So before we even build our classifier let’s take that into account in our features. Conversely if a word occurs in relatively few documents its more likely to be useful.</p><p>Formula is: log(total number of documents / number of documents a word occurred in)</p><p>So for a word like “the” we would ignore it because log(n/n) = log(1) = 0.</p><p>But if a word like “hamburger” occurs in only 5% of documents then log(1/0.05) = log(20) = 1.30 so we will multiply the frequency of hamburgers by log(20) or 1.3.</p><p>Disjunction of terms; Clustering: You can run clustering algorithms to get words that behave similarly. Suppose that Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday all land in a cluster together. We could have a feature that indicates if there’s a day of the week in this document. The feature will fire if either of those days of the week exist, doesn’t matter which one.</p><h3>Generative vs. Discriminative Classification</h3><p>Generative (or Joint) models place probabilities over both the observed data and the hidden classes (generates the observed data from hidden stuff).</p><p>Language models, Naïve Bayes, N-gram models, and hidden Markov models are also generative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*SHB0gmMAgcZm5uF_vfvJuw.png" /><figcaption>Graphical model diagram. The circles are random variables. The lines are direct dependencies between them. Each node is a classifier based on its incoming arch. For Naïve Bayes, at classification time we observe the various words of the document (d1, d2, d3) and we want to predict the class based on that. There’s the prior probability of the class P(c) and the probability of the words in the document given the class P(d1 | c).</figcaption></figure><h4>Naïve Bayes Classifier — Generative</h4><p>Naïve Bayes is a generative classifier because it tells a story about how the data is generated: first you pick the label, then for each feature you pick the feature condition, then the label. Then we get a random feature distribution that tells us how probable our data is. In other words, we have a generative direction where the words are “generated” from the class so you have a prior probability P(class) and P(data | class).</p><p>Naïve Bayes calculates the probability of all of the features together with a label. So it gives us a distribution of documents with their labels together. Here’s another way to think about how Naïve Bayes works, step by step. Let’s imagine that we have a dice that has our various labels on it:</p><ol><li>Roll the dice to pick a label.</li><li>For this particular label, walk though the features from 1 to d, and get a distribution of the feature values for each of the features.</li><li>Let’s imagine that we also have a dice for each label and each feature. So the total number of different dice = d*number of labels. And then we roll each dice.</li><li>Don’t forget to multiply in the prior probability, Π, of that label.</li></ol><p>Naiive Bayes is a <strong>probabilistic classifier</strong>. Here are some pros and cons:</p><p><strong>Pros</strong></p><ul><li>Often works quite well. Old/studied a lot.</li><li>Simplest. Easy to build so it’s a good starting point.</li><li>Fast.</li><li>No special optimization required.</li></ul><p><strong>Cons</strong></p><ul><li>The features are all treated as independent (that’s why it’s called naïve. Because we are separately estimating each feature distribution given each label, this means that if 2 features are going to collude, it does not taking that into account. If we have 2 features that co-occur very often, there’s no joint consideration about how much each feature should influence our classifier’s decision.</li></ul><h4>Discriminative Classifiers</h4><p>Sometimes we don’t need to spend all of this time building a (generative) model that tells us how probable our data is. For example, we might really be interested in the probability of the label given the text (output given the input).</p><p>In a discriminative model (also called conditional model) such as <strong>logistic regression</strong> we’ve observed the words of the document and want to predict the class. However, this time we are directly putting a probability over the class given all of the data we’ve observed P(c | d1, d2, d3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*zE_asryUGFaAfyK-giqWtA.png" /><figcaption>We are directly putting a probability over the class given all of the data we’ve observed P(c | d1, d2, d3).</figcaption></figure><p>Discriminative models focus on optimizing a performance measure like accuracy or something similar. Benefits include:</p><ul><li>They give high accuracy performance</li><li>They make it easy to incorporate lots of linguistically important features</li><li>They allow automatic building of language independent, retargetable NLP modules</li></ul><p>The rule of thumb/conventional wisdom is to use discriminative models when you have a large amount of data. Discriminative models will typically perform better than generative. However, if you have a small dataset, discriminative has a bigger problem with over-fitting.</p><p>There are many more discriminative classifiers, but I’ll focus on <strong>multinomial logistic regression</strong> and <strong>linear SVM</strong>.</p><h4>Logistic Regression vs. Linear SVM</h4><p>In Logistic Regression we seek to maximize conditional likelihood. We will choose the lambda (λ “weights”) parameters that maximize the conditional likelihood of the data according to this model. LR constructs a probability distribution over classifications.</p><p>Support Vector Machine (SVM) also known as <em>max-margin</em> classifier is an algorithm used for classification problems. SVM is also a good way of discriminating classes however it <strong>does not provide a probability distribution over classes</strong>.</p><p>If you look at the optimization problems of linear SVM and (regularized) Logistic Regression, they are very similar. They only differ in the loss function. <strong>SVM minimizes hinge loss</strong> while <strong>logistic regression minimizes log loss.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*1zsplJ_CV_55HV9sP5C7xQ.png" /><figcaption>Purple is hinge loss. Blue is log loss. Red is zero-one loss (error).</figcaption></figure><p>There are 2 differences to note:</p><ul><li>Logistic loss diverges faster than hinge loss. So, in general, it will be more sensitive to outliers.</li><li>Logistic loss does not go to zero even if the point is classified sufficiently confidently. This might lead to minor degradation in accuracy.</li></ul><blockquote>Rumor: random forests are widely used in industry when performance matters more than the ability interpretability.</blockquote><h3>Sequence Models (<a href="https://www.youtube.com/watch?v=MKl1rCWj6YI&amp;t=38s">Video lecture 4</a>)</h3><h3>Hidden Markov Model</h3><p>The <a href="https://www.youtube.com/watch?v=kqSzLo9fenk">first 10 minutes of this video</a> does a great job of explaining Hidden Markov Models using a very simple example.</p><p>A Hidden Markov Model (HMM) is a sequence classifier. As other machine learning algorithms it can be trained, i.e.: given labeled sequences of observations, then uses the learned parameters to assign a sequence of labels given a sequence of observations. Let’s define an HMM framework containing the following components:</p><ul><li><strong>States</strong> (e.g., labels): T=t1, t2, …, tN</li><li><strong>Observations</strong> (e.g., words) : W=w1, w2, …, wN</li><li><strong>Two special states</strong>: t_start and t_end which are not associated with the observation</li></ul><p>Definitions:</p><ul><li><strong>Transition probability</strong>: A matrix A with the probabilities from transitioning from one state to the next state, over time.</li><li><strong>Emission probability</strong>: A matrix B with the probabilities of an observation being generated from a state.</li><li><strong>Initial probability</strong>: An initial probability distribution over states</li><li><strong>Final probability</strong>: A final probability distribution over states</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDOwWNeUW4i2toJxwfyLLw.png" /><figcaption>Graphical Representation of Hidden Markov Models. Grey are elements that I know. T’s are labels. W’s are words. The arrows tell you which node is conditioning the current node.</figcaption></figure><h4>Intuition and Assumptions</h4><p>In HMM if we already knew the label of a node, then we would know more about the nodes to the left and right. For example if I knew y3 it would give me some evidence about y2.</p><p>The probability of a particular state is dependent only on the previous state. HMM does not have a direct way to look at all of the other states. So if we’re making a decision about t3, the other words in the sentence aren’t immediately available. So that is a weakness.</p><h4><strong>Some Use Cases</strong></h4><ol><li>HMM can be used in Supervised Training for POS training.</li><li>Another example, is named-entity recognition.</li><li>Unsupervised learning</li></ol><h4><strong>Sequence Models Takeaways</strong></h4><p>Sequence models are extremely useful:</p><p>Syntax:</p><ul><li>part-of-speech tags,</li><li>base noun phrase chunking</li></ul><p>Semantics:</p><ul><li>supersense tags</li><li>named entity recognition</li><li>multiword expressions</li></ul><p>All of these above are called “shallow” methods. Why? Because if we want to represent the full semantics of a sentence like who did it, why and where none of those methods will get us there. They are seen as “pre-processing” to something else (another method) richer or deeper.</p><h3>Syntactic Structure</h3><h3><strong>Constituency (phrase structure)</strong></h3><p>Constituents are units of a sentence, such as Noun Phrase (NP) or Verb Phrase (VP). E.g. with the sentence Fed raises interest rates we have their parts of speech. Fed is a proper noun. Raises is a verb. Interest is a noun. And rates is a noun. Those roll up into constituents. The verb phrases and noun phrases are constituents. So interest rates is a constituent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*e5s3t7o5r-t6QEaIHyG8Cw.png" /><figcaption>Verb Phrase and Noun Phrase are constituents of the sentence.</figcaption></figure><p>How do we know what is a constituent? We can look at distribution because a constituent behaves as a unit that can appear in different places, e.g. the constituents in the sentence John talked [to the children][about drugs] can be rewritten as John talked [about drugs][to the children].</p><p>Christopher Manning of Stanford’s NLP group made a <a href="https://www.youtube.com/watch?v=lyo6Zwkdins&amp;list=PLDcmCgguL9rxTEz1Rsy6x5NhlBjI8z3Gz&amp;index=58">great video</a> that explains this in a simple way.</p><h3>Dependency Structure (Linguistic Structure)</h3><p>Dependency structure shows which words depend on which other words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OJ2TovhbTbEWvemYCBwiKA.png" /><figcaption>The “head” of the entire sentence is <strong>put</strong>. Put has 3 arguments itself: “boy”, “tortoise”, and “on the rug”. It represents who…put what…where. Next, we ask if boy has a modifier? Yes, it’s modifier is “The”. Does “tortoise” have any modifiers or arguments? Yes, it’s modifier is “the”. Then “on”, being a preposition, takes a compliment which is “rug”. And lastly, “the” is the modifier for “rug”.</figcaption></figure><h3>CFGs and PCFGs</h3><p>CFG and PCFG stand for Context-Free Grammars and Probabilistic Context-Free Grammars, respectively. <strong>Phrase structure grammar = context-free grammar.</strong> Context-free grammar is a category which rewrites as a sequence of other categories, eventually writing down to the terminal (word).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-dL8sO5AhzHfRrjGIN0tg.png" /><figcaption>A phrase structure grammar a.k.a. a context-free grammar.</figcaption></figure><p>It can represented, formally, as a 5 tuple, G=(T, N, S, R, P).</p><pre>T is a set of terminal symbols (words, at the end)<br>N is a set of nonterminal symbols<br>S is the start symbol<br>R is a set of rules<br>P is a probability function</pre><p><strong>Here’s an example of a PCFG.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s0CRmROM9dQZwUk9BHhRoQ.png" /><figcaption>Example of a PCFG. Next to each rule there’s a probability. There’s only one possible rewrite for S so the probability is 1.0. However, there are 3 possible rewrites for NP so if we add up 0.1, 0.2, and 0.7 we get a total probability of 1.0.</figcaption></figure><h3>Grammar Transforms (Chomsky Normal Form)</h3><p>Chomsky Normal Form says that all rules must be of the form <em>X→Y Z</em> or <em>X→w</em> …where all of X, Y, and Z are nonterminals…or a nonterminal X rewrites as a terminal w.</p><p>Internally, when the system is doing Chomsky transformation steps it’s getting rid of any unary rules and empties.</p><p>You should think of this as a transformation that allows for more efficient parsing. <strong>Binarization is crucial for cubic time CFG parsing.</strong></p><h3>CKY Parsing Algorithm</h3><p>Parsing of (P)CFGs exactly in polynomial time. In particular this will give us the means of finding the most probable paths of a sentence according to a PCFG <strong>in polynomial time</strong> (rather than doing exponential amount of work). The CKY algorithm gives us a <strong>cubic</strong> time algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*P7uurIgTj7stUtwG1PFfXQ.png" /><figcaption>Visual example of the CKY triangle and probability math for “factory payrolls”.</figcaption></figure><h3>Dependency Parsing</h3><p>A dependency grammar has a notion of a head. Modern statistical parsers like the Stanford parser have “head rules”. E.g.</p><ul><li>The head of a Noun Phrase is a noun/number/adj/…</li><li>The head of a Verb Phrase is a verb/modal/…</li></ul><h4><strong>Methods of Dependency Parsing</strong></h4><p>There are several methods of dependency parsing:</p><ol><li>Dynamic programming (like in the CKY algorithm)</li><li>Graph algorithms</li><li>Constraint Satisfaction</li><li><strong>Deterministic parsing</strong></li></ol><p>Deterministic parsing is where you go from left to right through the sentence and make <strong>greedy decisions</strong> based on machine learning classifiers, as to which words to connect to other words as dependents. The <strong>MaltParser</strong> (transition-based) is one of the most well known methods for doing dependency parsing and it works very well (accurately and exceedingly quickly). So I’ll focus on that.</p><ul><li>The parser does a sequence of bottom up actions — kind of like “shift” or “reduce” in a shift-reduce parser, but the “reduce” actions are specialized to create dependencies with head on left or right.</li><li>In order to choose the next action, each action is predicted by a discriminative classifier (often SVM, could be maxent classifier).</li><li>The model’s accuracy is slightly below the best LPCFGs (evaluated on dependencies), but</li><li>It provides close to state of the art parsing performance</li><li><strong>It provides VERY fast linear time parsing</strong></li></ul><h4>Evaluating Dependency Parsers</h4><p>The standard way is to look at accuracy. Since we choose a “head” for each word, we can look at how many of those we got right.</p><p>Acc = (# correct dependencies)/(total # of dependencies). There are two ways we can do that.</p><ol><li>Ignore the labels Unlabeled Attachment Score (UAS)</li><li>Uses the Labeled Attachment Score, LAS</li></ol><h3>Latent Dirichlet Allocation (LDA)</h3><p><a href="https://medium.com/@lettier/how-does-lda-work-ill-explain-using-emoji-108abf40fa7d">This blog</a> is an excellent (and interactive!) guide to LDA for topic modeling.</p><h3>Build a Hidden Markov Model in PyTorch</h3><h4>[<a href="https://nbviewer.jupyter.org/github/nwams/Hidden_Markov_Model-in-PyTorch/blob/master/Hidden%20Markov%20Models%20in%20PyTorch.ipynb">View my code</a>] [<a href="https://github.com/nwams/Hidden_Markov_Model-in-PyTorch">or GitHub</a>]</h4><p>I use PyTorch to Build a Hidden Markov Model for both Weather Prediction and to predict whether a person is Healthy or Feverish. <strong>PyTorch</strong> is a deep learning neural networks package for Python. <a href="https://www.youtube.com/watch?v=iTKbyFh-7GM">Here’s a video of PyTorch Explained</a>.</p><p>The following algorithms are implemented:</p><ul><li><strong>Viterbi</strong></li><li><strong>Forward-Backward</strong></li><li><strong>Baum Welch</strong></li></ul><p>I added my own personal enhancements (for example, clearer code documentation/interpretation) and modifications to <a href="https://nbviewer.jupyter.org/github/TreB1eN/HiddenMarkovModel_Pytorch/blob/master/HiddenMarkovModel.ipynb">this original project</a> put together by <a href="https://github.com/TreB1eN">TreB1eN</a>.</p><p>A dynamic programming table is also used to make the repetitive recursive computations more efficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=259bc6665df9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nwamaka-imasogie/language-models-lexicons-259bc6665df9">Language Models &amp; Lexicons</a> was originally published in <a href="https://medium.com/nwamaka-imasogie">Nwamaka Imasogie’s Machine Learning and Artificial Intelligence Projects</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NLP Terminology and Pre-Processing]]></title>
            <link>https://medium.com/nwamaka-imasogie/nlp-terminology-and-pre-processing-4884f60416c5?source=rss----c1856a20555a---4</link>
            <guid isPermaLink="false">https://medium.com/p/4884f60416c5</guid>
            <category><![CDATA[nltk]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[stanford-university]]></category>
            <category><![CDATA[pre-processing]]></category>
            <dc:creator><![CDATA[Nwamaka Imasogie]]></dc:creator>
            <pubDate>Fri, 13 Sep 2019 21:07:14 GMT</pubDate>
            <atom:updated>2019-09-20T18:29:57.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Th-rbRbzJ_w7MAhdqBFCJQ.png" /></figure><p>Even though the majority of NLP state-of-the-art algorithms are primarily made up of deep learning, it’s important to understand the basics before introducing machine learning. I’ll be following along with the <a href="https://web.stanford.edu/~jurafsky/slp3/">Speech and Language Processing</a> course by Dan Jurafsky at Stanford and I’ll document what I’ve learned along the way. This will be from a combination of reading textbooks, slides, watching videos and doing hands on coding projects.</p><p>Before statistical analysis came along linguists devoted their lives to studying the theory of language. So having domain knowledge of language theory serves as a great foundational area to familiarize yourself with…things like: pragmatics, semantics, syntax, and morphology, etc.</p><p>In this blog I’ll cover all the different pre-processing techniques for text data like stemming, lemmatization, stop word removal and tokenization using NLTK. And finally I’ll wrap it up all up with a project!</p><h4>Pre-Processing</h4><p>Text data is usually very messy. Rarely will our data come in the form of a corpus that’s ready to be fed into a model. You’ll usually have to clean it up first by doing things like stemming, lemmatization, removing stop words, tokenization, etc.</p><p>I’ll be using <a href="https://www.nltk.org/">NLTK</a> to clean up text data.</p><p>I watched these 5 video lectures which cover basic text processing:</p><ul><li><a href="https://www.youtube.com/watch?v=2lJJGQmGLJQ&amp;list=PLDcmCgguL9rxTEz1Rsy6x5NhlBjI8z3Gz&amp;index=2">Regular Expressions</a></li><li><a href="https://www.youtube.com/watch?v=zA2qKLf2skQ&amp;list=PLDcmCgguL9rxTEz1Rsy6x5NhlBjI8z3Gz&amp;index=3">Regular Expressions in Practical NLP</a></li><li><a href="https://www.youtube.com/watch?v=OEfyWAhW8xg&amp;list=PLDcmCgguL9rxTEz1Rsy6x5NhlBjI8z3Gz&amp;index=4">Word Tokenization</a>.</li><li><a href="https://www.youtube.com/watch?v=N5f8jexSqYQ&amp;list=PLDcmCgguL9rxTEz1Rsy6x5NhlBjI8z3Gz&amp;index=5">Word Normalization and Stemming</a></li><li><a href="https://www.youtube.com/watch?v=bi7wF99oBzw&amp;list=PLDcmCgguL9rxTEz1Rsy6x5NhlBjI8z3Gz&amp;index=6">Sentence Segmentation</a></li></ul><h3>Word Tokenization</h3><p>Every NLP task needs to do segmenting/tokenizing words in running text, normalizing word formats and segmenting sentences in running text.</p><h4><strong>Definitions</strong></h4><ul><li><strong>Lemma</strong>: same stem, part of speech, or rough word sense like ‘cat’ and ‘cats’ are the same lemma. ‘They’ and ‘their’ are the same lemma but different wordforms.</li><li><strong>Wordform</strong>: the full inflected surface form. So ‘cat’ and ‘cats’ are different wordforms.</li><li><strong>Type</strong>: an element of the vocabulary.</li><li><strong>Token</strong>: an instance of that type of in running text.</li></ul><p>So in the following sentence:</p><blockquote>they lay back on the San Francisco grass and looked at the stars and their</blockquote><p>There are 15 tokens if you consider ‘San’ and ‘Fransisco’ two different tokens or 14 if you consider them as one token.</p><p>There are 13 types because ‘the’ occurs twice. Or 12 if you consider ‘San Fransisco’ as one word. Or 11 if you consider ‘they’ and ‘their’ as the same type, but this will depend on our goal.</p><h4><strong>Creating a Standard for Tokenization</strong></h4><p>You might run into some common issues during tokenization like apostrophe’s dashes, acronyms with periods, etc. So you’ll have to create a standard for handling those issues. And how you decide to handle the issues will depend on your goal. Here are some examples:</p><ul><li>Finland’s capital → Finland or Finlands or Finland’s ?</li><li>what’re, I’m, isn’t → what are, I am, is not ?</li><li>Hewlett-Packard → Hewlett Packard ?</li><li>state-of-the-art → state of the art ?</li><li>San Fransisco → one token or two?</li><li>m.p.h., PhD. → ??</li></ul><h3>Normalizing and Stemming</h3><p>Once we have tokenized our text (a.k.a. segmenting) we need to normalize and stem them.</p><h4>Case Folding</h4><p>For Information Retrieval purposes we would want to, for example, match <strong>U.S.A.</strong> and <strong>USA</strong>. We can implicitly define equivalence classes of terms by deleting the periods in a term.</p><p>In general, because users tend to use lower case we will reduce all letters to lower case in Information Retrieval, except when we see capital letters that occur mid-sentence like: General Motors. For Sentiment Analysis, Machine Translation and Information Retrieval the case is very important because <strong>US</strong> versus <strong>us</strong> have different meanings.</p><h4>Lemmatization</h4><p>In lemmatization we reduce variant forms to one base form. In general, the task of lemmatization is finding the correct dictionary headword form. For am example, we convert:</p><ul><li>am, are, is → be</li><li>car, cars, car’s, cars’ → car</li></ul><p>So a phrase like the boy&#39;s cars are different colors gets lemmatized to the boy car be different color.</p><h4>Morphology</h4><p>Morphemes are the smallest meaningful units that make up words. There are two types of morphemes:</p><ol><li>Stem: the core meaning-bearing unit.</li><li>Affix: A piece that adheres to a stem. Affixes usually have grammatical functions. For example, in the word <strong>meaningful</strong> , <strong>meaning</strong> is the stem and <strong>ful</strong> is the affix. And in the word <strong>units</strong>, <strong>unit</strong> is the stem and <strong>s</strong> is the affix.</li></ol><h4>Stemming</h4><p>Stemming is the task of reducing terms to their stems by crudely chopping off affixes. Stemming is a simplified version of lemmatization. We just use the prefix to represent a word and chop off the suffix. For example, <strong>automate(s)</strong>, <strong>automatic</strong>, <strong>automation</strong> all reduced to <strong>automat</strong>.</p><p>This sentence:</p><blockquote>for example compressed and compression are both accepted as equivalent to compress.</blockquote><p>After stemming it becomes:</p><blockquote>for exmpl compress and compress ar both accept as equival to compress</blockquote><p>We lost the e in example, turned compressed and compressing both became compress, accepted became accept and equivalent became equival.</p><h4>Porter’s algorithm</h4><p><a href="https://tartarus.org/martin/PorterStemmer/">Porter’s algorithm</a> is the most common English stemmer for simple stemming. It’s an iterative series of simple “replace” rules. I’ll walk through some parts of the algorithm:</p><p><strong>Step 1a</strong></p><p>It will take strings like sses and replaces them with ss (e.g. caresses becomes caress).</p><p>It replaces ies with i (e.g. ponies becomes poni).</p><p>The rules operate in order so if there is an ss left, it will remain ss (e.g. caress remains caress).</p><p>But if there is any other s left, it gets removed (e.g. cars becomes cat). Here’s the order of the logic:</p><pre>sses → ss       <strong>caresses → caress<br></strong>ies  → i        <strong>ponies → poni</strong><br>ss   → ss       <strong>caress → caress</strong><br>s    → ∅        <strong>cats → cat</strong></pre><p><strong>Step 1b</strong></p><p>If there’s a word in this format, (*v*)ing where there’s an additional <strong>vowel</strong> before the ing, then we remove the ing (e.g. walking becomes walk but note that sing will remain sing because there’s no vowel before the ing). The same vowel idea applies for ed as well. The logic is:</p><pre>(*v*)ing → ∅     <strong>walking → walk </strong><br>                 <strong>sing → sing</strong><br>(*v*)ed  → ∅     <strong>plastered → plaster</strong></pre><p>I’ll jump straight into summarizing the logic for step 2 and 3 below.</p><p><strong>Step 2 (for long stems)</strong></p><pre>ational → ate     <strong>relational → relate</strong><br>izer    → ize     <strong>digitizer → digitize<br></strong>ator    → ate     <strong>operator → operate</strong></pre><p>The rules get even more complicated as you get to longer stems.</p><p><strong>Step 3 (for longer stems)</strong></p><pre>al   → ∅     <strong>revival → reviv</strong><br>able → ∅     <strong>adjustable → adjust<br></strong>ate  → ∅     <strong>activate → activ</strong></pre><p>…</p><p>and the algorithm just keeps going in a similar fashion.</p><h3>Sentence Segmentation and Decision Trees</h3><p>How can we tell when a sentence ends and a new one begins? Exclamation marks, !, and question marks, ?, are great because they are relatively unambiguous. While periods can represent sentence boundaries, periods, ., are very ambiguous because they can represent abbreviations and decimal numbers like Inc. or 5.3. To solve this “period” problem we need to build a binary classifier which will look at a period and output a yes/no decision that you are either “at the end of a sentence” or “not at the end of a sentence”.</p><p>To make this classifier we could use hand-written rules, regular expressions, or a machine-learning classifier. The simplest kind of classifier for this is a decision tree. A decision tree is a simple if/then procedure that asks a question and branches based on the answer to the question.</p><p>Here’s a simple decision tree that decides whether a word is an end-of-sentence or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*WgXSKYRggtlktZE0rX2fUw.png" /></figure><p>There are still a bunch more sophisticated decision tree features that we could add that will tell us, for example:</p><ul><li>We could look at the word with the period. If it’s uppercase, lowercase, all caps or a number. Because a word that’s all caps is likely to be an abbreviation.</li><li>We could look at the case of the word that comes right after the period. Because if the next word after the period starts with a capital letter then it’s likely to be a period that ends the sentence.</li><li>We can look at numeric features such as the length of a word with the period. For example, abbreviations and acronyms tend to be relatively short.</li><li>For a more sophisticated assessment we could consider the scenario where we have a corpus and already know where the sentence boundaries are. We could calculate how this word occurs at the end of a sentence.</li><li>We could also look at the probability that a word after a period starts a sentence. For example, the word ‘The’ appearing after a period tends to start a sentence.</li></ul><p>In general, building the structure of a decision tree is difficult to do by hand. It can be hand-built for very simple features or simple domains. For numerical features it can be especially hard to pick thresholds. And that’s why we generally use machine learning. Machine learning will learn the structure from a training corpus.</p><h3>NLTK Hands-On Tutorial</h3><p>NLTK is one of the most popular Python packages for Natural Language Processing. I will do several hands on examples that demonstrate how to use NLTK. Here’s the <a href="https://github.com/nwams/NLTK-Hands-On-Tutorial">github repository</a> where my various examples are stored. I cover the following topics:</p><h4><strong>1. Text Analysis using </strong><a href="https://kite.com/python/docs/nltk.text.Text"><strong>nltk.text</strong></a><strong> (</strong><a href="https://nbviewer.jupyter.org/github/nwams/NLTK-Hands-On-Tutorial/blob/master/1-Text-Analysis-Using-nltk.text.ipynb"><strong>view code</strong></a><strong>)</strong></h4><p>I extract interesting data from a given text. I’ll highlight just a few subjects from this lesson…</p><ul><li><strong>Concordance: </strong>viewing every occurrence of a given word, together with some context.</li><li><strong>Collocations</strong>: A sequence of words that occur together unusually often, like red wine.</li><li><strong>Dispersion plot:</strong> I create a plot that shows the location of a word in the text (how many words from the beginning does it appear).</li><li><strong>Plotting the Frequency Distribution</strong>: I plot the 20 most common tokens.</li><li><strong>Common Contexts: </strong>Shows when the use of a list of words share the same surrounding words. I use the <a href="http://www.nltk.org/book/ch02.html">Reuters Corpus</a> from NLTK’s corpora and can see, for example, that August and June occur in several of the same surrounding words. For example, last August when and last June when.</li></ul><h4>2. Creating N-Grams for Language Classification (<a href="https://nbviewer.jupyter.org/github/nwams/NLTK-Hands-On-Tutorial/blob/master/2-Deriving-N-Grams-from-Text.ipynb">view code</a>)</h4><p>In this lesson I derive n-grams from text and categorize which language it belongs to. I’ll highlight some of the subjects that I cover:</p><ul><li>To demonstrate an understanding of the process, I dive deep into how to create a quad-gram, and flatten it into its proper format. I keep the top 300 most repeated quad-grams because starting at rank of 300 or so the N-gram frequency profile starts becoming specific to the topic. By the way, if you were wondering how to choose a value for “n” I touch on that in this Jupyter Notebook as well!</li><li>I derive bi-grams, tri-grams and quad-grams (for multiple values of n…for n = 1, 2, 3, 4) using NLTK’s <a href="https://tedboy.github.io/nlps/generated/generated/nltk.everygrams.html">everygrams</a> module.</li><li>I categorize French and English text using NLTK’s <a href="https://www.nltk.org/_modules/nltk/classify/textcat.html#TextCat.guess_language">guess_language</a> module.</li></ul><h4>3. Using Stop Words to Detect Language (<a href="https://nbviewer.jupyter.org/github/nwams/NLTK-Hands-On-Tutorial/blob/master/3-Detecting-Text-Language-by-Counting-Stop-Words.ipynb">view code</a>)</h4><p>Stop words are common words that add no additional meaning to text such as ‘a’, ‘the’, etc. We can use stop words to detect language as a simple way to find out what language a text is written in. In this segment I cover:</p><ul><li><strong>Exploring corpora</strong>: I explore NLTK’s <a href="https://www.nltk.org/book/ch02.html">stopwords</a> corpus which has a corpus of stop words from various languages. Corpus readers have a variety of ways to read data from a corpus like .words(), .raw(), and .sents()</li><li><strong>Classification</strong>: I start by computing language probability based on which stopwords are used. I do this by looping through the list of stop words in all of the languages. Then check how many stop words our tokenized text contains in each language. The text is finally classified based on the language in which it has the most stop words.</li></ul><h4>4. Identifying Language Using Word Bigrams (<a href="https://nbviewer.jupyter.org/github/nwams/NLTK-Hands-On-Tutorial/blob/master/4-Language-Identifier-Using-Word-Bigrams.ipynb">view code</a>)</h4><p>In this section I use bigrams, at the sentence level, to identify language. Here bigrams are basically a set of 2 co-occuring words within a given sentence. For example, for the sentence “The cow jumps over the moon” the bigrams would be:</p><pre>the cow<br>cow jumps<br>jumps over<br>over the<br>the moon</pre><p>In this section I demonstrate a few key things:</p><ul><li><strong>Step-by-step code demos to understand the process</strong>: I start by doing step-by-step code demonstrations before finally putting it all together and ultimately performing language classification. In order to demonstrate the process, I create a tokenizer, create unigrams and bigrams, and plot the frequency distribution, etc.</li><li><strong>Probability</strong>: I create a probability equation and give an in-depth breakdown explaining the math and the rationale.</li><li><strong>Classify</strong>: There are 3 training files. Each file contains meeting minutes from the same meeting but transcribed in different languages: English, French and Italian. Given a bigram and a language I calculate the probability that the bigram is of that language. Using the test data my classifier is able to predict the language with 98% accuracy.</li><li><strong>Confusion Matrix</strong>: I create a confusion matrix to visually evaluate the performance of the classifiers guessed languages versus the actual language.</li></ul><h4>5. Stemming, Lemmatization and Bigrams (<a href="https://nbviewer.jupyter.org/github/nwams/NLTK-Hands-On-Tutorial/blob/master/5-Stemming-Lemmatizing-and-Bigrams.ipynb">view code</a>)</h4><p>I work through examples on stemming, lemmatization and bigrams using NLTK. In this section I cover:</p><ul><li><strong>Explore the </strong><a href="http://www.nltk.org/book/ch02.html"><strong>Reuters</strong></a><strong> corpus</strong>:<strong> </strong>The Reuters Corpus contains 10,788 news documents from the Reuters financial newswire service, totaling 1.3 million words. The documents have been classified into 90 topics, and grouped into two sets, called “training” and “test”. This split is for training and testing algorithms that automatically detect the topic of a document.</li><li><strong>Word bigrams from the Reuters corpus</strong>: Remove stopwords and lowercase before creating bigrams. Create a frequency distribution and plot the 25 most common bigrams.</li><li><strong>Stemming</strong>: Stemming is the process of reducing inflected (or derived) words to their word stem. It usually refers to a crude heuristic process that chops off the ends of words. It reduces the size of the corpus that our model will work with (especially helpful when working with large datasets). Additionally, we are helping our model by <strong>explicitly</strong> correlating words that have similar meanings — this is beneficial in case our model is not be able to figure out which words are related by using context only. I code examples of a few stemming algorithms: Porter, Snowball and Lancaster; and I discuss the differences between them.</li><li><strong>Lemmatization</strong>: Lemmatization aims to achieve a similar base “stem” for a word, but it derives the proper dictionary root word, not just a truncated version of the word. I note the key differences and touch on how to determine whether you should perform stemming or lemmatization. Lemmatizing is slower than stemming because it uses WordNet (a large English dictionary) whereas stemming just follows predefined steps. And when lemmatizing you have to define the part-of-speech (POS) tag — noun, verb, adjective or adverb. My code demonstrates lemmatization based on it’s parts-of-speech using the nltk.stem WordNetLemmatizer() and the WordNet NLTK corpus reader.</li></ul><h4>6. Finding Unusual Words in a Given Language (<a href="https://nbviewer.jupyter.org/github/nwams/NLTK-Hands-On-Tutorial/blob/master/6-Finding-Unusual-Words-in-Given-Language.ipynb">view code</a>)</h4><p>This section demos how to find “unusual” within a text by using the <a href="http://www.nltk.org/book/ch02.html#fig-lexicon">nltk Wordlist corpus</a> and simply comparing the difference between my text and the words in the corpus. The nltk Wordlist corpus is just a newline-delimited list of dictionary words. It is a standard file located on any Unix operating systems. It’s used by some spell checkers and we can use the Words Corpus to find either unusual or mis-spelt words in our text.</p><h4>7. Creating a Part-of-Speech Tagger (<a href="https://nbviewer.jupyter.org/github/nwams/NLTK-Hands-On-Tutorial/blob/master/7-Creating-a-Part-of-Speech-Tagger.ipynb">view code</a>)</h4><p>Part-of-Speech tagging (or POS for short) is labelling each word with their appropriate Part-of-Speech such Noun, Verb, Adjective, Adverb, Pronoun, etc. These word classes (also known as lexical categories) are useful categories for many language processing tasks. In this notebook I train a classifier to determine which suffixes are most informative for POS tagging. Here are highlights from this section:</p><ul><li><strong>The Brown corpus</strong>: I train the POS tagger using the <a href="https://www.nltk.org/book/ch02.html#tab-brown-sources">Brown</a> corpus because it consists of about 1 million words of American English that was painstakingly tagged with part-of-speech markers.</li><li><strong>Feature Extraction</strong>: Before starting training a classifier, we must agree first on what features to use. I use the <strong>2-letter suffix</strong> and the <strong>3-letter suffix</strong>. The 2-letter suffix is a great indicator of past-tense verbs, ending in “-ed”. And the 3-letter suffix helps recognize the present participle ending in “-ing”. I’d like to note that we can do better by also looking at the word itself, the word before and the word after. However, for the scope of this project we’ll move forward with just the suffixes.</li><li><strong>Decision Tree Classifier</strong>: I do an 80/20 split and train a <a href="https://www.nltk.org/book/ch06.html#sec-decision-trees">Decision Tree Classifier from NLTK</a> resulting in a 62% accuracy, which is not great. To improve the classifier, if we worked with tagged sentences instead of tagged words we can add more contextual features as I mentioned before, like the word itself, the word before and the word after. As well as the previous tag!</li><li><strong>Pseudocode</strong>: Decision tree’s are fairly easy to interpret and NLTK makes it easy to print out the decision tree’s steps as pseudocode. I explain the tagger’s pseudocode step-by-step down to 4 levels.</li></ul><h4>8. Part-of-Speech and Meaning (<a href="https://nbviewer.jupyter.org/github/nwams/NLTK-Hands-On-Tutorial/blob/master/8-Parts-of-Speech-and-Meaning.ipynb">view code</a>)</h4><p>In this section I explore and code for the following topics:</p><ul><li><strong>WordNet</strong>: <a href="https://wordnet.princeton.edu/">WordNet</a> is a large English dictionary in the form of a <a href="http://davidvandegrift.com/blog?id=62">semantic graph</a> a.k.a. semantic network. In NLTK WordNet is just another corpus reader. It groups English words into sets of synonyms called <strong>synsets</strong>. A synset is a set of synonyms that share a common meaning. I also explore hypernym’s, hyponyms and antonyms. A hypernym is a word with a broad meaning constituting a category into which words with more specific meanings fall (e.g. color is a hypernym of red). A hyponym is a word of more specific meaning than a general or superordinate term applicable to it (e.g. spoon is a hyponym of cutlery).</li><li><strong>Similarity</strong>: I use the <a href="http://www.nltk.org/howto/wordnet.html">Wu-Palmer</a> score to determine how similar two word senses are. This score is based on the distance between the words in the semantic graph.</li><li><strong>Chunking</strong>: I created a Noun Phrase chunker using NLTK’s <a href="https://www.nltk.org/api/nltk.chunk.html">RegexpParser</a>. I defined the regex “rules” that tell the sentences when chunking should happen.</li><li><strong>Named Entity Recognition</strong>: I performed named entity recognition on a sentence using NLTK’s <a href="https://www.nltk.org/book/ch07.html#named-entity-recognition">ne_chunk</a>. The goal of entity recognition is to detect entities such as Person, Location, Time, etc. The most commonly used types of named entities are: Organization, Person, Location, Date, Time, Money, Percent, Facility and Geo-political entities such as city, state and country.</li></ul><h4>9. Eminem, Akon &amp; NLP — PROJECT (<a href="https://nbviewer.jupyter.org/github/nwams/NLTK-Hands-On-Tutorial/blob/master/9-Eminem%2C%20Akon%20%26%20NLP.ipynb">view code</a>)</h4><p>In this last (but not least) part of the NLTK Hands-On Tutorial I use NLTK to perform stemming, lemmatiziation, tokenization, stop word removal <a href="https://genius.com/a/akon-explains-how-eminem-treats-recording-music-like-a-nine-to-five-job">this dataset</a> where “<em>Akon explains how Eminem treats recording music like a nine-to-five job”</em>. I gather the data by scraping it from Genius.com and use it as my dataset. I pre-process the text, stem using the Porter stemmer and I wrote a mapping function to convert NLTK’s <a href="https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html">Treebank</a> tags to WordNet’s <a href="http://www.nltk.org/_modules/nltk/corpus/reader/wordnet.html">part-of-speech constants</a> so that I can proceed with using the WordNet <a href="https://www.nltk.org/_modules/nltk/stem/wordnet.html">lemmatizer</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4884f60416c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nwamaka-imasogie/nlp-terminology-and-pre-processing-4884f60416c5">NLP Terminology and Pre-Processing</a> was originally published in <a href="https://medium.com/nwamaka-imasogie">Nwamaka Imasogie’s Machine Learning and Artificial Intelligence Projects</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stand-Up Comedy and NLP]]></title>
            <link>https://medium.com/nwamaka-imasogie/stand-up-comedy-and-nlp-c7d64002520c?source=rss----c1856a20555a---4</link>
            <guid isPermaLink="false">https://medium.com/p/c7d64002520c</guid>
            <category><![CDATA[machine-learning-projects]]></category>
            <category><![CDATA[data-science-projects]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Nwamaka Imasogie]]></dc:creator>
            <pubDate>Thu, 25 Jul 2019 05:39:28 GMT</pubDate>
            <atom:updated>2019-10-24T18:46:38.659Z</atom:updated>
            <content:encoded><![CDATA[<p>This natural language processing python project started from this tutorial <a href="https://www.youtube.com/watch?v=xvqsFTUsOmc">https://www.youtube.com/watch?v=xvqsFTUsOmc</a>. This project started because the instructor, Alice Zhao, saw a stand-up comedian for the first time and she really loved it. But she wanted to figure out what makes <a href="https://www.imdb.com/title/tt5066574/?ref_=nm_knf_i1">Ali Wong’s routine</a> different than other comedians.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9YgP3LT62Ryl61h_005Zrg.png" /></figure><p>Here’s my <a href="https://github.com/nwams/nlp-stand-up-comedy">GitHub repo</a> if you’d like to follow along as I go. In order to display the full contents of an .ipynb file I recommend copy/pasting the link into <a href="https://nbviewer.jupyter.org/">NBViewer</a>.</p><p>This project uses several NLP libraries including NLTK, TextBlob, and gensim, as well as standard machine learning libraries like pandas and scikit-learn.</p><p>I’ll be using the the Jupyter Notebook IDE from the <a href="https://www.anaconda.com/distribution/">Anaconda Distribution</a>. I will post the entire Jupyter Notebook at the end of this blog as well as code snippets that you can follow along with as I go. There are a few python packages I will be using that are not included in Anaconda: wordcloud, textblob and gensim. They can be installed with the following commands:</p><pre>conda install -c conda-forge wordcloud</pre><pre>conda install -c conda-forge textblob</pre><pre>conda install -c conda-forge gensim</pre><h4>In this end-to-end project I will:</h4><ol><li>Start with a question</li><li>Get and clean the data</li><li>Perform exploratory data analysis</li><li>Apply NLP techniques</li><li>Share insights</li></ol><h3>1. Start with a Question</h3><p>The goal is to look at transcripts of various comedians and note their similarities and differences. Specifically, I’m trying to determine how Ali Wong’s comedy style is different than other comedians.</p><h3>2. Data Gathering and Cleaning [<a href="https://nbviewer.jupyter.org/github/nwams/nlp-stand-up-comedy/blob/master/1-Data-Cleaning.ipynb">Notebook w/code</a>]</h3><h4>Gathering the Transcript</h4><p>I need to get the transcript from her Netflix special called “Baby Cobra”. But how/where do we get the transcript? Doing a Google search for her transcript shows that a site called <a href="https://scrapsfromtheloft.com/">Scraps from the Loft</a> has full transcripts of several comedians’ routines as well as <a href="http://scrapsfromtheloft.com/2017/09/19/ali-wong-baby-cobra-2016-full-transcript/">Ali Wong’s</a>.</p><p>When I inspect the elements using Chrome Developer Tools I can see that all of the transcript data is in the &lt;div class=“post-content”&gt;. Here’s a screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tu55ELv0S7kKGoSGGbvETQ.png" /></figure><p>Defining the scope of a machine learning project is a very important step. So in deciding how much data to gather, the scope will be limited to the following criteria:</p><ol><li>Comedy specials within the past 5 years.</li><li>Use only comedy specials that have an <a href="https://www.imdb.com/?ref_=nv_home">IMDB</a> rating of at least 7.5 stars and 2000+ votes.</li><li>Select the top 12 stand-up comics (this is where domain expertise is crucial. If you’re not sure you should do a sanity check with someone who knows the industry well).</li></ol><p>In order to gather this data I will have to scrape the website. I will use the <a href="https://3.python-requests.org/">Requests</a> package to get info from the website and the <a href="https://pypi.org/project/beautifulsoup4/">Beautiful Soup</a> package to extract portions of the site.</p><p>Here is the code snippet for gathering the data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80cc3cc9934422b18aad9abf3d115587/href">https://medium.com/media/80cc3cc9934422b18aad9abf3d115587/href</a></iframe><p>Next, I created a dictionary named data where every key is a comedian and every value is the transcript.</p><p>I need the output in a clean and organized format that I can use for further analysis so I will be creating 1) a <strong>Corpus </strong>and 2) a <strong>Document-Term Matrix</strong>. A Corpus is a collection of text and a Document-Term Matrix is just word counts in a matrix format.</p><h4>Creating a Corpus</h4><p>In the code I go through a few steps to create a dictionary with the format {key: comedian, value: string} and then I convert it to a Pandas DataFrame. All of this can be found in the Jupyter Notebook.</p><p>Now on to the next step, cleaning the data! Why perform these cleaning steps? Because I want the computer to try to understand only the most important parts of the text.</p><p>Here are some common data cleaning steps that are usually done on all text:</p><ul><li>Make text lower case</li><li>Remove punctuation</li><li>Remove stop words</li><li>Remove numerical values</li><li>Remove common non-sensical text, like newline characters /n</li><li>Tokenize the text</li></ul><p>Below is a code snippet that shows how to clean the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa6ea06607d1f0eb2d8f2676ff9b968d/href">https://medium.com/media/fa6ea06607d1f0eb2d8f2676ff9b968d/href</a></iframe><p>Here is my corpus:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xL-HvQ5hLYxXU1Vadwbxxw.png" /></figure><h4>Creating a Document-Term Matrix</h4><p>Let’s walkthrough this concept using a line from <a href="http://scrapsfromtheloft.com/2017/08/02/john-mulaney-comeback-kid-2015-full-transcript/">John Mulaney’s routine</a>:</p><blockquote>“All right, Petunia. Wish me luck out there. You will die on August 7th, 2037.”</blockquote><p>How can a computer read this text? I will need to 1) clean it 2) tokenize it and 3) put it into a matrix.</p><p>Remember in the section above I did some initial cleaning by removing punctuation, remove numbers and making all letters lowercase. After the first pass at cleaning it now looks like this:</p><blockquote>“all right petunia wish me luck out there you will die on august”</blockquote><p>Now I will <strong>tokenize</strong> the text. Tokenization means splitting the text into smaller parts. Tokenization can be done as sentences, bi-grams or words. I will tokenize by ‘words’, so that every word will be its own item:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hF-7f8HjwV7r91JD7M8TwA.png" /></figure><p>Now I will remove <strong>stop words</strong> — words with very little meaning…like ‘a’, ‘the’, and ‘it’. After removing the stop words I’m left with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y-_vhYiRlCEBafe-yrnQ2A.png" /></figure><p>More simply put I’m left with just the following words:</p><blockquote>right petunia wish luck die august</blockquote><p>This is called a <strong>bag of words</strong> model. Bag of words is just a group of text where the order doesn’t matter. It’s a simple and powerful way to represent text data!</p><p>Now using this I can create a <strong>Document-Term Matrix</strong> that counts the occurrence of words used by each comedian.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82RzsPQLQUdfaZIRxKeNDQ.png" /></figure><ul><li>The numbers are word counts</li><li>Each row is a different document (or “transcript” for our case)</li><li>Each column is a different term (or “word” for our case)</li></ul><p>Here’s a code snippet below of the process of creating a document-term matrix. Let’s use scikit-learn’s CountVectorizer to tokenize and remove stop words.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6130662eed986e19a168e4ea5098851/href">https://medium.com/media/c6130662eed986e19a168e4ea5098851/href</a></iframe><p>Here’s a screenshot of the actual document term matrix. Notice that is has over 7,000 columns so it’s quite long. And it would be even longer if we had included bi-grams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n5G0pav0EmZJMcULZ2WO5A.png" /></figure><p>If we wanted to further clean the text, after tokenization, there are more steps we could take. <strong>Stemming / lemmatization </strong>which is grouping words like “driving, drive, drives” as the same. We could do <strong>Parts of speech tagging</strong>, create <strong>bi-grams </strong>like turning “thank you” into one term<strong> </strong>and also <strong>deal with typos</strong>, etc.</p><h3>3. Exploratory Data Analysis [<a href="https://nbviewer.jupyter.org/github/nwams/nlp-stand-up-comedy/blob/master/2-Exploratory-Data-Analysis.ipynb">Notebook w/code</a>]</h3><p>Here’s the fun part! The goal of EDA is to summarize the main characteristics of the data, which will help us to determine if the trends make sense. It’s often best to do this visually. And it’s best to do EDA before applying machine learning algorithms.</p><p>I’m going to start by looking at the most common words used most by each comedian. I’ll also look at the size of their vocabulary because it would be interesting to see if some comedians have a higher vocabulary than others. And lastly I’ll explore the amount of profanity (this came after I saw the top words. You’ll notice that the comedians use a lot of cuss words).</p><p>Here we go!</p><h4>Top Words</h4><p>Sort across the document-term matrix to find the top words. And visualize the data using <a href="http://amueller.github.io/word_cloud/">word clouds</a>. *As mentioned in the beginning of this blog the Word Cloud package is not included in Anaconda, so you’ll have to download it using this command: conda install -c conda-forge wordcloud.</p><p>I looked at the top 30 words said, per each comedian, along with a count of how many times it was said. I noticed that there were a lot of non-meaningful words such as “like”, “im”, and “know” amongst all comedians. The picture below of the top 15 words said by each comedian shows that a lot of stop words are included.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5HAU71YBKftSmACOjMWW4Q.png" /><figcaption>Top 15 words said by each comedian.</figcaption></figure><p>If these common words occur as top words by more than 50% of the comedians, then I’ll add those words to the list of stop words. Therefore I will be adding these to the list of stop words: [‘like’, ‘im’, ‘know’, ‘just’,‘dont’, ‘thats’, ‘right’, ‘people’, ‘youre’, ‘got’, ‘time’, ‘gonna’, ‘think’, ‘oh’, ‘yeah’, ‘said’].</p><p>After recreating a new document term matrix that includes the additional stop words, I made a word cloud to visualize the most common words for each comedian.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1L0dHHVz9e6nxIrux8Kelg.png" /></figure><p>Notice that Ali Wong says the S-word a lot, as well as ‘ok’ and ‘husband’. The instructor of this tutorial resonates with this because she says ‘ok’ a lot too and thinks her routine is funny because she also talks about her husband a lot too.</p><p>You’ll also notice that a lot of people say the F-word a lot, which we’ll also explore in a bit.</p><h4>Number of Words</h4><p>I want to see how big of a vocabulary they have so I’ll count how many unique words they use. But another thing that I’ll look at is the number of words-per-minute based on how long their entire comedy special was.</p><p>Here’s a pandas dataframe that shows the unique_words and the words_per_minute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bH44OIdigf9zeCGVrVc1AA.png" /></figure><p>I like to begin visualizing in the simplest ways possible first. So I’ll create a simple horizontal bar plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZ0WfV6WNgohj72GAqonCw.png" /></figure><p>I can see that Ricky and Bill have a the highest vocabulary while Anthony has the lowest vocabulary. Additionally I can see that Joe Rogan talks the fastest while Anthony talks the slowest. But this visualization doesn’t yield any particularly interesting insights regarding Ali Wong, so let’s move on.</p><h4>Profanity</h4><p>Remember in the word cloud above I noted that people say the F-word and the S-word a lot so I’m going to dive deeper into that by making a scatter plot that shows F-word and S-word usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8a4O8MEkrD9vy9pBuFsZjg.png" /></figure><p>Notice that Bill Burr, Joe Rogan, and Jim Jefferies use the F-word a lot. The instructor doesn’t like too much profanity so that might explain why she’s never heard of these guys. She likes clean humor so profanity could be a good indicator of the type of comedy she likes. Besides Ali Wong, her other two favorite comedians are John Mulaney and Mike Birbiglia. Notice how John and Mike are also very low on the use of profanity (Mike actually doesn’t use any S-words or F-words at all).</p><p>Remember that the goal of Exploratory Data Analysis is to take an initial look at the data to see if it makes sense. There’s always room for improvement like more intense clean up including more stop words, bi-grams etc. However perfection can serve to your disadvantage. The results, including profanity, are interesting and in general it makes sense. Since the science of machine learning is an iterative process, it’s best to get some reasonable results early on to determine whether your project is going in a successful direction or not. Delivering tangible results is key!</p><h3>4. Apply NLP Techniques</h3><h3>Sentiment Analysis [<a href="https://nbviewer.jupyter.org/github/nwams/nlp-stand-up-comedy/blob/master/3-Sentiment-Analysis.ipynb">Notebook w/code</a>]</h3><p>Because order is important in sentiment analysis I will use the corpus, not the document-term matrix. I will use <a href="https://textblob.readthedocs.io/en/dev/">TextBlob</a>, a python library that provides rule-based sentiment scores.</p><p>For each comedian I will assign a <strong>polarity</strong> score that tells how positive or negative they are and a <strong>subjectivity</strong> score that tells how opinionated they are.</p><p>But before we jump into using the TextBlob module it’s important to understand what’s happening in the code, let’s take a look…</p><p>Under the hood: A linguist named Tom De Smedt created a lexicon (<a href="https://github.com/sloria/TextBlob/blob/eb08c120d364e908646731d60b4e4c6c1712ff63/textblob/en/en-sentiment.xml">en-sentiment.xml</a>) where he manually assigned adjective words with polarity and subjectivity values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHKaYFueVJFcAkXlCsdOkw.png" /><figcaption>Subjectivity lexicon for English adjectives.</figcaption></figure><p>*From the image above, note that <a href="https://wordnet.princeton.edu/">WordNet</a> is a large English dictionary created by Princeton.</p><p>I will output a polarity score which tells how positive/negative they are, and a subjectivity score which tells how opinionated they are.</p><p>From the <a href="https://github.com/sloria/TextBlob/blob/eb08c120d364e908646731d60b4e4c6c1712ff63/textblob/_text.py">_text.py file in TextBlob’s github</a> there’s a section that defines the following: Words have a polarity (negative/positive of -1.0 to +1.0) and a subjectivity (objective/subjective of +0.0 to +1.0). The part-of-speech tags (pos) tags “NN”=noun and “JJ”=adjective. And the reliability specifies if an adjective was hand-tagged (1.0) or inferred (0.7). Negation words (e.g., “not”) reverse the polarity of the following word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6c4tUUK0kCjnC9qusMq_6g.png" /></figure><p>I use the corpus during my sentiment analysis, not the document-term matrix, because order matters. For example, “great”=positive but “not great”=negative.</p><p>TextBlob handles negation by multiplying the polarity by -0.5. And handles modifier words by multiplying the subjectivity of the following word by 1.3. Since “great” has a subjectivity of 0.75, “very great” will have a subjectivity of 0.975 which is just 0.75*1.3.</p><p>Notice that the word “great” occurs in the <a href="https://github.com/sloria/TextBlob/blob/eb08c120d364e908646731d60b4e4c6c1712ff63/textblob/en/en-sentiment.xml">lexicon</a> 4 times. In this situation textBlob will just take the average of the 4 scores. This is very basic and there’s nothing fancy or advanced happening here behind the scenes. So this is why it’s important for us to know what’s happening behind the scenes before we use a module.</p><p>Overall, TextBlob will find all of the words and phrases that it can assign a polarity and subjectivity score to, and it averages all of them together. So at the end of this task each comedian will be assigned <strong>one polarity score</strong> and <strong>one subjectivity score</strong>.</p><p>However be aware that this rules-based approach that TextBlob uses is not the most sophisticated, but it is a good starting point. There are also other statistical methods out there like Naive Bayes.</p><p>After creating a simple Sentiment Analysis scatter plot of the Polarity and the Subjectivity, I can see that Dave Chappelle’s routine is the most negative out of them all. And John Mulaney is most similar to Ali Wong, while Ricky Gervais isn’t too far away either.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*hhK-L3FwzGeMqKTQ-mKxyg.png" /></figure><p>In addition to the overall sentiment, it would also be interesting to also look at the sentiment over time throughout each routine. So I’ll split each comedian’s routine into 10 chunks and assess their polarity pattern to see if I can draw additional insights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WO3WFGm-JN350-qXIeo_Pw.png" /></figure><p>Ali Wong remained consistently positive throughout her routine. Louis C.K. and Mike Birbiglia are similar to her.</p><h3>Topic Modeling [<a href="https://nbviewer.jupyter.org/github/nwams/nlp-stand-up-comedy/blob/master/4-Topic-Modeling.ipynb">Notebook w/code</a>]</h3><p>Now I’d like to find themes across various comedy routines, and see which comedians tend to talk about which themes. In other words I want to see what topics are being said in this document. I will use the document-term matrix because order doesn’t matter, thus the bag-of-words model is a good starting point.</p><p>I will be using the <a href="https://github.com/RaRe-Technologies/gensim">gensim</a> library, a Python toolkit built specifically for topic modeling, to apply a popular topic modeling technique called Latent Dirichlet Allocation (LDA). LDA is one of many topic modeling techniques. Also I will be using nltk for parts-of-speech tagging.</p><p><strong>What is LDA and how does it work?</strong></p><p>Latent means hidden and Dirichlet is a type of probability distribution, so I’m looking at the probability distribution in the text in order to find hidden topics. LDA is an unsupervised algorithm. You’ll find that LDA is really useful when you have really large documents and have no idea what they’re about.</p><p>Here are two simple but important definitions. Every <strong>document</strong> consists of a mix of <strong>topics</strong>. And every <strong>topic</strong> consists of a mix of <strong>words</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fz7E-amdBJE6owJKl3VHrQ.png" /></figure><p>The goal is for LDA to learn what all of the topics in the document and what are all of the words in each topic.</p><p>Every topic is a probability distribution of words, something like this:</p><ul><li>Topic A: 40% banana, 30% kale, 10% breakfast…</li><li>Topic B: 30% kitten, 20% puppy, 10% frog, 5% cute…</li></ul><p>Here’s a visual summary of what LDA is about:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZgQPCBuxf5rtx1fPF5FH-Q.png" /></figure><p>Here’s how LDA works:</p><ol><li>You choose the number of topics you think are in your corpus (Example: K=2)</li><li>LDA randomly, and temporarily assigns each word in each document to one of the 2 topics (The word ‘banana’ in Document #1 is randomly assigned to Topic B the animal-like topic).</li><li>LDA will go through every word &amp; its assigned topic and it will update the topic assignments. So let’s say ‘banana’ is assigned to the Animal topic. It will decide whether it should re-assign it to the Food topic by first checking how often the Animal topic occurs in the document, then secondly it will check how often the word ‘banana’ occurs in the Animal topic. Both of those probabilities are low so it will re-assign ‘banana’ to the other Food topic. Here’s the math behind it:<br>Proportion of words in document d that are currently assigned to topic. <br>t = p(topic t | document d). <br>And Proportion of assignments to topic t over all documents that come from this word. <br>w=p(word w | topic t). <br>Multiply those two proportions and assign <strong><em>w</em></strong> a new topic based on that probability. <br>p(topic t | document d)*p(word w | topic t).</li><li>You have to go through multiple iterations of previous step. Go through a few dozen iterations yourself and eventually the topics should start making sense. If the topics don’t make sense then more data-cleaning is needed.</li></ol><p>The Gensim package will do steps 2 and 3 for you. It is up to you to set the number of topics you want (step 1), and how many iterations you want to go through (step 4).</p><p>Gensim will output the <strong>top words in each topic</strong>. It’s your job as a human to interpret the results to figure out what the topics are. If not, try altering the parameters, either: Terms in the document-term matrix, number of topics, iterations, etc. <strong>Stop when you’re able to come up with topics that make sense.</strong></p><h4>Topic Modeling with All of the Text</h4><p>In my first attempt I set the number of topics to 2, and the number of times the algorithm will pass over the whole matrix to 10. I then trained the LDA Model using <strong>all</strong> of the words from my term-document matrix. I’ll start by setting the number of topics to 2, assess, and then increment if needed.</p><p>These are the words output from the LDA model when number of topics is 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fcqNFKRjlTYrb5Zt-LQ6sw.png" /></figure><p>It’s not making sense yet and there’s overlap in the words. Here’s the output when number of topics is 3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V1afx7KqjDjOd_PHg5DOew.png" /></figure><p>It’s not quite making sense yet. Let’s increment again by setting the number of topics to 4 to see if it improves:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tDKRQbTF2Ad4q_reyUfnxQ.png" /></figure><p>These topics aren’t too meaningful.</p><h4>Topic Modeling with Nouns</h4><p>One popular technique is to only look at terms that are from one part of speech. So I’ll try modifying the bag of words to include only <strong>nouns</strong>. The results below are from trying 2, 3 and 4 topics respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpNMPB55sMWF7wE9BxYE7w.png" /></figure><p>Again, there isn’t much improvement and there’s still overlap.</p><h4>Topic Modeling with Nouns and Adjectives</h4><p>So in this next attempt I will add <strong>adjectives</strong>. My LDA model will now assess nouns and adjectives. The results are below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9jda0KUWPnVNrbVbc-uBQ.png" /></figure><p>As you can see there still isn’t much improvement. So I experimented with tuning the hyper-parameters, increasing the number of passes from 10 to 100. And setting <em>alpha</em> and <em>eta</em> values. For<em> alpha</em> I experimented with really low values as well as symmetric and auto. For <em>eta</em> I experimented with low values in an attempt to get less “overlap” between topics.</p><p><em>Alpha</em> and <em>eta</em> are hyper-parameters in Gensims LdaModel that I can tune.</p><p>A high <em>alpha</em> value means that every document is likely to contain a mixture of most of the topics, not just any single topic specifically. While a low <em>alpha</em> value means that a document is more likely to be represented by just a few of the topics.</p><p>A high <em>eta</em> value means that each topic is likely to contain a mixture of most of the words, not just any specific word. While a low <em>eta</em> value means a topic is more likely to contain a mixture of just a few of the words.</p><p>Simply put a high <em>alpha</em> will make documents appear more similar to each other. And a high <em>eta</em> will make topics appear more similar to each other.</p><p>Unfortunately tuning the hyper-parameters did not yield any meaningful topics. I also tried including <strong>verbs</strong> and retraining the model with nouns, adjectives and verbs but that didn’t help it either.</p><h4><strong>Why my data isn’t ideal for Topic Modeling</strong></h4><p>The model assumes that every chunk of text that we feed into it contains words that are somehow related. So starting with the right corpus is crucial. However, comedy specials are inherently dynamic in nature with no fixed topics in most streams. Since the subject matter is constantly switching throughout a comedian’s routine there usually isn’t one centralized topic. Whereas, in contrast, if we trained our LDA model with Wikipedia articles, each article (document) is already highly contextualized as it usually talks about a single topic, which is a good thing. It’s also good to note that the number of documents per topic is also important. LDA is extremely dependent on the words used in a corpus and <strong>how frequently they show up</strong>.</p><h3>Wrapping Up</h3><p>In this project I did Text Pre-Processing, Exploratory Data Analysis, Sentiment Analysis, and Topic Modeling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uKRgMp8vzRUrG5ylmNyPUw.png" /></figure><h3><strong>NLP Libraries</strong></h3><p>Here are some popular NLTK libraries to be aware of and some brief details.</p><ul><li>NLTK — <strong>This is the library that everyone starts with</strong>. It has a lot of text-pre-processing capabilities like tokenization, stemming, parts-of-speech tagging, etc.</li><li>TextBlob — This was built on top of NLTK, is <strong>easy to use</strong>, and includes some additional functionality like sentiment analysis and spell check.</li><li>Gensim — This library was built <strong>specifically for topic modeling</strong> and include multiple techniques including LDA and LSI. It can also calculate document similarity.</li><li>SpaCy — This is the newest of the bunch and is known for its <strong>fast performance</strong> since it was written in <a href="https://cython.org/">Cython</a>. It can do a lot of things that NLTK can do.</li></ul><h3>5. Summary of Insights</h3><p>Remember the original question the instructor wanted to answer was “What makes Ali Wong’s comedy routine stand out?”</p><ul><li>Ali talks about her husband a lot, and the instructor also talks about her husband a lot during her lectures.</li><li>In terms of profanity, Ali had the highest s-word to f-word ratio. The instructor doesn’t mind the s-word but does not like hearing the f-word at all.</li><li>Ali Wong tends to be more positive and less opinionated, which is similar to the instructors personality as well.</li></ul><p>Based on these findings, who are some other comedians the instructor might like?</p><ul><li>Comedians who don’t say the f-word that often: Mike Birbiglia (no curse words at all) and John Mulaney.</li><li>Comedians with a similar sentiment pattern: Louis C.K. and Mike Birbiglia.</li></ul><p><a href="https://www.imdb.com/title/tt2937390/?ref_=fn_al_tt_1">Mike Birbiglia</a> is a comedian that she’d probably like as well!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7d64002520c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nwamaka-imasogie/stand-up-comedy-and-nlp-c7d64002520c">Stand-Up Comedy and NLP</a> was originally published in <a href="https://medium.com/nwamaka-imasogie">Nwamaka Imasogie’s Machine Learning and Artificial Intelligence Projects</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>