<?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 Scott Jones on Medium]]></title>
        <description><![CDATA[Stories by Scott Jones on Medium]]></description>
        <link>https://medium.com/@scottcurtisjones?source=rss-7ec43ca7275c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aaeuI_XiEvl7evhC.</url>
            <title>Stories by Scott Jones on Medium</title>
            <link>https://medium.com/@scottcurtisjones?source=rss-7ec43ca7275c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 07:35:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@scottcurtisjones/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[Labeling Legal Documents Using Machine Learning]]></title>
            <link>https://medium.com/data-science/labeling-legal-documents-using-machine-learning-49e3a34f2619?source=rss-7ec43ca7275c------2</link>
            <guid isPermaLink="false">https://medium.com/p/49e3a34f2619</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[history]]></category>
            <category><![CDATA[labels]]></category>
            <category><![CDATA[legal]]></category>
            <dc:creator><![CDATA[Scott Jones]]></dc:creator>
            <pubDate>Wed, 06 Nov 2019 17:59:32 GMT</pubDate>
            <atom:updated>2022-07-19T13:47:04.060Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>The problem of labeling data is often considered the first step in a machine learning project, where a training data set is developed that accurately represents unseen, anticipated “test” data. However, for large data sets, including natural language corpora, the exercise of labeling may by itself bring immense value to an organization.</p><p>Libraries, especially those at academic institutions aiming to educate students and future researchers, bear just such a burden. While great strides have been made at digitizing the innumerable volumes of information, using optical character recognition (OCR), research can still prove tedious and time-consuming if the text is left without linkages to foundational appendices, or other reference material.</p><h3>The Data</h3><p>During a recent project with an esteemed library, I was tasked with facilitating the ease-of-use of the transcripts of historical court tribunals by identifying and labeling the source of the evidentiary documents that were presented. These were either trial documents, used by either the prosecution or defense to argue their case, or evidence file documents, which are part of a broader domain of documents and contain their own naming scheme.</p><p>Each have their own specific means of identification. In the case of evidence file documents, regular expressions (regex) were used to find any of a set of pre-defined, coded document groups. Differentiating between prosecution and defense trial documents, on the other hand, relied on much more subtle context clues, and oftentimes required a careful reading of the transcript so as to properly follow the conversation.</p><h3>The Method</h3><p>On a first pass, all possible references were flagged with regex, and the evidence file documents partitioned off. Of the remaining references, those that were obviously prosecution or obviously defense were immediately classified and set aside for use as a training set to a random forest algorithm, in order to make a determination on the more ambiguous cases.</p><p>This is where the model was most liable to make mistakes. Accuracy of the tags was most important, but followed closely by recall (finding as many references as possible). Therefore, we engaged in regular back-and-forths with the client, who performed manual inspections of the results and reported back. In this way, we could fine-tune the algorithm by, for example, supplying additional features, hyperparameter tuning, or augmenting the less represented class.</p><p>The primary feature used was the reference context. After collecting a given number of words, or tokens, on either side of the reference in question, the entities were stemmed and lemmatized, and finally converted to a term-frequency inverse document frequency (tf-idf) embedding. This method weights a count of the most common words by how often they occur across each “document” (in this case the context surrounding a single reference). As a consequence, all words will have an integer representation that is capable of being supplied as input to a machine learning algorithm.</p><p>The same scheme was also applied to the current speaker. Other features were constructed based on the presence or absence of key trigger words, such as “prosecution”, or one of the attorneys’ or defendants’ names. The random forest was implemented as:</p><pre>forest = RandomForestClassifier(criterion=&#39;entropy&#39;, n_estimators=500, random_state=0, n_jobs=-1)</pre><p>where the ‘entropy’ split selection criterion has been used. Although more computationally intensive, it is often more suitable for categorical data. The performance of the algorithm at each of a series of probability thresholds was determined so as to maximize both accuracy and recall. Thereafter, anything greater than the threshold was labeled “prosecution”, and less than, “defense”.</p><h3>Issues</h3><p>From the start, the accuracy of the model was high and required little further enhancement. More of a challenge was ensuring that we were capturing a large majority of the references. There was a big variation in the manner in which references were cited, including everything from abbreviations to stray punctuation. The regex had to be built to accept references appearing across multiple lines. Also, many references contained combinations of different possible types, that would, to a regex definition, appear like multiple unique tag opportunities. The latter would become especially troublesome when reconstructing the text at the end with the labels, as the trailing part of the reference was liable to being cut off and replaced prematurely by the tag.</p><p>The only thing that many of these edge cases had in common was the presence of a number, no more than five digits in length. Upon a second pass through the transcript, we identified all remaining such numbers, filtering any false positives that would be found (dates, page numbers, cardinal adjectives). Of those that were left, rules were developed to ensure a reference (the presence of certain introductory phrases) and labels assigned.</p><h3>Lessons Learned</h3><p>While functional, the work done during the second pass was very ad hoc, and cannot be easily used on other datasets. Nevertheless, much of that work, and that across the whole project, closely resembles the application of labeling functions (LFs) as part of Stanford’s <a href="https://www.snorkel.org/">Snorkel</a> project. Realizing that labeling data is the most time-intensive and inconsistent part of machine learning, they use rule-based LFs to codify the means to tag data. Here, coverage is often less controllable than precision, so it remains to be seen how well this formula would have helped given our constraints on recall.</p><p>The dataset that we worked with should not be seen as exceptionally unique or irregular. Legal text is some of the most dense of any profession, and appears ripe for many of the cost- and time-savings measures that natural language processing (NLP) provides. Search speed is of the essence, whether as it has been described here, or a means to relate <a href="https://towardsdatascience.com/why-we-switched-from-spacy-to-flair-to-anonymize-french-legal-cases-e7588566825f">textual entities</a> to broader keywords. And though our work was complicated by text inconsistencies that may have been a product of the OCR, we can’t expect more modern documents to be much better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49e3a34f2619" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/labeling-legal-documents-using-machine-learning-49e3a34f2619">Labeling Legal Documents Using Machine Learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Best-Selling Books of the Last Five Years]]></title>
            <link>https://medium.com/data-science/exploring-best-selling-books-of-the-last-five-years-8f4740449289?source=rss-7ec43ca7275c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f4740449289</guid>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[spectral-clustering]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[Scott Jones]]></dc:creator>
            <pubDate>Sat, 07 Sep 2019 00:34:30 GMT</pubDate>
            <atom:updated>2022-07-19T13:46:52.424Z</atom:updated>
            <content:encoded><![CDATA[<p>Every week, the New York Times (NYT) publishes a list of the top ten highest-selling novels in each of the fiction and non-fiction categories. As an avid reader, I wanted to determine whether these lists might offer suggestions for future reads (i.e. whether they might cater more strongly to a particular sub-genre) and to finally answer one of the most nagging questions for me of the past one plus years: is it just me or do a large percentage of recent best-sellers contain the word “girl”?!</p><p>What follows is a quick exploration of a NYT bestseller data set that I’ve self-curated using the newspaper’s own API. This work was partially inspired by work done by others, particularly that done by Michael Tauberg (<a href="https://medium.com/@michaeltauberg/how-to-name-a-bestseller-6f7313fbb9e6">https://medium.com/@michaeltauberg/how-to-name-a-bestseller-6f7313fbb9e, </a><a href="https://towardsdatascience.com/book-titles-are-getting-longer-1c341fbd4829">https://towardsdatascience.com/book-titles-are-getting-longer-1c341fbd4829</a>). I’ve chosen to examine two time periods: the last year, and the last five years, so as to unearth any underlying trends.</p><p>As you’d expect with a weekly publication rate, there is not much variation in the titles that appear on the list from one week to the next. As my first step I therefore removed any and all duplicates. The word cloud below shows the prevalence of each word in the remaining corpus for the preceding five years. Sure enough, we see right away that the word “Girl” dominates the diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*hJJN0mXEBa1PJLOXAJuPKA.png" /><figcaption>Best selling title words over the last five years.</figcaption></figure><p>In the last year exclusively, this trend does not disappear. Instead we are left with higher frequencies of words with darker themes, such as “murder”, “war”, “lost”, “devil” and indeed “dark” itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*3uh1PG4UChkAPJW6hgBqig.png" /><figcaption>Best selling title words over the last year.</figcaption></figure><p>In this era of sequels and prequels, we might also expect to see lengthier titles most recently, as series append modifying descriptions (think “Harry Potter and …”). Indeed this is marginally true, as the five year period has a mean title length of 2.74 words, while the last year increases to 2.79 (a year-by-year analysis would prove most useful here).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*9kN_a1yUlm2ghKoRlzeV5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*4tlVXVGCfG3DZeh2o6L85Q.png" /><figcaption>Distribution of title lengths over the last five years (left) and one year (right).</figcaption></figure><h3><strong>Clustering of Book Descriptions</strong></h3><p>Alongside the book titles, the API also provides a modestly thorough description of the novel. With this data, we should be able to make a first guess at classifying the book’s genre. However, as the best selling books are those that appeal to the broadest number of people, we might not expect outstanding results in this exercise.</p><p>The information content of the titles themselves is probably not dense enough to make any accurate judgments. Therefore, we’ll employ the raw text of the descriptions. As a matter of practice, anytime you are dealing with raw text, the standard preprocessing steps of tokenization, removing common (stop) words, and reducing each word to its basest form (stemming/lemmatization) must be performed. Here we do so prior to submitting the tokens to TfidfVectorizer, which converts them into numeric features based on the frequency of each token within the learned vocabulary. In this way we have built our own “book-related” corpus without the use of any previously created embeddings.</p><p>There are many widely-used and available clustering techniques. With any of these unsupervised learning methods, the toughest decision is the number of clusters to use as a starting parameter. In our case, there is certainly a limit to the number of genres that we can imagine, at least on a first cut. Again, it is unlikely that a NYT best-seller list will travel too deeply down the nested tree of possible sub-genres. (And most of the fun involved with unsupervised learning is seeing what the algorithm can come up with).</p><p>In the most common type of clustering, k-means, there are smart ways to justify this choice, such as the “elbow method”. This method attempts to select ‘k’ such that the marginal gain in variance explained by the next highest choice decreases for the first time. In other words, it selects the turning point, or “elbow” in a plot of variance explained versus number of clusters. With our dataset, up to 50 clusters, we obtain the plot below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*MD6aWWbEH4Vr5XHtJOPMog.png" /><figcaption>Attempt to select the ideal number of clusters using the elbow method.</figcaption></figure><p>Already, we can see that K-means is having difficulty sorting out the clusters, as there is no discernible elbow present in the plot. For this reason and others, it is more common to use the silhouette method, which uses a distance measure (often euclidean) to assess the separation between points of a cluster. A silhouette coefficient near 1 implies good separation. However here as well, we obtain nearly linearly increasing silhouette scores with the number of clusters, suggesting that there is no clear separation being achieved.</p><p>In our five-year dataset, we have roughly 1400 unique titles. The most obvious choice left is to assume an equal split among the clusters, and select sqrt(1400)=37 as a first guess.</p><p>Having done so, we can confirm our suspicion of the poorly separated clusters by using the TSNEVisualizer, which renders vectorized corpus in two dimensions, coloured by the predetermined clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*GUDaoJIq7K5ePZBBo6c0Hg.png" /><figcaption>TSNE Visualization of our novel descriptions.</figcaption></figure><p>Although at first glance this looks like a mess, there do seem to be some denser pockets that might truly be capturing similarities.</p><p>In contract to K-means clustering, spectral clustering is a graph-clustering technique which uses a similarity matrix to identify clusters, rather than simply a distance measure. Practically, spectral clustering is often better at separating overlapping data points; it cares less about where they lie in space, and more about their similarity in content. Such sounds quite relevant to us; we’ll use spectral clustering from here on.</p><p>Doing so, we get a distribution quite common with clustering, where the largest cluster dwarfs those that are smaller than it.</p><pre>Cluster_number Count<br>0     261<br>33     88<br>13     87<br>36     65<br>18     64<br>17     64<br>2      63<br>10     59<br>1      58<br>19     49<br>30     48<br>32     47<br>24     42<br>.<br>.<br>.</pre><p>How best do we visualize text clusters to learn what they contain? One of the best ways is with the <a href="http://vis.stanford.edu/papers/termite">Termite</a> d3 package out of the University of Washington, which charts the prevalence, or saliency, of common words by topic. Work for this project has been primarily in Python, so we’ll constrain ourselves to that language for now. Perhaps we can rank order the words in each topic and present the median one or two words? Often this still leads to words lacking meaning, especially if the size of a cluster is small.</p><p>The nltk package has a nice method called freqDist that determines the frequency distribution of words within a string. For cluster 0, shown above to be the most populous, if we sample only those words longer than 5 characters and occurring more than 3 times, we get a list that looks like:</p><pre>Cluster 0:<br><br>[&#39;america&#39;, &#39;american&#39;, &#39;ancient&#39;, &#39;artist&#39;, &#39;becomes&#39;, &#39;between&#39;, &#39;british&#39;, &#39;criminal&#39;, &#39;dangerous&#39;, &#39;during&#39;, &#39;encounters&#39;, &#39;father&#39;, &#39;follows&#39;, &#39;forensic&#39;, &#39;former&#39;, &#39;friendship&#39;, &#39;herself&#39;, &#39;investigation&#39;, &#39;investigator&#39;, &#39;involving&#39;, &#39;island&#39;, &#39;missing&#39;, &#39;mysterious&#39;, &#39;nantucket&#39;, &#39;parents&#39;, &#39;people&#39;, &#39;private&#39;, &#39;pursues&#39;, &#39;search&#39;, &#39;sequel&#39;, &#39;series&#39;, &#39;summer&#39;, &#39;together&#39;, &#39;treasure&#39;, &#39;vampire&#39;, &#39;wedding&#39;]</pre><p>There are certainly a lot of words to go from here, but they really are quite diverse and lacking consistency. Contrast that with a tighter cluster, 2, with 63 data points, and we start to see a pattern emerge:</p><pre>Cluster 2:<br><br>[&#39;detective&#39;, &#39;detectives&#39;, &#39;disappearance&#39;, &#39;husband&#39;, &#39;investigate&#39;, &#39;investigates&#39;, &#39;lieutenant&#39;, &#39;murder&#39;, &#39;partner&#39;, &#39;president&#39;, &#39;series&#39;]</pre><p>Indeed if we access the entire descriptions for the first 5 element of cluster 2, we get:</p><pre>Sally Grissom investigates the disappearance of President Harrison Tucker’s wife.<br>D.D. Warren and Flora Dane investigate whether a pregnant woman shot and killed her husband.<br>Detective Dave Robicheaux and his new partner Bailey Ribbons investigate the death of a young woman by crucifixion.<br>Nick Fourcade and Annie Broussard, a husband-and-wife detective team, investigate a boy’s murder and the disappearance of his babysitter.<br>A television producer investigates the murder of a physician and whether it was his wife who killed him.</pre><p>All clearly investigative mysteries!</p><p>Finally, we can also further sub-cluster the largest cluster found above using only its description as our new corpora. Now we have sqrt(261)=16 smaller clusters. For the largest of these, we now have the following common words and a sample of some of the descriptions:</p><pre>[&#39;american&#39;, &#39;encounters&#39;, &#39;finds&#39;, &#39;found&#39;, &#39;widow&#39;]<br>A Star Wars saga. Grand Admiral Thrawn must choose between his sense of duty to the Chiss Ascendancy and loyalty to the Empire.<br>A photographer embarks on a road trip to reconnect with three men she might have married.<br>Maxim Trevelyan inherits several estates and beds his cleaner Alessia Demachi, an Albanian piano prodigy who has been trafficked into England.<br>Hans-Peter Schneider pauses his ghastly deeds to seek a dead man’s gold hidden under a Miami mansion, but its caretaker’s surprising skills prove daunting.<br>Investigations by Leaphorn, Chee and Manuelito overlap in the desert Southwest.</pre><p>We still have the words “american” and “encounters”, but many less than in our initial cluster 0. However, the descriptions themselves still lack much consistency.</p><h3><strong>Conclusion</strong></h3><p>We have explored our New York Times best sellers dataset, unveiling a trend toward darker themes in more recent years. There also seems to be a suggestion that book title lengths are increasing. We then took a look at clustering the books based on their descriptions using both K-means and spectral clustering, and brainstormed a few ideas for ways in which to visualize the results. Although there were some common themes that emerged, it appears there is not enough information in order to make conclusive statements on genre.</p><p>Stay tuned for a follow up post where we’ll use transfer learning in order to predict the polarity (positive or negative) of Kindle book reviews!</p><p>Please find the code at <a href="https://github.com/scjones5/nyt-bestsellers.git">https://github.com/scjones5/nyt-bestsellers.git</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f4740449289" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/exploring-best-selling-books-of-the-last-five-years-8f4740449289">Exploring Best-Selling Books of the Last Five Years</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Classification of Freedom of Information Requests: Part III]]></title>
            <link>https://medium.com/data-science/text-classification-of-freedom-of-information-requests-part-iii-9b34e0a9df07?source=rss-7ec43ca7275c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b34e0a9df07</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[regularization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[recurrent-neural-network]]></category>
            <dc:creator><![CDATA[Scott Jones]]></dc:creator>
            <pubDate>Mon, 04 Mar 2019 03:12:07 GMT</pubDate>
            <atom:updated>2022-07-19T13:46:43.809Z</atom:updated>
            <content:encoded><![CDATA[<p>In Part I of this series, we ran an immature model against Kitchener-Waterloo freedom of information requests, attempting to predict a response. In Part II, we expanded our dataset by including requests in the city of Toronto, and added a bit of domain knowledge through exploratory data analysis. We also dealt with the inequality that existed between the number of observations in each of the six different decision classes.</p><p>In this third part, we’ll repeat the use of each of LinearSVC, Multinomial Naive Bayes, Logistic Regression and Random Forest but now individually for one class at a time, against all other classes. This is a technique often used for multi-label problems, where, in our case, each request has multiple decisions rendered by, for example, different parties. The key assumption needed is that every label, or class (decision) is mutually exclusive and independent of all others. While an argument can be made that that is not strictly true here (‘partly disclosed’ may eventually become ‘all disclosed’, or there may be cases where different decisions are made for identical requests), we will proceed understanding that the assumption has been made.</p><p>The basic code is structured as follows:</p><pre>from sklearn.metrics import accuracy_score</pre><pre>NB_pipeline = Pipeline([<br>                (&#39;tfidf&#39;, TfidfVectorizer(tokenizer=tokenizeText, stop_words=&#39;english&#39;)),<br>                (&#39;clf&#39;, OneVsRestClassifier(MultinomialNB())),<br>            ])</pre><pre>for decision in categories:<br>    print(decision)<br>    NB_pipeline.fit(X_train, y_train_dums[decision])<br>    prediction = NB_pipeline.predict(X_test)    <br>    print(&#39;Test accuracy is {}&#39;.format(accuracy_score(y_test_dums[decision], prediction)))</pre><pre>Disclosed in Part: Partially Exempt Test accuracy is 0.8520182907600126 <br>All Disclosed Test accuracy is 0.8698360138757489 <br>No Responsive Records Exist Test accuracy is 0.8816619362976978 Nothing Disclosed (exemption) Test accuracy is 0.934799747713655 Request withdrawn Test accuracy is 0.9653106275622831 <br>Transferred Out in Full Test accuracy is 0.9943235572374646</pre><p>where the target variable has been previously encoded as one-hot vectors. The results for LinearSVC:</p><p><strong><em>Disclosed in Part: Partially Exempt Test accuracy is 0.9100441501103753<br>All Disclosed Test accuracy is 0.9057079785556607<br>No Responsive Records Exist Test accuracy is 0.9505676442762535<br>Nothing Disclosed (exemption) Test accuracy is 0.9874645222327342<br>Request withdrawn Test accuracy is 0.9953484705140334<br>Transferred Out in Full Test accuracy is 0.9995269631031221</em></strong></p><p>Logistic Regression:</p><p><strong><em>Disclosed in Part: Partially Exempt Test accuracy is 0.8661305581835383<br>All Disclosed Test accuracy is 0.8785083569851782<br>No Responsive Records Exist Test accuracy is 0.8984547461368654<br>Nothing Disclosed (exemption) Test accuracy is 0.9661778618732261<br>Request withdrawn Test accuracy is 0.9869914853358562<br>Transferred Out in Full Test accuracy is 0.9981866918953012</em></strong></p><p>Random Forest:</p><p><strong><em>Disclosed in Part: Partially Exempt Test accuracy is 0.826631977294229<br>All Disclosed Test accuracy is 0.8324660990223904<br>No Responsive Records Exist Test accuracy is 0.8423210343740145<br>Nothing Disclosed (exemption) Test accuracy is 0.8342005676442763<br>Request withdrawn Test accuracy is 0.8341217281614632<br>Transferred Out in Full Test accuracy is 0.8315988647114475</em></strong></p><p>The LinearSVC method still seems to performs the best, looking most closely at the “Disclosed in Part” class. Generally the trend is to increasing accuracy to classes with less (pre-upsampled) data. Likely, the upsampled data is somewhat artificial, and by definition must closely resemble what is already there.</p><p>An attempt was also made at using XGBoost in the same manner, with an accuracy of 83.4% for “Disclosed in Part”, although at a much higher computational cost.</p><h3><strong>Deep Learning with Recurrent Neural Nets</strong></h3><p>As a last effort with this dataset, we’ll employ deep learning in the form of recurrent neural networks (RNNs). RNNs retain some memory of steps that come before in a sequence, or, for a bidirectional implementation, before <em>and</em> after the current step. They are therefore extremely useful in tasks like document summarization and machine translation and can deal with inputs and outputs of different sizes.</p><p>In our project, we have many input tokens as part of the request string, and, essentially, one output in the form of a decision class. The model can hence be thought of as a many-to-one classifier.</p><p>Using Google Colaboratory GPU capabilities, the following model was implemented:</p><pre>input= Input(shape=(max_len, ), dtype = &#39;int32&#39;)<br>embedding_layer = Embedding(len(word_index) + 1, embedding_dim, embeddings_initializer=Constant(embedding_matrix), input_length=max_len, trainable=False)<br>embedded_sequences = embedding_layer(input)<br>x = Bidirectional(GRU(units=32, return_sequences=True))(embedded_sequences)<br>x = GlobalMaxPooling1D()(x)<br>x = Dense(50, activation = &#39;relu&#39;)(x)<br>x = Dropout(0.2)(x)<br>output = Dense(num_classes, activation=&#39;softmax&#39;)(x)<br>model = Model(inputs=input, outputs=output)<br>model.compile(loss=&quot;categorical_crossentropy&quot;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])</pre><pre>metrics=[&#39;accuracy&#39;])<br>print(model.summary())</pre><p>We have used GloVe word embeddings padded to a length of 40 units, a maximum length to which most of the requests adhered:</p><pre>embeddings_index = {}</pre><pre># Download this file first<br>f = open(&quot;/content/drive/My Drive/foi-kw/glove.6B.300d.txt&quot;, encoding=&quot;utf8&quot;)</pre><pre>for line in f:<br>    values = line.split()<br>    word = &#39;&#39;.join(values[:-embedding_dim])<br>    coefs = np.asarray(values[-embedding_dim:], dtype=&quot;float32&quot;)<br>    embeddings_index[word] = coefs<br>f.close()</pre><pre>tokenizer = Tokenizer(num_words = None)<br>tokenizer.fit_on_texts(X_train)</pre><pre>sequences_train = tokenizer.texts_to_sequences(X_train)<br>X_train = pad_sequences(sequences_train, maxlen=max_len)</pre><pre>sequences_val = tokenizer.texts_to_sequences(X_test)<br>X_test = pad_sequences(sequences_val, maxlen=max_len)</pre><pre>word_index = tokenizer.word_index</pre><pre>#create embedding layer<br>embedding_matrix = np.zeros((len(word_index) + 1, embedding_dim))</pre><pre>for word, i in word_index.items():<br>    embedding_vector = embeddings_index.get(word)<br>    if embedding_vector is not None:<br>        embedding_matrix[i] = embedding_vector</pre><pre>import matplotlib.pyplot as plt</pre><pre>checkpoint = ModelCheckpoint(&quot;/content/drive/My Drive/foi-kw/colab/models/model.h5&quot;, monitor=&#39;val_loss&#39;, verbose=1, save_best_only=True, mode=&#39;min&#39;)<br>early = EarlyStopping(monitor=&#39;val_loss&#39;, mode=&#39;min&#39;, patience=3)<br>callback = [checkpoint, early]</pre><pre>history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, validation_data=(X_test, y_test), callbacks=callback, class_weight=class_weights)<br>loss, accuracy = model.evaluate(X_train, y_train, verbose=0)<br>print(&#39;Accuracy: %f&#39; % (accuracy*100))<br>print(history.history.keys())<br># Plot history for accuracy<br>plt.plot(history.history[&#39;acc&#39;])<br>plt.plot(history.history[&#39;val_acc&#39;])<br>plt.title(&#39;model accuracy&#39;)<br>plt.ylabel(&#39;accuracy&#39;)<br>plt.xlabel(&#39;epoch&#39;)<br>plt.legend([&#39;train&#39;, &#39;test&#39;], loc=&#39;upper left&#39;)<br>plt.show()<br># Plot history for loss<br>plt.plot(history.history[&#39;loss&#39;])<br>plt.plot(history.history[&#39;val_loss&#39;])<br>plt.title(&#39;model loss&#39;)<br>plt.ylabel(&#39;loss&#39;)<br>plt.xlabel(&#39;epoch&#39;)<br>plt.legend([&#39;train&#39;, &#39;test&#39;], loc=&#39;upper left&#39;)<br>plt.show()<br>model.reset_states()</pre><p>Early stopping has been used in an effort to avoid overfitting, as have ‘class_weights’ to deal with the class imbalance. For further description of the keywords and their meaning, I would point the reader to the excellent <a href="https://towardsdatascience.com/predicting-wine-quality-using-text-reviews-8bddaeb5285d">article</a> by Mandy Gu to predict wine ratings.</p><p>The accuracy and loss plots, as coded above, yield:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0hxdZ7nq9t3M6lqg3MQEA.png" /><figcaption>Training and test accuracy over 12 epochs.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*6DRETStQldBdhTv41tvdpg.png" /><figcaption>Training and test loss over 12 epochs.</figcaption></figure><p>Curiously, the test loss stays at a fairly constant value. In our model we have used dropout regularization during training, meaning the network is not run at full capacity, while dropout is not used during testing. Another explanation may be that testing loss for an epoch is calculated as it is at the end of the epoch, while training loss is the average over each batch of training data.</p><h3>Conclusion</h3><p>This series of articles has covered a lot of ground and represents the author’s first real foray into building machine learning models for text data. The analysis has benefited greatly from the addition of the Toronto data set, such that we can have some confidence that we are able to pick up on some common trends. All the same, there is probably little variation in the actual text of the requests, and the decisions remain judgments by human overseers, both factors that likely muddle our results. Finally, even through these three articles there remains much that could be attempted (different type of neural network, GridSearchCV for hyperparameter tuning, AutoML) to improve our results.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b34e0a9df07" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/text-classification-of-freedom-of-information-requests-part-iii-9b34e0a9df07">Text Classification of Freedom of Information Requests: Part III</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Classification of Freedom of Information Requests: Part II]]></title>
            <link>https://medium.com/data-science/text-classification-of-freedom-of-information-requests-part-ii-4d57b080d179?source=rss-7ec43ca7275c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d57b080d179</guid>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[imbalanced-data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Scott Jones]]></dc:creator>
            <pubDate>Sun, 03 Mar 2019 18:11:22 GMT</pubDate>
            <atom:updated>2019-03-10T18:18:27.683Z</atom:updated>
            <content:encoded><![CDATA[<p>In part I, we ingested the available Kitchener-Waterloo Freedom of Information data and managed to aggregate the prediction classes using fuzzy string matching. From there, we were able to attempt predictions using four different classifier algorithms: Random Forest, Linear Support Vector Classification, Multinomial Naive Bayes, and Logistic Regression. The results were not very impressive.</p><p>Here, we’ll add to our dataset by including requests made in the city of Toronto. We’ll do a bit more exploratory data analysis to see if there’s any way we might help our models along, and then we’ll try to be a bit smarter in how we use machine learning and, in part III, deep learning, to achieve the best possible results.</p><p>In part I our dataset had 832 entries; supplementing this with data from the larger city brings our total to 11521 entries, which begins to resemble something more befitting a machine learning problem. The KW data still covers a larger period of time, beginning in 1993 and complete up until 2016:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*qTnv1c0hsYfVFqk3y5OSBw.png" /><figcaption>FOI requests over time in KW</figcaption></figure><p>The Toronto data, from 2011–2018, does not show the same increasing trend,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*4xKmX_hNt9K01iqfLN41Aw.png" /><figcaption>Requests by year in Toronto</figcaption></figure><p>but there must nevertheless be some time to be saved if we can come up with some pattern linking the text in the requests themselves and the decision rendered.</p><p>What about the content of the requests themselves? To get a quick understanding of the phrases people are using, we can examine a word cloud for each of the two data sets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*3klvp7NZpr1op1zdSXWgEQ.png" /><figcaption>KW requests</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*UqufXGwLX0RodBD2Blz7cA.png" /><figcaption>Toronto requests</figcaption></figure><p>In each case I have removed a few bigrams that were being used to protect personal privacy but also by themselves conveyed no useful information. These included “address removed”, “name removed” and “location removed”. What we are left with are more interesting bigrams such as “Ontario Works”, “building permit”, and “environmental site”. Keeping the datasets separate like this allows us to note that the KW requests tend to hew more toward environmental concerns, while the Toronto requests appear more generic. It’s important to be careful before drawing too many conclusions here though, as it is unknown, and probably unlikely, that this is the text exactly as it was submitted by the individuals/businesses. More likely is that the data has been transcribed at some point from an online or print form.</p><p>An important part of dealing with any free-form text is to preprocess. Here, where each request normally fits nicely within a ~50 word sentence or two, things can be easily tokenized. Feeding each request to the below function:</p><pre>import spacy<br>from spacy.lang.en import English<br>from nltk.corpus import stopwords<br>from sklearn.feature_extraction.stop_words import ENGLISH_STOP_WORDS<br>from wordcloud import WordCloud, STOPWORDS<br>import string<br>parser = English()<br>STOPLIST = set(stopwords.words(&#39;english&#39;) + list(ENGLISH_STOP_WORDS)+ list(STOPWORDS))<br>SYMBOLS = &quot; &quot;.join(string.punctuation).split(&quot; &quot;) + [&quot;-&quot;, &quot;...&quot;, &quot;”&quot;, &quot;”&quot;]</pre><pre>def tokenizeText(sample):<br>    tokens = parser(sample)<br>    lemmas = []<br>    for tok in tokens:<br>        #lemmatizes, converts to lowercase, omits pronouns<br>        lemmas.append(tok.lemma_.lower().strip() if tok.lemma_ != &quot;-PRON-&quot; else tok.lower_)<br>    tokens = lemmas<br>    #removes stop word tokens and symbols<br>    tokens = [tok for tok in tokens if tok not in STOPLIST]<br>    tokens = [tok for tok in tokens if tok not in SYMBOLS]<br>    return tokens</pre><p>we can use SpaCy to first parse the text, and then find the lemma of each word and convert to lowercase. Using nltk, we can finally remove any stop words or symbols. nltk also provides the method ‘Morphy’ for lemmatization, a further step which is largely repetitive, but for me, has nevertheless caught some plurals that were missed by SpaCy:</p><pre>import nltk<br>nltk.download(&#39;wordnet&#39;)<br>from nltk.corpus import wordnet as wn<br>def get_lemma(word):<br>    #print(&quot;un-lemmad word: &quot;, word)<br>    lemma = wn.morphy(word)<br>    #print(&quot;lemma-d word: &quot;, lemma)<br>    if lemma is None:<br>        return word<br>    else:<br>        return lemma</pre><p>Calling these two functions and removing any tokens of length less than 5:</p><pre>def prepare_text_for_lda(text):<br>    # tokenizes text using spacy<br>    tokens = tokenizeText(text)<br>    # removes tokens less that five characters<br>    tokens = [token for token in tokens if len(token) &gt; 4]<br>    # here we are lemmatizing again too; noticed that previous lemmatization doesn&#39;t handle plurals<br>    tokens = [get_lemma(token) for token in tokens]<br>    return tokens</pre><p>Putting it all together and incorporating the results:</p><pre>import random<br>text_data = []<br>for request in (all_df[&#39;Summary_of_Request&#39;]):<br>    tokens = prepare_text_for_lda(request)<br>    text_data.append(tokens)</pre><p>As an example, here is the first request in the dataframe, and its associated tokens:</p><pre>Notes written by members of the Maintenance Review Committee for Clerk III, Healthy Environments.<br>[&#39;note&#39;, &#39;write&#39;, &#39;member&#39;, &#39;maintenance&#39;, &#39;review&#39;, &#39;committee&#39;, &#39;clerk&#39;, &#39;healthy&#39;, &#39;environment&#39;]</pre><p>One final bit of EDA that is always interesting with text data is to do a bit of topic modeling. The package GenSim can identify semantic similarity primarily through Latent Dirichlet Allocation (hence the name for the above function), and from that pick out a requested number of “topics”, showing the words that most identify with each topic. Based on a pre-defined dictionary, (here the <strong><em>text_data </em></strong>list from earlier) the method doc2bow uses the bag of words format to return an index and a frequency of each word. This is then passed to an LDA model until finally one is able to see the words, along with their relative importances, associated with each topic:</p><pre>(0, &#39;0.078*&quot;record&quot; + 0.063*&quot;permit&quot; + 0.057*&quot;build&quot; + 0.055*&quot;inspection&quot;&#39;)<br>------------------------------------------------------------------------------------------<br>(1, &#39;0.124*&quot;report&quot; + 0.092*&quot;incident&quot; + 0.076*&quot;occur&quot; + 0.032*&quot;address&quot;&#39;)<br>------------------------------------------------------------------------------------------<br>(2, &#39;0.167*&quot;specify&quot; + 0.084*&quot;address&quot; + 0.027*&quot;toronto&quot; + 0.020*&quot;include&quot;&#39;)<br>------------------------------------------------------------------------------------------<br>(3, &#39;0.044*&quot;water&quot; + 0.042*&quot;record&quot; + 0.029*&quot;toronto&quot; + 0.021*&quot;sewer&quot;&#39;)<br>------------------------------------------------------------------------------------------<br>(4, &#39;0.071*&quot;record&quot; + 0.034*&quot;property&quot; + 0.032*&quot;complaint&quot; + 0.021*&quot;investigation&quot;&#39;)<br>------------------------------------------------------------------------------------------</pre><p>We can see that the word ‘record’ is associated with multiple different topics but that overall the terms used are fairly generic.</p><p>In Part I, we talked primarily of the use of the fuzzywuzzy package to combine similar seeming decisions. With the inclusion of the Toronto data, the ‘partial_ratio’ method remains the most applicable, and allows us to narrow the decisions down to 6 categories, shown below alongside the count of the number of observations falling into each group.</p><pre>Disclosed in Part: Partially Exempt    6406<br>All Disclosed                           2847<br>No Records Exist                        1393<br>Nothing Disclosed                        371<br>Request withdrawn                        256<br>Transferred Out in Full                  168</pre><p>As we progress toward making predictions, we should keep in mind that the most frequent decision, ‘Disclosed in Part: Partially Exempt’, should offer the most stringent test of our models, as it is a case that lies between the ‘All Disclosed’ and ‘Nothing Disclosed’ extremes. If we can accurately predict this case, then the others should come more easily. Luckily it has the most data.</p><p>The figure below is updated to include the Toronto data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrgn1kfQ04V-jRo8P3yOTQ.png" /></figure><p>We have much more of an imbalanced classes problem now than we did in Part I. This will probably have to be addressed more thoroughly, especially if we hope to, as already stated, attempt binary “one vs. the rest” classifiers. It will not do to have the positive and negative cases with such a disparency.</p><p>The packaged imbalanced-learn has been built precisely with these types of use cases in mind. It can help to either oversample smaller classes, or undersample larger classes to balance the distribution of observations. The package offers a few different ways to oversample one’s data. The RandomOverSampler routine samples an underrepresented class, with replacement, until the frequency of the most dense class is achieved. However, this method is prone to lead to a lot of data duplication, which may cause models to overfit. The Synthetic Minority Oversampling Technique (SMOTE), instead interpolates in order to generate new samples. We’ll try SMOTE:</p><pre>from imblearn.over_sampling import RandomOverSampler, SMOTE</pre><pre>X_resampled, y_resampled = SMOTE().fit_resample(features, labels)</pre><pre>from collections import Counter</pre><pre>print(sorted(Counter(y_resampled).items()))</pre><p>[(0, 6406), (1, 6406), (2, 6406), (3, 6406), (4, 6406), (5, 6406)]</p><p>Each class now has the same number of observations.</p><p>As a baseline of our predictive capabilities, we can simply repeat the method used in Part I, here with the extra data and the resampled classes. Doing so already drastically increases our accuracy:</p><p>LinearSVC 0.858418</p><p>LogisticRegression 0.806723</p><p>MultinomialNB 0.752838</p><p>RandomForestClassifier 0.500750</p><p>In the remaining part of the series, <a href="https://towardsdatascience.com/text-classification-of-freedom-of-information-requests-part-iii-9b34e0a9df07">Part III</a>, we’ll deepen our models by finally introducing OneVsRest binary classifiers, and compare its performance against that offered by a fully-formed GRU recurrent neural network.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d57b080d179" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/text-classification-of-freedom-of-information-requests-part-ii-4d57b080d179">Text Classification of Freedom of Information Requests: Part II</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Classification of Freedom of Information Requests: Part I]]></title>
            <link>https://medium.com/data-science/text-classification-of-freedom-of-information-requests-part-i-8a75d1e7ea02?source=rss-7ec43ca7275c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a75d1e7ea02</guid>
            <category><![CDATA[multi-classifications]]></category>
            <category><![CDATA[information-technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[fuzz]]></category>
            <dc:creator><![CDATA[Scott Jones]]></dc:creator>
            <pubDate>Tue, 12 Feb 2019 18:03:57 GMT</pubDate>
            <atom:updated>2022-07-19T13:46:58.228Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using machine learning to predict the decision by a municipality.</h4><p>The province of Ontario, Canada is obligated to respond to requests for information under the Freedom of Information and Protection of Privacy Act (FIPPA). More specifically, the Municipal Freedom of Information and Protection of Privacy Act (MFIPPA) allows persons of any age, from any location, to issue such a request. The information, as is relevant to the individual, may include print, film, emails, drawings, photographs, etc. provided that the released content does not infringe upon another individual’s access to privacy. In this post, we will attempt to predict the decision rendered by a municipality, namely Kitchener-Waterloo, Ontario (Part I) and later Toronto (Part II).</p><p>The data used is made available under the open data portal of each city. Any identifying information has been previously removed.</p><p>Using the limited Kitchener-Waterloo data set will allow us to baseline some of our metrics and prototype our techniques. These data are made available via an API and cover the years 1992–2016.</p><p>Once it is all aggregated and converted to a Pandas dataframe, we need to take a closer look at what we have. Among the possible “decisions” are the following:</p><p><strong><em>All disclosed 238<br>Partly exempted 197<br>Withdrawn 116<br>No records exist 54<br>Information disclosed in part 50<br>Partly non-existent 32<br>Nothing disclosed 28<br>No record exists 21<br>All Information disclosed 16<br>Forwarded out 15<br>Abandoned 13<br>All information disclosed 13<br>No responsive records exist 11<br>Correction refused 3<br>Non-existent 3<br>Correction made 2<br>Transferred to Region of Waterloo Public Health 2<br>All disclosed 2<br>Transferred 1<br>No information disclosed 1<br>Statement of disagreement filed 1<br>No additional records exist 1<br>Correction granted 1<br>Request withdrawn 1</em></strong></p><p>There is clearly some overlap here among the possible decisions, of which there are 24. While these could (and have been) be merged manually in not too much time, what if there were hundreds of such classes, differing only in the presence (or absence) of a space? Or an ‘s’? Or in the manner of capitalization? The python package <a href="https://chairnerd.seatgeek.com/fuzzywuzzy-fuzzy-string-matching-in-python/">fuzzywuzzy</a>, developed by SeatGeek, is perfect for this type of fuzzy string matching.</p><p>The package offers four ways to probe the likeness of two strings. Essentially, ‘fuzz_ratio’ compares entire strings, ‘fuzz_partial_ratio’ searches the strings for partial matches, ‘fuzz_token_sort_ratio’ compares out-of-order strings, and ‘fuzz_token_set_ratio’ extends token sort for longer strings. Each returns a similarity ratio (the higher the more alike), whereafter a threshold can be set at an acceptable cutoff. Let’s test the performance of each.</p><pre>from fuzzywuzzy import fuzz</pre><pre>all_df_clean = all_df.copy()</pre><pre>for row in all_df[&#39;Decision&#39;].unique():<br>    for row2 in all_df[&#39;Decision&#39;].unique():<br>        matching_result = fuzz.ratio(row, row2) # could be ratio, partial_ratio, token_set_ratio, token_sort_ratio <br>        if matching_result &gt; 80:<br>            #print(row, row2)<br>            #print(matching_results)<br>            #Combine if match found<br>            all_df_clean[&#39;Decision&#39;][all_df_clean[&#39;Decision&#39;] == row2] = row<br>            <br>print(all_df_clean[&#39;Decision&#39;].value_counts())<br>print(len(all_df_clean[&#39;Decision&#39;].unique()))</pre><p><strong><em>All disclosed 240<br>Partly exempted 197<br>Withdrawn 116<br>No records exist 75<br>Information disclosed in part 50<br>Partly non-existent 32<br>No information disclosed 30<br>Nothing disclosed 28<br>Forwarded out 15<br>Abandoned 13<br>No responsive records exist 11<br>Non-existent 3<br>Correction refused 3<br>Correction made 2<br>Transferred to Region of Waterloo Public Health 2<br>Statement of disagreement filed 1<br>No additional records exist 1<br>Transferred 1<br>Correction granted 1<br>Request withdrawn 1<br>Name: Decision, dtype: int64<br>20</em></strong></p><p>Not bad. We have merged four classes (i.e. ‘No records exist’ and ‘No record exists’) but things like ‘No information disclosed’ and ‘Nothing disclosed’ clearly mean the same. The 80% cutoff has been decided by trail-and-error. Let’s try a partial ratio:</p><p><strong><em>All disclosed 240<br>Partly exempted 197<br>Request withdrawn 117<br>No responsive records exist 87<br>No information disclosed 80<br>Non-existent 35<br>Nothing disclosed 28<br>Forwarded out 15<br>Abandoned 13<br>Correction refused 3<br>Transferred 3<br>Correction made 2<br>Statement of disagreement filed 1<br>Correction granted 1<br>Name: Decision, dtype: int64<br>14</em></strong></p><p>Another six classes merged, but the algorithm doesn’t really know what to do with the substring ‘disclosed’. It has combined ‘Information disclosed in part’ with ‘No information disclosed’ which do not mean the same thing.</p><p><strong><em>All disclosed 240<br>Partly exempted 197<br>Withdrawn 116<br>No information disclosed 80<br>No records exist 75<br>Partly non-existent 32<br>Nothing disclosed 28<br>Forwarded out 15<br>Abandoned 13<br>No responsive records exist 11<br>Correction refused 3<br>Non-existent 3<br>Correction made 2<br>Transferred to Region of Waterloo Public Health 2<br>Transferred 1<br>No additional records exist 1<br>Statement of disagreement filed 1<br>Correction granted 1<br>Request withdrawn 1<br>Name: Decision, dtype: int64<br>19</em></strong></p><p>Similar to the basic ratio case.</p><p><strong><em>No information disclosed 348<br>Partly exempted 197<br>Request withdrawn 117<br>No responsive records exist 87<br>Non-existent 35<br>Forwarded out 15<br>Abandoned 13<br>Correction refused 3<br>Transferred 3<br>Correction made 2<br>Statement of disagreement filed 1<br>Correction granted 1<br>Name: Decision, dtype: int64<br>12</em></strong></p><p>The most aggressive matching case yet, but again we are tripped up on ‘disclosed’ as now we no longer have the case ‘All disclosed’, which is unacceptable. The partial ratio case seems to be a compromise — perhaps we can further merge a couple of categories manually. We will see what happens when the Toronto data is added in Part II.</p><pre>all_df_pr[&#39;Decision&#39;].loc[all_df_pr[&#39;Decision&#39;] == &quot;Abandoned&quot;] = &quot;Request withdrawn&quot;<br>all_df_pr[&#39;Decision&#39;].loc[all_df_pr[&#39;Decision&#39;] == &quot;Non-existent&quot;] = &quot;No responsive records exist&quot;<br>all_df_pr[&#39;Decision&#39;].loc[all_df_pr[&#39;Decision&#39;] == &quot;No information disclosed &quot;] = &quot;Nothing disclosed&quot;<br>all_df_pr[&#39;Decision&#39;].loc[all_df_pr[&#39;Decision&#39;] == &quot;Transferred&quot;] = &quot;Forwarded out&quot;<br>all_df_pr[&#39;Decision&#39;].loc[all_df_pr[&#39;Decision&#39;] == &quot;Correction granted&quot;] = &quot;Correction made&quot;<br>print(all_df_pr[&#39;Decision&#39;].value_counts())</pre><p><strong><em>All disclosed 240<br>Partly exempted 197<br>Request withdrawn 130<br>No responsive records exist 122<br>Nothing disclosed 108<br>Forwarded out 18<br>Correction made 3<br>Correction refused 3<br>Statement of disagreement filed 1<br>Name: Decision, dtype: int64</em></strong></p><p>Everything looks distinct now. Let’s cut off the classes where there is a big drop-off in numbers:</p><pre>all_df_over20 = all_df_pr.groupby(&#39;Decision&#39;).filter(lambda x: len(x) &gt; 20)</pre><p>The remainder of this article will borrow heavily from Susan Li’s <a href="https://towardsdatascience.com/multi-class-text-classification-with-scikit-learn-12f1e60e0a9f">excellent article on multi-class text classification</a>. The expectation is that based on the smaller size of our dataset and the fact that the text itself is fairly opaque, our results will not be very good. A quick overview of our data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owhMhjmFus8PVr0JsoX9zw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AGt-VVfrcOGrT9HKXQU_cg.png" /></figure><p>The classes are not as unbalanced as we might have thought. The ‘category_id’ column is an integer representation of the possible decision cases. Now, calculate a tf-idf vector for each request, removing all stop words.</p><pre>from sklearn.feature_extraction.text import TfidfVectorizer</pre><pre>tfidf = TfidfVectorizer(sublinear_tf=True, min_df=5, norm=&#39;l2&#39;, <br>                       encoding=&#39;latin-1&#39;, ngram_range=(1,2), stop_words=&#39;english&#39;)</pre><pre>features = tfidf.fit_transform(all_df_over20.Request_summary).toarray()<br>labels = all_df_over20.category_id<br>features.shape</pre><p>Print the common bigrams and unigrams for each class.</p><pre>from sklearn.feature_selection import chi2<br>import numpy as np</pre><pre>N=2<br>for Decision, category_id in sorted(category_to_id.items()):<br>    features_chi2 = chi2(features, labels == category_id)<br>    indices = np.argsort(features_chi2[0])<br>    feature_names = np.array(tfidf.get_feature_names())[indices]<br>    unigrams = [v for v in feature_names if len(v.split(&#39; &#39;)) ==1]<br>    bigrams = [v for v in feature_names if len(v.split(&#39; &#39;)) ==2]<br>    print(&quot;# &#39;{}&#39;:&quot;.format(Decision))<br>    print(&quot;  . Most correlated unigrams:\n. {}&quot;.format(&#39;\n.&#39;.join(unigrams[-N:])))<br>    print(&quot;  . Most correlated bigrams:\n. {}&quot;.format(&#39;\n.&#39;.join(bigrams[-N:])))</pre><p><strong><em># ‘All disclosed ‘:<br> . Most correlated unigrams:<br>. assistance<br>.personal<br> . Most correlated bigrams:<br>. information removed<br>.removed competition<br># ‘No responsive records exist’:<br> . Most correlated unigrams:<br>. site<br>.phase<br> . Most correlated bigrams:<br>. assessment address<br>.site assessment<br># ‘Nothing disclosed’:<br> . Most correlated unigrams:<br>. bus<br>.2014<br> . Most correlated bigrams:<br>. complete ontario<br>.works file<br># ‘Partly exempted’:<br> . Most correlated unigrams:<br>. competition<br>.94<br> . Most correlated bigrams:<br>. information competition<br>.rabies control<br># ‘Request withdrawn’:<br> . Most correlated unigrams:<br>. provincial<br>.evaluation<br> . Most correlated bigrams:<br>. treatment plant<br>.provincial offences</em></strong></p><p>This is what was meant when I said the requests themselves were fairly opaque in terms of being able to classify by eye. At least there appears to be good separation between the classes.</p><p>Try four different models:</p><pre>import warnings<br>warnings.filterwarnings(action=&#39;once&#39;)<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.svm import LinearSVC</pre><pre>from sklearn.model_selection import cross_val_score</pre><pre>models = [<br>    RandomForestClassifier(n_estimators=200, max_depth=3,<br>                          random_state=0), #, class_weight=&#39;balanced&#39;),<br>    LinearSVC(), #class_weight=&#39;balanced&#39;),<br>    MultinomialNB(),<br>    LogisticRegression(random_state=0)#, class_weight=&#39;balanced&#39;),<br>]<br>CV=5<br>cv_df = pd.DataFrame(index=range(CV * len(models)))<br>entries=[]<br>for model in models:<br>    model_name = model.__class__.__name__<br>    accuracies = cross_val_score(model, features, labels,<br>                                scoring=&#39;accuracy&#39;, cv=CV)<br>    for fold_idx, accuracy in enumerate(accuracies):<br>        entries.append((model_name, fold_idx, accuracy))<br>cv_df = pd.DataFrame(entries, columns=[&#39;model_name&#39;, &#39;fold_idx&#39;, &#39;accuracy&#39;])</pre><pre>import seaborn as sns</pre><pre>sns.boxplot(x=&#39;model_name&#39;, y=&#39;accuracy&#39;, data=cv_df)<br>sns.stripplot(x=&#39;model_name&#39;, y=&#39;accuracy&#39;, data=cv_df,<br>             size=8, jitter=True, edgecolor=&quot;gray&quot;, linewidth=2)<br>plt.show()<br>cv_df.groupby(&#39;model_name&#39;).accuracy.mean()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6GGedRVNtZMUlKpTuLCYUg.png" /></figure><p><strong><em>model_name<br>LinearSVC 0.362882<br>LogisticRegression 0.398066<br>MultinomialNB 0.398152<br>RandomForestClassifier 0.349038<br>Name: accuracy, dtype: float64</em></strong></p><p>As expected the performance is exceptionally poor. Let’s look at the confusion matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jPHd2fYKThQhARnv7u4FqQ.png" /></figure><pre>precision    recall  f1-score   support<br><br>             All disclosed        0.36      0.69      0.47        67<br>No responsive records exist       0.50      0.49      0.49        41<br>            Partly exempted       0.58      0.48      0.53        73<br>          Request withdrawn       0.38      0.11      0.17        47<br>          Nothing disclosed       0.58      0.39      0.47        36<br><br>                avg / total       0.48      0.45      0.44       264</pre><p>Well, the model is at least trying. In the <a href="https://towardsdatascience.com/text-classification-of-freedom-of-information-requests-part-ii-4d57b080d179">follow-up article</a> we’ll attempt to improve this both by significantly adding to the available data and by trying a series of binary classifiers on each class.</p><p>Code available on GitHub: <a href="https://github.com/scjones5/foi-kw">https://github.com/scjones5/foi-kw</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a75d1e7ea02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/text-classification-of-freedom-of-information-requests-part-i-8a75d1e7ea02">Text Classification of Freedom of Information Requests: Part I</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>