<?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 David Bartholomew on Medium]]></title>
        <description><![CDATA[Stories by David Bartholomew on Medium]]></description>
        <link>https://medium.com/@dbarth411?source=rss-3a8748091c6f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y8GFiBJSNFg5HI9hEGHdmw.png</url>
            <title>Stories by David Bartholomew on Medium</title>
            <link>https://medium.com/@dbarth411?source=rss-3a8748091c6f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 01:24:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dbarth411/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[Using Google Trends and pytrends API]]></title>
            <link>https://medium.datadriveninvestor.com/using-google-trends-and-pytrends-api-8c18ee9f5ebf?source=rss-3a8748091c6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c18ee9f5ebf</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[flatiron-school]]></category>
            <dc:creator><![CDATA[David Bartholomew]]></dc:creator>
            <pubDate>Wed, 24 Feb 2021 22:47:55 GMT</pubDate>
            <atom:updated>2021-05-14T17:50:04.350Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oy6-Ti0E-YfqVXlIn2IreQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Markus Winkler</a> on <a href="https://unsplash.com/s/photos/chart?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><a href="https://trends.google.com/trends/?geo=US">Google Trends</a> is an incredibly insightful tool to capture search trends of Google users. Coming from a revenue management background in the hotel industry, using search trends could influence several pricing and marketing decisions such as identifying need dates for promotions, potential high demand periods, evaluating potential lost business by comparing search trends to reservations made, and other revenue-related strategies. Practical business strategies can be applied for any company using Google Trends.</p><p>I just happened to stumble across pytrends recently and am fairly new to using the API, but I thought I would share some of my findings. From what I have gathered, using Google Trends is simple, and applying some automation and further analyzing data with pytrends can truly optimize your strategies. It’s best to visit <a href="https://trends.google.com/trends/?geo=US">Google trends</a> first to get an idea of what data you’re looking at before diving into pytrends. I searched for “hotels”, selected the state I was interested in (PA, in this case), and selected Philadelphia as the city to drill down further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-h6SvLIvLwfOzSRdv-5KA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYUjX2IQicS6Cp5zmk032g.png" /></figure><p>Once you select a city you’re interested in, you can use the geo code in the URL to pull this data in pytrends: <a href="https://trends.google.com/trends/explore?geo=US-PA-504&amp;q=hotels%20philadelphia">https://trends.google.com/trends/explore?geo=<strong><em>US-PA-504</em></strong>&amp;q=hotels%20philadelphia</a>. Here are some steps to install and work with pytrends.</p><ul><li>Install pytrends</li></ul><pre>pip install pytrends</pre><ul><li>Connect to Google</li></ul><pre>from pytrends.request import TrendReq<br>pytrends = TrendReq(hl=&#39;en-US&#39;, tz=360)</pre><ul><li>You can view trending searches if interested (this is for the entire U.S.)</li></ul><pre>pytrends.trending_searches(pn=&#39;united_states&#39;)</pre><ul><li>Or select top charts for a specific year</li></ul><pre>pytrends.top_charts(2020, hl=&#39;en-US&#39;, tz=300, geo=&#39;US&#39;)</pre><ul><li>In this case, we’re interested in hotels in Philadelphia, so we’ll use “hotels philadelphia” as our keyword. We can enter a specific start date and end date, a specific category if desired (full list available <a href="https://github.com/pat310/google-trends-api/wiki/Google-Trends-Categories">here</a>), and this is also where the geo code comes in handy.</li></ul><pre>hotels = pytrends.get_historical_interest([&#39;hotels philadelphia&#39;], year_start=2021, month_start=1,<br>day_start=1, hour_start=0, year_end=2021,<br>month_end=1, day_end=31, hour_end=0,<br>cat=0, geo=<strong>&#39;US-PA-504&#39;</strong>, gprop=&#39;&#39;, sleep=0)</pre><ul><li>Another useful tool is checking the top related queries, which returns a dictionary of query names and counts:</li></ul><pre>pytrends.related_queries()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Kib06vHbAzRO8PxBWkl8g.png" /></figure><ul><li>I won’t get into analyzing data here, but here is a simple plot of the time series.</li></ul><pre>hotels.plot(figsize=(14, 6))<br>plt.xlabel(‘Date’)<br>plt.ylabel(‘Total Searches’);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3e93jGp4zZbjdxC0SHggWQ.png" /></figure><p>Although somewhat brief, I hope this tutorial gives you an idea of the potential of utilizing pytrends to pull data from Google Trends. Capturing insightful trends from Google searches and forecasting trends is a great way to potentially get an edge on the competition. To me, this seemed like an easy way to get valid and interesting time series data. The documentation for pytrends is available <a href="https://pypi.org/project/pytrends/">here</a>.</p><p>I’m currently looking for data analyst or related roles, so if you are hiring or know any connections who are, please feel free to check out or share <a href="https://davidbbartholomew.com/">my portfolio website</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c18ee9f5ebf" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/using-google-trends-and-pytrends-api-8c18ee9f5ebf">Using Google Trends and pytrends API</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding NFL Helmets (and Attempting to Find Impacts) with Object Detection]]></title>
            <link>https://medium.com/swlh/finding-nfl-helmets-and-attempting-to-find-impacts-with-object-detection-e8823afca9ca?source=rss-3a8748091c6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8823afca9ca</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[flatiron-school]]></category>
            <dc:creator><![CDATA[David Bartholomew]]></dc:creator>
            <pubDate>Sat, 20 Feb 2021 20:30:43 GMT</pubDate>
            <atom:updated>2021-05-14T17:50:56.438Z</atom:updated>
            <content:encoded><![CDATA[<h3>Finding NFL Helmets (and attempting to find impacts) with Object Detection</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TZDu1j3mc5WDED_rSZc1g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@hencetheboom?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Adrian Curiel</a> on <a href="https://unsplash.com/s/photos/nfl?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The NFL continues its quest for improving player safety, working closely with Amazon Web Services to develop the “digital athlete” in order to virtually analyze, predict and prevent player injuries. Preventing concussions remains top on the list of priorities. As most recently <a href="https://www.nfl.com/playerhealthandsafety/health-and-wellness/injury-data/injury-data">reported by the NFL</a>, the 2019–2020 season involved 224 total concussions. As part of the initiative to reduce concussions and related injuries, the NFL created a <a href="https://www.kaggle.com/c/nfl-impact-detection/overview">Kaggle data science competition</a> for finding helmet impacts with computer vision models using a combination of thousands of images, 120 labeled videos with end zone and sideline views, and player tracking data provided by <a href="https://aws.amazon.com/nfl/">Next Gen Stats, powered by AWS</a>.</p><p>The provided data included images and videos with labeled bounding boxes surrounding each helmet with a goal of using the location of the bounding boxes to predict the location of the helmets in unlabeled videos and images. Some of the descriptions of the data are below along with a preview of the labels (modified version from the original data) and a specific frame in the video with labeled bounding boxes.</p><p>- gameKey: the ID code for the game.<br>- playID: the ID code for the play.<br>- view: the camera orientation (either end zone or sideline view)<br>- video: the filename of the associated video.<br>- frame: the frame number for this play.<br>- labels: whether an impact occurred or not<br>- [left/width/top/height]: the specification of the bounding box of the prediction. the right/bottom columns were added to be used later in the model.<br>- impactType: a description of the type of helmet impact: helmet, shoulder, body, ground, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AXTDJMjjdoq-w8oU33L_kg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*jYVIAEEHE42OT7Cp6uNAXA.png" /><figcaption>Labeled bounding boxes. Image provided by the NFL.</figcaption></figure><p>Detecting helmet impacts is no easy task. Before detecting impacts, the initial task is detecting helmets. Technically, this is considered the “easier” part of the project, and including player tracking information and considering 3D aspects of impacts would be more difficult. To be upfront, I didn’t use the player tracking information due to the fact that object detection in and of itself was completely new to me when I began the project, but I certainly aspire to improve on the work I’ve done. Below I’ll share my process of detecting helmets as well as my attempt at detecting impacts.</p><h3>Preprocessing data</h3><p>On a high level, detecting objects in an image involves two central tasks, localization and classification, i.e. identifying where objects are located in the image as well as identifying which objects they are (and how many). There are multiple algorithms that can be used to accomplish this, but I chose the RetinaNet model as it is a single-stage object detector that optimizes both speed and accuracy. The majority of the original structure of the model I used is available at this <a href="https://keras.io/examples/vision/retinanet/">link</a>.</p><p>Significant preprocessing was required to create an efficient input data pipeline for the RetinaNet model (without using PyTorch). In retrospect, some of the steps I took may have been unnecessary, but it was part of the learning process of what type of structure was required. I won’t cover every step taken, but here are some of the important ones.</p><p><strong>Capturing Video Frames</strong></p><p>Rather than using the provided images by the NFL, I used the CV2 module in Python to capture images from frames of the video files as arrays and then compressed the images to a memory cache and encoded as JPEG files (eliminates the need to download the 10,000 images). Below is the code for capturing video frames (images) as arrays using a DataFrame with previously created unique image ids for both end zone and sideline images.</p><pre>#Capture images from videos<br>video_list = []<br>missing_list = []<br>for i, j in tqdm.tqdm_notebook(enumerate(unique_df.video)):<br>    cap = cv2.VideoCapture(&#39;train/&#39; + j)<br>    cap.set(cv2.CAP_PROP_POS_FRAMES, unique_df.frame[i])<br>    success, img_array = cap.read()<br>    if success == True:<br>        video_list.append(img_array)<br>    else:<br>        missing_list.append(i)</pre><pre>#Convert the video_list to an array<br>train_arrays = np.array(video_list)</pre><p><strong>Converting Annotations</strong></p><p>The original bounding box annotations in the video CSV file were defined as Left, Top, Width, Height (x1, y1, w, h). The width and height needed to be converted to Right, Bottom (x1+w=right, y1+h=bottom) and normalized. To normalize the annotations, the x values were divided by the image width and y values were divided by the image height. Since all images were 1280x720, this was a simple calculation. Additionally, the final order of annotations needed to be y1 (top), x1 (left), y2 (bottom), x2 (right).</p><p><strong>Train/Test Split</strong></p><p>To properly evaluate the model, the image arrays as well as the annotations needed to be split into training and testing sets. I used sklearn’s train_test_split to do so, with 80% allocated to training and 20% allocated to the test set.</p><pre>#Train/Test Split<br>X_train, X_test, train_df, test_df = train_test_split(training_images, unique_df, test_size=.20,<br>                                                          random_state=set_seed)</pre><p>Skipping some steps in between, the final image count used was 1,081 and the overall annotations count was 21,843.</p><p><strong>Converting Data to COCO format</strong></p><p>RetinaNet requires the data format to be in COCO format, which stands for Common Objects in Context (<a href="https://cocodataset.org/#detection-2020">https://cocodataset.org/#detection-2020</a>). I first converted the data to multiple JSON files in the following format:</p><p>Images:<br>Image filenames and details of the image (height, width, id)</p><pre>#Example image<br>{&#39;file_name&#39;: &#39;57992301426.png&#39;,<br> &#39;height&#39;: 720,<br> &#39;width&#39;: 1280,<br> &#39;x_train_id&#39;: 0,<br> &#39;id&#39;: 57992301426}</pre><p>Categories:<br>One category: helmet</p><pre>[{&#39;id&#39;: 0, &#39;name&#39;: &#39;helmet&#39;}]</pre><p>Objects:<br>Bounding box annotations.</p><pre>{&#39;id&#39;: 0,<br> &#39;category_id&#39;: 0,<br> &#39;iscrowd&#39;: 0,<br> &#39;image_id&#39;: 580942819185,<br> &#39;objects&#39;: 17,<br> &#39;bbox&#39;: [0.42083333333333334, 0.65, 0.4513888888888889, 0.66484375]}</pre><p>Annotations:<br>Combining all above JSON files as nested dictionaries</p><pre>#Combine files as nested dictionary<br>annotations = {&quot;images&quot;: train_images, &quot;annotations&quot;: train_annotations, &quot;categories&quot;: train_categories}</pre><pre>Image sample:<br>{&#39;file_name&#39;: &#39;57992301426.png&#39;, &#39;height&#39;: 720, &#39;width&#39;: 1280, &#39;x_train_id&#39;: 0, &#39;id&#39;: 57992301426}</pre><pre>Annotations sample:<br>{&#39;id&#39;: 0, &#39;category_id&#39;: 0, &#39;iscrowd&#39;: 0, &#39;image_id&#39;: 580942819185, &#39;objects&#39;: 17, &#39;bbox&#39;: [0.42083333333333334, 0.65, 0.4513888888888889, 0.66484375]}</pre><pre>Categories sample:<br>{&#39;id&#39;: 0, &#39;name&#39;: &#39;helmet&#39;}</pre><p><strong>Using pycocotools API</strong></p><p>The <a href="https://github.com/cocodataset/cocoapi">pycocotools API</a> is used to assist in parsing, loading, and visualizing annotations in the COCO format.</p><pre>#Load train annotations file for parsing, loading, visualizing<br>train_annotations_file = ‘data/coco/2020/annotations/train/annotations.json’</pre><pre>train_coco=COCO(train_annotations_file)</pre><pre>loading annotations into memory...<br>Done (t=0.04s)<br>creating index...<br>index created!</pre><p><strong>Creating TFRecords (TensorFlow)</strong></p><p>Converting data to TFRecords has multiple advantages, the main being that TFRecords are TensorFlow’s binary file storage format, which can be read extremely efficiently from disk, and can be distributed to multiple TPUs (Tensor Processing Units) when training, which significantly reduces training time. Leaving out the code as it is somewhat lengthy and a multi-step process, but it is included in my preprocessing notebook in my <a href="https://github.com/dbarth411/NLF-Object-Detection">GitHub repo</a>.</p><h3>Intersection over Union &amp; Anchor Boxes</h3><p>Prior to looking at the structure of RetinaNet, it’s important to understand Intersection over Union (IoU) and Anchor Boxes. As described by the open source project, “[a]nchor boxes are fixed sized boxes that the model uses to predict the bounding box for an object. It does this by regressing the offset between the location of the object’s center and the center of an anchor box, and then uses the width and height of the anchor box to predict a relative scale of the object. In the case of RetinaNet, each location on a given feature map has nine anchor boxes (at three scales and three ratios)” (<a href="https://twitter.com/srihari_rh">Srihari Humbarwad, </a><a href="https://keras.io/examples/vision/retinanet/">https://keras.io/examples/vision/retinanet/</a>). Intersection over union is the calculation of the overlap of anchor boxes to ground truth boxes (our original annotations). It is calculated as the area where an anchor box intersects with the ground truth box divided by the combined total area of the anchor box and ground truth box.</p><p>While it is common to set the IoU threshold to 0.5, I altered the threshold to be less strict at 0.3 with an ignore threshold value at 0.2. This entails the following:</p><ul><li>An anchor box with an IOU less than 0.2 is considered background and the class label predicted is 0.</li><li>If the anchor box predicts an object with an IOU less than 0.2, it is penalized by the loss function</li><li>An anchor box with an IOU threshold between 0.2 and 0.3 is ignored by the loss function entirely.</li></ul><p>Setting the IoU threshold to 0.3, retrieving a statistical summary of bounding box width and height as well as plotting a few distributions gives some intuition for determining the scales, aspect ratios and areas of the anchor boxes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*54AA18JCvMr2p4HIsp20Iw.png" /></figure><p>Plotting Width / Height helps determine that the majority of bounding boxes are relatively square (with some clear outliers), so keeping the aspect ratios at 0.5, 1.0, and 1.5 would cover most of the ratios appropriately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lrbyECymcKMo3NKmMPdcUg.png" /></figure><p>Plotting the width * height gives us a general idea of the areas of the bounding boxes. Scales were left the same as the open source project (2^x for x in 0, 1/3, 2/3). The original areas were set to x**2 for x in [32, 64, 128, 256, 512]. Since the helmets in most cases are very small objects, the areas were altered to a range closer to the dataset: x**2 for x in [12, 24, 36, 48, 60].</p><h3>Model Structure</h3><p>With RetinaNet, a Feature Pyramid Network (FPN) creates a subnetwork for classification (predicting class labels) and a subnetwork for regression (localization, size and shape of bounding boxes) using the backbone’s output. Some details regarding the FPN:</p><ul><li>Bottom-up pathway: last feature map of each group of consecutive layers (c3_output, c4_output, c5_output shown below) are extracted from ResNet50, a prebuilt convolutional neural network. One important note is that the original open source did not include freezing the backbone layers so that the model would not train them as well. Freezing the backbone significantly reduces training time.</li></ul><pre>def get_backbone():</pre><pre>&quot;&quot;&quot;Builds ResNet50 with pre-trained imagenet weights&quot;&quot;&quot;</pre><pre>backbone = keras.applications.ResNet50(include_top=False, input_shape=[None, None, 3])</pre><pre><strong><em>backbone.trainable = False</em></strong></pre><pre>c3_output, c4_output, c5_output = [backbone.get_layer(layer_name).output <br>for layer_name in [&quot;conv3_block4_out&quot;, &quot;conv4_block6_out&quot;, &quot;conv5_block3_out&quot;]]</pre><pre>return keras.Model(inputs=[backbone.inputs], outputs=[c3_output, c4_output, c5_output])</pre><ul><li>Top-down pathway: using nearest neighbor sampling, the last feature map from the bottom-up pathway is expanded to the same scale as the second-to-last feature map. The two feature maps are then merged by element-wise addition to form a new feature map until each feature map from the bottom-up pathway has a corresponding feature map connected with lateral connections.</li><li>There are 5 levels in the pyramid (P3 through P7), and each level generates predictions using the classification and regression subnetwork</li><li>The output for classification is the probability distribution object classes</li><li>The output for regression is the offset of anchor boxes and ground truth boxes (4 values for each object)</li></ul><p>Higher level feature maps are proficient at detecting larger objects, covering larger areas of an image, while lower level feature maps are more proficient at detecting smaller objects. The original number of filters in the open source were set to 256. Although increasing the amount of filters could potentially improve accuracy of the model, it would also increase training time, so I left them as is.</p><p>When originally training with this structure, I found the model was significantly overfitting. In the end, the model was still slightly overfit to the training data, but adding 2D Spatial Dropout layers at outputs p3 through p6 helped reduce overfitting and reduce the loss for the test set.</p><pre>def call(self, images, training=False):</pre><pre>c3_output, c4_output, c5_output = self.backbone(images, training=training)<br>p3_output = self.conv_c3_1x1(c3_output)<br>p4_output = self.conv_c4_1x1(c4_output)<br>p5_output = self.conv_c5_1x1(c5_output)<br>p4_output = p4_output + self.upsample_2x(p5_output)<br>p3_output = p3_output + self.upsample_2x(p4_output)<br>p3_output = keras.layers.SpatialDropout2D(rate=0.4)(p3_output)<br>p3_output = self.conv_c3_3x3(p3_output)<br>p4_output = self.conv_c4_3x3(p4_output)<br>p4_output = keras.layers.SpatialDropout2D(rate=0.4)(p4_output)<br>p5_output = self.conv_c5_3x3(p5_output)<br>p5_output = keras.layers.SpatialDropout2D(rate=0.4)(p5_output)<br>p6_output = self.conv_c6_3x3(c5_output)<br>p6_output = keras.layers.SpatialDropout2D(rate=0.4)(p6_output)<br>p7_output = self.conv_c7_3x3(tf.nn.relu(p6_output))</pre><pre>return p3_output, p4_output, p5_output, p6_output, p7_output</pre><h3>Non-Max Suppression</h3><p>Another important technique utilized in the original open source is non-max suppression. With multiple anchor boxes, you could potentially have several predict the same ground truth bounding box. Each prediction generates a probability (between 0 and 1) whether the anchor box contains and object. This probability is also called the confidence score. The parameters and how non-max suppression works are as follows:</p><p>Parameters:</p><ul><li>Number of classes: (in this case, 1)</li><li>Confidence threshold: A value between 0 and 1. It’s the the lowest class probability you want to keep. The confidence threshold can be adjusted later, so keeping this low is ideal (0.05).</li><li>NMS IoU Threshold: A value between 0 and 1. This value determines the NMS operation, which I’ll explain.</li><li>Max Detections Per Class: Max detections you want to keep per class.</li><li>Max Detections: The total number of detections you want to keep. One suggestion is to look at training data and determine the max count of objects in your dataset for a specific image.</li><li>Box variance: Scaling factors used to scale the bounding box predictions.</li></ul><p>The NMS operation discards predictions under the confidence threshold and selects the prediction with highest confidence score. Other predictions above the confidence threshold are compared to the highest confidence score using intersection over union. If the IoU is above the set NMS IoU Threshold, then that prediction is also discarded.</p><p>The problem with this method is that there are multiple overlapping ground truth bounding boxes in the dataset, so selecting an NMS IoU Threshold may eliminate overlapping anchor boxes that actually match ground truth boxes, thus eliminating true positives. Rather than returning the NMS results after decoding predictions, this was altered to return all results (RetinaNet limits results to 1k for each prediction). While this returns more predictions than desired in the end, ultimately, a higher confidence threshold will be used after training the model to filter out unwanted results. The original NMS code has been commented out so the difference is clear.</p><pre>def call(self, images, predictions):</pre><pre>image_shape = tf.cast(tf.shape(images), dtype=tf.float32)<br>anchor_boxes = self._anchor_box.get_anchors(image_shape[1], image_shape[2])<br>box_predictions = predictions[:, :, :4]<br>cls_predictions = tf.nn.sigmoid(predictions[:, :, 4:])<br>boxes = self._decode_box_predictions(anchor_boxes[None, ...], box_predictions)<br>scores = cls_predictions</pre><pre># return tf.image.combined_non_max_suppression(<br>#     tf.expand_dims(boxes, axis=2),<br>#     cls_predictions,<br>#     self.max_detections_per_class,<br>#     self.max_detections,<br>#     self.nms_iou_threshold,<br>#     self.confidence_threshold,<br>#     clip_boxes=False)</pre><pre>return boxes, scores</pre><h3>Loss Function</h3><p>The loss function for RetinaNet is a duel-task loss function that includes a term for localization and a term for classification. A <strong><em>smooth l1 loss</em></strong> is used for the regression/localization task of matching ground truth boxes to anchor boxes. The regression subnet predicts 4 numbers, the first two numbers being the offset of the centers of ground truth and anchor boxes and the second two numbers being the offset of width and height.</p><p>Similar to a categorical cross entropy loss function, the <strong><em>focal loss</em></strong> function implements two additional parameters of alpha and gamma, which help address class imbalance. Especially with small object detection, there is a significant imbalance between the background class and the objects being detected. The gamma parameter is used to down-weight the loss of objects that are easy to classify and forces the network to focus on harder detections. On the other hand, alpha is used to down-weight the loss of examples in the background class.</p><p>Both the alpha and gamma parameters were left as the original open source project with alpha = 0.25 and gamma = 2.0. The num_classes parameter was changed to 1 since we are only detecting helmets. The loss functions are added together, combined as a single loss function when training.</p><p>The regression loss:</p><pre>class RetinaNetBoxLoss(tf.losses.Loss):</pre><pre>&quot;&quot;&quot;Implements Smooth L1 loss&quot;&quot;&quot;</pre><pre>def __init__(self, delta):</pre><pre>super(RetinaNetBoxLoss, self).__init__(reduction=&quot;none&quot;, name=&quot;RetinaNetBoxLoss&quot;)</pre><pre>self._delta = delta</pre><pre>def call(self, y_true, y_pred):</pre><pre>difference = y_true - y_pred</pre><pre>absolute_difference = tf.abs(difference)</pre><pre>squared_difference = difference ** 2</pre><pre>loss = tf.where(<br>tf.less(absolute_difference, self._delta),<br>0.5 * squared_difference,<br>absolute_difference - 0.5,)</pre><pre>return tf.reduce_sum(loss, axis=-1)</pre><p>The classification loss:</p><pre>class RetinaNetClassificationLoss(tf.losses.Loss):</pre><pre>&quot;&quot;&quot;Implements Focal loss&quot;&quot;&quot;</pre><pre>def call(self, y_true, y_pred):</pre><pre>cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(<br>labels=y_true, logits=y_pred)</pre><pre>probs = tf.nn.sigmoid(y_pred)</pre><pre>alpha = tf.where(tf.equal(y_true, 1.0), self._alpha, (1.0 - self._alpha))</pre><pre>pt = tf.where(tf.equal(y_true, 1.0), probs, 1 - probs)</pre><pre>loss = alpha * tf.pow(1.0 - pt, self._gamma) * cross_entropy</pre><pre>return tf.reduce_sum(loss, axis=-1)</pre><p>The wrapper to combine both loss functions:</p><pre>class RetinaNetLoss(tf.losses.Loss):</pre><pre>&quot;&quot;&quot;Wrapper to combine both the losses&quot;&quot;&quot;</pre><pre>def __init__(self, num_classes=1, alpha=0.25, gamma=2.0, delta=1.0):</pre><pre>super(RetinaNetLoss, self).__init__(reduction=&quot;auto&quot;, name=&quot;RetinaNetLoss&quot;)</pre><pre>self._clf_loss = RetinaNetClassificationLoss(alpha, gamma)<br>self._box_loss = RetinaNetBoxLoss(delta)<br>self._num_classes = num_classes</pre><pre>def call(self, y_true, y_pred):</pre><pre>y_pred = tf.cast(y_pred, dtype=tf.float32)<br>box_labels = y_true[:, :, :4]<br>box_predictions = y_pred[:, :, :4]</pre><pre>cls_labels = tf.one_hot(<br>tf.cast(y_true[:, :, 4], dtype=tf.int32),<br>depth=self._num_classes,<br>dtype=tf.float32,)<br>cls_predictions = y_pred[:, :, 4:]</pre><pre>positive_mask = tf.cast(tf.greater(y_true[:, :, 4], -1.0), dtype=tf.float32)<br>ignore_mask = tf.cast(tf.equal(y_true[:, :, 4], -2.0), dtype=tf.float32)</pre><pre>clf_loss = self._clf_loss(cls_labels, cls_predictions)<br>box_loss = self._box_loss(box_labels, box_predictions)<br>clf_loss = tf.where(tf.equal(ignore_mask, 1.0), 0.0, clf_loss)<br>box_loss = tf.where(tf.equal(positive_mask, 1.0), box_loss, 0.0)<br>normalizer = tf.reduce_sum(positive_mask, axis=-1)<br>clf_loss = tf.math.divide_no_nan(tf.reduce_sum(clf_loss, axis=-1), normalizer)<br>box_loss = tf.math.divide_no_nan(tf.reduce_sum(box_loss, axis=-1), normalizer)</pre><pre>loss = clf_loss + box_loss</pre><pre>return loss</pre><h3>Model Training</h3><p>Using TPUs (Tensor Processing Units) is necessary to avoid extremely long training times. This model was run in Google Colab, so here is the list of steps to ensure the input pipeline was efficient:</p><ul><li>Set the Hardware Accelerator to TPU (Runtime&gt;Change Runtime Type)</li><li>Initialize the TPU System</li></ul><pre>resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu=&#39;grpc://&#39; + os.environ[&#39;COLAB_TPU_ADDR&#39;])</pre><pre>tf.config.experimental_connect_to_cluster(resolver)</pre><pre># This is the TPU initialization code that has to be at the beginning.<br>tf.tpu.experimental.initialize_tpu_system(resolver)<br>print(&quot;All devices: &quot;, tf.config.list_logical_devices(&#39;TPU&#39;))</pre><ul><li>Set the distribution strategy</li></ul><pre>strategy = tf.distribute.TPUStrategy(resolver)</pre><ul><li>Establish model training parameters.<em> Important note:</em> a batch size that is divisible by 8 takes advantage of distributing training amongst 8 TPU cores. The model directory is set to my <a href="https://cloud.google.com/">Google Cloud</a> bucket path since that is where I am storing data.</li></ul><pre>#Create output directory for the model weights</pre><pre>model_dir = &quot;gs://nfl-object-detection123/&quot;</pre><pre>#Label encoder object<br>label_encoder = LabelEncoder()</pre><pre>#Number of classes and batch size for training/preprocessing<br>num_classes = 1<br>batch_size = 8</pre><ul><li>Compiling the model. Compiling the model must be included within strategy.scope() to take advantage of training across multiple TPUs.</li></ul><pre>#Establishing the resnet50_backbone, loss function, and model structure<br>resnet50_backbone = get_backbone()<br>loss_fn = RetinaNetLoss(num_classes)</pre><pre>model = RetinaNet(num_classes, resnet50_backbone)</pre><pre>#The Stochastic Gradient Descent optimizer is used with a learning rate of 0.001 and momentum of 0.95<br>optimizer = tf.optimizers.SGD(learning_rate=0.001, momentum=0.95)</pre><pre>#Compile the model<br>with strategy.scope():</pre><pre>model.compile(loss=loss_fn, optimizer=optimizer)</pre><ul><li>Setting up the input pipeline</li></ul><p>Setting up the input pipeline involves the following steps as mentioned in the original open source project:</p><ul><li>Apply the preprocessing function to the samples</li><li>Create batches with fixed batch size. Since images in the batch can have different dimensions, and can also have different number of objects, we use padded_batch to the add the necessary padding to create rectangular tensors</li><li>Autotune will automatically determine the appropriate level of parallelism and dynamically tune the value at runtime (preprocessing and encoding labels is a costly operation, so utilizing all cores in parallel is much more efficient)</li><li>Create targets for each sample in the batch using LabelEncoder</li></ul><pre>#Preprocess data, autotune defines appropriate number of threads to read the data<br>autotune = tf.data.experimental.AUTOTUNE</pre><pre>train_dataset = train_dataset.map(preprocess_data, num_parallel_calls=autotune)</pre><pre>#Randomly shuffles the dataset<br>train_dataset = train_dataset.shuffle(8*batch_size)</pre><pre># Creates batches with fixed batch size and pads image<br>train_dataset = train_dataset.padded_batch(batch_size=batch_size, padding_values=(0.0, 1e-8, -1), drop_remainder=True)</pre><pre>#Encode labels<br>train_dataset = train_dataset.map(label_encoder.encode_batch, num_parallel_calls=autotune)<br>train_dataset =<br>train_dataset.apply(tf.data.experimental.ignore_errors())<br>train_dataset = train_dataset.prefetch(autotune)</pre><pre>test_dataset = test_dataset.map(preprocess_data, num_parallel_calls=autotune)<br>test_dataset = test_dataset.padded_batch(batch_size=batch_size, padding_values=(0.0, 1e-8, -1), drop_remainder=True)<br>test_dataset = test_dataset.map(label_encoder.encode_batch, num_parallel_calls=autotune)<br>test_dataset = test_dataset.apply(tf.data.experimental.ignore_errors())<br>test_dataset = test_dataset.prefetch(autotune)</pre><ul><li>Finally, training the model. I used 25 epochs and established train_steps and test_steps per epoch by dividing the total number of samples in each by the batch size of 8, then using the repeat() function to ensure the model doesn’t run out of data.</li></ul><pre>#Set number of epochs<br>epochs = 25</pre><pre>#Establish steps per epoch for train and test sets<br>train_steps = np.ceil(train_samples // batch_size)<br>test_steps = np.ceil(test_samples // batch_size)</pre><pre>#Fit the model<br>model.fit(<br>train_dataset.repeat(),<br>validation_data=test_dataset.repeat(),<br>epochs=epochs,<br>steps_per_epoch=train_steps,<br>validation_steps=test_steps,<br>callbacks=callbacks_list,<br>verbose=1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*K7XGkhmZqoBLSCTxG3lyng.png" /></figure><h3>Implementing Soft Non-Max Suppression</h3><p>Since I replaced Non-Max Suppression earlier with predicting all possible results, I needed an alternate method to filter undesired results. Using TensorFlow’s <a href="https://www.tensorflow.org/api_docs/python/tf/image/non_max_suppression_with_scores">tf.image.non_max_suppression_with_scores</a> function, I was able to implement Soft-NMS, which works very similarly to the normal NMS function. Rather than eliminating predictions over a certain IoU threshold, Soft-NMS uses a sigma value (float between 0 and 1) to down-weight the confidence score of detections over the IoU threshold. Using an IoU threshold of 1.0 allowed me to keep all confidence scores as is and select the predictions for each object based on the confidence threshold alone. Ultimately, this eliminates any predictions under the specified confidence score and keeps potential true positives where bounding boxes are intersecting.</p><h3>Evaluating Results</h3><p>Since it’s difficult to evaluate results based on the loss function alone, I built a Pandas DataFrame including the model predictions and then built a residual DataFrame, labeling true positives (any detections above the confidence threshold), false positives (any detections above the confidence threshold but not in the original labeled data), and false negatives (comparing the counts of detections in the original labeled data to the predicted counts).</p><p>I compared the results of several confidence thresholds ranging from 0.15 to 0.90, allowing me to check which confidence threshold had the highest Precision, Recall, and F1 Score. I decided to use the highest F1 Score (the harmonic balance between precision and recall) as my determining evaluation metric, since that was also recommended in the Kaggle competition. With a confidence threshold of 0.22, the highest F1 Score was 0.949 for detecting helmets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96bzf3CBhlVK_X61i0Gacw.png" /></figure><p>Although a little convoluted due to the amount of overall objects, you can get an idea of how the model performed on helmet detection using a scatterplot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*snZcde-qDROs6axdZmZdZg.png" /></figure><p>Here is a visualization of an image with confidence scores:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pS9480revdp-MdgRVv2pQw.png" /></figure><p><strong>Detecting Impacts</strong></p><p>I set a strict filter for impacts using IoU between bounding box predictions for each image, knowing that helmets with impacts were extremely less likely than helmets without impacts. Any IoU between 0.1 and 0.4 was labeled as an impact. Since I was only dealing with 2D data and didn’t attempt to convert to 3D, this wasn’t overly accurate as mentioned before. There were several helmets without impact that had an IoU between .1 and .4 as shown below. The F1 Score was extremely low for impact detections.</p><h3>Predicting Unseen Test Videos</h3><p>I used the model weights to predict helmet and impact detections on unseen test videos for matching end zone and sideline views. In order to leave open the possibility of evaluating results on these unseen test videos, I set aside 2 videos that were included in the original training set with labels (they were not included when training the model) rather than using the provided test videos without labels. For both views, I used the IoU filter for impacts of 0.1 to 0.4 based on previous EDA.</p><p>Here is the scatterplot of helmet detections:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oy9YIWlAjK7eCFJpfYEPnw.png" /></figure><p>The scatterplot for impact detections:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kqTsTNiC9HCae4X8d3qT9w.png" /></figure><p>Finally, I created a side-by-side video of the end zone and sideline views showing the predicted helmet and impact detections.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8h1MnvDFl5Q%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8h1MnvDFl5Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8h1MnvDFl5Q%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f90ed97deb437638baedd364d070042/href">https://medium.com/media/1f90ed97deb437638baedd364d070042/href</a></iframe><h3>Conclusion/Further Work</h3><p>Although the model did reasonably well with detecting helmets with an F1 Score of .957 for the end zone view and .96 for the sideline view, it is obvious that further work is necessary to improve the detection of helmet impacts. If you’re interested in the notebook with additional details, please check out my <a href="https://github.com/dbarth411/NLF-Object-Detection">GitHub repository</a>. If you fork this notebook, note that the links for writing files to Google Cloud will need to be changed since you will only have reader access. If you want to download the entire dataset, it is best to download directly from <a href="https://www.kaggle.com/c/nfl-impact-detection/data">Kaggle</a>. Further work can include but is not limited to the following:</p><ul><li>Combining previous data with player tracking data and potentially using <a href="https://docs.opencv.org/master/d9/dab/tutorial_homography.html">homography</a> to locate players in videos based on tracking key points.</li><li>Potentially using 3D Convolutional Neural Network models to identify impacts (computationally expensive).</li><li>Using a <a href="https://www.youtube.com/watch?v=4BwXOcLqrGk">Temporal Shift Module</a> (the winner of the Kaggle competition used TSM). Videos have an additional dimension over images, the temporal dimension, which is the shift of objects in images between frames. Using this information, the TSM predicts actions based on a specified range of frames. This is a less computationally-expensive model as it only utilizes 2D CNNs. (With ResNet, this could be added after each convolutional block).</li></ul><p><em>I’m currently looking for data analyst or related roles, so if you are hiring or know any connections who are, please feel free to check out or share </em><a href="https://davidbbartholomew.com/"><em>my portfolio website</em></a><em>.</em></p><h3>References</h3><ul><li><a href="https://www.nfl.com/playerhealthandsafety/health-and-wellness/injury-data/injury-data">Injury Data Since 2012</a></li><li><a href="https://keras.io/examples/vision/retinanet/">Keras documentation: Object Detection with RetinaNet</a></li><li><a href="https://blog.zenggyu.com/en/post/2018-12-05/retinanet-explained-and-demystified/#fn10">RetinaNet Explained and Demystified | NickZeng|曾广宇</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8823afca9ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/finding-nfl-helmets-and-attempting-to-find-impacts-with-object-detection-e8823afca9ca">Finding NFL Helmets (and Attempting to Find Impacts) with Object Detection</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Pneumonia in X-Ray Images with a Convolutional Neural Network]]></title>
            <link>https://medium.com/analytics-vidhya/detecting-pneumonia-in-x-ray-images-with-a-convolutional-neural-network-735f68f40564?source=rss-3a8748091c6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/735f68f40564</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[David Bartholomew]]></dc:creator>
            <pubDate>Mon, 23 Nov 2020 16:12:11 GMT</pubDate>
            <atom:updated>2020-12-23T16:40:06.604Z</atom:updated>
            <content:encoded><![CDATA[<h3>Detecting Pneumonia in X-ray Images</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bzHjJxK3igS6D1JpyFKnpg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nci?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">National Cancer Institute</a> on <a href="https://unsplash.com/s/photos/x-ray?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>My primary goal with this article is to highlight a practical application as a result of building a convolutional neural network (CNN) model. In general, CNN models have a wide variety of applications; in this case, it’s building a model that can accurately detect pneumonia in x-ray images. Sounds cool, right? But why would we need a convolutional neural network when we have medical experts that can perform the same task?</p><p><strong>Why would we need a CNN to detect pneumonia?</strong></p><p>Across the world, there is a general lack of radiologists, and this number continues to diminish which causes significant resources to be spent in order to determine the results of medical imaging. In many cases, a lack of a radiologist delays test results. This could also mean relying on medical professionals that don’t have expertise in radiology, leading to misinterpreted results. Getting accurate results within a short period of time can be a difference-maker and possibly a life-saver for certain patients.</p><p>The images used in this particular project were for pediatric patients under 5 years old. According to the World Health Organization, pneumonia accounts for 15% of deaths in the world for children under 5 years old. Pneumonia that is caused by bacteria can be treated with antibiotics, but only one third of children receive them (<a href="https://www.who.int/news-room/fact-sheets/detail/pneumonia">https://www.who.int/news-room/fact-sheets/detail/pneumonia</a>). Streamlining the process of accurately detecting pneumonia in children is a necessity, and it truly could save lives.</p><p>So now that we understand the need for a CNN, let’s look at some details on the project and final model results. Before moving on, if you’re not interested in some of the code used to build the project and just want to see final results (which is understandable if you don’t know Python), then please feel free to scroll to the end of the article.</p><p><strong>The Data:</strong><br>The data for this project was downloaded directly from <a href="https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia">https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia</a>. The data contains 5,856 x-ray images with a mix of RGB and grayscale images.</p><p><strong>Resizing Images:</strong><br>Images were resized to 75x75 for efficiency when running on a local machine. Additionally, transfer learning was used with a pre-trained network, InceptionResNetV2, which requires that the minimum image size is 75x75.</p><p><strong>Train, Validation and Test Sets:</strong><br>The original train, test, and validation sets were 5,216, 624, and 16 images. All images and labels were combined and then resplit in order to increase the size of the test set to more accurately evaluate model results as 16 images alone would not give a clear enough picture. The final training set was slightly reduced to 5,153 images, the validation set with 632 total images was used in the modeling process to gauge model accuracy and tune the model further, and the test set was used to gauge how the model would handle unseen data with 71 total images.</p><p><strong>Data Augmentation:</strong><br>Data Augmentation was implemented to increase the size of the training set and give the model additional diversity of images to improve accuracy (you may have noticed the resplit training plot above was larger than the original). The initial training set was doubled with images having Pixel values under 25 replaced with 0. Essentially, this converts darker gray areas to black and allows the model to focus on the more important, lighter areas. Below is an original image compared to an altered image along with code used to make this alteration (the differences are very subtle, but effective):</p><pre>#Change pixel values for data augmentation<br>i = (X_train &gt;= 0) &amp; (X_train &lt; 25)<br>altered = np.where(i, 0, X_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OUnj47l9UeaYcIhBH04JjQ.png" /></figure><p>Additionally, here is a plot of the original vs. augmented training set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*WhvmBzSg7fgd7h85DmogJw.png" /></figure><p><strong>Building the Initial Model:</strong></p><p>The first function below was created to visualize a confusion matrix in order to understand the breakdown of true positives, true negatives, false positives and false negatives. The second function below was created for the modeling process. As the documentation states, this function was built to build the neural network model, return classification reports and confusion matrix, and save the best model using a model checkpoint callback based on validation accuracy.</p><pre>#Build Plot Confusion Matrix Function<br>def plot_confusion_matrix(cm, classes=[0, 1], normalize=False, title=None, cmap=plt.cm.Blues, ax=None):<br>    &quot;&quot;&quot;<br>    Print and plot a confusion matrix.<br>    Normalization can be applied by setting `normalize=True`.<br>    &quot;&quot;&quot;<br>    plt.imshow(cm, interpolation=&#39;nearest&#39;, cmap=cmap)<br>    plt.title(title)<br>    plt.colorbar()<br>    tick_marks = np.arange(len(classes))<br>    plt.xticks(tick_marks, classes)<br>    plt.yticks(np.arange(0, 1), [0, 1])</pre><pre>if normalize:<br>        cm = cm.astype(&#39;float&#39;) / cm.sum(axis=1)[:, np.newaxis]<br>    else:<br>        pass</pre><pre>thresh = cm.max() / 2.<br>    j_list = []<br>    for i in cm:<br>        for j in i:<br>            j_list.append(j)<br>    zero = j_list[:2]<br>    one = j_list[2:]<br>    for i, j in enumerate(zero):<br>        plt.text(x=i, y=0, s=j, horizontalalignment=&quot;center&quot;, fontsize=16, <br>                 color=&quot;white&quot; if j &gt; thresh else &quot;black&quot;)<br>        plt.text(x=0, y=0.2, s=&#39;True Negatives&#39;, horizontalalignment=&quot;center&quot;,<br>                 fontsize=16, <br>                 color=&quot;white&quot; if j &gt; thresh else &quot;black&quot;)<br>        plt.text(x=1, y=0.2, s=&#39;False Positives&#39;, horizontalalignment=&quot;center&quot;,<br>                 fontsize=16, <br>                 color=&quot;white&quot; if j &gt; thresh else &quot;black&quot;)<br>    for i, j in enumerate(one):<br>        plt.text(x=i, y=1, s=j, horizontalalignment=&quot;center&quot;, verticalalignment=&quot;center&quot;, fontsize=16, <br>                 color=&quot;white&quot; if j &gt; thresh else &quot;black&quot;)<br>        plt.text(x=0, y=1.2, s=&#39;False Negatives&#39;, horizontalalignment=&quot;center&quot;, <br>                 fontsize=16, <br>                 color=&quot;white&quot; if j &gt; thresh else &quot;black&quot;)<br>        plt.text(x=1, y=1.2, s=&#39;True Positives&#39;, horizontalalignment=&quot;center&quot;, <br>                 fontsize=16, <br>                 color=&quot;white&quot; if j &gt; thresh else &quot;black&quot;)</pre><pre>plt.tight_layout()<br>    plt.ylabel(&#39;True label&#39;)</pre><p>Function to build model:</p><pre>layers_list = []</pre><pre># Create Model Checkpoint <br>mc = ModelCheckpoint(&#39;best_model_test.h5&#39;, monitor=&#39;val_accuracy&#39;, mode=&#39;max&#39;, verbose=1, save_best_only=True)</pre><pre>def build_model(optimizer, epochs, batch_size, callbacks=mc, weights={0:1,1:1}):<br>    &quot;&quot;&quot;<br>    Build a neural network model, returning classification reports, confusion matrix, <br>    and save best model using model checkpoint based on val_accuracy.<br>    <br>    Input Parameters: optimizer, epochs, batch_size, callbacks, weights<br>    &quot;&quot;&quot;<br>    <br>    # Initialize a sequential model<br>    model = Sequential()</pre><pre># Add layers<br>    for i in layers_list:<br>        model.add(i)<br>    <br>    # Compile the model<br>    model.compile(optimizer=optimizer, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br>    <br>    results = model.fit(X_train, y_train, callbacks=callbacks, class_weight=weights, epochs=epochs, batch_size=batch_size, <br>                        validation_data=(X_test, y_test))<br>    build_model.results = results<br>    <br>    # Output (probability) predictions for the train and test set<br>    y_hat_train = model.predict(X_train)<br>    y_hat_test = model.predict(X_test)<br>    build_model.y_hat_train = y_hat_train<br>    build_model.y_hat_test = y_hat_test<br>    <br>    #Visualize Results<br>    history = results.history<br>    plt.figure()<br>    plt.plot(history[&#39;val_loss&#39;])<br>    plt.plot(history[&#39;loss&#39;])<br>    plt.legend([&#39;val_loss&#39;, &#39;loss&#39;])<br>    plt.title(&#39;Loss&#39;)<br>    plt.xlabel(&#39;Epochs&#39;)<br>    plt.ylabel(&#39;Loss&#39;)<br>    plt.show()<br>    <br>    plt.figure()<br>    plt.plot(history[&#39;val_accuracy&#39;])<br>    plt.plot(history[&#39;accuracy&#39;])<br>    plt.legend([&#39;val_accuracy&#39;, &#39;accuracy&#39;])<br>    plt.title(&#39;Accuracy&#39;)<br>    plt.xlabel(&#39;Epochs&#39;)<br>    plt.ylabel(&#39;Accuracy&#39;)<br>    plt.show()<br>    <br>    print(&#39;-----------------------------------\n&#39;)<br>    <br>    # Print the loss and accuracy for the training set <br>    results_train = model.evaluate(X_train, y_train)<br>    print(&#39;Train Results&#39;, results_train)<br>    print(&#39;-----------------------------------\n&#39;)<br>    <br>    # Print the loss and accuracy for the training set <br>    results_test = model.evaluate(X_test, y_test)<br>    print(&#39;Test Results&#39;, results_test)<br>    print(&#39;-----------------------------------\n&#39;)<br>    <br>    # Print Classification Reports<br>    print(&#39;Train Classification Report&#39;)<br>    print(classification_report(y_train, np.round(y_hat_train, 0), <br>                                target_names = [&#39;Normal (Class 0)&#39;,&#39;Pneumonia (Class 1)&#39;]))<br>    print(&#39;-----------------------------------\n&#39;)<br>    <br>    print(&#39;Test Classification Report&#39;)<br>    print(classification_report(y_test, np.round(y_hat_test, 0), <br>                                target_names = [&#39;Normal (Class 0)&#39;,&#39;Pneumonia (Class 1)&#39;]))<br>    print(&#39;-----------------------------------\n&#39;)<br>    <br>    # load the saved model<br>    saved_model = load_model(&#39;best_model_test.h5&#39;)</pre><pre># evaluate the model<br>    _, train_acc = saved_model.evaluate(X_train, y_train, verbose=0)<br>    _, test_acc = saved_model.evaluate(X_test, y_test, verbose=0)<br>    build_model.saved_model = saved_model<br>    print(&#39;Best Model Results\n&#39;)<br>    print(&#39;Train: %.3f, Test: %.3f&#39; % (train_acc, test_acc))<br>    print(&#39;-----------------------------------\n&#39;)<br>    <br>    #Create Confusion Matrices<br>    train_cm = confusion_matrix(y_true=y_train, y_pred=np.round(y_hat_train, 0))<br>    test_cm = confusion_matrix(y_true=y_test, y_pred=np.round(y_hat_test, 0))<br>    build_model.train_cm = train_cm<br>    build_model.test_cm = test_cm<br>    <br>    #Plot Train Confusion Matrices<br>    plt.figure(figsize=(12, 6))<br>    plt.subplot(121)<br>    plot_confusion_matrix(cm=train_cm, <br>                          cmap=plt.cm.Blues)<br>    <br>    plt.subplot(122)<br>    plot_confusion_matrix(cm=test_cm, <br>                          cmap=plt.cm.Blues)<br>    plt.subplots_adjust(wspace=0.4)</pre><p>Now that the functions have been set up, here is the structure of the first model:</p><pre>#Add layers<br>layers_list = []</pre><pre>layer1 = layers.Conv2D(75, (2, 2), padding=&#39;same&#39;, activation=&#39;relu&#39;, input_shape=(75, 75,  3))<br>layer2 = layers.MaxPooling2D((2, 2), padding=&#39;same&#39;)<br>layer3 = layers.Conv2D(75, (2, 2), padding=&#39;same&#39;, activation=&#39;relu&#39;)<br>layer4 = layers.MaxPooling2D((2, 2), padding=&#39;same&#39;)<br>layer5 = layers.Conv2D(75, (2, 2), padding=&#39;same&#39;, activation=&#39;relu&#39;)<br>layer6 = layers.MaxPooling2D((2, 2), padding=&#39;same&#39;)<br>layer7 = layers.Flatten()<br>layer8 = layers.Dense(75, activation=&#39;relu&#39;)<br>layer9 = layers.Dense(1, activation=&#39;sigmoid&#39;)</pre><pre>layers_list = [layer1, layer2, layer3, layer4, layer5, layer6, layer7, layer8, layer9]</pre><pre>#Utilize Stochastic Gradient Descent Optimizer<br>opt = keras.optimizers.SGD(learning_rate=0.01, momentum=.9)</pre><pre>#Build model with pre-built function<br>build_model(optimizer=opt, epochs=50, batch_size=100, callbacks=mc)</pre><p>This model performed well with 96.7% accuracy for the validation set. I tried a second model without transfer learning in an attempt to improve these results but to no avail. Truthfully, I tried what felt like millions of different parameters and hyperparameters and did achieve better results in some cases, but the best model results overall were determined with the prebuilt InceptionResNetV2 model. I won’t print the entire model structure here as it’s quite large, but if you’re interested, you can view the structure in Python with this code (and in my GitHub repo which is included at the end of this article):</p><pre>#Import InceptionResNetV2<br>from keras.applications import InceptionResNetV2</pre><pre>#Build the model base with required input shape 75x75x3<br>cnn_base = InceptionResNetV2(weights=&#39;imagenet&#39;, <br>                 include_top=False, <br>                 input_shape=(75, 75, 3))</pre><pre>#View base structure<br>cnn_base.summary()</pre><p>Typically, most would freeze the pre-trained network or at least part of the network to use the prebuilt model weights and reduce training time. I decided to be different and retrain the entire model to improve accuracy. This was possible to run on my Mac with the size of the dataset and using a smaller image size of 75x75x3. I included the base model as my first layer as shown below:</p><pre>#Set random seed<br>np.random.seed(123)</pre><pre>#Add layers including InceptionResNetV2 base<br>layers_list = []</pre><pre>layer1 = cnn_base<br>layer2 = layers.Flatten()<br>layer3 = layers.Dense(75, activation=&#39;relu&#39;)<br>layer4 = layers.Dense(1, activation=&#39;sigmoid&#39;)</pre><pre>layers_list = [layer1, layer2, layer3, layer4]</pre><pre>#Utilize Stochastic Gradient Descent Optimizer<br>opt = keras.optimizers.SGD(learning_rate=0.01, momentum=.9)</pre><pre>#Build model with pre-built function<br>build_model(optimizer=opt, epochs=50, batch_size=100, callbacks=mc)</pre><p><strong>Final Model Results:</strong></p><p>The function for making predictions on our unseen test set is below. The test set was held out until the final prediction in order to remove any bias that may be implemented when training the model.</p><pre>#Build a function to make predictions on unseen data<br>def predict_new_images(test_img, test_lbls):<br>    &#39;&#39;&#39;Predict saved model results on unseen test set, print classification report and plot confusion matrix.&#39;&#39;&#39;<br>    <br>    #Transpose val labels<br>    test_lbls = test_lbls.T[[1]]<br>    test_lbls = test_lbls.T<br>    <br>    #Standardize the data<br>    test_final = test_img/255<br>    <br>    predictions = build_model.saved_model.predict(test_final)<br>    predict_new_images.predictions = predictions<br>    test_cm = confusion_matrix(y_true=test_lbls, y_pred=np.round(predictions, 0))<br>    <br>    print(&#39;Classification Report&#39;)<br>    print(classification_report(test_lbls, np.round(predictions, 0), <br>                                target_names = [&#39;Normal (Class 0)&#39;,&#39;Pneumonia (Class 1)&#39;]))<br>    print(&#39;-----------------------------------\n&#39;)<br>    <br>    plt.figure(figsize=(10, 6))<br>    plot_confusion_matrix(cm=test_cm, <br>                      cmap=plt.cm.Blues)<br>    plt.savefig(&#39;images/final_model_result.png&#39;)</pre><p>The function plots a confusion matrix showing the final results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRBBLO_hNsY50iC3g7Q4Ng.png" /></figure><p>In some ways I’m a perfectionist, so having a result of 100% accuracy on the unseen test set made me happy. Personally, I find it amazing that out of 71 x-ray images in the unseen test set, this convolutional neural network model is able to detect whether or not a pediatric patient has pneumonia with 100% accuracy. Like I said, it is pretty cool.</p><p>For more details and the full notebook for this project, please visit my GitHub repo here: <a href="https://github.com/dbarth411/dsc-mod-4-project-v2-1-online-ds-sp-000">https://github.com/dbarth411/dsc-mod-4-project-v2-1-online-ds-sp-000</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=735f68f40564" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/detecting-pneumonia-in-x-ray-images-with-a-convolutional-neural-network-735f68f40564">Detecting Pneumonia in X-Ray Images with a Convolutional Neural Network</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Arrests as a Result of a Terry Stop]]></title>
            <link>https://medium.com/swlh/predicting-arrests-as-a-result-of-a-terry-stop-53583b526192?source=rss-3a8748091c6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/53583b526192</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[police]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[David Bartholomew]]></dc:creator>
            <pubDate>Sat, 10 Oct 2020 16:45:17 GMT</pubDate>
            <atom:updated>2021-05-14T17:51:50.695Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X6fyQG-gT8zbOiLNqZNf8Q.png" /></figure><p>Police reform is a huge topic these days, especially as we get closer to a presidential election with two candidates who seem to have very different ideologies on the matter. A topic that could potentially be reviewed when looking at police reform is Terry Stops. In 1968, the Supreme Court ruled that if an officer has reasonable suspicion that a person committed, is committing, or is about to commit a crime, the officer is not violating the Fourth Amendment’s prohibition on unreasonable searches and seizures if they choose to stop, investigate, and even frisk the suspect to determine if they are armed. As you can imagine, racial profiling could potentially be a huge issue, and has long been a topic of discussion. Rather than focusing on the subject of race, my goal was solely to predict the highest amount of arrests as a result of Terry Stops at the time of initial suspicion. Although race will not be the main topic of this article, there will be some highlighted demographic statistics as a result of the model.</p><p>My process involved an iterative approach to building a classification model in python to predict arrests as a result of Terry Stops, utilizing Terry Stop data in Seattle, WA, with reports starting in 2015. The description of the data is pulled directly from <a href="https://www.seattle.gov/police/information-and-data/terry-stops">https://www.seattle.gov/police/information-and-data/terry-stops</a> and is as follows: “[The data includes] police-civilian contacts that involve the stop and limited detention of an individual (Terry stop). Under Terry v. Ohio, 392 U.S. 1 (1968), such contacts authorized under law and policy for purposes of investigating, based on an officer’s reasonable suspicion, whether the individual is engaging, has engaged, or is about to engage in criminal activity. During the course of a Terry stop, an officer may develop probable cause to effect an arrest, but probable cause is not required to make the initial stop, nor does a stop that is based on probable cause to arrest fall within the category of a Terry stop.”</p><p>This project involved the OSEMN approach as outlined below:</p><p><strong>Obtain Data</strong></p><p>The data for this project was obtained directly from <a href="https://catalog.data.gov/dataset/terry-stops">https://catalog.data.gov/dataset/terry-stops</a>, downloaded as a csv file and imported into a pandas dataframe. The column descriptions are available in the github repo for this project as an md file.</p><pre>df = pd.read_csv(&#39;data/Terry_Stops.csv&#39;)</pre><p><strong>Scrub Data</strong></p><p>Scrubbing the data involved removing duplicate records, filling missing values, determining whether to keep or replace placeholder values, and converting to appropriate data types. A few code examples are below:</p><pre>#Change Stop Resolution to binary: arrested or not<br>df[&#39;Stop Resolution&#39;] = df[&#39;Stop Resolution&#39;].replace(&#39;Arrest&#39;, 1.0)<br>df[&#39;Stop Resolution&#39;] = df[&#39;Stop Resolution&#39;].map(lambda x: 0.0 if (x != 1.0) else 1.0)</pre><pre>#Split time from date and keep date in df<br>df[&#39;Reported Date&#39;] = df[&#39;Reported Date&#39;].str.split(&#39;T&#39;).str[0]</pre><pre>#Convert to datetime data type<br>df[&#39;Reported Date&#39;] = pd.to_datetime(df[&#39;Reported Date&#39;])</pre><pre>#Split date into multiple columns<br>df[&#39;Reported Year&#39;] = df[&#39;Reported Date&#39;].dt.year<br>df[&#39;Reported Month&#39;] = df[&#39;Reported Date&#39;].dt.month<br>df[&#39;Reported Day&#39;] = df[&#39;Reported Date&#39;].dt.day</pre><p><strong>Explore Data</strong></p><p>This step involved plotting all features vs. the target variable, Stop Resolution, to perform additional, necessary feature engineering, one hot encoding categorical variables, and getting an overall understanding of which features to include in our modeling. An example of Beat vs. Stop Resolution is below. Beat is the address associated with the underlying Computer Aided Dispatch (CAD) event and was converted to a binary column, whether the beat was reported or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*IMGDujwnUYuDQ9yEr8zBWA.png" /></figure><p><strong>Model Data</strong></p><p>The modeling approach was to utilize several different classification algorithms and compare scores, then implementing the Boruta algorithm for feature selection, and utilizing GridSearchCV with hyperparameter tuning to increase our score. The focus on this project was the recall/sensitivity score (measuring the proportion of positives that are correctly identified), with the ultimate goal of predicting arrests while minimizing false negatives.</p><p>The algorithms used are as follows: Logistic Regression, Multinomial Bayes, Decision Trees, Random Forest, Balanced Random Forest, Bagging with Decision Trees, Balanced Bagging with Decision Trees, AdaBoost, and XGBoost. To make this process easier, I created a function that would build a classification model for each algorithm, return the classification report, print train and test set accuracy, and plot a confusion matrix to view our total true positives, true negatives, false positives and false negatives. The function also created a pandas data frame with the model results.</p><pre>#Split features and target<br>X = df.drop(columns=[&#39;Stop Resolution&#39;], axis=1)<br>y = df[&#39;Stop Resolution&#39;]</pre><pre>#Create function to easily build models and display results<br>def build_model(classifier, predictors, labels):<br>    &#39;&#39;&#39;Build classification model, returning classification report, train and test accuracy, and confusion matrix.<br>    <br>    Keyword arguments: <br>    classifier -- classification algorithm<br>    predictors -- X, features<br>    labels -- y, target<br>    &#39;&#39;&#39;<br>    <br>    #Split the data into train and test sets<br>    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.20, random_state=123)<br>    <br>    #Scale the data<br>    scaler = MinMaxScaler()<br>    X_train = scaler.fit_transform(X_train)<br>    X_test = scaler.transform(X_test)<br>    <br>    #Create variables that can be called outside function<br>    build_model.X_train = X_train<br>    build_model.X_test = X_test<br>    build_model.y_train = y_train<br>    build_model.y_test = y_test<br>    <br>    #Fit model<br>    model = classifier.fit(X_train, y_train)<br>    score = np.mean(cross_val_score(classifier, X, y, cv=5, scoring=&#39;recall&#39;))<br>    <br>    #Create predictions<br>    y_hat_train = model.predict(X_train)<br>    y_hat_test = model.predict(X_test)<br>    <br>    #Create variables that can be called outside function<br>    build_model.y_hat_train = y_hat_train<br>    build_model.y_hat_test = y_hat_test<br>    <br>    #Print classification report<br>    print(&#39;Train Classification Report\n&#39;, classification_report(y_train, y_hat_train))<br>    print(&#39;\n----------------------------------\n&#39;)<br>    print(&#39;Test Classification Report\n&#39;, classification_report(y_test, y_hat_test))<br>    print(&#39;\n----------------------------------\n&#39;)<br>    <br>    print(&#39;Train Accuracy:&#39;, round(accuracy_score(y_train, y_hat_train), 3))<br>    print(&#39;Test Accuracy:&#39;, round(accuracy_score(y_test, y_hat_test), 3))<br>    print(&#39;Cross Validation Recall&#39;, round(score, 3))<br>    print(&#39;\n----------------------------------\n&#39;)<br>    <br>    #Create a results dataframe<br>    results = pd.DataFrame([[str(model), round(accuracy_score(y_train, y_hat_train), 3), <br>                             round(accuracy_score(y_test, y_hat_test), 3), round(score, 3)]], <br>                          columns=[&#39;Model&#39;, &#39;Train_Accuracy&#39;, &#39;Test_Accuracy&#39;, &#39;Cross_Val_Recall&#39;])<br>    build_model.results = results<br>    <br>    #Plot Confusion Matrices<br>    fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(14, 8))<br>    plot_confusion_matrix(classifier, X_train, y_train,<br>                     cmap=plt.cm.Blues, ax=axes[0])<br>    fig.suptitle(&#39;Train &amp; Test Confusion Matrices&#39;, fontsize=16);<br>    <br>    plot_confusion_matrix(classifier, X_test, y_test,<br>                     cmap=plt.cm.Blues, ax=axes[1])<br>    plt.subplots_adjust(wspace=0.4)<br>    return model</pre><pre>#Create function to easily build models and display results<br>def build_model(classifier, predictors, labels):<br>    &#39;&#39;&#39;Build classification model, returning classification report, train and test accuracy, and confusion matrix.<br>    <br>    Keyword arguments: <br>    classifier -- classification algorithm<br>    predictors -- X, features<br>    labels -- y, target<br>    &#39;&#39;&#39;<br>    <br>    #Split the data into train and test sets<br>    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.20, random_state=123)<br>    <br>    #Scale the data<br>    scaler = MinMaxScaler()<br>    X_train = scaler.fit_transform(X_train)<br>    X_test = scaler.transform(X_test)<br>    <br>    #Create variables that can be called outside function<br>    build_model.X_train = X_train<br>    build_model.X_test = X_test<br>    build_model.y_train = y_train<br>    build_model.y_test = y_test<br>    <br>    #Fit model<br>    model = classifier.fit(X_train, y_train)<br>    score = np.mean(cross_val_score(classifier, X, y, cv=5, scoring=&#39;recall&#39;))<br>    <br>    #Create predictions<br>    y_hat_train = model.predict(X_train)<br>    y_hat_test = model.predict(X_test)<br>    <br>    #Create variables that can be called outside function<br>    build_model.y_hat_train = y_hat_train<br>    build_model.y_hat_test = y_hat_test<br>    <br>    #Print classification report<br>    print(&#39;Train Classification Report\n&#39;, classification_report(y_train, y_hat_train))<br>    print(&#39;\n----------------------------------\n&#39;)<br>    print(&#39;Test Classification Report\n&#39;, classification_report(y_test, y_hat_test))<br>    print(&#39;\n----------------------------------\n&#39;)<br>    <br>    print(&#39;Train Accuracy:&#39;, round(accuracy_score(y_train, y_hat_train), 3))<br>    print(&#39;Test Accuracy:&#39;, round(accuracy_score(y_test, y_hat_test), 3))<br>    print(&#39;Cross Validation Recall&#39;, round(score, 3))<br>    print(&#39;\n----------------------------------\n&#39;)<br>    <br>    #Create a results dataframe<br>    results = pd.DataFrame([[str(model), round(accuracy_score(y_train, y_hat_train), 3), <br>                             round(accuracy_score(y_test, y_hat_test), 3), round(score, 3)]], <br>                          columns=[&#39;Model&#39;, &#39;Train_Accuracy&#39;, &#39;Test_Accuracy&#39;, &#39;Cross_Val_Recall&#39;])<br>    build_model.results = results<br>    <br>    #Plot Confusion Matrices<br>    fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(14, 8))<br>    plot_confusion_matrix(classifier, X_train, y_train,<br>                     cmap=plt.cm.Blues, ax=axes[0])<br>    fig.suptitle(&#39;Train &amp; Test Confusion Matrices&#39;, fontsize=16);<br>    <br>    plot_confusion_matrix(classifier, X_test, y_test,<br>                     cmap=plt.cm.Blues, ax=axes[1])<br>    plt.subplots_adjust(wspace=0.4)<br>    return model</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1T9F10Sef1fLBxhABXPzaw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*NQOoFGFH2tOTFkKwXRJk3Q.png" /></figure><p><strong>Interpreting Data</strong></p><p>Using features selected from the Boruta algorithm and fitting the model with the XGBoost algorithm with hyperparameter tuning, the model result had a recall score of 95.5% while maintaining approximately 50% accuracy overall for both train and test data. Ultimately, my goal was to focus on recall and predict the highest amount of arrests along with minimizing false negatives, while at the same time maintaining an accuracy above 50%. This result could potentially contribute to reducing the amount of unnecessary Terry Stops.</p><blockquote><em>This result could potentially contribute to reducing the amount of unnecessary Terry Stops.</em></blockquote><p>The final features determining our model results are below with Beat being our feature with the highest importance. The interesting fact is that the majority of cases do not result in arrests where Computer Aided Dispatch is not used and the address (Beat) associated with the Computer Aided Dispatch is not reported. This leads to further investigation of how these events are reported and why CAD is not being used.</p><ul><li>Beat (whether the address associated with the underlying Computer Aided Dispatch (CAD) event was reported or not)</li><li>Initial Call Type (whether an initial call type was reported or not)</li><li>Call Type_911 (call received by the communication center by dialing 911)</li><li>Officer YOB</li><li>Reported Year</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*5meVIZYVXC77EpaO9frkZA.png" /></figure><p>Finally, I built a function to test the model:</p><pre>def predict_arrests():<br>    &#39;&#39;&#39;Predict whether a stop resolution will result in an arrest using previously built classification model.<br>    <br>    Parameters: Input by User&#39;&#39;&#39;<br>    <br>    Beat = input(&quot;Was the address (beat) associated with the underlying Computer Aided Dispatch (CAD) event reported ? (1=yes, 0=no) &quot;)<br>    Initial_Call_Type = input(&quot;Was an initial call type reported? (1=yes, 0=no) &quot;)<br>    Call_Type_911 = input(&quot;Was the report of suspiscion a 911 call? (1=yes, 0=no) &quot;)<br>    Call_Type_Other = input(&quot;Was the report of suspiscion an alternative to a 911 call or onsite viewing? (1=yes, 0=no) &quot;)<br>    Officer_YOB = input(&quot;What year was the officer born? &quot;)<br>    Reported_Year = input(&quot;What is the reported year? &quot;)<br>    Reported_Minute = input(&quot;What is the reported minute? (1 to 59) &quot;)<br>    <br>    features = np.array([[Beat, Initial_Call_Type, Call_Type_911, Call_Type_Other, Officer_YOB, Reported_Year, <br>                        Reported_Minute]], dtype=float)<br>    <br>    result = xg_model.predict(features)<br>    if result == 1:<br>        answer = &#39;Yes&#39;<br>    else:<br>        answer = &#39;No&#39;<br>    <br>    print(&quot;\nShould officer conduct a Terry Stop? &quot;)<br>    return answer</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZIjH_R84LqJnzjt8u26V7g.png" /></figure><p>One question that arose as a result of this model was the reliability of the reporting process for Terry Stops. See the graph below again on Beat vs. Stop Resolution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*i2kmZqV0cWH0RAfmm4efWQ.png" /></figure><p>Out of 9,523 cases in which reporting was lacking in some form, there were only 234 arrests. With 97.5% of these cases resulting in no arrest, there should be additional information on why these Terry Stops were conducted. This quote is pulled directly from <a href="http://www.seattle.gov/Documents/Departments/Tech/Privacy/SPD%20Computer%20Aided%20Dispatch%20Final%20SIR.pdf">http://www.seattle.gov/Documents/Departments/Tech/Privacy/SPD%20Computer%20Aided%20Dispatch%20Final%20SIR.pdf</a>: “There are two main functions of the CAD system: to initiate and log the appropriate police response, and to document the assignment and response of the correct police resources. CAD is the real-time record-keeping system for officers’ response to calls for service, thereby documenting SPD’s actions related to each of those requests in an organized and reportable method.” The question remains, why is address information not being reported for roughly every 1 in 5 cases? Is CAD not being used?</p><p>As a result of questionable reporting, I also wanted to look at what the breakdown of subject race was with cases missing address information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*xINtkm5PuL62B-ij7p2kfw.png" /></figure><p>An interesting note is that 53% of these cases with unreported information are White subjects, 15% lower than the government census of the white population in Seattle at 68%. Additionally, 26% of these cases with unreported information are Black subjects, 19% higher than the government census of the black population in Seattle at 7%.</p><p>Another question: are there officers with repeat cases of unreported information?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*Q4PCGcyhZ4MhsDrrEN0FAg.png" /></figure><p>It’s interesting to see that there are multiple (19) officers that have over 50 cases where information was not reported as a result of a Terry Stop.</p><p>Conclusions of racial disparity would be theoretical with this data alone, so rather than providing a theoretical conclusion, I recommend that the Seattle Police Department reduce questions of racial disparity by improving reporting in these cases, whether it be requiring officers to report this information or automating processes further with Computer Aided Dispatch. Further investigation could include researching why there are so many events with unreported information.</p><p>Full details of this project are available in the GitHub repository: <a href="https://github.com/dbarth411/dsc-mod-3-project-v2-1-online-ds-sp-000">https://github.com/dbarth411/dsc-mod-3-project-v2-1-online-ds-sp-000</a>. I welcome any comments, questions, and suggestions/recommendations related to this project.</p><p><em>I’m currently looking for data analyst or related roles, so if you are hiring or know any connections who are, please feel free to check out or share </em><a href="https://davidbbartholomew.com/"><em>my portfolio website</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53583b526192" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/predicting-arrests-as-a-result-of-a-terry-stop-53583b526192">Predicting Arrests as a Result of a Terry Stop</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiple Linear Regression in Python: King County Housing Data]]></title>
            <link>https://medium.com/swlh/multiple-linear-regression-in-python-king-county-housing-data-beef1c3982a1?source=rss-3a8748091c6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/beef1c3982a1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[David Bartholomew]]></dc:creator>
            <pubDate>Sun, 27 Sep 2020 19:59:36 GMT</pubDate>
            <atom:updated>2021-05-14T17:49:14.218Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xEOInDwizj2UIkCkh0jq1Q.png" /></figure><p>This project involed an iterative approach to building a multiple linear regression model with python, scikit-learn, and statsmodels to predict sale prices for houses in King County, WA, utilizing data of homes sold in 2014 and 2015 (data provided by Flatiron School and a similar dataset is available on Kaggle). The first portion of this project is spent cleaning the data, engineering a few new features, and then building models, tweaking each model until a final model is built. Rather than using log transformations to normalize data, I decided to keep the model as interpretable as possible, using alternative techniques to normalize residuals. As a result, I narrowed down the data to predict homes under 900k, favoring predictions for middle class families. The full notebook is available here: <a href="https://github.com/dbarth411/dsc-mod-2-project-v2-1-online-ds-sp-000">https://github.com/dbarth411/dsc-mod-2-project-v2-1-online-ds-sp-000</a>.</p><p>Here is a list of the column descriptions as some column names are ambiguous:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CeHzgpE_yr8zIz8_PzaYXw.png" /><figcaption>Column Descriptions</figcaption></figure><p>Here is an info snapshot of the data:</p><pre>#Import and preview the data<br>df = pd.read_csv(&#39;kc_house_data.csv&#39;)<br>display(df.info())<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*tm98mnbO5-k-Q5qzVHE7tg.png" /><figcaption>Df.info()</figcaption></figure><p>There are 20 columns and over 21k rows of data. Several columns had missing values and certain filler values that needed to be replaced accordingly. Filling missing values for this dataset was fairly straightforward, so I won’t review what I did in this post. Instead, I’ll jump straight to engineered features.</p><h4><strong>Feature Engineering</strong></h4><p>First, I split the date sold column into two separate columns of month sold and year sold, figuring that the specific day wouldn’t have a significant impact on my model, but the month or year might have an impact. Here is the code I used:</p><pre>#Convert date column to 2 separate columns for month and year<br>date = df[&#39;date&#39;].str.split(&#39;/&#39;, expand=True)<br>df[&#39;month_sold&#39;] = date[0].astype(&#39;float64&#39;)<br>df[&#39;year_sold&#39;] = date[2].astype(&#39;float64&#39;)</pre><pre>#Drop original date column<br>df.drop(columns=[&#39;date&#39;], axis=1, inplace=True)</pre><p>Second, I converted the year built column into an age column as this made the model more interpretable. Since the latest year in the dataset was 2015, I created this column by subtracting year built from 2015.</p><pre>df[&#39;age&#39;] = 2015 - df.yr_built<br>df = df.drop(columns=[&#39;yr_built&#39;], axis=1)</pre><p>Third, I changed the year renovated column into a binary column. 1 for homes renovated in the past 10 years or built within the past 5 (most likely not needing renovations), and 0 for homes that were not renovated within 10 years.</p><pre>#Fill missing values<br>df.yr_renovated.fillna(0.0, inplace=True)</pre><pre>#Create renovated column<br>df[&#39;renovated&#39;] = df.year_sold - df.yr_renovated</pre><pre>#Replace any values less than 10 with 1, and any values over 10 with 0renovated = df.renovated.values<br>age = df.age.values<br>values = np.where(renovated &lt;= 10, 1, 0)<br>df[&#39;renovated&#39;] = np.where(age &lt;= 5, 1, values)</pre><pre>#Drop yr_renovated column<br>df.drop(columns=[&#39;yr_renovated&#39;], axis=1, inplace=True)</pre><p>Finally, a simple Seaborn scatterplot shows homes by their latitude and longitude, with price set as the hue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*_WFpoGZHBd-F7Yvwtxp8ew.png" /></figure><p>Visualizing this plot and noticing that, to a certain degree, price seems to go down as homes are further away from downtown, I created distance from downtown Seattle as another feature utilizing the geopy library. Essentially, this calculates distance in miles from specific latitude and longitude points:</p><pre>from geopy import distance</pre><pre>lat_long = df[&#39;lat&#39;].astype(str) + &#39;,&#39; + df[&#39;long&#39;].astype(str)<br>lat_long = list(map(eval, lat_long))</pre><pre>Seattle = (47.6062, -122.3321)</pre><pre>miles = []<br>for i in lat_long:<br>    miles.append(round(distance.distance(i, Seattle).miles, 1))</pre><pre>df[&#39;distance&#39;] = miles</pre><p>After engineering new features, I began the iterative process of building my model, making adjustments after each model as necessary. Below is the function used to build my regression model. This function determines feature and target variables, splits the data into training and test sets, builds a model in sklearn, calculates training and test r-squared and coefficients, then builds the same model with statsmodels, printing the model summary:</p><pre>#Function for linear regression<br>def linear_model(dataframe):<br>    &#39;&#39;&#39;Build linear regression model, return model and print model summary from statsmodels.&#39;&#39;&#39;</pre><pre>    #Create feature and target columns<br>    X = dataframe.drop(columns=[&#39;price&#39;], axis=1)<br>    y = dataframe.price<br>    <br>    #Split data into training and test sets<br>    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.20, random_state=123)<br>    <br>    #Fit the model<br>    linreg = LinearRegression()<br>    model = linreg.fit(X_train, y_train)<br>    model<br>    <br>    #View model accuracy<br>    train_score = model.score(X_train, y_train)<br>    test_score = model.score(X_test, y_test)</pre><pre>print(&#39;Training Score:&#39;, round(train_score, 2))<br>    print(&#39;Test Score:&#39;, round(test_score, 2))<br>    print(&#39;Coefficients:&#39;, model.coef_)<br>    <br>    #View model summary in statsmodels<br>    X_train = sm.add_constant(X_train)<br>    smmodel = sm.OLS(y_train, X_train).fit()<br>    print(smmodel.summary())<br>    return smmodel</pre><p><strong>Model 1: Using All Features</strong></p><p>My first model had an adjusted r-squared of .736, but residuals were not normal, violating the one of the assumptions for linear regression: normality. Although a visualization in and of itself is subjective, a quantile-quantile plot gave me a clear indication that the distribution of residuals was not normal.</p><pre>plt.figure(figsize=(12, 8))<br>fig = sm.graphics.qqplot(model.resid, dist=stats.norm, line=&#39;45&#39;, fit=True)<br>plt.title(&#39;QQ Plot&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*jI5iiq0nOJ3eTB3oTxOb7g.png" /></figure><p><strong>Model 2: Normalizing the Dependent Variable</strong></p><p>Rather than log transforming the dependent variable, I wanted to focus on keeping my model as interpretable as possible. As an alternative, I reduced price under 900k to help normalize residuals. Consequently, reducing our dependent variable brought down our r-squared to .723, but our residuals are much closer to a normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*gFxYLgRoEDKzqg-gvQ3vsg.png" /><figcaption>Prior to reducing data. Heavy tail with extreme outliers.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*LqYX0qDRBZuQ15xobKRzWw.png" /><figcaption>After reducing data to under 900k. Not a perfect normal distribution but much better.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*C4odau6vYOlrJNkv3Uxa8Q.png" /><figcaption>QQ-Plot after reducing price under 900k.</figcaption></figure><p>There are still several insignificant p-values above 0.05, but prior to dealing with those I dealt with potential multicollinearity first.</p><p><strong>Model 3: Dealing with Multicollinearity</strong></p><p>Multicollinearity occurs when independent variables have a strong correlation, or in other words, one independent/predictor variable can be linearly predicted by another predictor variable. The main problem with multicollinearity is that it undermines statistical significance of our independent/predictor variables.</p><p>Initially, I inspected potential mutlicollinearity with a heatmap to see how the independent variables might be correlated:</p><pre>#View heatmap to get an idea of multicollinearity<br>X = df.drop(columns=[&#39;price&#39;], axis=1)</pre><pre>plt.figure(figsize=(14, 10))<br>sns.heatmap(X.corr(), center=0)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*4gViCuV2TQiH1TC210kluA.png" /></figure><p>There is definitely multicollinearity among independent variables. In order to determine which variables to drop as a result of multicollinearity, I used the variance inflation factor (VIF) as my metric. The variance inflation factor measures the amount of multicollinearity among independent variables. I created a dictionary of features along with their VIF. Note that a constant/intercept must be added to calculate the VIF. This can easily be done using statsmodels add_constant method.</p><pre>from statsmodels.stats.outliers_influence import variance_inflation_factor</pre><pre>#Create dictionary of features and their variance inflation factor<br>X = sm.add_constant(X)<br>vif = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]<br>vif_dict = dict(zip(X.columns, vif))<br>vif_dict</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*zxLvjhJcxej2v7f_3J3Mow.png" /><figcaption>VIF Dictionary</figcaption></figure><p>Using a VIF cutoff of 5, I removed two features.</p><pre>#Create a list of columns to drop with a vif cutoff of 5<br>new_dict = {}<br>for (key, value) in vif_dict.items():<br>    if value &gt;= 5:<br>        new_dict[key] = value</pre><pre>columns_to_drop = list(new_dict.keys())<br>columns_to_drop = columns_to_drop[1:]<br>columns_to_drop</pre><pre>Out: [&#39;sqft_living&#39;, &#39;sqft_above&#39;, &#39;sqft_basement&#39;]</pre><p>After removing sqft_above and sqft_basement, the VIF for all features was under 5 and the multicollinearity reduced. I rebuilt a model with the new dataframe. The adjusted R squared stayed the same at .723, but the month_sold column had a p-value of 0.38 and needed to be removed.</p><p><strong>Model 4: Removing Insignificant Features</strong></p><p>After removing month_sold, the adjusted r-squared stayed at .723. The next model deals with refining features by removing additional outliers.</p><p><strong>Model 5: Refining Features</strong></p><p>Looking at distributions for all features in the data was my first step.</p><pre>#View distribution plots for all columns<br>for col in df.columns:<br>    plt.subplots(1, 1)<br>    sns.distplot(df[col])</pre><p>After viewing these plots, I arbitrarily chose to reduce features based on present outliers. I ended up dropping a few more features for this model, but won’t go into detail of why in this post. Changes shown below:</p><pre>df = df[df[&#39;bedrooms&#39;] &lt;= 11]<br>df = df[df[&#39;sqft_lot&#39;] &lt;= 15000]<br>df = df[df[&#39;sqft_living&#39;] &lt;= 5000]</pre><pre>df = df.drop(columns=[&#39;zipcode&#39;], axis=1)<br>df = df.drop(columns=[&#39;floors&#39;], axis=1)</pre><p>After removing outliers and removing certain features, my adjusted r-squared is now at .721. There are most certainly interactions among features, so I created interaction terms in our next model.</p><p><strong>Model 6: Dealing with Interactions</strong></p><p>Interactions occur when an independent variable has a different effect on the outcome when depending on the values of another independent variable. Using combinations, I created a list of top interactions, and created two interaction terms as a result of this list:</p><pre>linreg = LinearRegression()</pre><pre>#Split features and target<br>X = df.drop(columns=[&#39;price&#39;], axis=1)<br>y = df.price</pre><pre>#Utilize cross validation to determine baseline score<br>crossvalidation = KFold(n_splits=10, shuffle=True, random_state=1)<br>baseline = np.mean(cross_val_score(linreg, X, y, scoring=&#39;r2&#39;, cv=crossvalidation))</pre><pre>from itertools import combinations</pre><pre>interactions = []</pre><pre>feat_combinations = combinations(X.columns, 2)</pre><pre>data = X.copy()<br>for i, (a, b) in enumerate(feat_combinations):<br>    data[&#39;interaction&#39;] = data[a] * data[b]<br>    score = np.mean(cross_val_score(linreg, data, y, scoring=&#39;r2&#39;, cv=crossvalidation))<br>    if score &gt; baseline:<br>        interactions.append((a, b, round(score,3)))<br>    <br>    if i % 50 == 0:<br>        print(i)<br>            <br>print(&#39;Top 5 interactions: %s&#39; %sorted(interactions, key=lambda inter: inter[2], reverse=True)[:10])</pre><pre><br>Out:</pre><pre>Top 5 interactions: [(&#39;lat&#39;, &#39;distance&#39;, 0.749), (&#39;grade&#39;, &#39;distance&#39;, 0.728), (&#39;sqft_living&#39;, &#39;distance&#39;, 0.726), (&#39;sqft_living15&#39;, &#39;distance&#39;, 0.726), (&#39;sqft_living&#39;, &#39;lat&#39;, 0.725), (&#39;grade&#39;, &#39;lat&#39;, 0.725), (&#39;lat&#39;, &#39;sqft_lot15&#39;, 0.724), (&#39;sqft_lot&#39;, &#39;lat&#39;, 0.723), (&#39;lat&#39;, &#39;sqft_living15&#39;, 0.723), (&#39;long&#39;, &#39;distance&#39;, 0.722)]</pre><p>I rebuilt a model with two interaction terms. These are created by simply multiplying two interacting, independent variables:</p><pre>df[‘lat_distance’] = df[‘lat’] * df[‘distance’]<br>df[‘sqft_living15_distance’] = df[‘sqft_living15’] * df[‘distance’]</pre><p>My new model had an adjusted r-squared of .757. Along with sqft_lot15 being insignificant in this model result, another issue was the bedrooms had a positive correlation to price but a negative coefficient. Again, my goal was to make my model as interpretable as possible, so I decided to drop this feature.</p><p><strong>Model 7: Final Model</strong></p><p>After dropping bedrooms and sqft_lot15, the final model had an adjusted r-squared of .756, and all p-values were significant. Below is the model summary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*jSWCzG0W4SmEUexCAwgHZQ.png" /><figcaption>Final Model</figcaption></figure><p><strong>Model Summary</strong></p><p>Multiple regression analysis was used to test if certain variables significantly predicted the sale price of homes in King County, Washington. The results of the regression indicated that 14 predictors and 2 interaction terms explained 75.6% of the variance (R2= 0.756, F=2622, p&lt; 0.01). All of the independent variables used in the model were significant predictors of sale price with p-values less than 0.05.</p><p><strong>Interpreting Coefficients</strong></p><p>Printing the final regression formula:</p><pre>print(&quot;Final Regression Formula\n&quot;)<br>print(model.intercept_, &#39;+&#39;)<br>print(&#39;sum(&#39;)<br>for i in range(len(model_coefficients)):<br>    print(model_coefficients.coefficients[i], &#39;*&#39;, model_coefficients.index[i])<br>print(&#39;)&#39;)</pre><pre>Out:<br>Final Regression Formula<br><br>-30602542.83254475 +<br>sum(<br>8875.896126406791 * bathrooms<br>76.48922676734944 * sqft_living<br>-1.9165517689290728 * sqft_lot<br>273549.5343291163 * waterfront<br>21735.09058989604 * view<br>21941.740311421723 * condition<br>59042.33314211221 * grade<br>890730.8205766763 * lat<br>414358.54325871647 * long<br>103.63861035136415 * sqft_living15<br>19158.636202298992 * year_sold<br>947.3916140076603 * age<br>43401.868300294445 * renovated<br>2087170.6107680988 * distance<br>-44069.613195667 * lat_distance<br>-3.8970828618299813 * sqft_living15_distance<br>)</pre><p>Looking at 3 coefficients and predictors, specifically, we can conclude from the final model that:</p><ul><li>Homes that are renovated in the last 10 years or built within the last 5 years increase the sale price of a home by $43,401.87.</li><li>A one unit increase in square footage of internal living space increases the sale price by $76.49. Increasing the square footage by 1k increases the sale price by $76,490.</li><li>A one unit increase in building grade increases the sale price by $59,042.33.</li></ul><p><strong>Conclusion</strong></p><p>This was my first multiple regression model, so please feel free to offer suggestions on any improvements that can be made. For further analysis, other models can potentially be used to improve accuracy of results, such as a Random Forest regression model. Additionally, one could build a second model to predict prices of homes over 900k. If anything, I hope that this was a clear and insightful method of approach for this project.</p><p>I’m currently looking for data analyst or related roles, so if you are hiring or know any connections who are, please feel free to check out or share <a href="https://davidbbartholomew.com/">my portfolio website</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=beef1c3982a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/multiple-linear-regression-in-python-king-county-housing-data-beef1c3982a1">Multiple Linear Regression in Python: King County Housing Data</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploratory Data Analysis: A Beginner Data Science Project]]></title>
            <link>https://dbarth411.medium.com/exploratory-data-analysis-a-beginner-data-science-project-3f2b3afa1674?source=rss-3a8748091c6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f2b3afa1674</guid>
            <dc:creator><![CDATA[David Bartholomew]]></dc:creator>
            <pubDate>Wed, 26 Aug 2020 19:34:50 GMT</pubDate>
            <atom:updated>2021-05-14T17:52:33.782Z</atom:updated>
            <content:encoded><![CDATA[<h3>Movie Industry Analysis: A Beginner Data Science Project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZxUfn1ln6K0WvZRBZ-fsrQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jakehills?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jake Hills</a> on <a href="https://unsplash.com/s/photos/movie?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This post covers some of the steps involved with basic exploratory data analysis in Python, primarily utilizing the Pandas, Matplotlib, and Seaborn libraries. We won’t be diving into machine learning, modeling deep neural networks or utilizing gradient descent to minimize the cost function for a logistic regression model, primarily because this is my first data science project, so deep neural networks are slightly out of the question (for now)! This post is for true beginners.</p><p>If there’s anything that I would want a beginner like me to know when starting out their data science journey, it’s that reading books, articles, blogs, and watching video tutorials are all great (and necessary) things to do to expand your knowledge, but completing data science projects is the #1 method to gain applied knowledge and instill concepts that you have learned. I’m sharing my experience with hopes that other aspiring data scientists can not only relate to the pains and frustrations, but also the overwhelming feeling of success after completing a project, no matter how elementary you think it might be. Personally, I had to knock down a ginormous wall of self-doubt and completing my first project was key to doing that (not saying all self-doubt is completely gone, but I’ve learned not to be so hard on myself).</p><h3><strong>The Project</strong></h3><p>This project is the first of five as part of Flatiron School’s Online Data Science program. We were given a fictional scenario: Microsoft is looking to enter the movie industry, and we need to provide recommendations along with meaningful visualizations to present to non-technical stakeholders at Microsoft as a foundation for steps to success in the movie biz. I won’t be covering all the details of the project in this post, and the project itself is definitely not entirely comprehensive, but we’ll look at some highlights that I think may be insightful. The overall idea is to practice working with real-world data and presenting clear analytics as a result.</p><h3><strong>The Data</strong></h3><p>The data we were given were pulled from several sources: Box Office Mojo (<a href="https://www.boxofficemojo.com/">https://www.boxofficemojo.com</a>), IMDB (<a href="https://www.imdb.com/interfaces/">https://www.imdb.com/interfaces/</a>), Rotten Tomatoes (<a href="https://www.rottentomatoes.com/">https://www.rottentomatoes.com</a>), and The Movie Database (<a href="https://www.themoviedb.org/?language=en-US">https://www.themoviedb.org/?language=en-US</a>). There were 11 files/tables overall that could be utilized (additional data mining/web scraping/API calls were allowed, but I decided for multiple reasons not to go that route). You may notice the data is slightly dated, so please don’t accept my recommendations as hard facts. They are solely based on analysis from this data.</p><h3><strong>The Process</strong></h3><p><strong>Importing the necessary libraries</strong></p><p>Along with Pandas, Matplotlib, and Seaborn, I also utilized Numpy and SciPy but won’t be focusing on those libraries here.</p><pre><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np</strong><br><strong>from</strong> <strong>scipy.stats</strong> <strong>import</strong> pearsonr<br><strong>import</strong> <strong>seaborn</strong> <strong>as</strong> <strong>sns</strong><br><strong>import</strong> <strong>matplotlib.pyplot</strong> <strong>as</strong> <strong>plt</strong><br>%matplotlib inline</pre><p><strong>Importing and previewing the data</strong></p><p>Pandas allows you to manipulate data easily in a two-dimensional data structure in the form of rows and columns. Since these particular files were zipped CSV files, you can either unzip them manually and then import them into a Pandas DataFrame, or import them with the compression parameter as shown below.</p><pre>movie_gross_df = pd.read_csv(&#39;zippedData/bom.movie_gross.csv.gz&#39;, compression=&#39;gzip&#39;)</pre><pre>movie_basics_df = pd.read_csv(&#39;zippedData/imdb.name.basics.csv.gz&#39;, compression=&#39;gzip&#39;)</pre><pre>movie_title_akas_df = pd.read_csv(&#39;zippedData/imdb.title.akas.csv.gz&#39;, compression=&#39;gzip&#39;)</pre><pre>movie_title_basics_df = pd.read_csv(&#39;zippedData/imdb.title.basics.csv.gz&#39;, compression=&#39;gzip&#39;)</pre><pre>movie_title_crew_df = pd.read_csv(&#39;zippedData/imdb.title.crew.csv.gz&#39;, compression=&#39;gzip&#39;)</pre><pre>movie_title_principals_df = pd.read_csv(&#39;zippedData/imdb.title.principals.csv.gz&#39;, compression=&#39;gzip&#39;)</pre><pre>movie_title_ratings_df = pd.read_csv(&#39;zippedData/imdb.title.ratings.csv.gz&#39;, compression=&#39;gzip&#39;)</pre><pre>movie_info_df = pd.read_csv(&#39;zippedData/rt.movie_info.tsv.gz&#39;, compression=&#39;gzip&#39;, sep=&#39;<strong>\t</strong>&#39;)</pre><pre>movie_reviews_df = pd.read_csv(&#39;zippedData/rt.reviews.tsv.gz&#39;, compression=&#39;gzip&#39;, sep=&#39;<strong>\t</strong>&#39;, encoding=&#39;cp1252&#39;)</pre><pre>tmdb_movies_df = pd.read_csv(&#39;zippedData/tmdb.movies.csv.gz&#39;, compression=&#39;gzip&#39;)</pre><pre>movie_budgets_df = pd.read_csv(&#39;zippedData/tn.movie_budgets.csv.gz&#39;, compression=&#39;gzip&#39;)</pre><p>After the data was imported into Pandas DataFrames, I created a list of all data frames and used a for loop to preview the first five rows of data and the data info which gives an idea of the number of rows with values, column names, and data types for each data frame. You can also use the Pandas describe method to get a statistical summary of the data. These methods will help you get an initial understanding of which features of the data you want to engineer and potentially draw conclusions from.</p><pre>all_dfs = [movie_gross_df, movie_basics_df, movie_title_akas_df, movie_title_basics_df,<br>             movie_title_crew_df, movie_title_principals_df, movie_title_ratings_df, movie_info_df,<br>             movie_reviews_df, tmdb_movies_df, movie_budgets_df]</pre><pre>df_names = [&#39;movie_gross&#39;, &#39;movie_basics&#39;, &#39;movie_title_akas&#39;, &#39;movie_title_basics&#39;,<br>           &#39;movie_title_crew&#39;, &#39;movie_title_principals&#39;, &#39;movie_title_ratings&#39;, &#39;movie_info&#39;,<br>           &#39;movie_reviews&#39;, &#39;tmdb_movies&#39;, &#39;movie_budgets&#39;]</pre><pre><strong>for</strong> i <strong>in</strong> range(len(all_dfs)):<br>    print(df_names[i], &#39;<strong>\n</strong>&#39;)<br>    display(all_dfs[i].info())<br>    display(all_dfs[i].head())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R6yIQbFo1Nebmkcu7DFfwg.png" /><figcaption>movie_gross_df.info(), movie_gross_df.head()</figcaption></figure><p><strong>Cleaning the data</strong></p><p>Cleaning the data took the majority of my time with this project. I won’t go through each detail of how I cleaned the data, but the majority of the data frames had some form of missing values in one or more columns, so determining how I would handle those was different for each column. There were a few columns that I dropped entirely since the majority of the data was missing, and for the purpose of this project, they were basically useless (shown below):</p><pre>movie_basics_df.drop([&#39;birth_year&#39;, &#39;death_year&#39;], axis=1, inplace=<strong>True</strong>)</pre><pre>movie_title_akas_df.drop([&#39;language&#39;, &#39;attributes&#39;, &#39;types&#39;], axis=1, inplace=<strong>True</strong>)</pre><pre>movie_title_principals_df.drop([&#39;job&#39;, &#39;characters&#39;], axis=1, inplace=<strong>True</strong>)</pre><p>Another technique was imputing missing values with the median in order to avoid affecting the distribution of the data:</p><pre>movie_gross_df[&#39;domestic_gross&#39;].fillna(movie_gross_df.domestic_gross.median(), inplace=<strong>True</strong>)</pre><pre>movie_gross_df[&#39;foreign_gross&#39;].fillna(movie_gross_df.domestic_gross.median(), inplace=<strong>True</strong>)</pre><p>Along with filling missing values, I also needed to ensure data types were correct by converting object data types to either integers or floats as necessary, converting dates to the proper date time format, and also splitting lists within a single column into several columns. Here’s an example of converting a column from an object data type to a float (had to remove comma first before I could convert the data type):</p><pre><em>#Remove extraneous comma</em> movie_gross_df[&#39;foreign_gross&#39;].replace(&#39;,&#39;, &#39;&#39;, regex=<strong>True</strong>, inplace=<strong>True</strong>)</pre><pre><em>#Change foreign_gross to float64</em><br>movie_gross_df[&#39;foreign_gross&#39;] = movie_gross_df[&#39;foreign_gross&#39;].astype(&#39;float64&#39;)</pre><p><strong>Merging dataframes</strong></p><p>Using the Pandas merge method, I combined several data frames based on either similar column values or indices in order to analyze a combination of different features. In most cases, I used an inner join to ensure values matched and I didn’t have duplicates. This method is similar to joining tables in SQL:</p><pre>genres_df = movie_budgets_df.merge(movie_title_basics_df, left_on=&#39;movie&#39;, right_on=&#39;original_title&#39;, how=&#39;inner&#39;)</pre><pre>crew_df = genres_df.merge(movie_title_crew_df, left_on=&#39;tconst&#39;, right_on=&#39;tconst&#39;, how=&#39;inner&#39;)</pre><pre>combined_df = crew_df.merge(movie_basics_df, left_on=&#39;directors&#39;, right_on=&#39;nconst&#39;, how=&#39;inner&#39;)</pre><p><strong>Visualizing the data</strong></p><p>Once you’ve determined questions that you want to answer with the data, making the data speak with visualizations is incredibly important. Seaborn is built on top of Matplotlib and is primarily used to make your visualizations look “prettier” than a standard pyplot with Matplotlib. I used several visualizations throughout my project to help answer questions like “When hiring a director, how much experience do they need?” The visualization below is a box plot from Seaborn showing the amount of movies directed vs. net profit:</p><pre><em># Plot net profit vs. count of movies directed </em><br>plt.figure(figsize=(12,8))<br>sns.boxplot(top_directors_df.movie, top_directors_df.net_profit)<br>plt.title(&#39;Net Profit vs. Movies Directed&#39;, fontsize=16)<br>plt.xlabel(&#39;Total Movies Directed&#39;)<br>plt.ylabel(&#39;Net Profit (in billions)&#39;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*HMJ06jY9yjt--odZYmKzUg.png" /></figure><p>It seems that directors who have directed 4 or more movies have a positive net profit. Knowing this, let’s use that as a filter and see the top 25 directors by net profit with a bar plot:</p><pre><em>#Plot bar graph</em><br>plt.figure(figsize=(12, 8))<br>sns.barplot(four_or_more_movies.key_0, four_or_more_movies.average_profit)<br>plt.xticks(rotation=35, horizontalalignment=&#39;right&#39;)<br>plt.xlabel(<strong>None</strong>)<br>plt.ylabel(&#39;Average Profit (in 100 millions)&#39;)<br>plt.title(&#39;Top 25 Directors with Four or More Movies&#39;, fontsize=16)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*YvAi6b-ERvhsueI-QQjpfw.png" /></figure><p>Looks like Joss Whedon, Christopher Nolan, Michael Bay, and Jon Favreau top the list with over 500 million in net profit! (Keep in mind the data is slightly dated.)</p><p><strong>Conclusion</strong></p><p>Although I definitely didn’t touch on every aspect of this project, I hope this helps you get an initial understanding of some basic exploratory data analysis of the movie industry in Python using Pandas, Matplotlib and Seaborn. For more details on this project, feel free to check it out here: <a href="https://github.com/dbarth411/dsc-mod-1-project-v2-1-online-ds-sp-000">https://github.com/dbarth411/dsc-mod-1-project-v2-1-online-ds-sp-000</a>.</p><p>As an aspiring data scientist, I happily welcome any comments, questions, or recommendations!</p><p><em>I’m currently looking for data analyst or related roles, so if you are hiring or know any connections who are, please feel free to check out or share </em><a href="https://davidbbartholomew.com/"><em>my portfolio website</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f2b3afa1674" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Path to Data Science]]></title>
            <link>https://dbarth411.medium.com/my-path-to-data-science-1babcacb716d?source=rss-3a8748091c6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1babcacb716d</guid>
            <category><![CDATA[education]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[David Bartholomew]]></dc:creator>
            <pubDate>Wed, 26 Aug 2020 17:01:20 GMT</pubDate>
            <atom:updated>2021-05-12T20:57:11.445Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mpyrgqwMjfclV2oN1U2VIA.jpeg" /></figure><p>I grew up in a very religious home, including going to church every Sunday morning, Sunday night and Wednesday night. I went to a small Christian school K-12th grades, which eventually led me to go to one of the few Christian colleges that was highly encouraged in that environment. Truthfully, I had no idea what I wanted to do with my life, but I thought appeasing my teachers and my peers was the right thing to do at the time.</p><p>Despite realizing midway through my junior year of college that this was not the path for me, I ended up sticking it out and graduated with a B.A. in Biblical Studies. As you can imagine, the amount of job offers was incredibly overwhelming (i.e. zero). Like many graduates, I could only ask, “What the hell do I do now?”</p><p>I had a few odd jobs here and there. I even tried to join the Navy, but I broke my thumb, had to have surgery, and was told it would be another year till I could re-enlist. Putting my life on hold wasn’t super appealing, so I decided to move out to Colorado, somehow stumbling into the hospitality industry as a reservationist/revenue analyst. Thankfully, I quickly grew into a management position, and a few years down the road became and area director of revenue and an assistant general manager with both independent and branded hotels. As I grew into this role and gained more experience in the hotel industry with both revenue and operations management, I began to understand my strengths (and weaknesses) in the workplace along with what I truly enjoyed.</p><p>Whether it was making pricing decisions, determining sales and marketing opportunities, establishing budgets, or project managing two property management system cutovers, I was analyzing data to make business decisions on a daily basis. I loved that aspect of my job, and knowing that was my passion, I wanted to learn more about how I could improve those skills. I also wanted to pursue education that expanded across multiple industries, potentially opening a world of opportunity to grow my career.</p><p>Eventually, data science came up in a conversation with family, and to be candid, I had a very limited knowledge of what data science was at the time. The subject immediately caught my interest, so after some research, I found Flatiron School’s self-paced online program. I decided to leave my most recent position and pursue school full time. Being just a few months in, I can say it was one of the best decisions I’ve ever made. I am by no means a data scientist yet, but I will be, and the idea of learning something new every day excites me.</p><p>I write this amidst a global pandemic in which there is a plethora of uncertainties. It’s easy to worry about pretty much everything, including the unbelievable lack of toilet paper everywhere, so I’m beyond thankful that learning data science is my diversion right now. It’s possible you need a distraction from worrying like I do. I wouldn’t necessarily encourage everyone to study data science, but I hope this inspires you to take the time to do something you love and to learn something new while we’re social distancing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1babcacb716d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>