<?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[Stories by Jordan on Medium]]></title>
        <description><![CDATA[Stories by Jordan on Medium]]></description>
        <link>https://medium.com/@jmyers.xyz?source=rss-3881d68a1fc5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0sc19Sw5Rpufn4FSTu3w-w.png</url>
            <title>Stories by Jordan on Medium</title>
            <link>https://medium.com/@jmyers.xyz?source=rss-3881d68a1fc5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:58:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jmyers.xyz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Sentiment analysis for movie reviews using classical and deep learning]]></title>
            <link>https://medium.com/@jmyers.xyz/sentiment-analysis-for-movie-reviews-using-classical-and-deep-learning-9aa1183c9825?source=rss-3881d68a1fc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aa1183c9825</guid>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Jordan]]></dc:creator>
            <pubDate>Sun, 08 May 2022 17:23:02 GMT</pubDate>
            <atom:updated>2022-05-08T17:23:02.898Z</atom:updated>
            <content:encoded><![CDATA[<h4>Comparing a classical machine learning approach and a deep learning transformer model approach for categorizing movie/tv reviews into positive, negative, or irrelevant classes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GOPTnOrPJRm33RoTXsKwiQ.png" /><figcaption>Approximately what we’re trying to analyze sort of… 😋</figcaption></figure><p>As we are people with innate linguistic intuitions, the task of dividing something like tv/movie reviews into positive or negative reviews may seem easy, maybe even trivial. Given its trivial nature, imagine being<em> assigned</em> to classify millions of movie reviews. Now, a once singularly easy task has become <em>unmanageable and unruly</em>. Computers do not possess this same innate linguistic intuition, so how can we leverage modern advancements in artificial intelligence, specifically natural language processing, to do the heavy lifting of this task for us?</p><h3>The Task</h3><p>Continue to imagine this scenario where you are assigned to classify tv/movie reviews ad nauseum.</p><p>This task requires you categorize those reviews into <em>three categories</em>:</p><ul><li><strong>Not a TV/Movie Review</strong> (represented by a 0)</li><li><strong>A Positive TV/Movie Review</strong> (represented by a 1)</li><li><strong>A Negative TV/Movie Review</strong> (represented by a 2)</li></ul><p>Now, we’re going to be training the machine learning models to do this task for us, so we need a dataset that represents some of this work already done for us.</p><p>Specifically, we have a csv file (<strong><em>train.csv</em></strong>) containing 3 columns:</p><ul><li><strong>ID</strong> : A unique ID associated with movie review</li><li><strong>TEXT</strong> : The actual text of the review.</li><li><strong>LABEL</strong> : The label for the category (0,1,2 corresponding with the categories mentioned above)</li></ul><p>Additionally, we have another csv file (<strong><em>test.csv</em></strong>) containing only 2 columns, the ID and TEXT. This conceptually represents the task of having to categorize the reviews ourselves.</p><p>After training our models, we will predict the categories associated with those reviews and submit that to whomever assigned us this task.</p><p>This data is a modified version of this dataset:</p><pre><a href="http://twitter.com/inproceedings">@inproceedings</a>{pang-lee-2004-sentimental,<br> title = “A Sentimental Education: Sentiment Analysis Using Subjectivity Summarization Based on Minimum Cuts”,<br> author = “Pang, Bo and Lee, Lillian”,<br> booktitle = “Proceedings of the 42nd Annual Meeting of the Association for Computational Linguistics ({ACL}-04)”,<br> month = jul,<br> year = “2004”,<br> address = “Barcelona, Spain”,<br> url = “<a href="https://aclanthology.org/P04-1035">https://aclanthology.org/P04-1035</a>&quot;,<br> doi = “10.3115/1218955.1218990”,<br> pages = “271–278”,<br>}</pre><p>To accomplish this task, I’ll be comparing a few methods and then opting for the approach that yields the greatest performance.</p><h3>Exploratory Data Analysis</h3><p>To begin, we need a way to work with this data.</p><p>We can use the python library <em>pandas</em> to read the <strong><em>train.csv</em></strong> into a useable format called a <em>DataFrame</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/244abb9b6c6dfc81d1185ae7fea2464f/href">https://medium.com/media/244abb9b6c6dfc81d1185ae7fea2464f/href</a></iframe><p>Then we can begin some exploratory analysis.</p><p>Let’s start by observing some key properties:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6991b4a674ca438ecb465544371b981e/href">https://medium.com/media/6991b4a674ca438ecb465544371b981e/href</a></iframe><p>Output:</p><pre>Total rows: 70187<br>Empty values in column ID: 0<br>Empty values in column TEXT: 7<br>Empty values in column LABEL: 0</pre><pre>Number of Irrelevant Reviews 35000<br>Number of Positive Reviews 17645<br>Number of Negative Reviews 17542</pre><pre>Avg Length of Irrelevant Reviews 426.21105714285716<br>Avg Length of Positive Reviews 1332.3479739302918<br>Avg Length of Positive Reviews 1298.990822027135</pre><p>From this it appears that we have a roughly even split of tv/movie reviews and irrelevant reviews. Among tv/movie reviews we have another even split between positive and negative reviews.</p><p>We have seven empty values in the TEXT column. That’s a pretty small portion, but just to be safe, let’s fill them with empty strings that we can still pass into our models.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6468e9b23b7e407ed00530144830d99a/href">https://medium.com/media/6468e9b23b7e407ed00530144830d99a/href</a></iframe><p>We should also take a peak at some random samples from each class.<br>I’ll highlight a few here:</p><h4>The Irrelevant:</h4><blockquote>This was a pretty good book. I only wish i did not have to buy 2 more to finish it…..</blockquote><p>Irrelevant reviews seem to frequently mention other products apart from movies/tv. In this case, this review mentioned books.</p><h4>The Positive:</h4><blockquote>No music. No stupid masala. A reasonably realistic portrayal of the police system in India and based on a real “encounter” specialist in India, Daya Nayak. That is Ab Tak 56 (56 symbolises how many criminals the lead “Sadhu Agashe” has killed” — well you already know that bit)Brilliance exudes Nan Patekar in the role as a relaxed and calculating Indian cop. THe one liners are just hilarious. The plot though slightly predictable on review, is intriguing all the same. Another one of the films from Ram Gopal Vermas The Factory. Movies which are either decent or really good, Ab Tak CHappan meanders close to very good. But yet remains one of the Top 70 films released from India, commercial and artsy included.</blockquote><blockquote>What is great is the story telling is relaxed and showcases finally (in an Indian flick) how the police network works. The cast is really damn good but seriously the one liners are funny as hell (though i dont know if the subtitled version will appear as funny) The producers are trying for a Cannes release, which is interesting.</blockquote><blockquote>Made by debut director Shamit Aman (i think thats his name).</blockquote><blockquote>… continued …</blockquote><p>Immediately the length discrepancy we observed earlier is clear (and I’ve specifically chosen a shorter sample to share and crop my selections too).</p><p>In the positive we see many positive sentiment adjectives and adverbs: <em>reasonably</em>, <em>brilliance</em>, <em>hilarious</em>, <em>good</em>, etc..</p><h4>The Negative:</h4><blockquote>I gave this a 3 out of a possible 10 stars.</blockquote><blockquote>Unless you like wasting your time watching an anorexic actress, in this film it’s Carly Pope, behaving like a ditz, don’t bother.</blockquote><blockquote>Carly Pope plays Sara Novak, a young college student, who becomes intrigued with a game of riddles, that leads her down into subway tunnels underneath the city — a dangerous thing for even a well-armed man to go in alone.</blockquote><blockquote>There are various intrigues in the film</blockquote><blockquote>… continued …</blockquote><p>Similar to the positive, we see a much longer review than non-movie reviews.</p><p>Here we see negative sentiment phrases like <em>wasting your time</em> and probably most importantly the imperative <em>don’t bother</em>.</p><p>Additionally, both positive and negative samples contain <em>ratings</em> and therefore I posit that higher numbers like <em>7</em> could lean towards classifying something as positive, while the presence of a number like <em>3</em> could lean towards classifying as negative. This of course depends on our tokenization strategy and whether or not we even include single digit numbers.</p><p>Overall, it seems it will be much easier to distinguish between irrelevant and relevant reviews than it is for positive and negative. This is due to the major differences and length, format, and content between irrelevant and relevant reviews.</p><p>However, between positive and negative, the qualities of length, format, and content are all similar. We will instead have to rely on finding these characteristic positive and negative words or phrases.</p><h3>scikit-learn Approach:</h3><p>To begin we need to separate our training data into two parts, the training data and the <em>development data</em>.</p><p>This will allow us to evaluate our models by checking our predictions against the actual reported values in the development set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae4e2d80cfa5d2766ea245e28928452a/href">https://medium.com/media/ae4e2d80cfa5d2766ea245e28928452a/href</a></iframe><p>Next we can fit the text to a scikit-learn <em>TfidfVectorizer</em> and get a sparse matrix of TF-IDF values for each word for each document.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/faaa9637ec9cc133326bc7ecad2546d7/href">https://medium.com/media/faaa9637ec9cc133326bc7ecad2546d7/href</a></iframe><p>For this problem I’m going to try three of the popular classical machine learning models included with scikit-learn’s machine learning libraries:</p><ul><li>Logistic Regression</li><li>Multinomial Naïve Bayes</li><li>Linear Support Vector Machine</li></ul><p>I’ll setup another class to handle training and fitting all of these models:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01827351ce686a131bfe5a0757eb7762/href">https://medium.com/media/01827351ce686a131bfe5a0757eb7762/href</a></iframe><h3>scikit-learn Evaluation:</h3><p>Once we have our predictions, we can evaluate them for each model on the common metrics of precision, recall, and f1-score.</p><pre>Linear Regression : -------------------<br>          precision    recall  f1-score   support</pre><pre>Not Movie      0.98      0.99      0.98      5247<br>Positive       0.88      0.87      0.88      2710<br>Negative       0.89      0.88      0.89      2572</pre><pre>accuracy                           0.93     10529<br>macro avg      0.92      0.91      0.92     10529<br>weighted avg   0.93      0.93      0.93     10529</pre><pre>Multinomial NB : -------------------<br>           precision    recall  f1-score   support</pre><pre>Not Movie      0.96      0.98      0.97      5247<br>Positive       0.86      0.78      0.82      2710<br>Negative       0.83      0.88      0.85      2572</pre><pre>accuracy                           0.90     10529<br>macro avg      0.88      0.88      0.88     10529<br>weighted avg   0.90      0.90      0.90     10529</pre><pre>Linear Support Vector Machine : -------------------<br>           precision    recall  f1-score   support</pre><pre>Not Movie      0.98      0.99      0.99      5247<br>Positive       0.88      0.88      0.88      2710<br>Negative       0.89      0.88      0.89      2572</pre><pre>accuracy                           0.93     10529<br>macro avg      0.92      0.92      0.92     10529<br>weighted avg   0.93      0.93      0.93     10529</pre><p>After running the metrics evaluation, we can see that the <strong><em>Support Vector Machine</em></strong> model wins out<em> just by a bit</em> over the Logistic Regression model.</p><h3>Huggingface 🤗 Transformers Approach:</h3><p>Now that we’ve tried the classical machine learning approach using scikit-learn, it’s time to indulge in the current state-of-the-art for natural language processing: <strong><em>transformer models!</em></strong></p><p>Using Huggingface🤗’s <em>transformers</em> library, we can achieve some pretty incredible results with minimal effort!</p><p>For this approach, I’m going to import and fine-tune a distilled version of BERT available on Huggingface’s hub, <em>DistilBERT</em>.</p><p>Specifically, I’ll be using <em>distilbert-base-uncased</em>. Please refer to the huggingface hubs page for distilbert-base-uncased for more details on the model including its intended uses, problems with bias, and evaluation on the raw model.</p><p><a href="https://huggingface.co/distilbert-base-uncased">distilbert-base-uncased · Hugging Face</a></p><p>We should start by getting our data in order. We can reuse those pandas dataframes that we split up earlier and cast them as huggingface Datasets.</p><p>Although notably, trying to run empty strings through the transformer model will cause some errors, so let’s change our strategy to add some filler text:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a256cbae55ed8945f309b3864925ec2/href">https://medium.com/media/6a256cbae55ed8945f309b3864925ec2/href</a></iframe><p>We’re also going to need some preprocessing steps to get everything ready for the model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd7fecbbe7cad58a9ab6414cc608c012/href">https://medium.com/media/cd7fecbbe7cad58a9ab6414cc608c012/href</a></iframe><p>So here we have imported the tokenizer associated with the pretrained DistilBERT model. We’ve also setup a data collator to handle padding.</p><p>We can then use the preprocess function and Dataset.map to tokenize our Datasets.</p><p>Now that we’ve got our data in order, we just need to import our model to train:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f52f3516d55ab86d18be254ce06fbd74/href">https://medium.com/media/f52f3516d55ab86d18be254ce06fbd74/href</a></iframe><p>This will download the pretrained DistilBERT model and set it to expect 3 labels for further training! We also send the model to the first cuda device. For simplicity I’ve trained this model in Google Colaboratory and have my runtime set to GPU to increase performance.</p><p>Now finally we can fine tune our model on our training data!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e3beb38f8a4c28796ad81489ce0f134/href">https://medium.com/media/6e3beb38f8a4c28796ad81489ce0f134/href</a></iframe><p>This is also really easy using the pyTorch version of Huggingface🤗 transformers. All we need to do is initialize Trainer and TrainerArguments objects with our desired hyper-parameters and then let it run.</p><p>Now, I’m impatient <em>(and worried that google colab will disconnect on me) </em>so I only ran my trainer for less than a full epoch clocking in at 1 hour and 15 minutes.</p><p>But now we can save our model’s current checkpoint:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd5d557bbe4badc447fe0d9fbcc24a25/href">https://medium.com/media/fd5d557bbe4badc447fe0d9fbcc24a25/href</a></iframe><h3>Transformer Evaluation:</h3><p>And that’s it for training! Now we just need to evaluate the model and compare it to our scikit-learn approach.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e143806fe348c73f82323632ad0a8d88/href">https://medium.com/media/e143806fe348c73f82323632ad0a8d88/href</a></iframe><p>Output:</p><pre>Distilbert Finetuned Transformer Evaluation : -------------------<br>           precision    recall  f1-score   support</pre><pre>Not Movie      1.00      0.99      0.99      5267<br>Positive       0.93      0.91      0.92      2768<br>Negative       0.90      0.93      0.92      2494</pre><pre>accuracy                           0.95     10529<br>macro avg      0.94      0.94      0.94     10529<br>weighted avg   0.95      0.95      0.95     10529</pre><p>That&#39;s definitely a bit better than the scikit-learn approach- we managed to get at or above 0.90 for each metric!</p><h3>Conclusion:</h3><p>Our finetuned <em>DistilBERT</em> model definitely outperforms our scikit-learn classical machine learning models. However, for this task if you compare the transformers model to specifically the support vector machine model, we really only see a marginal difference.</p><p>There is <em>information</em> we were unable to capture and represent in both models! However the way we approach understanding that information for both approaches would be much different.</p><p>For the linear support vector machine, we could most likely see vast improvements with some clever feature engineering. Currently we’re just feeding it an incredibly sparse matrix of TFIDF scores for each document. Some more effort could be put into reducing the dimensionality of that matrix by excluding uninformative words and maybe performing a dimensionality reduction technique like <a href="https://en.wikipedia.org/wiki/Latent_semantic_analysis">latent semantic analysis</a> on it. Additionally, we could potentially provide more information by supplementing our matrix with features created from word vectors, thus encapsulating more semantic information.</p><p>For the transformer approach, with more time and resources we could have kept training to reach a lower loss. I believe we reached a local minimum as seen here:</p><pre>Step | Training Loss<br>500    0.333200<br>1000   0.213200<br>1500   0.199800<br>2000   0.193000<br>2500   0.192600<br>3000   0.189900<br>3500   0.187600<br>4000   0.193100<br>4500   0.189700<br>5000   0.173800<br>5500   0.178900<br>6000   0.181100<br>6500 ***0.169900***<br>7000   0.176900</pre><p>At step 6500 we hit a significant minimum and then curve back up again. <br>However, I’m pretty sure we could reach an even lower loss given some more training time, as that is common with more robust neural net models like transformer models.</p><p>This concept is known as <strong><em>double descent</em></strong> and is certainly outside the scope of this blog post, but you can <a href="https://mlu-explain.github.io/double-descent/">read here for more information</a>.</p><h3>Source Code and Reproducibility:</h3><p>You can find my code here!: <a href="https://github.com/jayyydyyy/ling-539-sentiment-analysis-competition">https://github.com/jayyydyyy/ling-539-sentiment-analysis-competition</a></p><p>If you’d like to reproduce my results, make sure to install all the dependencies listed in the requirements.txt</p><p>However, for the transformers notebooks, I would recommend running them in Google Colaboratory or some other remote environment with GPU acceleration. You can always install and setup CUDA support on your local machine if you have a supported graphics card, but not everyone does! 😊</p><p>For these reasons, I’ve included a jupyter notebook and a link to a google colab notebook for each approach!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aa1183c9825" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Syllabifying toki pona with a Regular Expression]]></title>
            <link>https://medium.com/@jmyers.xyz/creating-a-regular-expression-to-syllabify-toki-pona-fcf7bff4b3d7?source=rss-3881d68a1fc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcf7bff4b3d7</guid>
            <category><![CDATA[phonology]]></category>
            <category><![CDATA[syllables]]></category>
            <category><![CDATA[toki-pona]]></category>
            <category><![CDATA[linguistics]]></category>
            <category><![CDATA[regular-expressions]]></category>
            <dc:creator><![CDATA[Jordan]]></dc:creator>
            <pubDate>Fri, 11 Mar 2022 22:26:36 GMT</pubDate>
            <atom:updated>2022-03-13T17:52:58.152Z</atom:updated>
            <content:encoded><![CDATA[<p>A quick regular language approach to syllabification of the constructed language toki pona.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQ8otssANndlrltjn2q6Ig.png" /><figcaption>ni li ilo Lekula Epesen. Literally “this is tool Regular Expression”. <a href="https://smoishele.com/sitelensitelen/examples/liveinput/liveinput.html">Written in <em>sitelen sitelen</em></a><em>, a fun nonlinear writing style developed by </em><a href="https://jonathangabel.com/toki-pona/"><em>Jonathan Gabel.</em></a></figcaption></figure><p>Hello everyone! Recently, the minimalist conlang <a href="https://tokipona.org/">toki pona</a> has captured my interest. For those who are unaware, toki pona is a <em>constructed-language </em>created by <a href="https://lang.sg/">Sonja Lang</a> with the purpose of allowing one to reduce the clutter of their mind down to a few essential semantic building blocks. It’s surprisingly simple to pick up while remaining robust enough to cover a variety of general conversation. I would recommend reading <em>pu, </em>the official book for those interested.</p><p>Syllabification is the process of breaking up a word into syllables, a typically very easy task for native speakers of a language, but nonetheless a task that is much more difficult to formalize.</p><p>Take for example the English word <em>banana.</em></p><p>I’m sure many of you would agree that <em>banana</em> is made up of three syllables, but where would you draw the boundaries? Do you split it up like <em>ba|na|na</em>, or perhaps would you opt to include the <em>n </em>as the coda (final position) of the syllables as such: <em>ban|an|a</em>. Or perhaps <em>ba|nan|a. </em>I think that many would agree that the second and third syllabifications are clunky,<strong><em> </em></strong>but why? Without diving too far into phonology, most would agree that speakers elect the syllabification of <em>ba|na|na </em>because it follows the <a href="http://www.glottopedia.org/index.php/Maximal_Onset_Principle"><em>maximal onset principle</em></a><em>. </em>This states that consonants between vowels should be assigned to the initial position of the syllable as long as they conform with the rest of the specific language’s phonotactics (the rules for how sequences of sound are allowed to be arranged).</p><p>So to begin with toki pona, we need a way to understand the syllable structure and phonotactics of toki pona. So I’ve prepared this chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*hGyjzPVvkNdWXe9qdQD1sw.png" /><figcaption>Table created by me in excel because medium doesn’t have native table support. It was created with knowledge of the official book as well as supplemental knowledge from: <a href="https://devurandom.xyz/tokipona/7a.html">https://devurandom.xyz/tokipona/7a.html</a></figcaption></figure><p>As a brief aside, when written in latin characters, toki pona essentially follows the pronunciation prescribed by the IPA (international phonetic alphabet). Therefore [aeiou] all sound as they would in Spanish or Japanese, while the [j] is pronounced like a <em>y</em> would sound in English.</p><p>This chart covers all the <em>segmental </em>features of toki pona. There are additional <em>suprasegmental </em>features like stress and intonation. Stress in toki pona always occurs on the initial syllable, and there are no hard prescribed rules around intonation (other than maybe rising intonation for questions).</p><p>To the uninitiated, this could seem like a lot, however this is an astoundingly brief piece of information that covers the totality of the <em>prescribed </em>phonotactics of toki pona. Due to toki pona’s minimalist phonology, I thought it could be appropriate and possible to tackle the issue of syllabification with a simple regular expression. If I could, that would show that the syllabification process in toki pona can be described as regular language.</p><p>I posit that a human language (constructed or otherwise) with phonotactics that follow a simple regular language reduce the cognitive workload on individuals attempting to acquire the language and allow for quicker acquisition. I will not be able to prove this argument true in this article, but instead will show you the inner mechanics of the regular expression approach I’ve taken to syllabification, while maintaining the position that this can be a fruitful area of further research.</p><p><em>ni li ilo Lekula Epesen. ilo ni li ken lanpan e nimi wan ale pi toki pona.</em></p><p>This is the regular expression. This tool can capture all the syllables of toki pona.</p><pre># Note this regular expression is running with global, case-insensitive, and extended (ignore whitespace) flags.</pre><pre>[ptkmnlswj]?<br>(?:(?&lt;=w)[aei]|<br>(?&lt;=[jt])[aeou]|<br>(?&lt;=[pkmnls])[aeiou]|<br>(?&lt;=\b)[aeiou])<br>(?:n(?![nm]?[aeiou]))?</pre><p><em>kin, sina wile lanpan e nimi ale la sina ken kepeken e ni:</em></p><p>Additionally, if you want to capture whole words, you can use this:</p><pre># Note this regular expression is running with global, case-insensitive, and extended (ignore whitespace) flags.</pre><pre>\b(?:[ptkmnlswj]?<br>(?:(?&lt;=w)[aei]|<br>(?&lt;=[jt])[aeou]|<br>(?&lt;=[pkmnls])[aeiou]|<br>(?&lt;=\b)[aeiou])<br>(?:n(?![nm]?[aeiou]))?)+\b</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*lvgd_BeIPLOsqAdbiEyF2g.png" /><figcaption>All individual syllables captured by the regular expression.</figcaption></figure><p>These regular expressions contain no backreferences, and therefore can be modeled with finite state machines.</p><p>Let’s break the regular expression down into three components:</p><h3>The onset:</h3><pre>[ptkmnlswj]?</pre><p>The onset is simple. It consists of an optional consonant from the complete inventory of consonants in toki pona.</p><h3>The nucleus:</h3><pre>(?:(?&lt;=w)[aei]|<br>(?&lt;=[jt])[aeou]|<br>(?&lt;=[pkmnls])[aeiou]|<br>(?&lt;=\b)[aeiou])</pre><p>The nucleus is a bit more complex.</p><p>Here I have a non-capturing group of four different possibilities. Each of the four routes we could go down starts with a positive lookbehind:</p><ol><li>If we started with a <strong><em>w </em></strong>then only <strong><em>a</em></strong>,<strong><em> e</em></strong>, or<strong><em> i</em></strong> can follow.</li></ol><p>2. If we started with <strong><em>j </em></strong>or <strong><em>t</em></strong>, then only <strong><em>a</em></strong>,<strong><em> e</em></strong>, <strong><em>o</em></strong>, or<strong><em> u </em></strong>can follow.</p><p>3. If we started with <strong><em>any of the other consonants</em></strong>, <strong><em>any of the vowels</em></strong> can follow.</p><p>4. If we started with a <strong><em>word boundary</em></strong> (we omitted the onset), then <strong><em>any of the vowels</em></strong> can follow.</p><h3>The coda:</h3><pre>(?:n(?![nm]?[aeiou]))?</pre><p>The coda is probably the most complex part.</p><p>Here I have another non capturing group, but this one is optional.</p><p>The expression here states to capture an n, but then a negative lookahead follows. The negative lookahead will cause the n coda to fail to capture if what follows afterward is one of the following:</p><ul><li><strong><em>n</em></strong> and then <strong><em>any vowel</em></strong></li><li><strong><em>m</em></strong> and then <strong><em>any vowel</em></strong></li><li><strong><em>any vowel</em></strong></li></ul><p>This ensures that words like <em>nanpa </em>are correctly syllabified as <em>nan|pa</em>, but an invalid word like nanma will fail to syllabify. The segments <em>na</em> and <em>ma</em> will be captured, but the middle n will not be. This means that the tokenization version of the regular expression will also fail to capture the whole invalid word, which is desirable.</p><p>This abstraction of the syllabification process is not without its warrants.</p><p>Primarily, this process is applying to textual phonetic data (since all the symbols in toki pona’s latin orthography are pronounced only one way). This regularity allows for a description of the syllabification process to be done with a regular expression, although the computation for this specific process applies more towards the case for learning to <em>read and parse</em> toki pona, rather than syllabify utterances phonologically. However, <a href="https://www.sciencedirect.com/science/article/pii/S0960982209007246">the two cases of listening/phonological comprehension and reading/lexical comprehension are thought to be related.</a></p><p>Secondarily, as a constructed language, toki pona has the benefit of containing no phonetic irregularity whatsoever. This is not the case for many natural languages. The true insight from this work will come with further research comparing toki pona to natural languages.</p><p><a href="https://regex101.com/r/EZitx5/10">Link to the regular expression for syllabification.</a></p><p><a href="https://regex101.com/r/Z953P5/7">Link to the regular expression for tokenization.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcf7bff4b3d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>