<?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 John Lenehan on Medium]]></title>
        <description><![CDATA[Stories by John Lenehan on Medium]]></description>
        <link>https://medium.com/@john_lenehan?source=rss-2eb00da71bb6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9ddSLrm56MNaB59sD4Qx6w.jpeg</url>
            <title>Stories by John Lenehan on Medium</title>
            <link>https://medium.com/@john_lenehan?source=rss-2eb00da71bb6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 10:17:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@john_lenehan/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[AI Mapping: Using Neural Networks to Identify House Numbers]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/ai-mapping-using-neural-networks-to-identify-house-numbers-12f194a95d75?source=rss-2eb00da71bb6------2"><img src="https://cdn-images-1.medium.com/max/2600/0*1ayWOgXDRFsYKmme" width="5671"></a></p><p class="medium-feed-snippet">Comparing artificial and convolutional neural networks in classifying Google Street View house numbers</p><p class="medium-feed-link"><a href="https://medium.com/data-science/ai-mapping-using-neural-networks-to-identify-house-numbers-12f194a95d75?source=rss-2eb00da71bb6------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/ai-mapping-using-neural-networks-to-identify-house-numbers-12f194a95d75?source=rss-2eb00da71bb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/12f194a95d75</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[John Lenehan]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 15:28:05 GMT</pubDate>
            <atom:updated>2024-04-16T15:28:05.108Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Farm to Table: The Workflow of a Classification Model]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/farm-to-table-the-workflow-of-a-classification-model-7abc41989767?source=rss-2eb00da71bb6------2"><img src="https://cdn-images-1.medium.com/max/2600/0*b55XOR0SysTYeKr-" width="6000"></a></p><p class="medium-feed-snippet">Comparing logistic regression and random forest classification in recipe recommendations</p><p class="medium-feed-link"><a href="https://medium.com/data-science/farm-to-table-the-workflow-of-a-classification-model-7abc41989767?source=rss-2eb00da71bb6------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/farm-to-table-the-workflow-of-a-classification-model-7abc41989767?source=rss-2eb00da71bb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7abc41989767</guid>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[random-forest]]></category>
            <dc:creator><![CDATA[John Lenehan]]></dc:creator>
            <pubDate>Tue, 02 Apr 2024 05:29:13 GMT</pubDate>
            <atom:updated>2024-09-29T13:48:13.358Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Data at a Glance: Creating Dynamic Dashboards for Data Analytics]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/data-at-a-glance-creating-dynamic-dashboards-for-data-analytics-1dce62fc6638?source=rss-2eb00da71bb6------2"><img src="https://cdn-images-1.medium.com/max/1815/1*kXyAZAPhlp6uBlAp2b_Wtg.png" width="1815"></a></p><p class="medium-feed-snippet">Using Tableau to build interactive data visuals</p><p class="medium-feed-link"><a href="https://medium.com/data-science/data-at-a-glance-creating-dynamic-dashboards-for-data-analytics-1dce62fc6638?source=rss-2eb00da71bb6------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/data-at-a-glance-creating-dynamic-dashboards-for-data-analytics-1dce62fc6638?source=rss-2eb00da71bb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dce62fc6638</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[vizualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[tableau]]></category>
            <dc:creator><![CDATA[John Lenehan]]></dc:creator>
            <pubDate>Mon, 20 Nov 2023 03:10:30 GMT</pubDate>
            <atom:updated>2023-11-20T10:47:58.961Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Guide your Audience: Creating Compelling Narratives in your Presentation]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/guide-your-audience-crafting-a-cohesive-narrative-from-the-data-4032538ff252?source=rss-2eb00da71bb6------2"><img src="https://cdn-images-1.medium.com/max/2600/0*rx9_Nl9_iSS17d3W" width="3000"></a></p><p class="medium-feed-snippet">How to structure your data presentation coherently using narrative techniques</p><p class="medium-feed-link"><a href="https://medium.com/data-science/guide-your-audience-crafting-a-cohesive-narrative-from-the-data-4032538ff252?source=rss-2eb00da71bb6------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/guide-your-audience-crafting-a-cohesive-narrative-from-the-data-4032538ff252?source=rss-2eb00da71bb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4032538ff252</guid>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[office-hours]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[narrative]]></category>
            <category><![CDATA[visualization]]></category>
            <dc:creator><![CDATA[John Lenehan]]></dc:creator>
            <pubDate>Thu, 02 Nov 2023 06:34:48 GMT</pubDate>
            <atom:updated>2023-11-03T00:11:45.562Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Know Your Audience: A Guide to Preparing for Technical Presentations]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/know-your-audience-a-guide-to-preparing-for-technical-presentations-1a83fdb21050?source=rss-2eb00da71bb6------2"><img src="https://cdn-images-1.medium.com/max/2600/0*lyJ3PYfXAKJUmL3e" width="5184"></a></p><p class="medium-feed-snippet">A structured approach to creating addresses tailored to the stakeholders&#x2019; needs and concerns</p><p class="medium-feed-link"><a href="https://medium.com/data-science/know-your-audience-a-guide-to-preparing-for-technical-presentations-1a83fdb21050?source=rss-2eb00da71bb6------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/know-your-audience-a-guide-to-preparing-for-technical-presentations-1a83fdb21050?source=rss-2eb00da71bb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a83fdb21050</guid>
            <category><![CDATA[office-hours]]></category>
            <category><![CDATA[stakeholder-management]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[communication]]></category>
            <category><![CDATA[presentations]]></category>
            <dc:creator><![CDATA[John Lenehan]]></dc:creator>
            <pubDate>Fri, 06 Oct 2023 05:34:10 GMT</pubDate>
            <atom:updated>2024-09-29T13:48:46.690Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Sampling Techniques in Data Analysis]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/sampling-techniques-in-data-analysis-cea8f58b1fe7?source=rss-2eb00da71bb6------2"><img src="https://cdn-images-1.medium.com/max/2600/0*NVbR74YeoZsWj4ta" width="6016"></a></p><p class="medium-feed-snippet">How to choose the right data sampling method for your data</p><p class="medium-feed-link"><a href="https://medium.com/data-science/sampling-techniques-in-data-analysis-cea8f58b1fe7?source=rss-2eb00da71bb6------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/sampling-techniques-in-data-analysis-cea8f58b1fe7?source=rss-2eb00da71bb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/cea8f58b1fe7</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[sampling-methods]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[John Lenehan]]></dc:creator>
            <pubDate>Wed, 06 Sep 2023 14:29:13 GMT</pubDate>
            <atom:updated>2023-09-06T14:29:13.805Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Ink to Insights: Comparing SQL and Python Queries using Bookshop Analytics]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/ink-to-insights-comparing-sql-and-python-queries-using-bookshop-analytics-90e3bb200671?source=rss-2eb00da71bb6------2"><img src="https://cdn-images-1.medium.com/max/2600/0*jc64BwuBYn2qInnA" width="5775"></a></p><p class="medium-feed-snippet">Which approach is better for your exploratory data analysis?</p><p class="medium-feed-link"><a href="https://medium.com/data-science/ink-to-insights-comparing-sql-and-python-queries-using-bookshop-analytics-90e3bb200671?source=rss-2eb00da71bb6------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/ink-to-insights-comparing-sql-and-python-queries-using-bookshop-analytics-90e3bb200671?source=rss-2eb00da71bb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/90e3bb200671</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[John Lenehan]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 17:13:31 GMT</pubDate>
            <atom:updated>2023-09-02T12:32:54.042Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Data-Driven Dispatch]]></title>
            <link>https://medium.com/data-science/data-driven-dispatch-76b7e998a7a7?source=rss-2eb00da71bb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/76b7e998a7a7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[John Lenehan]]></dc:creator>
            <pubDate>Fri, 04 Aug 2023 15:08:58 GMT</pubDate>
            <atom:updated>2023-08-04T23:47:29.983Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using supervised learning to predict service callouts to Chicago car collisions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fmWnQEeucHDrq4B4" /><figcaption>Photo by <a href="https://unsplash.com/@sawyerbengtson?utm_source=medium&amp;utm_medium=referral">Sawyer Bengtson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In today’s fast-paced world, the need for data-driven decisions in dispatch response systems is becoming essential. Dispatchers will perform a kind of triage when listening to calls, prioritising cases based on severity and time sensitivity among other factors. There is potential in optimising this process by leveraging the power of supervised learning models, to make more accurate predictions of case severity in tandem with a human dispatcher’s assessment.</p><p>In this post, I’m going to run through one solution I developed to improve predictions of casualties and/or serious vehicular damage from car collisions in Chicago. Factors such as crash location, road conditions, speed limit, and time of occurrence were taken into account to answer a simple yes or no question — <em>will this car crash require an ambulance or tow truck?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2mdodL6yNGWhe1jK" /><figcaption>Photo by <a href="https://unsplash.com/@chrisdickens?utm_source=medium&amp;utm_medium=referral">Chris Dickens</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In a nutshell, this machine learning tool’s primary objective is to classify collisions that will most likely require a callout (medical, tow, or both) based on other known factors. By leveraging this tool, responders would be able to efficiently allocate their resources across different parts of the city, based on various conditions such as weather and time of day.</p><p>For such a tool to be accurate and effective, a large data source would be needed to make predictions from the historical data — thankfully the city of Chicago already has such a resource (the <a href="https://data.cityofchicago.org/"><strong>Chicago Data Portal</strong></a><strong>),</strong> so this data will be used as the test case.</p><p>Implementing these kinds of predictive models would certainly improve preparedness and response time efficiency when dealing with collisions on city streets. By gaining insights into the underlying patterns and trends within the collision data, we can work towards fostering safer road environments and optimising emergency services.</p><p>I go into the details of data cleaning, model building, fine tuning and evaluation below, before analysing the model’s results and drawing conclusions. A link to the github folder for this project, which includes a jupyter notebook and a more comprehensive report on the project, can be found <a href="https://github.com/jlenehan/Chicago_Dispatch_Classification"><strong>here</strong></a>.</p><h3>Data Collection and Preparation</h3><h4>Initial Setup</h4><p>I’ve listed the basic data analysis libraries used in the project below; standard libraries such as pandas and numpy were used throughout the project, along with matplotlib’s pyplot and seaborn for visualisation. Additionally, I used the missingno library to identify gaps in the data — I find this library incredibly useful for visualising missing data in a dataset, and would recommend it for any data science project involving dataframes:</p><pre>#generic data analysis <br>import os<br>import pandas as pd<br>from datetime import date<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import seaborn as sns<br>import missingno as msno</pre><p>Functions from the machine learning module SciKit learn (sklearn) were imported to build the machine learning engine. these functions are shown here — I will describe the purpose of each of these functions in the Classification Model section later:</p><pre>#Preprocessing<br>from sklearn.preprocessing import LabelEncoder<br>from sklearn.preprocessing import StandardScaler<br><br># Models<br>from sklearn.neighbors import KNeighborsClassifier<br><br># Reporting<br>from sklearn.model_selection import train_test_split<br>from sklearn.model_selection import RandomizedSearchCV<br><br>#metrics<br>from sklearn.metrics import accuracy_score<br>from sklearn.metrics import f1_score<br>from sklearn.metrics import precision_score<br>from sklearn.metrics import recall_score</pre><p>The data for this project were all imported from the Chicago Data Portal, from two sources:</p><ol><li><a href="https://data.cityofchicago.org/Transportation/Traffic-Crashes-Crashes/85ca-t3if"><strong>Traffic Crashes</strong></a><strong>: </strong>Live dataset of vehicle collisions in the Chicago area. The features of this dataset are conditions recorded at the time of the collision, such as weather conditions, road alignment, latitude and longitude data, among other details.</li><li><a href="https://data.cityofchicago.org/Public-Safety/Boundaries-Police-Beats-current-/aerh-rz74"><strong>Police Beats Boundaries</strong></a><strong>: </strong>A static dataset indicating the boundaries of CPD beats; this dataset is used to supplement district information to the traffic crashes dataset. This can be joined to the original dataset to run analysis on districts with the most frequent collisions.</li></ol><h4>Data Cleaning</h4><p>With both datasets imported, they can now be merged to add district data to the final analysis. This is done using the .merge() function in pandas — I used an inner join on both dataframes to capture all information in both, using the beat data in both as the join key (listed as beat_of_occurrence in the traffic crashes dataset, and BEAT_NUM in the police beats dataset):</p><pre>#joining collision data to beat data - inner join<br>collisions = collision_raw.merge(beat_data, how=&#39;inner&#39;,<br>                                 left_on=&#39;beat_of_occurrence&#39;,<br>                                 right_on=&#39;BEAT_NUM&#39;<br>                                 )</pre><p>A quick look at the information provided from the .info() function shows a number of columns with sparse data. This can be visualized using the missingno matrix function:</p><pre>#visualising missing data<br>#sorting values by report received date<br><br>collisions = collisions.sort_values(by=&#39;crash_date&#39;, ascending=True)<br><br>#plotting matrix of missing data<br>msno.matrix(collisions)<br>plt.show()<br><br>#info of sorted data<br>print(collisions.info())</pre><p>This displays a matrix of missing data in all columns, as can be seen here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLxFaUyicszWIidepbsBNw.png" /><figcaption>Unrefined dataset, with multiple columns containing a large number of null values</figcaption></figure><p>By dropping columns with sparse data, a much cleaner dataset can be extracted; the columns to drop are defined in a list and then removed from the dataset using the .drop() function:</p><pre>#defining unnecessary columns<br>drop_cols = [&#39;location&#39;, &#39;crash_date_est_i&#39;,&#39;report_type&#39;, &#39;intersection_related_i&#39;,<br>       &#39;hit_and_run_i&#39;, &#39;photos_taken_i&#39;, &#39;crash_date_est_i&#39;, &#39;injuries_unknown&#39;,<br>       &#39;private_property_i&#39;, &#39;statements_taken_i&#39;, &#39;dooring_i&#39;, &#39;work_zone_i&#39;,<br>       &#39;work_zone_type&#39;, &#39;workers_present_i&#39;,&#39;lane_cnt&#39;,&#39;the_geom&#39;,&#39;rd_no&#39;,<br>            &#39;SECTOR&#39;,&#39;BEAT&#39;,&#39;BEAT_NUM&#39;]<br><br>#dropping columns<br>collisions=collisions.drop(columns=drop_cols)<br><br>#plotting matrix of missing data<br>msno.matrix(collisions)<br>plt.show()<br><br>#info of sorted data<br>print(collisions.info())</pre><p>This leads to a much cleaner msno matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNeLUh-Guxu19MRypXuZyg.png" /><figcaption>msno matrix of the pruned dataset</figcaption></figure><p>Looking at the data for latitude and longitude, a small handful of rows had null values, and others mistakenly had zero values (most likely a reporting error):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*-VTY_JeXIdXjZ9V74i6uWA.png" /><figcaption>Both the latitude and longitude columns contain zero values (see min and max of each)</figcaption></figure><p>These would cause errors in training the model, so I removed them:</p><pre>#Some incorrect lat/long data - need to remove these rows<br>collisions = collisions[collisions[&#39;longitude&#39;]&lt;-80]<br>collisions = collisions[collisions[&#39;latitude&#39;]&gt;40]</pre><p>With the data adequately cleaned, I was able to progress with developing the classification model.</p><h3>Classification Model</h3><h4>Exploratory Data Analysis</h4><p>Before proceeding with the machine learning model some exploratory data analysis (EDA) needs to be performed — each of the columns of the data frame are plotted on a histogram, with bins of 50 to show the distribution of the data. Histograms are useful in the EDA step for a number of reasons, namely that they give an overview of the data distribution, help to identify outliers, and ultimately assist in making decisions on feature engineering:</p><pre>#plotting histograms of numerical values<br>collisions.hist(bins=50,figsize=(16,12))<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*QIwJkCWGNyruz63AuWwmUg.png" /><figcaption>Histograms of columns in the final dataset</figcaption></figure><p>A cursory look at the column histograms indicates that the latitude data is bimodal, while the longitude data is rightly skewed. This will need to be standardized so that it can be better applied for machine learning purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*yrI0ge5Rru-Rg_rUSXINLQ.png" /><figcaption>Latitude-longitude data without scaling</figcaption></figure><p>Additionally, it appears the crash hour column is cyclic in nature — this can be transformed using a trigonometric function (for example sine).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*vpXsn_Ei2bLslIKvBU7ptQ.png" /><figcaption>Unscaled crash hour data</figcaption></figure><h4>Scaling and Transformation</h4><p>Scaling is a technique used in data preprocessing to standardise features so they have similar magnitudes. This is particularly important for machine learning models, since models are generally sensitive to the scale of input features. I’ve defined the StandardScaler() function to act as the scaler in this model — this scaling function transforms the data so that it has a mean of 0 and standard deviation of 1.</p><p>For data with a skewed or bimodal distribution, scaling can be done using logarithmic functions. Log functions make skewed data more symmetrical and reduce the tail on the data — this is useful when dealing with outlier values. I scaled the latitude and longitude data in this way; as the longitude data is all negative, the negative log was calculated and then scaled.</p><pre>#scaling latitude and longitude data<br>scaler = StandardScaler()<br><br># Logarithmic transformation on longitude<br>collisions_ml[&#39;neg_log_longitude&#39;] = scaler.fit_transform(np.log1p(-collisions_ml[&#39;longitude&#39;]).<br>                                                          values.reshape(-1,1))<br><br># Normalisation on latitude<br>collisions_ml[&#39;norm_latitude&#39;] = scaler.fit_transform(np.log1p(collisions[&#39;latitude&#39;]).<br>                                                      values.reshape(-1, 1))</pre><p>This produces the desired effect, as can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*uEIRc5hzYyDcqFgXih4VoA.png" /><figcaption>Scaled latitude-longitude data</figcaption></figure><p>In comparison, cyclic data is usually scaled using trigonometric functions such as sine and cos. The crash hour data looks roughly cyclic based on earlier observations, so I applied a sine function to the data as below — since numpy’s sin() function is in radians, I first converted the input to radians before calculating the sine of the input:</p><pre>#transforming crash_hour <br>#data is cyclic, can be encoded using trig transforms<br><br>#trig transformation - sin(crash_hr)<br>collisions_ml[&#39;sin_hr&#39;] = np.sin(2*np.pi*collisions_ml[&#39;crash_hour&#39;]/24)</pre><p>A histogram of the transformed data can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*cJdezFaVwqTcpwV8vsX_IA.png" /><figcaption>Scaled crash hour data</figcaption></figure><p>Finally I removed the unscaled data from the model to avoid this interfering with model predictions:</p><pre>#drop previous latitude/longitude columns<br>lat_long_drop_cols = [&#39;longitude&#39;,&#39;latitude&#39;]<br>collisions_ml.drop(lat_long_drop_cols,axis=1,inplace=True)<br><br>#drop crash_hour column<br>collisions_ml.drop(&#39;crash_hour&#39;,axis=1,inplace=True)</pre><h4>Data Encoding</h4><p>Another important step in data preprocessing is data encoding — this is where non-numerical data (for example categories) are represented in numerical format, to make it compatible with machine learning algorithms. For categorical data in this model, I used a method called label encoding — each category in a column is given a numerical value before it’s inputted to the model. A diagram of this process is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*VANp9LwCoxoSEK1IA705PQ.png" /><figcaption>An example of label encoding (credits to Zach M—<a href="https://www.statology.org/label-encoding-in-python/">source</a>)</figcaption></figure><p>I encoded the columns in the dataset, first segmenting out the columns I wanted to keep from the original dataset and making a copy of the dataframe (collisions_ml). I then defined the categorical columns in a list, and used the LabelEncoder() function from sklearn to fit and transform the categorical columns:</p><pre>#segmenting columns into lists<br>ml_cols = [&#39;posted_speed_limit&#39;,&#39;traffic_control_device&#39;, &#39;device_condition&#39;, &#39;weather_condition&#39;,<br>          &#39;lighting_condition&#39;, &#39;first_crash_type&#39;, &#39;trafficway_type&#39;,&#39;alignment&#39;, <br>           &#39;roadway_surface_cond&#39;, &#39;road_defect&#39;, &#39;crash_type&#39;,&#39;damage&#39;,&#39;prim_contributory_cause&#39;,<br>          &#39;sec_contributory_cause&#39;,&#39;street_direction&#39;,&#39;num_units&#39;, &#39;DISTRICT&#39;,<br>          &#39;crash_hour&#39;,&#39;crash_day_of_week&#39;,&#39;latitude&#39;, &#39;longitude&#39;]<br>cat_cols = [&#39;traffic_control_device&#39;, &#39;device_condition&#39;, &#39;weather_condition&#39;, &#39;DISTRICT&#39;,<br>           &#39;lighting_condition&#39;, &#39;first_crash_type&#39;, &#39;trafficway_type&#39;,&#39;alignment&#39;,<br>           &#39;roadway_surface_cond&#39;, &#39;road_defect&#39;, &#39;crash_type&#39;,&#39;damage&#39;,&#39;prim_contributory_cause&#39;,<br>           &#39;sec_contributory_cause&#39;,&#39;street_direction&#39;,&#39;num_units&#39;]<br><br>#making a copy of the dataset<br>collisions_ml = collisions[ml_cols].copy()<br><br>#encoding categorical values<br>label_encoder = LabelEncoder()<br>for col in collisions_ml[cat_cols].columns:<br>    collisions_ml[col] = label_encoder.fit_transform(collisions_ml[col])</pre><p>With the data now sufficiently preprocessed, the data can now be split into train and test data, and a classification model can be fitted to the data.</p><h4>Splitting the Train &amp; Test Data</h4><p>It’s important to separate data into a training and test sets when building a machine learning model; the training set is a fraction of the initial data which is used to train the model on the right responses, whereas the test set is used to evaluate model performance. Keeping these separate is necessary to reduce the risk of overfitting and model bias.</p><p>I separated out the crash_type column using the drop() function (the remaining features will be used as the variables to predict crash_type), and defined crash_type as the y result to be predicted using the model. The train_test_split function from sklearn was used to take 20% of the initial dataset as training data, with the rest to be used for model testing.</p><pre>#Create test set<br>#setting X and y values<br><br>X = collisions_ml.drop(&#39;crash_type&#39;, axis=1)<br>y = collisions_ml[&#39;crash_type&#39;]<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><h4>K-Nearest Neighbors Classification</h4><p>For this project, a K-Nearest Neighbors (KNN) classification model is used to predict results from the features. KNN models work by checking the value of the K nearest known values around an unknown data point, then classifying the data point based on the values of those “neighbor” points. It’s a non-parametric classifier, meaning it doesn’t make any assumptions about the underlying data distribution; however it is computationally expensive, and can be sensitive to outliers in the data.</p><p>I instantiated the KNN classifier with an initial n_neighbors equal to 3, using Euclidean metrics, before fitting the model to the training data:</p><pre>#Classifier - K Nearest Neighbours<br>#instantiate KNN Classifier<br>KNNClassifier = KNeighborsClassifier(n_neighbors=3, metric = &#39;euclidean&#39;)<br><br>KNNClassifier.fit(X_train,y_train)</pre><p>Once the model was fitted to the training data, I made predictions on the test data as below:</p><pre>#Predictions<br>#predict on training set<br>y_train_pred = KNNClassifier.predict(X_train)<br><br>#predict on test data<br>y_test_pred = KNNClassifier.predict(X_test)</pre><h4>Evaluation</h4><p>Evaluation of a machine learning model is typically done using four metrics; accuracy, precision, recall, and F1 score. The differences between these metrics are very subtle, but in plain English these terms can be defined as follows:</p><ol><li><strong><em>Accuracy:</em></strong><em> </em>the percentage of true positive predictions out of all model predictions. Typically the accuracy of both the train and test data should be measured to evaluate model fit.</li><li><strong><em>Precision:</em></strong><em> </em>the percentage of true positive predictions out of all <em>positive </em>model predictions.</li><li><strong><em>Recall:</em></strong><em> </em>the percentage of true positive predictions out of all <em>positive cases in the dataset</em>.</li><li><strong><em>F1 Score:</em></strong><em> </em>An overall metric of the model’s ability to identify positive instances in the data, combining the precision and recall scores.</li></ol><p>I computed the metrics of the KNN model using the below code snippet — I also calculated the difference between the model’s accuracy on the train and test set, to assess fit:</p><pre>#Evaluate model<br># Calculate the accuracy of the model<br><br>#calculating accuracy of model on training data<br>train_accuracy = accuracy_score(y_train, y_train_pred)<br><br>#calculating accuracy of model on test data<br>test_accuracy = accuracy_score(y_test, y_test_pred)<br><br>#computing f1 score,precision,recall<br>f1 = f1_score(y_test, y_test_pred)<br>precision = precision_score(y_test,y_test_pred)<br>recall = recall_score(y_test,y_test_pred)<br><br>#comparing performances<br>print(&quot;Training Accuracy:&quot;, train_accuracy)<br>print(&quot;Test Accuracy:&quot;, test_accuracy)<br>print(&quot;Train-Test Accuracy Difference:&quot;, train_accuracy-test_accuracy)<br><br>#print precision score<br>print(&quot;Precision Score:&quot;, precision)<br><br>#print recall score<br>print(&quot;Recall Score:&quot;, recall)<br><br>#print f1 score<br>print(&quot;F1 Score:&quot;, f1)</pre><p>The initial metrics of the KNN model are given below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*rGYCFUOYhS4W9C01Sh8kbQ.png" /><figcaption>Metrics of the KNN model on the 1st iteration</figcaption></figure><p>The model scored well on test accuracy (79.6%), precision (82.1%), recall (91.1%), and F1 score (86.3%) — however the test accuracy was much higher than the train accuracy at 93.1%, a 13.5% difference. This indicates the model is overfitting the data, which means it would struggle to accurately make predictions on unseen data. Therefore the model needs to be adjusted for a better fit — this can be done using a process called hyperparameter tuning.</p><h4>Hyperparameter Tuning</h4><p>Hyperparameter tuning is the process of selecting the best set of hyperparameters for a machine learning model. I fine-tuned the model using <em>k-fold cross-validation</em> — this is a resampling technique where the data is split into <em>k</em> subsets (or <em>folds</em>), then each fold in turn is used as the validation set while the remaining data is used as the training set. This method is effective at reducing the risk of bias being introduced to the model by a particular choice of training/test set.</p><p>The hyperparameters for the KNN model are number of neighbors (<em>n_neighbors</em>) and the distance metric. There are a number of different ways to measure distance in a KNN classifier, but here I focused on two options:</p><ol><li><strong><em>Euclidean:</em></strong> This can be thought of as the straight-line distance between two points — it’s the most commonly used distance metric.</li><li><strong><em>Manhattan:</em></strong> Also called “city block” distance, this is the sum of absolute differences between the coordinates of 2 points. If you imagine standing at the corner of a city building and trying to get to the opposite corner — you wouldn’t cross through the building to get to the other side, but instead go up one block, then across one block.</li></ol><p>Note that I could have also fine-tuned the weight parameter (which determines whether all neighbors vote equally or if the closer neighbors are given more importance), but I decided to keep the voting weight uniform.</p><p>I defined a parameter grid with n_neighbors of 3, 7, and 10, as well as metrics of Euclidean or Manhattan. I then instantiated a <em>RandomizedSearchCV</em> algorithm, passing in the KNN classifier as the estimator, along with the parameter grid. I set the algorithm to split the data into 5 folds by setting the <em>cv </em>parameter to 5; this was then fit to the training set. A snippet of the code for this can be seen below:</p><pre>#Fine tuning (RandomisedSearchCV)<br># Define parameter grid<br>param_grid = {<br>    &#39;n_neighbors&#39;: [3, 7, 10],<br>    &#39;metric&#39;: [&#39;euclidean&#39;,&#39;manhattan&#39;]<br>}<br><br># instantiate RandomizedSearchCV<br>random_search = RandomizedSearchCV(estimator=KNeighborsClassifier(), param_distributions=param_grid, cv=5)<br><br># fit to training data<br>random_search.fit(X_train, y_train)<br><br># Retrieve best model and performance<br>best_classifier = random_search.best_estimator_<br>best_accuracy = random_search.best_score_<br><br>print(&quot;Best Accuracy:&quot;, best_accuracy)<br>print(&quot;Best Model:&quot;, best_classifier)</pre><p>The best accuracy and classifier were retrieved from the algorithm, indicating the classifier performs best with n_neighbors set to 10 while using the Manhattan distance metric, and that this would lead to an accuracy score of 74.0%:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*8mKFAjq5lztpaw0LETJTog.png" /><figcaption>Results of cross-validation — the random search classifier recommends n_neighbors=10 using the manhattan distance metric</figcaption></figure><p>as such these parameters were inputted to the classifier, and the model was retrained:</p><pre>#Classifier - K Nearest Neighbours<br>#instantiate KNN Classifier<br>KNNClassifier = KNeighborsClassifier(n_neighbors=10, metric = &#39;manhattan&#39;)<br><br>KNNClassifier.fit(X_train,y_train)</pre><p>Performance metrics were again extracted from the classifier, in the same manner as before — a screengrab of the metrics for this iteration can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*Dey6fWpwH3N9EvzZuvW2_g.png" /><figcaption>Metrics of the tuned KNN model</figcaption></figure><p>Cross-validation led to slightly poorer results for all metrics; test accuracy dropped by 2.6%, precision by 1.5%, recall by 0.5%, and F1 score by 1%. however the training-test accuracy difference dropped to 3.8%, where it was initially 13.5%. This indicates the model is no longer overfitting the data, and is therefore more suitable for predicting unseen data.</p><h3>Conclusion</h3><p>In summary, the KNN classifier performed well in predicting whether a collision would require a tow or ambulance. Initial metrics from the model’s first iteration were impressive, however the disparity between test and training accuracy indicated overfitting. Hyperparameter tuning allowed for the model to be optimised, which significantly reduced the gap in accuracies between the two datasets. While performance metrics did take a small hit during this process, the benefit of a model with better fit outweighs these concerns.</p><h3>References</h3><ol><li>Levy, J. (n.d.). Traffic Crashes — Crashes [Dataset]. Retrieved from Chicago Data Portal. Available at: <a href="https://data.cityofchicago.org/Transportation/Traffic-Crashes-Crashes/85ca-t3if">https://data.cityofchicago.org/Transportation/Traffic-Crashes-Crashes/85ca-t3if</a> (Accessed: 14th May 2023).</li><li>Chicago Police Department. (n.d.). Boundaries — Police Beats (current) [Data set]. Retrieved from Chicago Data Portal. Available at: <a href="https://data.cityofchicago.org/Public-Safety/Boundaries-Police-Beats-current-/aerh-rz74">https://data.cityofchicago.org/Public-Safety/Boundaries-Police-Beats-current-/aerh-rz74</a> (Accessed: 14th May 2023).</li><li>Zach M. (2022). “How to Perform Label Encoding in Python (With Example).” [Online]. Available at: <a href="https://www.statology.org/label-encoding-in-python/">https://www.statology.org/label-encoding-in-python/</a> (Accessed: July 19th, 2023).</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76b7e998a7a7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/data-driven-dispatch-76b7e998a7a7">Data-Driven Dispatch</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>