<?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 Mun Loon Kok on Medium]]></title>
        <description><![CDATA[Stories by Mun Loon Kok on Medium]]></description>
        <link>https://medium.com/@kokmunloon?source=rss-fecab5388808------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*w_f18VNwS5M3-xIdn9ny3Q.png</url>
            <title>Stories by Mun Loon Kok on Medium</title>
            <link>https://medium.com/@kokmunloon?source=rss-fecab5388808------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 02:41:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kokmunloon/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[A Sentiment Analysis of Donald Trump’s 6th Jan Speech]]></title>
            <link>https://kokmunloon.medium.com/a-sentiment-analysis-of-donald-trumps-6th-jan-speech-51664712d848?source=rss-fecab5388808------2</link>
            <guid isPermaLink="false">https://medium.com/p/51664712d848</guid>
            <dc:creator><![CDATA[Mun Loon Kok]]></dc:creator>
            <pubDate>Tue, 16 Feb 2021 15:07:24 GMT</pubDate>
            <atom:updated>2021-03-31T04:11:44.461Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Dgu4Nu5rW6oK2ocP" /></figure><p>Photo by <a href="https://unsplash.com/@webmaster13870?utm_source=medium&amp;utm_medium=referral">Frédéric Barriol</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></p><p>As I watched the security camera footage presented by the House managers at former US President Donald Trump’s second impeachment trial, a rather eerie segment caught my attention. It showed a man stalking House speaker Nancy Pelosi along a Capitol building corridor, replete with sound effects. Echoes of “Nancyy oh Naancyyy…. “ reminded me of the character Sam in Netflix’s Van Helsing, who had a penchant for calling out to his intended victim’s name in a drawn-out syllable. Sam often stalked his victims with a baseball bat (later, he turned vampire, so he no longer needed one).</p><p>Following the case presented by the House Managers was indeed a lesson in the art of fine advocacy, destined to find its place as a locus classicus in any textbook on the subject. Lead manager Jamie Raskin in particular displayed a perfect choice of words, impeccable timing, poise, and delivered a powerful message with his video where he juxtaposed parts of Mr. Trump’s speech against scenes of the mayhem that was taking place at the Capitol Building. Though the video may well be objected to in a courtroom on the basis that its probative value outweighs its prejudicial effect, as arguably, there is no direct causal link between Mr. Trump’s words and the actual acts of the mob that the video links the words to.</p><p>On the other side, just as well was the technique of stoically hankering down and doggedly repeating a handful of the strongest points, over and over again, used by Mr. Trump’s lawyers.</p><p>At the time of posting this article, the Senate had delivered a verdict of “Not Guilty,” with 7 Republicans breaking ranks to vote to convict together with the 50 Democrat senators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DfPQ9VQpK4gM7Pyk" /><figcaption>Photo by <a href="https://unsplash.com/@joshuas?utm_source=medium&amp;utm_medium=referral">Joshua Sukoff</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It is against this backdrop that I think it useful to present a sentiment analysis of Mr. Trump’s 6 Nov speech, which was the center of focus at the Senate trial of the charge of incitement of insurrection against Mr. Trump. The full text of his speech is available at <a href="https://edition.cnn.com/2021/02/08/politics/trump-january-6-speech-transcript/index.html">https://edition.cnn.com/2021/02/08/politics/trump-january-6-speech-transcript/index.html</a></p><p>However, I proceed with the caveat that sentiment analysis as a text analytics tool is not designed to indicate the precise intended meaning of the speaker’s words but rather, the writer’s general mood or attitude towards a subject or situation. For this exercise, I will be using a Jupyter notebook as my coding tool. I have also created a helper library to factor away data processing code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HrJvKUOztYZRrsbx" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A basic approach in sentiment analysis is to use the count of positive and negative words used in a sentence to determine its polarity. One lexicon of positive and negative words for such purpose is available from researcher Bing Liu, who has made available his curated set of more than 6,800 words — <a href="https://www.cs.uic.edu/~liub/FBS/sentiment-analysis.html">https://www.cs.uic.edu/~liub/FBS/sentiment-analysis.html</a>.</p><p>As I have already downloaded the necessary datasets and we can simply load this into the notebook.</p><pre>trump_file_objects = pickle.load(open(&#39;trump_file_objects.pkl&#39;, mode=&#39;rb&#39;))</pre><p>For our first task, for every sentence, we assign a score of -1 for each negative word and a score of +1 for each positive word. The total sentiment score for the sentence is the sum of the positive words and negative words scores. We can then feed the resulting sequence of words lists into a Python Counter object and plot a histogram of the counts of the total sentiment score.</p><pre>#Using the Counter object to process the counts of the different score<br>sentiment_count = Counter(total_sentiment_score)<br>for _count in sorted(sentiment_count.keys()):<br>    print(&quot;Score of: {}; Total count is {}.&quot;.format(_count,sentiment_count[_count]))</pre><pre>Score of: -6; Total count is 1.<br>Score of: -4; Total count is 3.<br>Score of: -3; Total count is 10.<br>Score of: -2; Total count is 23.<br>Score of: -1; Total count is 169.<br>Score of: 0; Total count is 497.<br>Score of: 1; Total count is 150.<br>Score of: 2; Total count is 32.<br>Score of: 3; Total count is 9.<br>Score of: 4; Total count is 3.<br>Score of: 5; Total count is 1.</pre><pre>#Create datafram for plotting.<br>total_sentiment_score_df = pd.DataFrame({<br>    &#39;score&#39; : total_sentiment_score<br>})</pre><pre>#Plot bar chart using plotly express.<br>import plotly.express as px<br>fig = px.histogram(total_sentiment_score_df, x=&#39;score&#39;, color=&#39;score&#39;, template=&#39;plotly_white&#39;, title=&#39;Sentence Scores&#39;)<br>fig.show()</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7Ekloon99%2F3.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7Ekloon99%2F3%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bd67f9f30d56006832531b894cb2047/href">https://medium.com/media/4bd67f9f30d56006832531b894cb2047/href</a></iframe><p>Next, we get a plot of the 50 most negative sentences and a corresponding plot of the most positive sentences. Using Plotly express, we can see a bar chart of these sentences and the actual text comprised within with a mouse hover.</p><pre>sents_neg_count, sents_pos_count = helper.get_plot_for_wc(trump_file_objects)</pre><pre>fig_wc_neg = helper.ploty_fig_wc(sents_neg_count, &#39;neg&#39;)<br>fig_wc_neg.show()</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7Ekloon99%2F5.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7Ekloon99%2F5%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/52186c705c0a5c9878bebc9748a07fde/href">https://medium.com/media/52186c705c0a5c9878bebc9748a07fde/href</a></iframe><p>Often, it is useful to see the text with the keywords highlighted. We can do this by creating a style sheet to display the text as an HTML snippet. Here in this sample of 10 sentences, red indicates a negative word, blue indicates a positive word, and neutral words are displayed in the default black font.</p><pre>NEG_WORDS = list(wd.lower() for wd in trump_file_objects[&#39;negative_words&#39;])<br>POS_WORDS = list(wd.lower() for wd in trump_file_objects[&#39;positive_words&#39;])</pre><pre>#Process setences as HTML code with color key words highlighting.<br>trump_wc_df = helper.get_df_for_wc(trump_file_objects)<br>display_neg_sents = helper.get_disp_sent(helper.display_process_sents(trump_wc_df, &#39;negative_count&#39;, &#39;sents&#39;, <br>                                                                      ascending=True, num_sents=5))<br>color_sents_list = helper.get_color_sents_htm(display_neg_sents,POS_WORDS, NEG_WORDS)</pre><pre>from IPython.core.display import HTML<br>display(HTML(<br>    r&#39;&#39;&#39;&lt;style&gt;<br>        .blue1 {  <br>          color: blue;<br>          margin: 0px;<br>          padding: 0px;<br>        }<br>        .red1 {  <br>          color: red;<br>          margin: 0px;<br>          padding: 0px;<br>        }<br>        .black1 {  <br>          color: black;<br>          margin: 0px;<br>          padding: 0px;<br>        }<br>    &lt;/style&gt;&#39;&#39;&#39;<br>))<br>HTML(color_sents_list)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zNmMv_7QrA2DnFH78_utmQ.png" /><figcaption>rendered in HTML with cascading style sheets</figcaption></figure><p>Another more informative lexicon takes into account the parts-of-speech of the words to determine their subjectivity as well. <a href="https://github.com/clips/pattern/blob/master/pattern/text/en/en-sentiment.xml">https://github.com/clips/pattern/blob/master/pattern/text/en/en-sentiment.xml</a><br>This lexicon has been incorporated into the textblob natural language processing library and can be used out of the box.</p><p>The sentiment function of textblob returns two properties, polarity and subjectivity. The polarity score is a floating-point number between 1 and -1 where 1 is the most positive and -1 means is the most negative. The subjectivity score is, in turn, a floating-point number between 0 and 1, where 1 is the highest possible score indicating subjectivity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kaINKXBRW3VS0znqAdNMgQ.png" /></figure><p>We can use the negative words set and positive words set to generate word clouds to display the most prominent negative and positive words used.</p><pre>#Get polarity column.<br>trump_senti_df[&#39;sentiment&#39;] = trump_senti_df[&#39;sents&#39;].apply(lambda x: TextBlob(x).polarity)</pre><pre>#Get subjectivity column.<br>trump_senti_df[&#39;subjectivity&#39;] = trump_senti_df[&#39;sents&#39;].apply(lambda x: TextBlob(x).subjectivity)</pre><pre>#Remove standard and custome stop words.<br>STOPWORD = STOPWORD + [&#39;going&#39;, &#39;away&#39;, &#39;get&#39;, &#39;dont&#39;, &#39;one&#39;, &#39;way&#39;, &#39;want&#39;, &#39;go&#39;, &#39;said&#39;, &#39;much&#39;, &#39;say&#39;]</pre><pre>#negative word cloud<br>helper.get_senti_wcd(trump_senti_df, top_num_words=50, sentiment=&#39;neg&#39;, _ascending=False, _stopwords=STOPWORD)</pre><pre>#positive word cloudhelper.get_senti_wcd(trump_senti_df, top_num_words=50, sentiment=&#39;pos&#39;,_ascending=True, _stopwords=STOPWORD)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*9VkL-6yfcYV_0zMCZQuUhw.png" /><figcaption>negative word cloud</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*SPRqvvSdZ2wElVeCopLQ7Q.png" /><figcaption>positive word cloud</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tvnUUU_ZcPHewiMz" /><figcaption>Photo by <a href="https://unsplash.com/@samule?utm_source=medium&amp;utm_medium=referral">Samule Sun</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The third method uses a pre-trained transformer model. It can capture complex patterns within a long sequence of data, such as sequences of words in text data. In this exercise, I will use the transformer models created by developers at hugginingface.co. Their models are capable of high performance on natural language understanding and natural language generation tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*JUKZWkNDNdNRa2XAS8qUbQ.png" /><figcaption><a href="https://huggingface.co/transformers/index.html">https://huggingface.co/transformers/index.html</a></figcaption></figure><pre>from transformers import pipeline<br>nlp = pipeline(&quot;sentiment-analysis&quot;)<br>result = nlp([&quot;I hate you&quot;, &#39;I love you&#39;])<br>print(result)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SxeKDGORUBwMGI1g43_qsg.png" /></figure><p>We can similarly plot a histogram of the top negative and positive sentences but some scaling is necessary for the plots to be intuitive.</p><pre>#Get transformer dataframe<br>trump_transform_df = helper.get_transform_pd(trump_file_objects[&#39;trump_sents&#39;])</pre><pre>#Get top most negative 50 sentences <br>trump_trans_neg_df = trump_transform_df.loc[trump_transform_df[&#39;label&#39;] == &#39;NEGATIVE&#39;].sort_values(by=&#39;score&#39;, ascending=False )[:50]</pre><pre>trump_trans_neg_df.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PsvlWGKYGdhkd3qRNnMXUw.png" /><figcaption>sample of top 10 most negative sentences</figcaption></figure><p>Plotting the histogram of the top 50 most negative sentences:</p><pre>trump_trans_pos_fig = helper.trump_trans_pos_df_plot(trump_trans_pos_df)<br>trump_trans_pos_fig.show()</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7Ekloon99%2F9.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7Ekloon99%2F9%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/c26da3decd5ea697c7424d800f3c06a3/href">https://medium.com/media/c26da3decd5ea697c7424d800f3c06a3/href</a></iframe><p>Similarly for the positive sentiment sentences:</p><pre>#Get top most positive 50 sentences <br>trump_trans_pos_df = trump_transform_df.loc[trump_transform_df[&#39;label&#39;] == &#39;POSITIVE&#39;].sort_values(by=&#39;score&#39;, ascending=False )[:50]<br>trump_trans_pos_df.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CeUimnCX_CVEJYECpfNhvg.png" /><figcaption>sample of top 10 most negative sentences</figcaption></figure><p>Plotting the histogram of the top 50 most positive sentences:</p><pre>trump_trans_pos_fig = helper.trump_trans_pos_df_plot(trump_trans_pos_df)<br>trump_trans_pos_fig.show()</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7Ekloon99%2F11.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7Ekloon99%2F11%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0966ec238714bf2b5b1c54a967d01702/href">https://medium.com/media/0966ec238714bf2b5b1c54a967d01702/href</a></iframe><p><strong><em>Conclusions from sentiment analysis — an excellent tool to gauge a speaker’s overall mood and attitude towards a topic or subject matter</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Da1-yX1RIOTg_0qiASMbQ.jpeg" /></figure><p>We can quite accurately and easily glean central themes from sentiment analysis. From the 50 most negative sentences, we can see Mr. Trump’s great disappointment at losing the US 2020 presidential elections, which he attributes to election fraud, and what he perceives to be the Republican Party’s lack of support in his fight to overturn the elections. On the side of the 50 most positive sentences, we see Mr. Trump’s big show of gratitude and praise for his supporters.</p><h4>Final thoughts …</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wSnYfgU-pdo0GjIR" /><figcaption>Photo by <a href="https://unsplash.com/@rebepascual7?utm_source=medium&amp;utm_medium=referral">Rebe Pascual</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The Senate’s verdict of “Not Guilty” has been criticized by commentators as being too partisan and failing to hold Mr. Trump accountable for his words and actions. According to legal experts however, this verdict is no bar to civil actions, nor does it afford Mr. Trump the defence of autrefois acquit since the Senate charge was not a charge of a criminal offence.</p><p>Whatever one may think of the merits of the verdict, the result remains that is for the people of the USA to decide if Mr. Trump is fit to be president again in the 2024 elections.</p><p><em>The </em><a href="https://github.com/kloon99/trump_sentiment_analysis.git"><em>code </em></a><em>for this article is available at my Github repository.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51664712d848" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning For Lawyers Part 3]]></title>
            <link>https://kokmunloon.medium.com/machine-learning-for-lawyers-part-3-8960386b09d4?source=rss-fecab5388808------2</link>
            <guid isPermaLink="false">https://medium.com/p/8960386b09d4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[legal-ai]]></category>
            <category><![CDATA[law]]></category>
            <category><![CDATA[ai-lawyer]]></category>
            <category><![CDATA[legal]]></category>
            <dc:creator><![CDATA[Mun Loon Kok]]></dc:creator>
            <pubDate>Tue, 25 Jun 2019 15:30:51 GMT</pubDate>
            <atom:updated>2021-09-01T06:14:48.381Z</atom:updated>
            <content:encoded><![CDATA[<p>In this Part 3, we explore the use of machine learning model explainers such as LIME:</p><p><a href="https://arxiv.org/abs/1602.04938">&quot;Why Should I Trust You?&quot;: Explaining the Predictions of Any Classifier</a></p><p>These explainers allow us to catch a glimpse into the inner workings of a machine learning model. Such a facility is useful in many ways, it engenders trust in the model and may also provide troubleshooting guides when things do not go as well as expected. I believe it can also be deployed to improve the quality of datasets that are approximately tagged using methods such as text patterns and word and n-gram frequencies.</p><p>Similar to Parts 1 and 2 of this article, we import the datasets into a dataframe. In this Part 3, we take a peek into how a machine learning model may decide to place weightage on different elements of the datasets it is presented with.</p><p>Again, the resulting dataframe has 2 columns. The ‘sentence’ column holds the text sample and the ‘polarity’ column represents the type of indemnity. 0 is for a user-provided indemnity and 1 is for owner provided indemnity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQDhQFdKMyIIjBV-0dkiGQ.png" /></figure><p>To encode the words, we will use the term-frequency, inverse-document frequency vectorizer provided by scikit-learn. In summary, this vectorizer does a count of the words appearing in a text sample from a batch but also reduces emphasis on words that appear in many text samples across the batch. <br>The intuition here is that if several words appear many times in a sample text, then those words may indicate the subject matter of that text sample. <br>For instance, if we find the words ‘banana’ and ‘cake’ appearing many times in a paragraph, we may infer that the paragraph may be a recipe for banana cakes. However words like ‘the’, ‘and’, ‘of’ that appear in almost every sample of a batch may not give away much about what a specific sample is about. In fact, those are called stop-words and are usually removed altogether.</p><p>Next, the usual split into a training and validation set.</p><pre>from sklearn.model_selection import train_test_split<br>_train_vectors, _test_vectors = train_test_split(train_df, test_size=0.2)<br>vectorizer = <br>sklearn.feature_extraction.text.TfidfVectorizer(lowercase=False, ngram_range=(2,4), stop_words=stopwds)<br>train_vectors = vectorizer.fit_transform(_train_vectors[&#39;sentence&#39;])<br>test_vectors = vectorizer.transform(_test_vectors[&#39;sentence&#39;])</pre><p>We will use random forests for our text classification as it provides greater accuracy based on its algorithm of polling independent decision making logic flows (“decision trees”).</p><pre>rf = sklearn.ensemble.RandomForestClassifier(n_estimators=500)<br>rf.fit(train_vectors, _train_vectors[&#39;polarity&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*62eIcz4KQNajq8xQW0DONA.png" /></figure><pre>pred = rf.predict(test_vectors)<br>sklearn.metrics.f1_score(_test_vectors[&#39;polarity&#39;], pred, average=&#39;binary&#39;)</pre><pre>0.9600000000000001</pre><p>We see that this classifier achieves a 0.96 F1 score.</p><p>We will run a prediction and get LIME to explain its treatment of the sample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*uSws7VbvCl2DBXPzVULgsw.png" /></figure><pre>from lime import lime_text<br>from sklearn.pipeline import make_pipeline<br>c = make_pipeline(vectorizer, rf)<br>#Predict<br>print(c.predict_proba([_licensor_indem[17][1]])[0,1])</pre><pre>0.984</pre><p>The above shows the Random Forest model determined that the probability of the sample belonging to class 1 is 98% which appears to be correct.</p><p>Now we create an explainer object.</p><pre>from lime.lime_text import LimeTextExplainer<br>explainer = LimeTextExplainer(class_names=target_names)</pre><p>We then generate an explanation with at most 15 features the sample.</p><pre>exp = explainer.explain_instance(_licensor_indem[17][1], c.predict_proba, num_features=15)<br>print(&#39;Probability(licensor_indem) =&#39;, c.predict_proba([_licensor_indem[17][1]])[0,1])<br>#print(&#39;True class: %s&#39; % target_names[])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*i8xAYqJA-U17CTcmTFk20A.png" /></figure><p>The explanation is presented below as a list of weighted features.</p><pre>exp.as_list()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eb78lEZmZWgL82cKfYRW9Q.png" /></figure><p><strong>Visualizing explanations</strong></p><p>The explanations can be returned as a matplotlib barplot:</p><pre>%matplotlib inline<br>fig = exp.as_pyplot_figure()</pre><p>Let’s render the explanation in this notebook.</p><pre>exp.show_in_notebook(text=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*953eS1gi9i80i_RMjkDVsA.png" /></figure><p>This explanation actually approximates the pattern of the regular expressions I used to hazy tag the samples. The key pattern is roughly (licensor|owner|XXX) indemnifies the (user|licensee|customer|client). This pattern is flipped around for the user’s indemnification. XXX is meant to be the name of the licensor or software owner but often times it is not easy to detect the entity name accurately, though I have had limited success with NLTK’s named entity sets.</p><p><strong><em>Conclusions:</em></strong> Classification explainers such as LIME I believe are useful for assist in the hazy tagging process. This is especially in cases where the probability of which category of labels a sample belongs to is in the mid-range. We will then be able to see the ‘for’ and ‘against’ weights of the words to fine tune our hazy tagging.</p><pre>This notebook is based on the one found here: <a href="https://github.com/marcotcr/lime/blob/master/doc/notebooks/Lime%20-%20basic%20usage%2C%20two%20class%20case.ipynb">https://github.com/marcotcr/lime/blob/master/doc/notebooks/Lime%20-%20basic%20usage%2C%20two%20class%20case.ipynb</a> under the following license: <a href="https://github.com/marcotcr/lime/blob/master/LICENSE">https://github.com/marcotcr/lime/blob/master/LICENSE</a> This notebook itself and associated materials are free for personal academic research use and are provided as-is and without warranty of any sort.</pre><pre>Author: Kok Mun Loon, 25 June 2019.</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b64f2afcd108d157c25fbb476ee873bb/href">https://medium.com/media/b64f2afcd108d157c25fbb476ee873bb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8960386b09d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning For Lawyers Part 2]]></title>
            <link>https://kokmunloon.medium.com/machine-learning-for-lawyers-part-2-a1724f29373d?source=rss-fecab5388808------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1724f29373d</guid>
            <category><![CDATA[legal]]></category>
            <category><![CDATA[law]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[legal-ai]]></category>
            <category><![CDATA[ai-lawyer]]></category>
            <dc:creator><![CDATA[Mun Loon Kok]]></dc:creator>
            <pubDate>Tue, 25 Jun 2019 15:30:15 GMT</pubDate>
            <atom:updated>2021-09-15T09:37:39.638Z</atom:updated>
            <content:encoded><![CDATA[<p>We continue our exploration of Machine Learning for machine identification of contractual provisions of interest.</p><p>In part 1 of this article, we explored implementing a machine learning pipeline to train a ML model to detect indemnity provisions in software end user license agreements. There the machine was able to distinguish between indemnities granted by the licensee (user) from indemnities granted by the licensor (software owner). We used a simple one layer network with a maxpool layer configured using Keras as front end and Tensorflow as backend. With a relatively small dataset, we achieved over 97% accuracy with only 40 epochs or training cycles.</p><p>In Part 2, we will explore using dense word vectors instead of just one hot encoding to represent words. Google provides pre-trained word vectors to encode our word so we will use these.</p><p>These pre-trained word vectors were trained over millions of words and are encoded such that the vector distance between 2 words can determine their closeness in meaning.</p><p>Since the legal vocabulary is rather unto itself, how well will these generalized word embeddings work, albeit trained over a very large number of words? Let’s put them to the test …</p><p>We will use the same dataset that we used in Part 1 and this time we will deploy Google’s Tensorflow Hub, which is a high-level front end along the vein of Keras but provides easier access to Google’s pre-trained word embeddings.</p><p>As was done in Part 1, the datasets are read into a Pandas Dataframe.<br>Code will not be explained as these are stock utility functions discussed in Part 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZM-wKxlNvLg7xuorSHAvXw.png" /></figure><p>As was the case in Part 1, the resulting data frame has 2 columns. The ‘sentence’ column holds the text sample and the ‘polarity’ column represents the type of indemnity. 0 is for a user-provided indemnity and 1 is for owner provided indemnity.</p><p>Next, the split into a training and validation set.</p><pre><em>#Data set split into 0.8 &amp; 0.2</em></pre><pre>train_df, test_df <strong>=</strong> train_test_split(_train_df2, test_size<strong>=</strong>0.2)</pre><p>The Tensorflow modules provide convenience functions that accept data frames and feeds them into the models.</p><pre><em># Training input on the whole training set with no limit on training epochs.</em></pre><pre>train_input_fn <strong>=</strong> tf.estimator.inputs.pandas_input_fn(train_df, train_df[&quot;polarity&quot;], num_epochs<strong>=None</strong>, shuffle<strong>=True</strong>)</pre><pre><em># Prediction on the whole training set.</em></pre><pre>predict_train_input_fn <strong>=</strong> tf.estimator.inputs.pandas_input_fn(train_df, train_df[&quot;polarity&quot;], shuffle<strong>=False</strong>)</pre><pre><em># Prediction on the test set.</em></pre><pre>predict_test_input_fn <strong>=</strong> tf.estimator.inputs.pandas_input_fn(test_df, test_df[&quot;polarity&quot;], shuffle<strong>=False</strong>)</pre><p>We import the pre-trained word embeddings module from Tensorflow Hub and cache this into a destination folder.<br>The feature column will translate the words in our text samples into dense contextual word embeddings.</p><pre>embedded_text_feature_column <strong>=</strong> hub.text_embedding_column(key<strong>=</strong>&quot;sentence&quot;,module_spec<strong>=</strong>&quot;https://tfhub.dev/google/nnlm-en-dim128/1&quot;)</pre><p>We configure a model with 3 hidden layers. We also add a regularisation layer to prevent over-fitting.</p><pre>estimator = tf.estimator.DNNClassifier(<br>    hidden_units=[1024, 512, 256],<br>    feature_columns=[embedded_text_feature_column],<br>    n_classes=2,<br>    optimizer=tf.train.ProximalAdagradOptimizer(<br>      learning_rate=0.1,<br>      l1_regularization_strength=0.05<br>    ),<br>    model_dir=r&quot;D:\data\tf_hub2&quot;)</pre><p>The model will be trained for training cycles.</p><pre># Training for 1000 steps<br>estimator.train(input_fn=train_input_fn, steps=1000);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*2QhDmdSUNZGXGRBc4JkmQA.png" /></figure><p>Let’s now run some tests for the data from the training set and the data from the test set. You will notice that the predictions results from the training set will be higher than the results from the test set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WhfB194GdUbnMBG_NsWB6g.png" /></figure><p>We can examine the other prediction metrics of the test results from the test set.</p><pre>test_eval_result</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3np9FOE5JF42lWkg73lkOw.png" /></figure><p>We notice that the ‘auc_precision_recall’ metric discloses some misses<br>Let’s run some code to see where these might be.</p><p>Let’s run some code to see where these might be.</p><pre>test_pre_result <strong>=</strong> estimator.predict(input_fn<strong>=</strong>predict_test_input_fn)</pre><pre>tf.logging.set_verbosity(tf.logging.ERROR)<br>count = 0<br>index = 0<br>for item, pred in zip(test_df[&quot;polarity&quot;],test_pre_result):<br>    if item == 1:<br>        count += 1  <br>    if item != pred[&#39;class_ids&#39;]:<br>        print(&quot;Index={}, X{}P{}&quot;.format(index,item,pred[&#39;class_ids&#39;][0]))   <br>    index += 1<br>print(r&quot;Total of [1] classes: {}&quot;.format(count))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cz3rm9ob8X-8unaJ5IrqEg.png" /></figure><pre><strong>for</strong> _ind <strong>in</strong> [9,42]:<br>    print(test_df.iloc[_ind, :].values.tolist(), &quot;\n&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YR652RYiG2BHO5n-xXJMow.png" /></figure><p>These are mixed results. One can only tell if the Classifier can do better than hazy tagging with better-curated datasets.<br>Let’s see the confusion matrix. Here’s a good explanation of what this is: <a href="https://www.dataschool.io/simple-guide-to-confusion-matrix-terminology/">https://www.dataschool.io/simple-guide-to-confusion-matrix-terminology/</a></p><pre>def get_predictions(estimator, input_fn):<br>    <br>      return [x[&quot;class_ids&quot;][0] for x in estimator.predict(input_fn=input_fn)]</pre><pre>LABELS = [<br>    &quot;negative&quot;, &quot;positive&quot;<br>]<br>cm_out = None<br># Create a confusion matrix on training data.<br>with tf.Graph().as_default():<br>    cm = tf.confusion_matrix(test_df[&quot;polarity&quot;], <br>                           get_predictions(estimator, predict_test_input_fn))<br>    with tf.Session() as session:<br>        cm_out = session.run(cm)</pre><pre># Normalize the confusion matrix so that each row sums to 1.<br>cm_out = cm_out.astype(float) / cm_out.sum(axis=1)[:, np.newaxis]</pre><pre>sns.heatmap(cm_out, annot=True, xticklabels=LABELS, yticklabels=LABELS);<br>plt.xlabel(&quot;Predicted&quot;);<br>plt.ylabel(&quot;True&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*dVFdabmnTYaW0gykiwxwdg.png" /></figure><p>Within the confines of a very small and approximately tagged dataset, Machine Learning appears to be quite promising in its application to machine identification of contractual clauses of interest. Better curated datasets will be necessary to take the exploration further. In Part 3 of my article, we attempt to catch a glimpse into how a Machine Learning model looks at the data it is presented with.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81d872ed9c8d69e78c637d25afced977/href">https://medium.com/media/81d872ed9c8d69e78c637d25afced977/href</a></iframe><pre>This notebook is based on the one found at: <a href="https://www.tensorflow.org/hub/tutorials/text_classification_with_tf_hub">https://www.tensorflow.org/hub/tutorials/text_classification_with_tf_hub</a> which is licensed under Apache License, Version 2.0. This notebook itself and associated materials are free for personal academic research use and are provided as-is and without warranty of any sort.</pre><pre>Author: Kok Mun Loon, 25 June 2019.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1724f29373d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning For Lawyers Part 1]]></title>
            <link>https://kokmunloon.medium.com/machine-learning-for-lawyers-part-1-2c36a1016341?source=rss-fecab5388808------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c36a1016341</guid>
            <category><![CDATA[legaltech]]></category>
            <category><![CDATA[legal-ai]]></category>
            <category><![CDATA[machine]]></category>
            <category><![CDATA[ai-lawyer]]></category>
            <category><![CDATA[legal]]></category>
            <dc:creator><![CDATA[Mun Loon Kok]]></dc:creator>
            <pubDate>Tue, 25 Jun 2019 15:29:22 GMT</pubDate>
            <atom:updated>2021-09-01T06:45:03.283Z</atom:updated>
            <content:encoded><![CDATA[<p>Since words are the expression of our thoughts, we can hypothesize that carefully crafted sentences in a contract is an expression of a lawyer’s thinking and hence his or her expertise. If then, we can somehow model this drafting, we can model an area of a lawyer’s expertise, such as in the drafting and interpretation of contracts.</p><p>Machine learning (ML) is a tool which can model information well. Given enough samples, ML can derive a generalized pattern of the samples that is finely tuned with weights and biases. For instance, if we are trying to model a particular type of contractual indemnity, ML can determine the types of words and sequence of words (phrases) that such an indemnity will typically contain.</p><p>In drafting indemnity provisions, a lawyer will typically use such words and phrases as “indemnify”, “hold harmless against”, “direct, indirect and consequential losses”, etc. ML can model such an indemnity clause by processing samples of these and determine the keywords and phrases that such these clauses contain, which distinguish them from other types of contractual provisions.</p><p>Based on these assumptions, are we therefore able to train a ML model to be able to determine whether extracts of text from a contract qualify as such contractual provisions of interest? Such a ML model will be useful as a tool for lawyers to produce a first cut review of contracts, or perhaps to spot misses, especially where there are constraints of time coupled with voluminous documents to digest, a situation practicing lawyers are all too familiar with!</p><p>Fortunately for us lawyers without access to big budgets for technology, there is this wonderful movement called the “democratization of AI” with leading software houses producing high-level software libraries which enable a developer to effectively put together a machine learning pipeline with relatively few lines of code. Popular ones which researchers commonly use include Tensorflow, Scikit-Learn, NLTK, etc. These software libraries will drastically cut down development costs and time.</p><p>In the next segments, we will explore such a Machine Learning pipeline using Keras (created by Mr. Francoise Chollet) with Tensorflow as the backend. Keras is now incorporated into Tensorflow, though it can still support other platforms like Theano, CNTK, Pytorch, etc. The code will run in a Jupyter notebook.</p><p>For the purposes of this demonstration, we will be exploring sample texts from software end-user license agreements (EULAs) which are available freely on the internet and generally contain contractual provisions that are carefully worded to protect the intellectual property in the associated software.</p><p>We will train the machine to identify two different types of indemnities commonly found in these EULAs. The first category will be indemnities given by the end-user (licensee) to the software proprietor (licensor). These are intended to monetarily compensate the software owner should the end-user act in breach of the license terms. The second category will be indemnities given by the software owner to the end-user. Generally, in the context of EULAs, these are intended to protect the end-user against third-party claims that the use of the software by them is in breach of these third parties’ intellectual property rights. The licensor’s indemnification is less common for breach of other licensing terms as most software owners offer as the sole remedy, their best endeavors to fix defects or a refund, as part of the ‘off-the-shelf’ software business model.</p><p>With that, let&#39;s dive into the coding proper and fire up a Jupyter notebook:</p><p>First, we import the necessary libraries and modules:</p><pre><strong>from</strong> <strong>__future__</strong> <strong>import</strong> print_function<br><strong>import</strong> <strong>tensorflow</strong> <strong>as</strong> <strong>tf</strong><br><strong>import</strong> <strong>tensorflow.keras</strong> <strong>as</strong> <strong>keras</strong><br><strong>import</strong> <strong>os</strong>, <strong>sys</strong>, <strong>io</strong>, <strong>re</strong>, <strong>pickle</strong>, <strong>random</strong><br><strong>import</strong> <strong>matplotlib.pyplot</strong> <strong>as</strong> <strong>plt</strong><br><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np</strong><br><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><strong>from</strong> <strong>sklearn.utils</strong> <strong>import</strong> shuffle<br><strong>from</strong> <strong>sklearn.model_selection</strong> <strong>import</strong> train_test_split<br><strong>from</strong> <strong>tensorflow.keras.preprocessing.text</strong> <strong>import</strong> Tokenizer</pre><p>We start by importing two sets of text samples, the first set comprising of indemnity provisions in favor of the licensor (software owner) and the second set comprising of indemnity provisions in favor of the licensee (end-user).</p><p>Drawing from the experience of researchers who have successfully classified spam mail, tweet sentiments and forum postings categories, and the intuition that lawyers very carefully choose and weigh the meaning of words to be used in a contractual provision, we will implement a text classification model for our purpose of machine-detection of the indemnity provisions.</p><p>These samples were extracted from end-user license agreements sourced from the internet. There is an abundance of these but picking out the relevant provisions is not an easy task. In machine learning terms, this process is often called ‘tagging’, which creates a set of samples and their corresponding ‘labels’ or class identifiers called the ‘ground truth’. Often this is a manual process where a ‘domain expert’ will set out to manually classify the samples, a process which is laborious and time-consuming. Researchers often avail themselves of pre-tagged data sets such as the MINST, CIFAR-10, IMDB Movie Reviews datasets, etc. for their machine learning explorations. However, for other specific purposes, we are left to create our own.</p><p>For this demonstration, I used regular expression tools with random sampling checks to prepare the datasets. Here I would caution the reader that such methodology does not create a perfect sample set but I believe it will be close enough for demonstrating the feasibility of deploying machine learning for such a task of identifying relevant provisions of a contract.</p><p>In fact, I think that some method of ‘hazy’ tagging is probably the only practical way forward for many such undertakings. It will be left to the iterative process of validation and correction to refine the dataset and model itself.</p><p>As the datasets are imbalanced, I have taken a slice of the larger list ( _user _indem) to even out numbers to approximately 1:3. Do note that the actual datasets are very small so I have boosted the numbers by generating overlapping sequences of sentences.</p><p>The dataframe displays the data in a tabular format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ri4UZ94Hs7YkMlXrzHwo9Q.png" /></figure><p>The column ‘sentence’ contains the text samples and the column ‘polarity’ contains the 2 clause types. 0 represents an indemnity given by the licensee (user) and 1 represents an indemnity given by the licensor (owner).</p><p>The next step is to convert the columns into numerical values which are the only inputs the machine can accept. Before that, we will put our data sets into data-to-label lists for the next set of processing.</p><pre><em>#Creates the X, Y set, where X is the training data and Y the associated lables.</em><br>X, Y = all_indem[&#39;sentence&#39;], all_indem[&#39;polarity&#39;]</pre><p>The sentences need to be split into words, which are the units of expression in most forms of drafting where precision is important. These words in turn need to be codified using a simple one-hot encoding method. This involves extracting the vocabulary for the entire text corpus and associating each word with a unique integer. Fortunately for us, Keras provides the Tokenizer for such a purpose.</p><pre><em>#Initiate the Tokenzier &amp; train on the text data.</em><br>tokenizer = Tokenizer()<br>tokenizer.fit_on_texts(X)<br>X2 = tokenizer.texts_to_sequences(X)</pre><p>Let’s have a peek into how an encoded sentence looks like.</p><pre>print(X2[0])</pre><pre>[122, 4, 247, 227, 47, 9, 594, 595, 166, 116, 4, 96, 55, 3, 273, 1, 4, 220, 304, 3, 4, 62, 34, 5, 75, 3, 69, 53, 72, 12, 273, 9, 4, 15, 2, 5, 35, 736, 63, 12, 273, 66, 20, 67, 595, 200, 4, 62, 445, 1, 737, 21, 65, 4, 62, 596, 20, 67, 1, 273, 2, 17, 24, 28, 738, 3, 739, 15, 927, 5, 147, 100, 446, 2, 187, 129, 2, 188, 64, 17, 167, 3, 4, 45, 273, 2, 4, 24, 28, 738, 3, 4, 739, 15, 84, 928, 88, 112, 129, 22, 4, 62, 595, 343, 4, 62, 26, 16, 273, 1, 13, 273, 14, 22, 18, 29, 40, 57, 1, 30, 123, 22, 273, 64, 17, 167, 3, 5, 75, 3, 929, 2, 5, 24, 387, 69, 53, 72, 23, 8, 4, 179, 2, 88, 930, 228, 388, 3, 5, 344, 3, 4, 15, 2, 35, 736, 63, 12, 273, 2, 5, 45, 3, 20, 67]</pre><p>We can also convert the integer tokens back into the words forming the text. Notice that the Tokenizer removes the punctuations and lower case all words. This provides a hint that the machine largely looks at the presence or absence of certain keywords. We will explore how a classifier places emphasis on certain keywords in Part 3 of my article.</p><pre><em>#This does a lookup of each integer to its correponding word stored in a Python dictionary.<br>#We join each word with a space character.</em></pre><pre>&#39; &#39;.join([tokenizer.index_word.get(_token, &#39;&#39;)<strong>for</strong> _token <strong>in</strong> X2[0]])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ekPwl9dYrfsIPfksmf4B5w.png" /></figure><p>In the machine learning tradition, we will split the dataset into a training set and a test set. A popular split is an 80–20 split. We can use the utility function provided by Scikit-Learn to do this.</p><pre><em>#Splits into training and test datasets and their corresponding lables using </em><br><em>#the built in randomising feature.</em><br>X_train, X_test, Y_train, Y_test = train_test_split(X2, Y, test_size = 0.2, random_state=0)</pre><p>As the machine expects to see samples of a uniform length, we will have to pad shorter sentences with null values.</p><pre>train_data = keras.preprocessing.sequence.pad_sequences(X_train,<br>                                                        value=0.0,<br>                                                     padding=&#39;post&#39;,<br>                                                        maxlen=552)</pre><pre>test_data = keras.preprocessing.sequence.pad_sequences(X_test,<br>                                                       value=0.0,<br>                                                     padding=&#39;post&#39;,<br>                                                       maxlen=552)</pre><h4>Build the model</h4><p>In this discussion, I will use a fairly simple model architecture taken from this notebook <a href="https://www.tensorflow.org/tutorials/keras/basic_text_classification">https://www.tensorflow.org/tutorials/keras/basic_text_classification</a>. This is a simple neural network with one hidden layer with 16 nodes. An averaging layer is added to minimize over-fitting.</p><pre><em>#The vocabulary size is retured by the Vectoriser in the earlier steps.</em><br>vocab_size = 1654</pre><pre>model = keras.Sequential()<br>model.add(keras.layers.Embedding(vocab_size, 16))<br>model.add(keras.layers.GlobalAveragePooling1D())<br>model.add(keras.layers.Dense(16, activation=tf.nn.relu))<br>model.add(keras.layers.Dense(1, activation=tf.nn.sigmoid))</pre><pre>model.summary()</pre><pre>_________________________________________________________<br>Layer (type)                 Output Shape              Param #   <br>=================================================================<br>embedding (Embedding)        (None, None, 16)          26464     <br>_________________________________________________________________<br>global_average_pooling1d (Gl (None, 16)                0         <br>_________________________________________________________________<br>dense (Dense)                (None, 16)                272       <br>_________________________________________________________________<br>dense_1 (Dense)              (None, 1)                 17        <br>=================================================================<br>Total params: 26,753<br>Trainable params: 26,753<br>Non-trainable params: 0<br>_________________________________________________________________</pre><h4>Loss function and optimizer</h4><p>We will use binary_crossentropy loss function recommended for binary classifications and the popular Adam Optimiser.</p><pre>model.compile(optimizer=&#39;adam&#39;,<br>              loss=&#39;binary_crossentropy&#39;,<br>              metrics=[&#39;acc&#39;])</pre><h4>Training the model</h4><p>Next, we train the model for 40 cycles or epochs in mini-batches of 5 samples.</p><pre>history <strong>=</strong> model.fit(train_data, <br>                    Y_train, <br>                    epochs<strong>=</strong>40,<br>                    batch_size<strong>=</strong>5, <br>                    validation_data<strong>=</strong>(test_data, Y_test),<br>                    verbose<strong>=</strong>1)<br>D:\Anaconda3\lib\site-packages\tensorflow\python\ops\gradients_impl.py:108: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory.<br>  &quot;Converting sparse IndexedSlices to a dense Tensor of unknown shape. &quot;</pre><pre>D:\Anaconda3\lib\site-packages\tensorflow\python\ops\gradients_impl.py:108: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory.<br>  &quot;Converting sparse IndexedSlices to a dense Tensor of unknown shape. &quot;</pre><pre>Train on 193 samples, validate on 49 samples<br>Epoch 1/40<br>193/193 [==============================] - 2s 11ms/step - loss: 0.6589 - acc: 0.7720 - val_loss: 0.6655 - val_acc: 0.6327<br>Epoch 2/40<br>193/193 [==============================] - 0s 749us/step - loss: 0.5980 - acc: 0.7720 - val_loss: 0.6589 - val_acc: 0.6327</pre><pre>...</pre><h4>Evaluate the model</h4><p>Finally, we evaluate our model and return the ‘Loss’ rate and accuracy.</p><pre>results = model.evaluate(test_data, Y_test)</pre><pre>print(&quot;Results: Loss:<strong>{0}</strong> Accuracy: <strong>{1}</strong> &quot;.format(results[0], results[1]))</pre><pre>49/49 [==============================] - 0s 81us/step Results: Loss:0.10914735039886163 Accuracy: 0.9795918367346939</pre><h4><em>This simple model achieves an accuracy of about 97%.</em></h4><p>However, this is a rather contrived model with a very small dataset which was tagged largely using a simple regular expression pattern. Still, the relatively good performance of the classifier may indicate that with properly curated training sets and more sophisticated models, good performance can equally be expected.</p><p>Let’s see a graph of the accuracy over each training cycle.</p><pre><strong>import</strong> <strong>matplotlib.pyplot</strong> <strong>as</strong> <strong>plt</strong></pre><pre>history_dict = history.history<br>history_dict.keys()</pre><pre>acc = history_dict[&#39;acc&#39;]<br>val_acc = history_dict[&#39;val_acc&#39;]<br>loss = history_dict[&#39;loss&#39;]<br>val_loss = history_dict[&#39;val_loss&#39;]</pre><pre>epochs = range(1, len(acc) + 1)</pre><pre>plt.clf()   <em># clear figure</em></pre><pre>plt.plot(epochs, acc, &#39;bo&#39;, label=&#39;Training acc&#39;)<br>plt.plot(epochs, val_acc, &#39;b&#39;, label=&#39;Validation acc&#39;)<br>plt.title(&#39;Training and validation accuracy&#39;)<br>plt.xlabel(&#39;Epochs&#39;)<br>plt.ylabel(&#39;Accuracy&#39;)<br>plt.legend()</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*wngx2-iuIJihPR7Nf1F0zw.png" /></figure><p>We see the training accuracy stabilizing at around 95–98% mark. I have avoided running the training for a higher number of epochs as previous runs with a greater number of cycles produced an accuracy of 100% which might indicate overtraining.</p><p>Next, let’s run some predictions over the test set and print out the results where the prediction does not match with the true class label.</p><pre>pred_classes = model.predict_classes(test_data)</pre><pre><strong>for</strong> _pred, _label, _sent <strong>in</strong> zip(pred_classes, Y_test, test_data):<br>    <strong>if</strong> _pred != _label:<br>        print(&quot;P=[<strong>{}</strong>]Y=[<strong>{}</strong>]S=[<strong>{}</strong>]&quot;.format(_pred, _label,&#39; &#39;.join([tokenizer.index_word.get(i, &quot;&quot;)  <strong>for</strong> i <strong>in</strong> _sent])))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*hlG35w-E8MltohEgv6qS8w.png" /></figure><p>Indeed it did not agree with the truth set in this instance and the classifier seems to have done better than the ‘hazy’ tagging process. One can surmise that it might have picked up the correct pattern from the majority of the properly hazy tagged set. Only with more and better-curated datasets can we verify this conjecture.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4948acab8eec653ec4869e911982756a/href">https://medium.com/media/4948acab8eec653ec4869e911982756a/href</a></iframe><p>This notebook is based on the one found at: <a href="https://www.tensorflow.org/tutorials/keras/basic_text_classification">https://www.tensorflow.org/tutorials/keras/basic_text_classification</a> which is licensed under the MIT License. This notebook itself and associated materials are free for personal academic research use and are provided as-is and without any warranty of any sort.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c36a1016341" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>