<?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 Joel Mott on Medium]]></title>
        <description><![CDATA[Stories by Joel Mott on Medium]]></description>
        <link>https://medium.com/@joel.mott8?source=rss-a0581c989279------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WGCq3ZiJ1vSZOjbYQh85hg.jpeg</url>
            <title>Stories by Joel Mott on Medium</title>
            <link>https://medium.com/@joel.mott8?source=rss-a0581c989279------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 09:42:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joel.mott8/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[Making Messy Data Clear for Anyone]]></title>
            <link>https://medium.com/@joel.mott8/making-messy-data-clear-for-anyone-33fb8ccf1c61?source=rss-a0581c989279------2</link>
            <guid isPermaLink="false">https://medium.com/p/33fb8ccf1c61</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Joel Mott]]></dc:creator>
            <pubDate>Thu, 30 May 2024 22:14:49 GMT</pubDate>
            <atom:updated>2024-05-30T22:14:49.309Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zuiK025DApeVUnEC" /><figcaption>Photo by <a href="https://unsplash.com/@dnevozhai?utm_source=medium&amp;utm_medium=referral">Denys Nevozhai</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’ve learned a lot of details about cleaning &amp; modeling data during my Data Science course at Flatiron School, but a big piece of the big picture came into place while working on my most recent project.</p><p>While some of my past projects involved relatively clean data, this project examined a much larger &amp; more complex dataset on traffic crashes from the City of Chicago (raw dataset <a href="https://data.cityofchicago.org/Transportation/Traffic-Crashes-Crashes/85ca-t3if/about_data">here</a>, my downloaded snapshot in May 2024 used in this project <a href="https://www.kaggle.com/datasets/joelmott/chicago-traffic-crashes-may-2024">here</a>).</p><p>Dating back to 2015, it features 146 columns on over 836,000 accidents (as of May 2024). Combined with every record on the people and vehicles involved in each crash, it includes over 3.8 million records.</p><p>146 columns is a lot to go through on your own, but it turned out to be a fun challenge, even when it involved overcoming obstacles along the way. What made this project exciting was the opportunity to apply my background skills in education: the final model had to be an easily-interpretable, “white-box” one. <strong>I’d need to convey my modeling process and results in an intrinsically interpretable way.</strong></p><p>In other words, despite the complex dataset, my final predictive model had to be easy for the non-technical stakeholder to understand. This doesn’t just apply to the results, but also the modeling <em>process</em> itself. This limits the kind of final model I use, but I was allowed to implement some more complex “black-box” models along the way (specifically, when reducing the 146 columns down to 22, but not for the final model).</p><p><strong>Making sense of this data myself was challenging and fun, but finding a way to explain my findings so clearly was especially fulfilling.</strong></p><p>One other challenge was attempting to set this project apart from others. Many have chosen the target as fatal accidents or have done a multi-class problem with fatal accidents, those resulting in just injuries, and no-injury crashes.</p><p><strong>I took a broader look and included all accidents</strong>, making the target a feature-engineered condensing of the 40 classes from the ‘primary contributory causes’ column down to two classes: <strong>whether an accident was more or less avoidable</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G9jBMpwDiUSoRlZzxupwnw.jpeg" /></figure><p>While this resulted in some target class imbalance issues I would later have to over/under-sample for, it would also ultimately result in findings that may help reduce <em>all </em>kinds of traffic accidents.</p><p>Below, I briefly discuss how I “tamed” these columns down from 146 to 22, tried and failed to fit a (useful) Logit model to this data, and ultimately made sense of it for myself and the non-technical stakeholder with a simple decision tree model.</p><p><strong>Reducing columns</strong> took place in three main stages:</p><ol><li>First, I simply examined each column’s data in Pandas and determined which columns pertain to whether an accident was avoidable. I did this in a separate, data engineering notebook <a href="https://github.com/joeldmott/chicago_auto_accidents_project/blob/main/data_engineering_notebook.ipynb">found here</a>. For example, columns describing the aftermath weren’t as relevant as those that related to the crash’s cause. This got the columns down to just 16, but that’s <em>before </em>one-hot encoding (82 columns would have resulted afterwards).</li><li>I used <strong>Principal Component Analysis (PCA)</strong> and a <strong>Random Forest</strong> model to see which of those 82 numeric &amp; categorical columns could be dropped. While these are two very different models, they mostly agreed on which features <em>weren’t</em> helpful. This helped trim another 30 columns, but the resulting 52 is still a lot if model interpretability is our top priority. This is how PCA and the random forest’s feature importances compared:</li></ol><pre>fig, ax = plt.subplots(figsize=(8,20))<br>ax.barh(loadings_sums_scaled.index, loadings_sums_scaled.values, label=&#39;PCA features&#39;)<br>ax.barh(fi_series.index, fi_series.values, label=&#39;random forest features&#39;)<br>plt.legend();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tksWkZWCf1_Uj1PMt1mF2A.png" /></figure><p>I eliminated columns with mutually low significance/importance (everything below ‘ROADWAY_SURFACE_COND_ICE’ with a few exceptions).</p><p>3. My StatsModels Logistic Regression model performed poorly when it came to making predictions, but it <em>could </em>tell me which remaining models had no correlation with whether an accident was avoidable. I dropped those and wound up the remaining 22.</p><p><strong>Fitting white-box models to complicated data</strong> was challenging from the usual priority of strong predictive performance. The StatsModels Logit performance was dismal — I couldn’t look to it to see which features were important; it only helped trim some that <em>weren’t.</em></p><p>This poor predictive power likely stemmed from the fact that there was no real <em>linear </em>relationship between these 22 columns and the condensed target feature. Even after accounting for things like class imbalance and hyperparameter-tuning, the model was unusable.</p><p>However, logistic regression isn’t the only white-box model in town; a decision tree’s workflow through entropy-based decisions regarding which features help make strong predictions was a great fit for this complicated dataset.</p><p>The true baseline decision tree model included the features I had dropped from the StatsModel Logit features, but when I ran another version without those statistically insignificant features, the model performed the same. Subsequently, I was able to still drop them to help simplify the model.</p><p>While the results after optimizing were more in the “acceptable” range than they were “great,” it was worth it to have a list of feature importances that showed which factors contributed most to more avoidable accidents:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*UYYz6MNh1R76J80XVzPllA.jpeg" /><figcaption>confusion matrix &amp; classification report on final model: fine, not great</figcaption></figure><pre>#gathering its feature importances<br>final_feature_importances = dt_oversample.feature_importances_<br>ffi_rounded = np.around(final_feature_importances, decimals=3)<br>ffi_series = pd.Series(ffi_rounded, index=X_train_nonstandardized_and_trimmed_over.columns).sort_values(key=abs)<br>#visualizing them<br>fig, ax = plt.subplots(figsize=(6,6))<br>ax.barh(ffi_series.index, ffi_series.values)<br>plt.savefig(&#39;final model feature importances&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*oTFIQQzYN9CizClObGKR7w.jpeg" /><figcaption>helpful visualization on which features stood out as important</figcaption></figure><p>This diagram of feature importances shows explained data percentages (they all add up to 1.0) and clearly delineates three outstanding features: location (taken as latitude &amp; longitude), driver age, and crash hour-of-day.</p><p>All well and good, but I still hadn’t explained <em>how </em>these features related and I also hadn’t really discussed the decision tree’s modeling process. <strong>Making a decision tree modelling process interpretable to a non-technical stakeholder may involve some careful planning, but it’s a lot easier than explaining something like a neural network. </strong>In order to instill more trust into the final model, I made an explanatory diagram that, while simplified from the actual model, still showed the same general logic and feature priorities at work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fwfd8o8ICL-K1_17FsQICw.png" /></figure><p>This illustration may have been a simplification of the actual, final decision tree model. However, it still related to the data at hand, showing a few of the final 22 columns being input to our white-box decision tree.</p><p>It figured out which columns show the most unbalanced distribution of more &amp; less avoidable accidents — aka the columns which <em>first </em>help guide us to predicting whether a given accident was avoidable. We see our top three columns inside the model box on the left.</p><p>After determining “location” as the root node, the decision tree worked through these columns to find which ordering results in the best predictions. Not all paths are the same depending on how they diverge from the root node onward.</p><p>Showing the entire tree diagram would <em>not </em>be intrinsically interpretable, but this simplified version with just a few columns reflects a lot of the same logic and overall feature prioritization that the massive tree diagram works through.</p><p>With this brief decision tree workflow explained, I was able to discuss how location, age, and time-of-day related to our project.</p><p>At first, I was a little disappointed to see just how <em>unsurprising </em>these findings were. In the map below, thin grey lines are the main/busier streets of Chicago while the spaces between are mostly filled in with less busy ones.</p><p>This mapping procedure with GeoPandas below was a learning process for me, but I figured it out largely help to <a href="https://towardsdatascience.com/geopandas-101-plot-any-data-with-a-latitude-and-longitude-on-a-map-98e01944b972">this post</a> from Towards Data Science by Ryan Steward.</p><pre>#importing GeoPandas and Shapely for help mapping the data<br>import geopandas as gpd<br>from shapely.geometry import Point, Polygon<br><br>#establishing the major street map<br>street_map = gpd.read_file(&#39;/content/chicago_auto_accidents_project/street_map_files/Major_Streets.shp&#39;)<br>#street_map.crs &lt;---the map&#39;s CRS code needs to be changed to 4326, otherwise the projection is way off<br>street_map = street_map.to_crs(4326)<br><br>#bringing in the coordinate reference system (CRS) for Geopandas as well<br>crs = {&#39;init&#39;:&#39;EPSG:4326&#39;}<br>#creating the Points from our latitude &amp; longitude columns<br>geometry = [Point(xy) for xy in zip(X_train_nonstandardized_and_trimmed_over[&#39;LONGITUDE&#39;],<br>                                    X_train_nonstandardized_and_trimmed_over[&#39;LATITUDE&#39;])]<br>#establishing the geo DataFrame<br>geo_df = gpd.GeoDataFrame(X_train_nonstandardized_and_trimmed_over,<br>                          crs=crs,<br>                          geometry=geometry)<br>#trimming it down to just the relevant columns<br>geo_df = geo_df[[&#39;CRASH_HOUR&#39;, &#39;AGE&#39;, &#39;geometry&#39;]]<br>geo_df = pd.concat([geo_df, y_train_over], axis=1)<br><br>#layering the street map with our Geopandas points (lat &amp; long)<br>fig, ax = plt.subplots(figsize=(15,15))<br>#just the street map grid<br>street_map.plot(ax=ax, alpha=0.4, color=&#39;grey&#39;)<br>#plotting the data&#39;s geographical points<br>geo_df[geo_df[&#39;TARGET&#39;] == 0].plot(ax=ax,<br>                                   alpha=0.01,<br>                                   markersize=7,<br>                                   color=&#39;blue&#39;,<br>                                   marker=&#39;o&#39;,<br>                                   label=&#39;less avoidable crash&#39;)<br>geo_df[geo_df[&#39;TARGET&#39;] == 1].plot(ax=ax,<br>                                   alpha=0.01,<br>                                   markersize=7,<br>                                   color=&#39;red&#39;,<br>                                   marker=&#39;^&#39;,<br>                                   label=&#39;more avoidable crash&#39;)<br>plt.title(&#39;Density of More &amp; Less Avoidable Accidents&#39;)<br>leg = plt.legend(prop={&#39;size&#39;:15})<br>for lh in leg.legendHandles:<br>  lh.set_alpha(1)<br>plt.xlabel(&#39;longitude&#39;)<br>plt.ylabel(&#39;latitude&#39;)<br>plt.savefig(&#39;Density of More &amp; Less Avoidable Accidents&#39;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*vPEKVjQUVzUer4_2A-bjLA.png" /></figure><p>What a surprise — busier streets have more accidents. We also find similarly earth-shattering revelations when looking at age (younger drivers are riskier) and time of day (commute times have more crashes):</p><pre>#examining more avoidable crashes by hour-of-day<br>fig, ax = plt.subplots()<br>ax.hist(more_avoidable_crashes[&#39;CRASH_HOUR&#39;], bins=24, color=&#39;r&#39;, alpha=0.4, edgecolor=&#39;k&#39;)<br>ax.set_title(&#39;Distribution of Avoidable Accidents by Hour-of-Day&#39;)<br>ax.set_xlabel(&#39;hour of day&#39;)<br>ax.set_ylabel(&#39;no. of accidents&#39;)<br>plt.savefig(&#39;Distribution of Avoidable Accidents by Hour-of-Day&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ym3gJUlysZvB6SvGZ5zRSQ.png" /></figure><pre>fig, ax = plt.subplots()<br>ax.hist(more_avoidable_crashes[&#39;AGE&#39;], bins=40, color=&#39;r&#39;, alpha=0.4, edgecolor=&#39;k&#39;)<br>ax.set_title(&#39;Distribution of Avoidable Accidents by Age&#39;)<br>ax.set_xlabel(&#39;age&#39;)<br>ax.set_ylabel(&#39;no. of accidents&#39;)<br>plt.savefig(&#39;Distribution of Avoidable Accidents by Age&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*132P1HBZ8iTe6OXh2UeUUg.png" /></figure><p>While I’m not exactly paving new roads with these results, <strong>they <em>do</em> offer support for our intuitions about traffic safety </strong>and also show some insight into how to improve traffic safety from a broader perspective:</p><ol><li>an ad campaign on <strong>heavy traffic </strong>safety targeting <strong>drivers aged 23–40</strong></li><li>a potential road condition/traffic signal study <strong>just on the most densely accident-prone parts of the map</strong> (downtown and westward)</li><li>radio PSA’s on safety <strong>during commute times</strong></li></ol><p>These strategies may help reduce all kinds of crashes and maximize a budget allocated to safety initiatives. Perhaps just as importantly, this project helps convey a <strong>confidence in these findings by keeping the non-technical stakeholder in the loop throughout the predictive modeling process and going deeper than the final model’s results and accuracy</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33fb8ccf1c61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bank Marketing Campaign Predictions with Decision Trees vs. Logistic Regression]]></title>
            <link>https://medium.com/@joel.mott8/bank-marketing-campaign-predictions-with-decision-trees-vs-logistic-regression-80914bc02180?source=rss-a0581c989279------2</link>
            <guid isPermaLink="false">https://medium.com/p/80914bc02180</guid>
            <category><![CDATA[banking]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[marketing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <dc:creator><![CDATA[Joel Mott]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 23:18:29 GMT</pubDate>
            <atom:updated>2024-01-16T23:23:12.723Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zkPDuf0SlFyqMZN4" /><figcaption>Photo by <a href="https://unsplash.com/@micheile?utm_source=medium&amp;utm_medium=referral">micheile henderson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The latest part of my transition from music theorist to data scientist at the Flatiron School covered logistic regression. It’s been a fun tool to add to my analytical belt, especially when applying it to a larger project.</p><p>I found <a href="https://www.kaggle.com/datasets/prakharrathi25/banking-dataset-marketing-targets/data">a dataset on Kaggle</a> that comes from a Portuguese bank’s marketing campaign that help put these skills into practice. Specifically, this campaign involved calling existing clients to persuade them to open a term deposit.</p><p>Unlike checking accounts, these deposits cannot be withdrawn for fixed periods without a heavy fee. In return, the customer receives a higher interest rate. Subsequently, banks have more flexibility to invest these funds, so term deposits generate more revenue for banks.</p><p>The data contains just under 50,000 records with fifteen features and an outcome/target variable: whether the client opened a term deposit. The client data included things like age, education level, job type, annual average account balance as well as whether the client ever made a term deposit before, has a loan, or ever defaulted on one.</p><p>During the campaign, the bank paid a call center to reach out to their clients. The result was 11.7% success (the client made a term deposit) and 88.3% failure (the client wasn’t interested).</p><p>My goal wasn’t so much to net <em>more</em> term deposits, but rather to help make future campaigns more efficient. Specifically, how much of this call list could we trim by better predicting which kind of client to target next time?</p><p><strong>The real challenge was twofold: (1) finding which model worked best by way of (2) refining a decision tree and a logistic regression model for optimal predictions.</strong></p><p>This was further complicated by the <strong>class imbalance</strong> issue: there were <em>far</em> more unsuccessful outcomes than successful ones and that makes a predicting model’s job more difficult.</p><p>For each model, I began with a baseline attempt at running the model and then tried gradual improvements until I was making the best predictions. These improvements included:</p><ul><li>over-sampling the minority class (the far fewer successful outcomes)</li><li>under-sampling the majority class (the more common “no” outcomes)</li><li>refining model hyperparameters (depending on the model)</li></ul><p>The results were clear: a Scikit-Learn decision tree model was much better at making predictions than a StatsModels logistic regression (“Logit”) model was, but the Logit model told me a lot more about the data itself. Taken together, I was able to recommend (1) which model to use on future data and (2) which aspects of client data to focus on.</p><p>Below, I briefly discuss the model refining process and then summarize how each one was ultimately quite helpful.</p><p>Establishing a baseline decision tree was an easy process with horrendous results. First, the easy part: below I import what we need, fit a decision tree model, and then generate the resulting decision tree diagram.</p><pre>#Importing everything we&#39;ll need for our baseline model<br>from sklearn import tree<br>from sklearn.tree import DecisionTreeClassifier<br><br>#instantiating &amp; fitting the DecisionTreeClassifier model<br>clf_baseline = DecisionTreeClassifier(criterion=&#39;entropy&#39;, random_state=713)<br>clf_baseline.fit(X_train_preprocessed, y_train)<br><br>#Checking out the tree plot<br>fig, ax = plt.subplots(figsize=(20,30))<br>tree.plot_tree(clf_baseline,<br>              feature_names = X_train_preprocessed.columns,<br>              class_names = np.unique(y).astype(&#39;str&#39;),<br>              filled=True)<br>plt.show();</pre><p>It doesn’t take much to realize the Leviathan monstrosity generated below needs some work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P1fYLUjMqUjFd2ndHl8aHw.jpeg" /></figure><p>Not only is this baseline decision tree diagram difficult to interpret, but it almost certainly will lead to overfitting (and, thereby, an inability to make decent predictions on future data).</p><p>However, before moving on, the real usefulness of the baseline was to establish whether (and how much) any <em>future</em> optimization efforts worked. So let’s see how well this baseline model really did.</p><p>Evaluating progress isn’t a one-size-fits-all ordeal; it’s critical to keep the stakeholder’s concerns in mind. In our case, a positive prediction was a successful outcome (a term deposit) while a negative prediction was an unsuccessful one.</p><p>Ideally, we’d only have true predictions with an identical outcome to the previous campaign: 11.7% yes, 88.3% no. Of course, data is usually (at least a little) messy and we can only hope to come close to this ideal.</p><p>In this scenario, <strong>a false positive prediction would have been a wasted phone call</strong> (the model predicted a client would make a term deposit when they really wouldn’t). <strong>A false negative seems like a bigger deal: a missed term deposit</strong> because the model predicted someone would not make a term deposit when they actually would have.</p><p>But just how big a deal is a wasted phone call versus a missed term deposit? In reality, we’d probably know the exact call center costs and average term deposit gains, but that information isn’t provided here. <strong>Subsequently, models were evaluated on how well they avoided false negatives a little more so than false positives.</strong></p><p>In other words, I privileged <strong>recall </strong>when checking to see how model improvements faired, but I didn’t just focus on false negatives, I also used the area-under-the-curve (<strong>AUC</strong>) metric to measure overall performance. This baseline had a recall score of 0.51502, which is terrible, and an AUC of 0.72369, which is decent.</p><p>The confusion matrix looked just okay considering we have 4,645 total positives (that’s the true positives and false negatives together, with “0” assigned to the no’s and “1” to the yes’s in the diagram below). While it doesn’t appear to be predicting successful outcomes very well, it was doing an okay job of balancing missed term deposits against wasted phone calls:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*j-OYdebmwC6YIINo-05dtg.jpeg" /></figure><p>Refining the decision tree model started with Imblearn’s RandomOverSampler, which has some default hyperparameters that didn’t really help in this case. Next, I tried iterating through different oversampling rates.</p><p>Specifically, I tried oversampling the successful outcome records in ten-percent increments up to 150% (110%, 120%, 130%, 140%, 150%), which helped fine-tune the best place for the decision tree:</p><pre>from imblearn.over_sampling import RandomOverSampler<br>#establishing the specific ratios for oversampling<br>sampling_strategies = [{0:35140, 1:6968}, <br>                       {0:35140, 1:6503}, <br>                       {0:35140, 1:6039}, <br>                       {0:35140, 1:5574}, <br>                       {0:35140, 1:5156}]<br>#setting up blank lists to append later<br>recall_scores = []<br>auc_scores = []<br>#looping through each oversampling ratio<br>for i in sampling_strategies:<br>    # define oversampling strategy<br>    oversample = RandomOverSampler(random_state=713, sampling_strategy=i)<br>    # fit and apply the transform<br>    X_train_preprocessed_over, y_train_over = oversample.fit_resample(X_train_preprocessed, y_train)    <br>    #instantiate &amp; fit the model to X_over &amp; y_over<br>    clf_oversample_temp = DecisionTreeClassifier(criterion=&#39;entropy&#39;, random_state=713)<br>    clf_oversample_temp.fit(X_train_preprocessed_over, y_train_over)<br>    #make predictions for our evaluation metrics<br>    y_pred_test_over = clf_oversample_temp.predict(X_test_preprocessed)<br>    #find &amp; append recall scores<br>    recall_scores.append(recall_score(y_test, y_pred_test_over))<br>    #find &amp; append auc scores<br>    fpr, tpr, thresholds = roc_curve(y_test, y_pred_test_over)<br>    auc_scores.append(auc(fpr,tpr))<br><br>print(&quot;Recall &amp; AUC scores for 1.5 down through 1.1 sample_strategy dictionaries:&quot;)<br>print(&quot;recall scores:&quot;, recall_scores)<br>print(&quot;auc_scores:   &quot;, auc_scores)</pre><pre>Recall &amp; AUC scores for 1.5 down through 1.1 sample_strategy dictionaries:<br>recall scores: [0.5210300429184549, 0.5218884120171674, 0.5253218884120172, 0.527038626609442, 0.5236051502145923]<br>auc_scores:    [0.7271513229850758, 0.726840357226985, 0.7299235267612352, 0.7286753142156752, 0.7292359615796259]</pre><p>In this way, I found oversampling at 120% worked best. I did the same process for under-sampling the majority class (by 90%, 80%, 70%, 60%, 50%) and found that 50% under-sampling worked even better.</p><p>I also tried combining over &amp; under-sampling as well as SMOTE, but they didn’t come close to under-sampling at 50%.</p><p>Now that I had my sampling strategy in place, the second half of optimizing my decision tree involved tuning the hyperparameters. This also involved an iterative process of trying different modes for the max_depth, min_samples_split, and min_samples_leaf params.</p><p>For concision’s sake, it turned out that optimizes min_samples_split and min_samples_leaf didn’t help at all, but “pruning” the tree with max_depth set to 6 made a helpful difference:</p><pre>max_depth = np.arange(1,20)<br><br>#setup lists for plotting <br>train_auc_values = []<br>test_auc_values = []<br><br>#iterating through max_values and filling the lists above<br>for i in max_depth:<br>    #initialize &amp; train the classifier<br>    temp_clf = DecisionTreeClassifier(criterion=&quot;entropy&quot;, <br>                                      random_state=713, <br>                                      max_depth=i)<br>    temp_clf.fit(X_train_preprocessed_under, y_train_under)<br>    #calculate &amp; append training AUC<br>    y_train_hat = temp_clf.predict(X_train_preprocessed)<br>    train_fpr, train_tpr, train_thresholds = roc_curve(y_train, y_train_hat)<br>    train_roc_auc = auc(train_fpr, train_tpr)<br>    train_auc_values.append(train_roc_auc)<br>    #calculate &amp; append AUC<br>    y_test_hat = temp_clf.predict(X_test_preprocessed)<br>    test_fpr, test_tpr, test_thresholds = roc_curve(y_test, y_test_hat)<br>    test_roc_auc = auc(test_fpr, test_tpr)<br>    test_auc_values.append(test_roc_auc)<br>print(&quot;best test score:&quot;, max(test_auc_values))<br>#Plotting<br>fig, ax = plt.subplots()<br>ax.plot(max_depth, train_auc_values, color=&#39;mediumseagreen&#39;, label=&#39;Train AUC scores&#39;)<br>ax.plot(max_depth, test_auc_values, color=&#39;darkorange&#39;, label=&#39;Test AUC scores&#39;)<br>ax.set_title(&#39;Train versus Test AUC scores&#39;)<br>ax.set_xlabel(&#39;max_depth hyperparameter setting&#39;)<br>ax.set_ylabel(&#39;AUC&#39;)<br>ax.vlines(6, ymin=0.5, ymax=0.935, color=&#39;k&#39;, linestyle=&#39;--&#39;, label=&quot;best test AUC score&quot;)<br>ax.legend();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*qmYKhEZrgWWxtPAxMFK-aQ.jpeg" /></figure><p>I now had a much-improved decision tree model with an improved recall score (up to 0.62146 from the baseline’s 0.51502), AUC score of 0.77059 (baseline was 0.72369), and better-looking predictions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*iIwqp9-ddUS-dbUqKAOX3Q.jpeg" /></figure><p>Also, I had a much less frightening decision tree diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MkdmloDf82tsiE2u8yaxBg.jpeg" /></figure><p>However helpful its predictions were, my decision tree model did not tell me a whole lot more about the <em>nature </em>of the data itself. It turns out the Logit model could help me make some more specific recommendations to the stakeholder.</p><p>When I tried the same overall process (over &amp; under-sampling, although with different hyperparameters) on a StatsModels Logit model, it couldn’t predict as well, but it <em>did</em> tell me a lot more about which features mattered the most to our stakeholder.</p><p>After optimizing the Logit model, I ran the following to de-log the log-odds coefficients (turn them into regular odds), pair them up with their column names, and sort them in order of impact:</p><pre>import math<br><br>#gathering the coefficients&#39; names and values<br>logit_coef_names = over_at_150_result.params.index.to_list()<br>logit_coef_values = list(over_at_150_result.params.values)<br>#un-logging coefficients<br>logit_coef_values_odds = []<br>for i in logit_coef_values:<br>    logit_coef_values_odds.append(math.exp(i))<br>#adding their respective names<br>logit_coefs = zip(logit_coef_names, logit_coef_values_odds)<br>#sorting them by size<br>logit_coefs = sorted(logit_coefs, key = lambda x: x[1], reverse=True)<br>logit_coefs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*KaSdC1WOAqR6KS7EI4QDaQ.jpeg" /></figure><p>Specifically, the model summary’s coefficient lists told me that the following attributes made the biggest impact on whether someone opened a term deposit:</p><ul><li><strong>If someone had made a term deposit before</strong>, the odds they would do so again increased by 869%!</li><li>The <strong>higher a client’s average annual checking account balance</strong>, the more likely they were to make a deposit (this was a normalized attribute, so interpreting its odds were not as straightforward as the other two here).</li><li><strong>Repeat-calling a client didn’t help</strong>: after a couple follow-ups, the odds a client called repeatedly would make a term deposit decreased 0.07%!</li></ul><p>In this way, I was able to garner the best of both modeling worlds. Specifically, I could provide deliverables that included strong predictive power and insightful recommendations on what kind of data made the biggest difference to help optimize further marketing efforts.</p><p>This topic has been well-covered before: decision trees make better predictions on larger datasets with unrelated attributes while Logit models perform better on smaller datasets with more related features. However, it was fun to see how both can be optimized and insightful for marketing campaign purposes.</p><p>As I continue with my transition into Data Science, I’ll learn about methods that help automate this process, like Random Forests. However, getting the opportunity to work with these predictive and inferential modeling methods in a more “hands-on” way helped me to appreciate the nature of what we input and how we interpret the output to make it make sense for each specific case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80914bc02180" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applying Instacart Data to New Product Promotion for Grocery Stores]]></title>
            <link>https://medium.com/@joel.mott8/applying-instacart-data-to-new-product-promotion-for-grocery-stores-08e9560946e0?source=rss-a0581c989279------2</link>
            <guid isPermaLink="false">https://medium.com/p/08e9560946e0</guid>
            <category><![CDATA[regression-analysis]]></category>
            <category><![CDATA[grocery-home-delivery]]></category>
            <category><![CDATA[statsmodels]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[grocery-store]]></category>
            <dc:creator><![CDATA[Joel Mott]]></dc:creator>
            <pubDate>Fri, 13 Oct 2023 20:57:55 GMT</pubDate>
            <atom:updated>2023-10-13T20:57:55.272Z</atom:updated>
            <content:encoded><![CDATA[<p>Since the early 2010’s, online grocery delivery services like Instacart and Shipt have become mainstream. Today, their shoppers make grocery runs for both direct users and online customers at Target, Costco, Publix, Safeway/Tom Thumb/Randall’s, Wegmans, and Sprouts.</p><p>Back in 2017, <a href="https://www.kaggle.com/c/instacart-market-basket-analysis/data">Instacart uploaded a dataset to Kaggle</a>, challenging analysts to predict users’ next orders. This anonymized dataset contains insightful information regarding product details, whether the product constituted a new item for the user or a reorder, how often orders were placed, the order’s day-of-week and time-of-day, and even the sequence in which each product was placed in the online cart.</p><p>Since the pandemic, numerous grocery chains have gotten in on the action with their own delivery services. These include Aldi, Kroger, Walmart, and HEB. Unlike Instacart, these companies can also offer curbside-pickup service and have at least <em>some</em> more control over restocking.</p><p><strong>It turns out that this dataset can also help optimize grocers’ new product promotion</strong>. I applied linear regression analysis to this dataset to find out what aspects correlate with reordering products. The final regression model showed some helpful correlations that inform a few business recommendations.</p><p>While some of these insights are doubtlessly obvious to any well-established grocer (customers tend to shop once a week, weekends are busier, the produce &amp; dairy departments are the biggest sellers), one online pattern stood out: the order in which customers add items to their cart.</p><h3>Exploratory Data Analysis</h3><p>This is one of the strongest correlations in the dataset with reordering; <strong>customers add their reordered products first</strong>. Let’s take a look at how the data gets us here. I used Python’s SQLite3, Pandas, and StatsModels modules to load, analyze, and run regression analysis, respectively.</p><p>To begin, I took this dataset (which consists of a few Excel spreadsheets) and turned them into a SQL database from which I could run queries to find these correlations.</p><pre>import pandas as pd<br>import sqlite3<br><br>#Creating the database/connection<br>conn = sqlite3.connect(&#39;instacart.db&#39;)<br><br>#Reading in each Instacart file as a table in the database (one example):<br>df = pd.read_csv(&#39;aisles.csv&#39;)<br>df.to_sql(&#39;aisles&#39;, conn)<br>#Then do the same for each table</pre><p>Once every table was loaded in, I ran the following query to form the first Pandas DataFrame for EDA that’s primarily focused on products:</p><pre>product_info_df = pd.read_sql(<br>                &quot;&quot;&quot;SELECT<br>                    order_products__prior.product_id,<br>                    COUNT(product_id) AS times_ordered,<br>                    products.product_name,<br>                    products.department_id,<br>                    departments.department AS dept_name,<br>                    products.aisle_id,<br>                    aisles.aisle AS aisle_name<br>                FROM order_products__prior<br>                JOIN products<br>                    USING(product_id)<br>                JOIN aisles<br>                    USING(aisle_id)<br>                JOIN departments<br>                    USING(department_id)<br>                GROUP BY product_id<br>                ORDER by times_ordered DESC;<br>                &quot;&quot;&quot;, conn)<br>product_info_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*fVJI8Ol5iUZP5GejZA-WqA.png" /></figure><p>In this manner, I was able to find and visualize some preliminary observations, such as the most popular products and departments. A similar query constructed a DataFrames more focused on shopping frequency.</p><pre>order_times_df = pd.read_sql(<br>                    &quot;&quot;&quot;SELECT<br>                            products.product_id,<br>                            products.product_name,<br>                            orders.order_number,<br>                            orders.order_dow AS day_of_week,<br>                            orders.order_hour_of_day,<br>                            orders.days_since_prior_order,<br>                            departments.department AS dept_name,<br>                            aisles.aisle AS aisle_name<br>                        FROM aisles<br>                        JOIN products <br>                            USING(aisle_id)<br>                        JOIN departments<br>                            USING(department_id)<br>                        JOIN order_products__prior<br>                            USING(product_id)<br>                        JOIN orders<br>                            USING(order_id);<br>                    &quot;&quot;&quot;, conn)<br>order_times_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_TtqyEiL08HRw-KVYfa4A.png" /></figure><p>This is where I found the aforementioned data on weekly trips and busy weekends: old news for the grocer, but (at least for me) still interesting to visualize:</p><pre>fig, ax = plt.subplots(figsize=(10,6))<br>ax.hist(order_times_df[&#39;days_since_prior_order&#39;], bins=31, color=&#39;seagreen&#39;, edgecolor=&#39;k&#39;, alpha=0.8)<br>plt.xticks(ticks=np.arange(0,31,1))<br>ax.set_title(&#39;Histogram of the Number of Days Since the Previous Order&#39;)<br>ax.set_xlabel(&#39;the number of days since the last order was placed&#39;)<br>plt.savefig(&#39;Histogram of the Number of Days Since the Previous Order.png&#39;)<br>ax.set_ylabel(&#39;count&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*AJ4OgpHIj4_xRkGoEU_CCA.png" /></figure><p>Many users order groceries more frequently than once a week, but the largest spike comes at every seven days. Smaller spikes every seven days thereafter are noteworthy; some users only order once every two, three, or even four (?) weeks.</p><p>The “30” spike at the end is almost certainly a placeholder for those who use Instacart every thirty or more days for the occasional break from in-store shopping.</p><p>This weekly trend is reflected in the days of the week; weekend shopping dominates the weekdays. Below, I had to substitute the Instacart’s 0–7 day labels with a dictionary for the days of the week:</p><pre>#Grouping the order_times_df<br>orders_by_dow = order_times_df.groupby(&#39;day_of_week&#39;).count()<br>orders_by_dow.reset_index(inplace=True)<br><br>#Replacing the numeric day of the week values<br>day_of_week_dict = {0: &#39;Saturday&#39;, 1: &#39;Sunday&#39;, 2: &#39;Monday&#39;, 3: &#39;Tuesday&#39;, <br>                    4: &#39;Wednesday&#39;, 5: &#39;Thursday&#39;, 6: &#39;Friday&#39;}<br>orders_by_dow[&#39;day_of_week&#39;].replace(day_of_week_dict, inplace=True)<br><br>#Plotting<br>fig, ax = plt.subplots(figsize=(7,5))<br>ax.bar(orders_by_dow[&#39;day_of_week&#39;], orders_by_dow[&#39;product_id&#39;], color=&#39;orange&#39;, alpha=0.8)<br>ax.set_title(&quot;Amount of Orders per Day of the Week&quot;)<br>plt.savefig(&quot;Amount of Orders per Day of the Week.png&quot;)<br>plt.tight_layout();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*c6P9yACFWcpRNSZ4i_NQ8A.png" /></figure><p>It looks like Thursday already begins ramping up to the weekend. Again, nothing a grocer doesn’t already know, but we’ll see this cycle play out in our reordering correlations and new product promotion recommendations.</p><p>Returning to our add-to-cart-orders, the graph below just shows the top 100 products because, as we’ll see later, including all 35,449 unique products will make this underlying correlation difficult to see.</p><pre>fig, ax = plt.subplots(figsize=(7,7))<br>ax.scatter(top_100_reorders_by_count[&#39;avg_place_in_added_to_cart_sequence&#39;], top_100_reorders_by_count[&#39;percentage_as_a_reorder&#39;])<br>ax.set_title(&quot;Added-to-Cart-Order &amp; Product-Reorder-Percentage&quot;)<br>ax.set_ylabel(&#39;percent of the time the product is ordered as a reorder&#39;)<br>ax.set_xlabel(&#39;average place in sequence of being added to cart&#39;)<br>plt.savefig(&quot;Added-to-Cart-Order &amp; Product-Reorder-Percentage.png&quot;)<br>plt.tight_layout();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*btDrsYDQ3GmQ1oGR5o39yg.png" /></figure><p>There’s a strong negative correlation between adding an item to the cart and that item’s likelihood of being a reorder for the user. However, when I included <em>every</em> product in this model, this correlation disappeared into a chaotic mess:</p><pre>fig, ax = plt.subplots(figsize=(7,7))<br>ax.scatter(product_reorders_df[&#39;avg_place_in_added_to_cart_sequence&#39;], product_reorders_df[&#39;percentage_as_a_reorder&#39;], alpha=0.4)<br>ax.set_title(&quot;The Order in Which a Product is Added to the Cart versus Product Percentage as a Reorder&quot;)<br>ax.set_ylabel(&#39;percent of the time the product is ordered as a reorder&#39;)<br>ax.set_xlabel(&#39;average place in sequence of being added to cart&#39;)<br>plt.tight_layout();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*3U62IC5opexu-6gU5JxPGg.png" /></figure><p>The problem is the <em>wide</em> variance in the amount of times these products had been ordered over the course of collection this data. Bananas were ordered well over 150,000 times while a number of products were only ordered once.</p><p>Subsequently, we see the accumulation of lower-count reorder percentages in the graph above (like 0% and 100% for products only ordered once or twice, then 33% and 66% for those only ordered three times, etc.).</p><p>It turns out that eliminating products ordered fewer than 100 times provides a happy medium between preserving as much of these sales records as we can while being able to identify useful trends in reordering:</p><pre>products_worth_considering = broader_product_df[broader_product_df[&#39;times_ordered&#39;] &gt; 100]</pre><p>With this more useful dataset in mind, we can now segue into building a regression model in order to more clearly specify the nature of these preliminary findings.</p><p>Regression Analysis</p><p>The overall regression process used here involves (1) constructing a baseline model with the single strongest correlating aspect (or “feature”) of this data, then (2) evaluating that baseline, and finally (3) improving on it by adding and/or transforming more features as needed and warranted.</p><p>One immediate obstacle was finding an appropriate dependent or “target” variable for this model. In other words, how was I measuring “reordering” here when there was no such obvious column in the dataset?</p><p>In this case, I produced an aggregate “target” column made up of the reorder-percentage for each product. Specifically, this is a DataFrame column that divides the amount of reorders-per-product by the total number of orders-per-product.</p><pre>product_reorders_df[&#39;percentage_as_a_reorder&#39;] = \<br>product_reorders_df[&#39;times_reordered&#39;] / product_reorders_df[&#39;times_ordered&#39;]</pre><p>As interesting as the add-to-cart-order pattern was, I wanted to make sure the baseline model was actually built on the single strongest correlation in the Instacart data.</p><p>This is where a Seaborn correlation heatmap came in handy:</p><pre>heatmap_data = products_worth_considering<br>corr = heatmap_data.corr()<br>fig, ax = plt.subplots(figsize=(15,15))<br>sns.heatmap(data=corr, mask=np.triu(corr), ax=ax, annot=True, cmap=&quot;crest&quot;,<br>            cbar_kws={&#39;label&#39;:&#39;correlation&#39;, &#39;orientation&#39;:&#39;horizontal&#39;, &#39;pad&#39;:.2, &#39;extend&#39;:&#39;both&#39;});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*07Cb0vpk20ETYmqPBmVK2A.png" /></figure><p>Good news: the strongest (legitimate) correlation with the percentage-as-a-reorder target is in fact our (aggregated average-per-product) add-to-cart order.</p><p>I used StatsModels’ OLS module to construct the baseline model, which produces a reasonable R-squared score of 0.320 (considering the more categorical nature of this dataset and the amount of variance involved, a reasonable R-squared score <a href="https://www.statology.org/good-r-squared-value/#:~:text=How%20high%20an%20R%2Dsquared,extreme%20variability%20in%20the%20dataset.">may not be as high</a> as models with more straightforward targets):</p><pre>#Importing the StatsModels library:<br>import statsmodels.api as sm<br>from statsmodels.formula.api import ols<br>#Constructing the baseline model:<br>formula = &#39;percentage_as_a_reorder ~ avg_added_to_cart_order&#39;<br>model = ols(formula=formula, data=broader_product_df).fit()<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*LWOQW3kl-UgZ9cpxv8WsWg.png" /></figure><p>This model summary looks good as far as p-values go, but the measures that check for a normal distribution are a little problematic. Ultimately, instituting a logarithmic transformation or further reducing the amount of products did not turn out to be worth it, so I decided to proceed with the understanding that this dataset contains a lot of variation.</p><p>It may not be an ideal set for regression modeling, but applying regression analysis can still tell us something valuable since many grocery stores are moving into the online-ordering realm with their own services.</p><p>Therefore, with a baseline model in play and a percentage-based target in mind, we can decipher a coefficient for our avg_add_to_cart_order model: <strong>as we progress through products added to the cart, they become 4.3% less likely to be a reordered one</strong>.</p><p>We can now add more features of our data to see whether they improve our model as long as it makes sense to do so. Looking back at our correlation heatmap, the next-strongest correlation is the amount of times a product was reordered (“times_reordered”).</p><p>However, this feature is unusable. It is too closely tied to our target variable (it is literally one of two components that make up the target) and its distribution is disastrously far from normal. Even logarithmic transformation did little to improve it, so we are better off moving on to the next feature.</p><p>There are actually three features with the same or similar correlation here and they all deal with order frequency: (1) the average number of days since a product was ordered, (2) the average hour of day it was ordered, and (3) the average day of the week it’s ordered on.</p><p>Long story short, the hour-of-day feature is (1) too closely interrelated with day-of-the-week and (2) has a high p-value, so we eliminate it. Along with avg_days_since_prior_order, avg_order_day_of_week can be added to our model without introducing new problems while also improving the R-squared score to 0.434:</p><pre>predictors = products_worth_considering[[&#39;avg_added_to_cart_order&#39;, <br>                                         &#39;avg_days_since_prior_order&#39;, <br>                                         &#39;avg_order_day_of_week&#39;]]<br>predictors = sm.add_constant(predictors)<br>model = sm.OLS(target, predictors).fit()<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*UGNxArgyrMi3F4ZUDG4v2g.png" /></figure><p>The skew, kurtosis, and other distribution-checking measures are not showing normal results. Let’s investigate further before making recommendations based on this model:</p><pre>#Set up figure<br>fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20,6))<br>#Plot histograms<br>ax1.hist(products_worth_considering[&#39;avg_added_to_cart_order&#39;], color=&#39;mediumseagreen&#39;, bins=&#39;auto&#39;)<br>ax2.hist(products_worth_considering[&#39;avg_days_since_prior_order&#39;], color=&#39;mediumseagreen&#39;, bins=&#39;auto&#39;)<br>ax3.hist(products_worth_considering[&#39;avg_order_day_of_week&#39;], color=&#39;mediumseagreen&#39;, bins=&#39;auto&#39;)<br>#Title histograms<br>ax1.set_title(&#39;avg_added_to_cart_order Histogram&#39;)<br>ax2.set_title(&#39;avg_days_since_prior_order Histogram&#39;)<br>ax3.set_title(&#39;avg_order_day_of_week Histogram&#39;)<br>#Polish figure<br>plt.tight_layout();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZQTYuibDC_Rh7lLC9FZdOg.png" /></figure><p>That ‘avg_added_to_cart_order’ seems a bit off. Let’s investigate that a little further:</p><pre>from scipy.stats import kurtosis, skew<br>print(&quot;skewness of avg_added_to_cart_order:&quot;, skew(products_worth_considering[&#39;avg_added_to_cart_order&#39;]))<br>print(&quot;kurtosis of avg_added_to_cart_order:&quot;, kurtosis(products_worth_considering[&#39;avg_added_to_cart_order&#39;]))<br>print(&quot;-------------------------------------------------&quot;)<br>print(&quot;skewness of avg_days_since_prior_order:&quot;, skew(products_worth_considering[&#39;avg_days_since_prior_order&#39;]))<br>print(&quot;kurtosis of avg_days_since_prior_order:&quot;, kurtosis(products_worth_considering[&#39;avg_days_since_prior_order&#39;]))<br>print(&quot;-------------------------------------------------&quot;)<br>print(&quot;skewness of avg_order_day_of_week:&quot;, skew(products_worth_considering[&#39;avg_order_day_of_week&#39;]))<br>print(&quot;kurtosis of avg_order_day_of_week:&quot;, kurtosis(products_worth_considering[&#39;avg_order_day_of_week&#39;]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*CQb3mllugSftlID9vDO74A.png" /></figure><p>It seems that our avg_added_to_cart_order is the culprit, but applying a logarithmic transformation here just makes it worse, so we’re probably looking at the best model given the less-than-ideal dataset for regression analysis.</p><h3>Results and Conclusions</h3><p>Nonetheless, even if not ideal, these Instacart insights are still valuable and worthwhile. Specifically, we can at least identify one more somewhat strong correlation in our model summary besides the aforementioned avg_add_to_cart_order one: <strong>over the course of a week, as a product’s average order day of the week increases away from Saturday by one whole day, the likelihood of that product being ordered as a reorder decreases by 15.2%.</strong></p><p>We can also offer the following three recommendations (the first two based on our first, added_to_cart_order correlation and the third based on the avg_order_day_of_week one):</p><p><strong>recommendation 1:</strong> Advertising a new or as-of-yet-unordered product online or in-app may be more effective towards the end of the online ordering process.</p><p><strong>recommendation 2:</strong> Finding a way to cluster reorders may allow greater user patience for newer product promotion; this is likely part of the reason “click to reorder previous” options are available in some existing apps/desktop sites.</p><p><strong>recommendation 3:</strong> Promoting new products in commercials, online, or in-app on Thursdays or Fridays may help increase interest in new products before the weekend rush.</p><p>In conclusion, we can say that Instacart’s helpful dataset can also inform grocery chains’ own delivery, curbside, and restocking operations.</p><p>Future or similar projects tailored towards specific stores may help:</p><ul><li>optimize aisle layouts</li><li>quantify reserved parking spaces for curbside pickup</li><li>inform allocation of staff to delivery &amp; curbside services</li><li>improve grocery ordering app design</li></ul><p>Future projects may also include data on in-store shopping to help refine these correlations with restocking. This current project may also help inform online-only stores (aka “online fulfillment centers”).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08e9560946e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rising above the data weeds: keeping the big picture in focus]]></title>
            <link>https://medium.com/@joel.mott8/rising-above-the-data-weeds-keeping-the-big-picture-in-focus-through-the-details-5706c3dd9cb7?source=rss-a0581c989279------2</link>
            <guid isPermaLink="false">https://medium.com/p/5706c3dd9cb7</guid>
            <dc:creator><![CDATA[Joel Mott]]></dc:creator>
            <pubDate>Sun, 06 Aug 2023 23:59:06 GMT</pubDate>
            <atom:updated>2023-08-07T02:39:30.972Z</atom:updated>
            <content:encoded><![CDATA[<p>An eye for detail is great. Deliberating on big decisions is often important. An anxious obsession with detailed minutia isn’t helping anyone.</p><p>I recently worked on a project at Flatiron’s Data Science program that involved (1) a fictional stakeholder looking to purchase &amp; operate commercial aircraft — specifically low-risk airplanes — and (2) a dataset from the NTSB with records from every US aircraft incident since 1962.</p><p>In other words, a flexible and generalized prompt with a large dataset containing tons of details (88,889 records and 30 columns).</p><p>Even with a decent background in Python and Pandas, I promptly started by worrying about it.</p><p>How would I tackle so many rows of data? How would I make sense of them all as “low-risk” or not? Don’t I need to know more stuff than what I see here?</p><p>After all, I don’t see information on how *old* every plane was when it crashed. I’m not seeing the amount of planes every manufacturer has made; how can I compare them all? I’ll simply *have* to go through and add all that information in!</p><p>In other words, I immediately gravitated to the details and my own ideas about what does and doesn’t matter to this fictional stakeholder. While I ultimately created a clear and concise project presentation, it *definitely* didn’t follow the frenzied train of thought I began with.</p><p>Datasets like this NTSB one have their own logic. There’s a reason location data, make &amp; model information, fatality &amp; injury counts, and phase-of-flight records are here and *not* the plane’s age or manufacturer metadata.</p><p>I had to take a step back, “rise above the weeds” and see the big picture: this dataset already excelled at certain data perspectives. It already had underlying, graspable stories to tell and it was my job to find them.</p><p>My instructor had made this clear before, but it was this project that helped drive it home…especially after I had already spent hours trying to Google endless amounts of information on plane manufacturer data that didn’t need to be done.</p><h4>‘Zooming out’ from the weeds</h4><p>Performing some exploratory data analysis (EDA) is a common knowledge for Data Analysts &amp; Scientists when beginning to work with a new dataset. In this case, I went through each column whose nature wasn’t immediately obvious and checked its contents, often using the following</p><pre>example_df[&#39;some column&#39;].unique()<br>or<br>example_df[&#39;some column&#39;].value_counts()</pre><p>Simple enough, but a good Data Scientist hasn’t made too many snap-judgements yet (that’s a lot of NaN’s! How will I fix them? There are 3,486 unique airplane models here, how will I ever make sense of them?).</p><p>I may not be the first burgeoning analyst to feel overwhelmed by a new dataset and struggle to not dive straight into the weeds of minutia among so many rows and columns. However, it wasn’t until I focused on the bigger picture that things became “figure-out-able.”</p><p>What did the data already do well?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*oKMMT1dNHk6roAc-pnv9cg.png" /></figure><p>This dataset is built to tell us a lot about each accident’s location, the aircraft involved, and the severity of the accident when it comes to injuries and fatalities. It turns out that these strengths alone are more than enough to satisfy the stakeholder’s business inquiry.</p><p>The location data may not be *too* relevant; we’d want a plane that’s safe anywhere. If singling out low-risk aircraft is the main concern, the data about the aircraft involved and how severe the crash are critical.</p><p>Looking at these two built-in perspectives can tell us what kind of aircraft (make &amp; model and, maybe later with a little bit of Googling, how big it is) have been involved in accidents more often than others. It tells us the make &amp; model, how many engines, and -with a little bit of Googling- we could also find out how big the plane is, whether it’s still being made, and whether it’s part of a larger group of planes (the models ‘B200’ and ‘B300’ are both Beechcraft King Air planes with some slight differences).</p><p>This can also help inform our data cleaning; we can group these kinds of discrepancies together into a consolidated aircraft model.</p><p>The injury &amp; fatality columns also tell us whether we had a minor incident or major accident occur. We can later turn these into dummy values or add them together for a broader look.</p><p>*Now* the details were being put into perspective: what *kind* of weeds to foray through were becoming clear. After cleaning the make and model columns to condense the manufacturer and endless models (to an extent), I could begin to use Pandas’ groupby function to see how all this helpful plane specification data related to the injury data:</p><p>I first began by making a correlation matrix to see what related to what else:</p><pre>import seaborn as sns<br>heatmap_data = filtered_df<br>corr = heatmap_data.corr()<br>fig, ax = plt.subplots(figsize=(15,15))<br>sns.heatmap(data=corr, mask=np.triu(corr), ax=ax, annot=True, <br>            cbar_kws={&#39;label&#39;:&#39;correlation&#39;, &#39;orientation&#39;:&#39;horizontal&#39;, &#39;pad&#39;:.2, &#39;extend&#39;:&#39;both&#39;});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*bhIJOb0_-zt0QgXSnluSkQ.png" /></figure><p>The strongest meaningful correlation was a negative one: the more engines a plane had, the more uninjured passengers there tended to be.</p><p>Exploring that further:</p><pre>from matplotlib.ticker import MaxNLocator<br>#source: https://stackoverflow.com/questions/12050393/how-to-force-the-y-axis-to-only-use-integers<br>fig, ax = plt.subplots(figsize=(10,8))<br>ax.bar(injuries_and_fatalities_by_engine_count.index, injuries_and_fatalities_by_engine_count.values, color=&#39;r&#39;)<br>ax.xaxis.set_major_locator(MaxNLocator(integer=True))<br>ax.set_xlabel(&#39;Number of Engines on Plane&#39;)<br>ax.set_ylabel(&#39;Number of Injuries and Fatalities&#39;)<br>ax.set_title(&#39;Total Injuries and Fatalities by Engine Count&#39;)<br>plt.tight_layout;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*lKmvBFkhH_WSA5jmH0mA_A.png" /></figure><p>So far, the only “weeds” I had sorted through were some manufacturer and model name duplication &amp; discrepancy cleaning. The big picture focus on what the data told well had shown me some compelling correlations to follow.</p><p>Relating back to my stakeholder’s question on low-risk aircraft, it looks like I could already recommend avoiding single-engine aircraft. Even if smaller aircraft were much more common than larger planes, the fact that they still lead the injury count when they hold far fewer passengers was concerning.</p><h4>Leveling-up: what could I meaningfully add to the data?</h4><p>I knew it was a good idea to refrain from a deep-diving rabbit hole of extensive, exterior research to bring to this project. However, I *could* add a little more information if it would be feasible and meaningful.</p><p>What was the dataset missing that would (1) relate to my stakeholder and (2) add to the dataset’s existing strengths?</p><p>One thing that bugged me was the lack of a comparison measure. As I mentioned before, there wasn’t any data on how big each plane was. I could get a general idea with the number of engines, but I wanted more specifics, especially after I saw how the *percentage* of fatalities &amp; injuries in accidents seemed to break down by passenger capacity:</p><pre>mfg_size_df.plot(x=&#39;manufacturer&#39;, y=[&#39;Fatality.Percentage&#39;, &#39;Injury.Percentage&#39;], kind=&#39;barh&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*yV5atzM56kpy6UJujmXNUQ.png" /></figure><p>You can see Boeing and Airbus are in their own league, then regional and larger private aircraft manufactures like Embraer, Bombardier, Learjet, and Gulfstream, followed by the smaller aircraft makes (Piper, Cessna, Beechcraft).</p><p>After narrowing down the models with 2+ engines and some further data cleaning, I only had 218 unique plane models to deal with. I decided I could add some specifics in terms of passenger capacity.</p><p>I exported the ‘Model’ column to Excel:</p><pre>#exporting the &#39;Models&#39; column to Excel so I can add the size tier column in<br>unique_models = filtered_df[&#39;Model&#39;].unique()<br>np.savetxt(&#39;filtered_df_Model_column.csv&#39;, unique_models, delimiter=&#39;,&#39;, fmt=&#39;%s&#39;)</pre><p>Then added a new column alongside it. I placed a “P” in the column if it was a private jet (seating 15 or fewer people), an “R” if it was a regional airliner (seating 16 to 100), and an “L” it was a large airliner (more than 100 seats). It took a while, but it was a reasonable and (turned out to be) a meaningful addition.</p><p>I was able to save that new column in Excel as a CSV file then read it back in to the Jupyter Notebook relatively easily:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*ThveHhPtOF5_gGwjD9-Yqg.jpeg" /></figure><p>Then I turned it into a Python dictionary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*qZkDgYZNzCAtF4NLnhEDGg.jpeg" /></figure><p>Then mapped that dictionary onto the ‘Model’ column in order to create a new capacity-tier column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-6Oix6yquDHh-7cT4sOBhQ.jpeg" /></figure><p>With this small addition, I was able to support the underlying trend of injuries-by-size with some more specific data:</p><pre><br>percent_inj_or_killed_by_capacity_tier = filtered_df.groupby(&#39;Passenger.Capacity.Tier&#39;)[&#39;Percent.Injured.or.Killed&#39;].mean().sort_values()<br><br>fig, ax = plt.subplots()<br>ax.barh(percent_inj_or_killed_by_capacity_tier.index, percent_inj_or_killed_by_capacity_tier.values)<br>ax.set_title(&#39;Percent of People Injured or Killed in Accidents per Capacity Tier&#39;)<br>ax.set_xlabel(&#39;Percentage of Injuries and/or Fatalities&#39;)<br>ax.set_ylabel(&#39;Capacity Tier of Plane&#39;)<br>plt.tight_layout();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*LRqj3s649AgdYb52beAcmw.png" /></figure><p>In turn, this allowed me to both show the stakeholder what size planes are lower-risk than others and to break down specific models to recommend by these tiers.</p><p>This was simply a matter of making new DataFrames based on the new “PLR” column:</p><pre>large_airliners = filtered_df[filtered_df[&#39;Passenger.Capacity.Tier&#39;] == &#39;large airliner&#39;]<br>regional_airliners = filtered_df[filtered_df[&#39;Passenger.Capacity.Tier&#39;] == &#39;regional airliner&#39;]<br>private_planes = filtered_df[filtered_df[&#39;Passenger.Capacity.Tier&#39;] == &#39;private plane&#39;]</pre><p>Then grouping by their respective ‘Model’ columns and the number of injuries and fatalities showed which planes were safest:</p><pre>ki_sum_per_large_model = large_airliners.groupby(&#39;Model&#39;)[&#39;total.inj.or.killed&#39;].sum().sort_values()<br>ki_sum_per_regional_model = regional_airliners.groupby(&#39;Model&#39;)[&#39;total.inj.or.killed&#39;].sum().sort_values()<br>ki_sum_per_private_model = private_planes.groupby(&#39;Model&#39;)[&#39;total.inj.or.killed&#39;].sum().sort_values()</pre><p>For example, large airliners broke down this way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*6JJqiasfnLp6Az3nTOXUMw.png" /></figure><p>Finally, after calming down and zooming out from the initial weeds, I could see what the dataset’s inherent strenghts were and *which* weeds to wander through. Keeping my stakeholder’s concerns in mind helped me pinpoint where additional data could help and led me to make meaningful cleaning and grouping efforts with the data.</p><p>On my next project, I’ll be sure to temper the detail-obsessive jitters with (that can be helpful when directed a little more wisely) with an appreciation for what the dataset may already be telling me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5706c3dd9cb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing and Narrowing Linear Regression Results with Outside Data]]></title>
            <link>https://medium.com/@joel.mott8/enhancing-and-narrowing-linear-regression-results-with-outside-data-5f0d22c67132?source=rss-a0581c989279------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f0d22c67132</guid>
            <category><![CDATA[real-estate]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[statsmodels]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <dc:creator><![CDATA[Joel Mott]]></dc:creator>
            <pubDate>Sun, 05 Feb 2023 16:16:53 GMT</pubDate>
            <atom:updated>2023-02-07T19:13:46.062Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uMXCybdrJfn7unBs" /><figcaption>Photo by <a href="https://unsplash.com/@element5digital?utm_source=medium&amp;utm_medium=referral">Element5 Digital</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Making results make more sense for your stakeholder from the start</h3><p>I began my Phase 2 project at Flatiron School with a desire to go beyond the minimum requirements and use linear regression to provide insight to a stakeholder that:</p><p>· isn’t already obvious to them</p><p>· covers an aspect of their field they may not thoroughly understand yet</p><p>· applies to data that may not be easy to find or compile on their own</p><p>· still has a meaningful, practical application to their bottom line</p><p>In this project, I was given a preexisting dataset with residential real estate sales records in King County, Washington, which encompasses Seattle, many of its suburbs, and rural areas to the east. This data includes over 22,000 house sale records and numerous columns such as data of sale, square footage, zip code, number of bedrooms/bathrooms, and listing price. For purposes of this project, the stakeholder would be a real estate company looking for more insight into this data to better advise their clients.</p><p>I performed some exploratory data analysis (EDA) and, using a correlation heatmap, found the strongest single correlation to the target variable (listing price) was a home’s square footage.</p><p>While square footage is something almost every buyer and seller considers, it’s also something that the stakeholder is likely already quite familiar with. Subsequently, this particular correlation makes for a good benchmark (or “baseline”) regression model. As I construct a new regression model that pertains to my stakeholder and their clients, I’ll compare it to this benchmark.</p><p>I began to go beyond the minimum of the project by looking for outside data that would provide new (or at least less-thoroughly-understood) insight. As a parent with school-age children hoping to purchase a home one day, I though to research common considerations such families often have. However, I can only speak for myself when it comes to what I’d want in a home for my family, so I did some extensive Googling into school-age familial home-buying criteria.</p><p>There were numerous answers here, but consistent desires included good schools, “room to grow” (aka square footage), the number of bedrooms, walkability (specifically parks &amp; trails), and crime levels. The preexisting dataset could only cover square footage and bedrooms. I didn’t have time to do all three of the additional considerations and stay on track, so I chose to incorporate outside data on school districts.</p><h3>Gathering outside data online:</h3><p>I already knew about a reputable site that gathers data and calculates scores on school districts: <a href="http://www.niche.com/">Niche.com</a>. It uses a number of factors, including test scores, safety, diversity, parents reviews, and teacher reviews to calculate a score or “grade” for every district in the US. It uses a normal distribution of grades throughout the nation on a scale of 1–12 mapped onto twelve grade school scores: D-/D/D+/C-/C/C+/B-/B/B+/A-/A/A+.</p><p>Before I could apply these scores, I had to ensure there was a path between the preexisting dataset and outside information. A ‘zipcode’ column in the provided CSV file would allow me to join an exterior Pandas DataFrame to the existing one I had already explored.</p><p>The next issue was finding out more about school districts and the zip codes they encompass in King County, since that information was not in the original data. I found each school district listed on <a href="https://localscape.property/#kingcountyassessor/Education">this part</a> of the King County Tax Assessor’s website, which was simply a list of every school district alongside community colleges and universities. However, this site did not show which zip codes are zoned to the districts.</p><p>At this point, I began a simple Excel spreadsheet that listed each King County school district’s name. Next, I looked for information on district zip codes and found that I could see each one on <a href="https://zipdatamaps.com/">zipdatamaps.com</a>. It didn’t seem like it’d take <em>too</em> long to compile each zip code for all nineteen school districts in King County. However, I learned pretty quickly that not all zip codes are zoned for just one school district; some zip codes contained four or five district boundaries!</p><p>Subsequently, I would need my Excel spreadsheet to contain a row for not just every district, but every district and a zip code it encompassed. In other words, I would have multiple rows for every district, but each one had a unique zip code. This took a little longer, but was definitely manageable.</p><p>Finally, I was prepared to search up each district and match its score (as a number 1–12 correlating to its “grade”) in my spreadsheet. However, I was still faced with the multi-district zip code issue: how would I match each home record on the original dataset to its individual score?</p><p>The short answer is it would take too long to go through every home record in a multi-district zip code and ensure I placed it in the right district: there were over 17,000 such homes! Luckily, the school districts that tended to encompass such zip codes almost always had the same or similar score. Subsequently, I could take the average of each school district score in those zip codes and apply it to the Excel spreadsheet.</p><p>Finally, including the district name column in this spreadsheet wouldn’t help any longer since not all zip codes aligned with just one district, so I removed it and had a final exterior dataset ready, a snippet of which is shown here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*LwaD7iyZ3zWjqhpXfgbJlA.png" /></figure><p>Before I first merged this file with the original one, I wondered exactly <em>when</em> I should merge it regarding a regression model staple: the train-test-split.</p><p>For the uninitiated, this is a measure taken to keep regression results “honest” and avoid “data leakage.” In other words, I would divide my overall dataset into two parts: one for training the regression model and one for testing it, usually along the lines of a 70/30 or 80/20 split.</p><p>It’s critical to treat these two parts separately and to only apply transformations or new features/columns to the training set first. Once complete, only then would I apply the same processes to my testing data to see how the model performs.</p><p>I thought I had to keep the outside data out of my testing data until my training data had been completely finished, but this was a mistake: merging the outside data into the test data later would be very difficult due to the different indexes of both sets. In other words, I’d likely import a lot of the same records into my test set that were already in the training set this way.</p><p>The solution was simple: merge the datasets first and <em>then</em> train-test-split. This was a completely viable option because I had not <em>transformed</em> the data or done any model-construction yet, I was just adding a new column that was simply an extension to every row in the original dataset. Thus, it did not introduce inherent bias that would necessarily upset the train-test-split aspect.</p><p>Now it was only a matter of saving my school district score spreadsheet as a CSV file in my project data folder and then I could import it into my preexisting dataset as an inner Pandas merge:</p><pre>df = df.merge(sds, how=’inner’, on=’zipcode’)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*8UoXP1a4aqwuTABmer9UXg.png" /></figure><p>Hooray: I have a new column in my dataset that may not speak to <em>every</em> buyer client but would certainly concern many. After all, the King County tax assessor’s <a href="https://localscape.property/#kingcountyassessor/Overview">website</a> had also shown how 55% of its population was either under the age of 19 or between 25–44, which would encompass a lot (though not all) of households with school age children.</p><h3>Overcoming data modelling challenges with new data</h3><p>It likely seems unsurprising that school district scores don’t boast as strong a correlation with square footage. The correlation of square footage and listing price (aka my baseline model) shown below resulted in an R-squared score of 0.493. In other words, this correlation was capable of explaining 49.3% of the variance from its line of best fit for the data:</p><pre>import statsmodels.api as sm<br>from statsmodels.formula.api import ols<br>formula = ‘price ~ sqft_living’<br>model = ols(formula=formula, data=training_data).fit()<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*4LzjjVthXzIuG010KROG7Q.png" /></figure><p>Not a particularly strong R-squared score, but a respectable one. Another concern I had was the large <strong>condition number</strong> (highlighted at the bottom of the image above), which isn’t necessarily an alarming issue when it comes to dealing with one predictor/independent variable (in this case, square footage). However, it could belie an issue with that predictor’s distribution, which I had to handle later.</p><p>In the meantime, this issue shouldn’t be addressed in the baseline: it’s merely a benchmark to compare my own model-building to, so I moved on toward constructing a useful linear regression model with school-age family considerations, which showed an…unimpressive R-squared score on its own:</p><pre>formula = ‘price ~ school_district_score’<br>model = ols(formula=formula, data=training_data).fit()<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*sHSX_akT6rYtAFPTSgSNRA.png" /></figure><p>So, school district score alone doesn’t explain a whole lot about listing price, but it’s more than nothing and a place to start. Maybe this was too simple — I’m sure buyers would want to know how much to expect for each district score tier. In other words, what’s the difference between price in districts with an “A-“ versus an “A” score?</p><p>To find out, I used one-hot encoding (aka, making “dummy variables”) for each district score. Using dummy variables is often reserved for categorical variables, where there isn’t an obvious numerical correlation. School districts scores aren’t inherently good candidates for one-hot encoding: you can see that (at least in general), the better the district, the higher the price. However, it would still helpful in this instance to see how each score affected price. Subsequently, I also found a <em>slight</em> increase in the R-squared score to 0.152:</p><pre>school_dist_score_dummies = pd.get_dummies(X_train[‘school_district_score’], prefix=’sds’, drop_first=True)<br>X_train = X_train.drop(‘school_district_score’, axis=1)<br>X_train = pd.concat([X_train, school_dist_score_dummies], axis=1)<br>X_train</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*lwHeKIyesZ8fC7j7YDKrtA.png" /><figcaption>a snippet of X_train showing the new “dummy variables”</figcaption></figure><p>Here we can see how all school districts in King County have a grade of 7 or higher (aka “B-” or higher). Must be nice! The 7/“B-” scores have been dropped here to avoid issues of multicollinearity, so just 8–12 (“B” up to “A+”) appear in the refined DataFrame.</p><p>This was great and all, but I still had a ton of room for improvement to beat the baseline model. I brought in the other two things that matter to parents from the original dataset: square footage (below, the column is titled ‘sqft_living’) and bedrooms, which raised the R-squared score to 0.482, <em>just</em> under the baseline.</p><p>While I could simply add in more columns to raise that score, I only wanted to include information that mattered to the school-age family concerns subset. Another thought was to check on the distribution issue I worried about earlier: what was going on with the listing price column itself? It turns out it was quite positively skewed:</p><pre>from scipy.stats import skew<br>skewness = skew(y_train)<br>print(“skew of y_train, aka ‘price’:”, skewness)<br><br>skew of y_train, aka &#39;price&#39;: 3.82104252</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*3EqDDP_aMkPGc8UUs-7vUQ.png" /><figcaption>skew in the y_train/’price’ target variable</figcaption></figure><p>Subsequently, I had to transform this column’s distribution in order to satisfy the requirements of linear regression: normal distribution. Afterward, I had a strong model that delivered more specific results than my baseline and also featured a much lower condition number!</p><pre>y_train[‘price_log’] = np.log(y_train[‘price’])<br>y_train[‘price_log’].hist(bins=25);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*HD6gmaTQiObmTlV4iV00_w.png" /><figcaption>Yay! The target has been ‘normalized’</figcaption></figure><p>This made for a vastly improved model that beat the baseline’s R-squared score of 0.493 and it’s very high condition number:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*MmUwjHON2A3HQqxTdiQjyg.png" /></figure><p>Cause for celebration — or so I thought until I wondered how I would relay these results to my stakeholder when price is no longer shown in USD, but that the logarithmic transformation of USD.</p><p>It turns out there are a number of ways to “unlog” logged values, but that wasn’t really necessary here. These logs still showed percentages, so I could present my price changes as percentage changes and still convey meaningful results that my stakeholder could understand.</p><p>Below, my stakeholder-friendly presentation of the final results shows coefficients speaking to their own 1% changes. For example, a 1% increase in square footage correlates with a 0.869% increase in price:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*ep9lFH5ih-2E9_bJPJDR7g.png" /></figure><p>While I definitely faced challenges with this project in terms of gathering outside data, incorporating it into my model, and making sure it could be conveyed in a clear, meaningful way to stakeholders and their clients, I also learned a lot about how regression modeling can go so much further than averages, standard errors, and bar charts. It helps not only show the data from the past, but can make helpful predictions about the future.</p><p>As someone who earned his PhD in Music Theory, analyzing music scores and presenting my ideas to classes of undergraduate students or theory professors, only to graduate right as the higher education job market plummeted, it’s exciting to see that I can still put my analytical skills to use in a way that can make a difference to a broader audience.</p><p>Gathering data, making it make sense to either a general or specific group, and then presenting those ideas to a non-technical audience has a lot in common with my past role as a music theorist. I’m excited to continue learning and applying what I know at Flatiron and beyond on my journey to become a Data Scientist!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f0d22c67132" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let the Data Guide You: Moving from the Big Picture to Helpful Insights in Film Revenue]]></title>
            <link>https://medium.com/@joel.mott8/let-the-data-guide-you-moving-from-the-big-picture-to-helpful-insights-in-film-revenue-f7d5ac72cb85?source=rss-a0581c989279------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7d5ac72cb85</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[major-life-changes]]></category>
            <category><![CDATA[box-office]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Joel Mott]]></dc:creator>
            <pubDate>Tue, 02 Aug 2022 20:23:30 GMT</pubDate>
            <atom:updated>2022-08-02T20:23:30.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-OwPhiGidqF1lj8J" /><figcaption>Photo by <a href="https://unsplash.com/@iam_os?utm_source=medium&amp;utm_medium=referral">iam_os</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>My first project in the Data Science program at Flatiron School puts some newly-acquired Python, Pandas, SQL, and visualization skills to work with a pitch to an imaginary, emerging Microsoft film studio. I take a bunch of data from <a href="https://www.imdb.com/">IMDb</a> and <a href="https://www.the-numbers.com/">the-numbers.com</a>, then turn it into three concise business recommendations on the kinds of films that tend to earn a strong ROI (return on investment).</p><p>In other words, what kinds of movies would a big corporation like Microsoft want to make that would earn big box office returns? Whatever I recommend, I need to present my findings with minimal jargon, maximum clarity, and concise yet insightful visuals.</p><p>This isn’t my first rodeo when it comes to taking disparate data and making it easy (and hopefully interesting) for a non-technical audience. While earning my Master’s and PhD in music theory, I presented at local and national conferences.</p><p>While the research methods and tools may have changed with my transition to Data Science, the big picture is similar: find something interesting to say, build on what others have said before, and present your ideas as clearly as possible.</p><p>I found (what I hope are) interesting findings when it comes film revenue and genre, release dates, and directors. I used the datasets others have built and turned to online resources to overcome challenges. Finally, I strove to convey those ideas without any technical assumptions about my audience, instead creating intuitive, straightforward graphs and translating results into easy-to-read slides.</p><p>In this post, I’ll cover what I learned about using Pandas and SQL to move from the big picture of film ROI to three recommendations on genres, release dates, and directors. Along the way, I discuss refining my questions based on the datasets and overcoming some challenges with my ever-evolving Googling skills. Finally, I’ll show how I turned all this movie data into cool graphs that don’t overwhelm an audience.</p><h3>Grasping the big picture</h3><p>First, I had to access the two datasets. I import the Pandas library to read the-numbers.com CSV file (which just took one line) and establish a SQLite connection to access the IMDb database.</p><pre>import pandas as pd<br>import sqlite3</pre><pre>conn = sqlite3.connect(“im.db”)</pre><pre>df = pd.read_sql(”””SELECT name FROM sqlite_master WHERE type = ‘table’;”””, conn)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*moKTYndb7nao7N5AuU0npQ.jpeg" /><figcaption>The tables in the IMDb database</figcaption></figure><p>For the sake of concision (and since this post isn’t about data cleaning), I’ll skip to the final, combined dataset I used. In brief, it’s a Pandas DataFrame that only shows the information I want from both the-numbers.com and IMDb. Here’s a snapshot showing all the columns and then the first and last five rows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4jaYBX0TizIweB5Zk4RGgA.jpeg" /></figure><p>This is the “big picture” dataset I’m going to draw three concise business recommendations from. Reading any one row seems easy enough, but gleaning some insight from 1,949 rows in this format isn’t so simple. The first few visualizations below wouldn’t be a part of my presentation, but they do help me see an actual “big picture” from each row.</p><p>The first is a simple histogram showing the distribution of budgets in my dataset. In the code below, it’s worth noting that I’m referring to this refined, cleaned DataFrame as “filtered_df” to distinguish it from earlier dataset drafts.</p><p>I began by importing matplotlib and setting it up to work within a Jupyter Notebook (%matplotlib inline) and then I set up the histrogram along with axis labels.</p><pre>from matplotlib import pyplot as plt<br>%matplotlib inline</pre><pre>fig, ax = plt.subplots(figsize =(10, 7))<br>ax.hist(filtered_df[&#39;production_budget&#39;])<br>plt.xlabel(&#39;budget in hundreds of millions&#39;)<br>plt.ylabel(&#39;no. of movies&#39;)<br>plt.axvline(filtered_df[&#39;production_budget&#39;].mean(), color=&#39;k&#39;, linestyle=&#39;dashed&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*-KUZyfHnuHW9w0FIIPpTMQ.jpeg" /></figure><p>As a student still learning the ropes, you better believe I didn’t have the code for that cool dashed vertical line showing the average in my back pocket. This one of many consultations with Stack Overflow that helped me along. Credit goes to <a href="https://stackoverflow.com/users/1217358/warren-weckesser">Warren Weckesser</a> and his answer on <a href="https://stackoverflow.com/questions/16180946/drawing-average-line-in-histogram-matplotlib">this post</a>. Below, I did the same thing for the ROI column and got this graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*wYeCk31hrpohUS-rRa-dwQ.jpeg" /></figure><p>So far, I’ve gone from an overwhelming amount of rows in a DataFrame to knowing that the average film in my dataset (movies with budgets over $2.5 million dollars and having complete information between both datasets) has an average budget around $43 million and an average ROI around $87 million.</p><p>However, this was simply my first impression of what to compare; what other patterns might lie in my dataset that I had yet to uncover? The scatter matrix might help reveal underlying correlations I hadn’t considered. This tool cross-references all numeric columns with scatter plots and offers histograms when they meet.</p><p>The following code resulted in a scatter matrix based on my filtered DataFrame with the “alpha” parameter referring to the transparency of individual points (so clustered points show in a darker hue). Also worth noting is my reduction of release dates down to the month of the year so I could move from 365 potential times of year to just twelve to help with concision.</p><pre>pd.plotting.scatter_matrix(filtered_df, alpha=0.2, figsize=(20,20));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQvA9doIsZJyc91fQp5UUw.png" /></figure><p>This chaotic smattering of graphs seems a little chaotic at first; after all, it’s hard to even decipher the labels on the x and y axes. However, scatter matrices help put the “big picture” in perspective; I’m just looking for any emergent patterns among these numeric columns. I’ve already seen the budget/ROI correlations, but another pattern that stands out is the release month and ROI, so I take a closer look:</p><pre>iltered_df.plot.scatter(x=&#39;release_month&#39;, y=&#39;ROI&#39;, c=&#39;g&#39;, alpha=0.2, figsize=(10,10));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*_mknBeviBdf9xSesOblGvw.jpeg" /></figure><p>Now I’m starting to see further into the big picture; it looks like more movies that garner higher ROI’s tend to be released between April-July and then again in November-December. However, this is just an imprecise guess on a preliminary observation. How can I start to make more precise insights on this data?</p><h3>Moving towards specific business recommendations</h3><p>This is where I start to isolate individual columns and make categorical bar charts. In this case, I wanted to know exactly what the average budget and ROI was <em>per</em> <em>release month</em>. After all, could these higher ROI values simply be a by-product of more films being released during those months?</p><p>I put my Pandas skills to work and made a sort of pivot table; a new, reorganized perspective on my primary DataFrame which was now organized by averages among release month:</p><pre>avg_monthly_ROI = filtered_df.groupby(&#39;release_month&#39;).mean().sort_values(&#39;release_month&#39;).reset_index()</pre><p>Specifically, the “groupby” function takes in many rows and produces one summary row. In this case, I’m “regrouping” my dataset by release month, then specifying I want the average of each month with “.mean()” and sorting those results by the month in the year (as opposed to the lowest-to-highest-grossing month that Pandas would normally default to). This new take on my dataset could then produce the following bar graph that builds on the previous scatter matrix:</p><pre>avg_monthly_ROI.plot(x=&#39;release_month&#39;, kind=&#39;bar&#39;, figsize=(10,10))<br>plt.title(&#39;average film budget and ROI per month&#39;, fontsize=20)<br>plt.xlabel(&#39;month of year&#39;, labelpad=20, fontsize=17)<br>plt.ylabel(&#39;ROI (in hundred of millions USD)&#39;, labelpad=20, fontsize=17)<br>plt.xticks(rotation = 0)<br>plt.savefig(&#39;average_ROI_per_month.png&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*PFhO-lR_zdNzuB6ReaiE0A.jpeg" /></figure><p>Neat! Now I can refine my scatter matrix observations: even though April had seemed to hold promise for a number of high-ROI films, it doesn’t really compare to May-July or the holiday season in November-December. However, all I’ve really done so far is confirm some well-known film standards: summer blockbusters and holiday seasons. What more can I do to build on these industry norms?</p><p>This is where I began to delve into other factors besides release dates; specifically, what roles did genre and director play when it comes to ROI? Do certain genres and directors seem to garner more revenue?</p><p>I continued down the path of reorganizing my data and producing visualizations to help make sense of it. Returning to my main DataFrame, the genre column was more than a little eclectic. Some films had a singular genre listed, others had two or three. I employed Pandas’ value counts tool to see how many unique genre descriptors were used:</p><pre>filtered_df[&#39;genres&#39;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*_HNvDWjN7gVVauSa9HH1Bg.jpeg" /></figure><p>Wow, 294 unique genre listings! No one has time for that; this definitely won’t help a Microsoft executive make decisions about film-making. How can I reduce these descriptions down in a meaningful way? My first thought was to prune them down to their first descriptive term. I took a sampling of films and asked myself whether the first genre listing fit as well or better than the other one (or two) and, for the most part, the first descriptor seemed to do the trick.</p><p>Consequently, I “stripped” the multi-genre listings apart and then dropped all but the first term. The “str.split” used commas to separate each word and then the [0] locater only took the first result (aka the first descriptor whether there was one or three):</p><pre>filtered_df[&#39;genres&#39;] = filtered_df[&#39;genres&#39;].str.split(&#39;,&#39;, expand=True)[0]</pre><p>This took 294 genres down to 19. Some genre listings only held a handful of films (two or seven) and I feared they would throw off average ROI data and, honestly, they seemed too obscure for a major emerging film studio to consider, so I dropped them along with any other genre that tended to lose money. This resulted in a final tally of twelve different genres, which in turn produced a more meaningful and concise graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*-Nu695KqPNl2C5ud_l-Otw.jpeg" /></figure><p>Now I’m getting closer to the kind of concise visuals worthy of presenting to my audience: the kind of information they might find compelling but shown in a concise manner. However, I’m sure they would want more precise insights: even if adventure, animation, and action movies seem to bring home the big bucks, what more in the way of specifics can I offer?</p><p>This is where my two further business recommendations came into play: release month and director. First, I tackled what I already had a grasp on and regrouped genres by their respective release months. I started with the top-earning adventure genre and worked all the way through to crime films to show which months tend to return the highest revenue for that respective genre.</p><p>Here’s the initial regroup-and-graph routine for adventure. I simply replaced the genre name in this code to produce results for each of the other eight genres in the graph above:</p><pre>adventure_movies = filtered_df.loc[filtered_df[&#39;genres&#39;] == &#39;Adventure&#39;]</pre><pre>adventure_ROI_by_month.plot(x=&#39;release_month&#39;, y=&#39;ROI&#39;, kind=&#39;bar&#39;, color=&#39;tab:blue&#39;, figsize=(12,9))<br>plt.title(&#39;average adventure film ROI per month&#39;, fontsize=20)<br>plt.xlabel(&#39;month of year&#39;, labelpad=20, fontsize=17)<br>plt.ylabel(&#39;ROI (in hundred of millions USD)&#39;, labelpad=20, fontsize=17)<br>plt.xticks(rotation = 0)<br>plt.savefig(&#39;average adventure film ROI per month.png&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*1yvzmRzXvmFm5XiTpqPnuA.jpeg" /></figure><p>Now I can go beyond simply recommending each genre to showing the optimal months for its release. In my presentation, simply cycling through each genre only to circle back to optimal directors seemed redundant, so I grouped film genres by directors who, in turn, seemed to garner the highest ROIs, and reproduced that list <em>alongside</em> each graph.</p><p>This proved to be quite the challenge; I wasn’t just reorganizing my dataset by one element as I had done previously with genre; I wanted both genre <em>and</em> the respective directors which were <em>then</em> sorted by highest-to-lowest ROI. I had to turn to Google again, and found helpful insights from <a href="https://sparkbyexamples.com/">sparkbyexamples</a> on<a href="https://sparkbyexamples.com/pandas/pandas-sort-dataframe-by-multiple-columns/#:~:text=You%20can%20sort%20pandas%20DataFrame,descending%20and%20True%20for%20ascending."> this post</a>, where I learned how to group by multiple columns:</p><pre>directors_by_genre = filtered_df.groupby([&#39;genres&#39;, &#39;director&#39;]).agg({&#39;ROI&#39;: sum}).reset_index()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*_rQadfnVvA8icVHsKMtdRQ.jpeg" /></figure><p>Now I could produce presentation slides with graphs that showed each genre’s breakdown by release month and an accompanying list of its top-ten most promising directors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hgjhWHuwwMpFUD0Ys_1YYQ.jpeg" /></figure><p>Now a Microsoft film studio executive has a concise list of top-earning genres, when to release each one, and a group of directors to consider recruiting. Even though the films in this dataset were all relatively recent, I went though each list to make sure each director was still alive and not decisively retired.</p><h3>Learning about myself during this project and my first phase at Flatiron</h3><p>This project was a fun way to put my skills to work alongside my background of presenting on complex data. Data Science isn’t something I originally set out to do; I wanted to be a music theory professor. Over the course of earning my PhD at The University of Texas at Austin, the higher education faculty job market went from somewhat risky to dismal, and now those jobs are paying less and asking more from faculty. Subsequently, I’m grateful for the opportunity to use my analytical leanings and educational background in a field like Data Science where I can make a big difference helping make sense of big data and look forward to learning more at Flatiron.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7d5ac72cb85" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>