<?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 Will Stauffer-Norris on Medium]]></title>
        <description><![CDATA[Stories by Will Stauffer-Norris on Medium]]></description>
        <link>https://medium.com/@willstauffernorris?source=rss-2bebc4143b5b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Gm9kduCbdd6Q30AJdGmHZg.jpeg</url>
            <title>Stories by Will Stauffer-Norris on Medium</title>
            <link>https://medium.com/@willstauffernorris?source=rss-2bebc4143b5b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:11:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@willstauffernorris/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[Predicting the flow of the South Fork Payette River using an LSTM neural network]]></title>
            <link>https://medium.com/data-science/predicting-the-flow-of-the-south-fork-payette-river-using-an-lstm-neural-network-65292eadf6a6?source=rss-2bebc4143b5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/65292eadf6a6</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[hydrology]]></category>
            <category><![CDATA[idaho]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Will Stauffer-Norris]]></dc:creator>
            <pubDate>Wed, 09 Sep 2020 22:44:59 GMT</pubDate>
            <atom:updated>2020-09-22T00:53:39.748Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to make a prediction with time-series data using machine learning.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m-3eA-_ns9fzRQDOh0LjSw.jpeg" /><figcaption>Idaho has some of the most beautiful rivers in the world! (📷 Will Stauffer-Norris | East Fork South Fork Salmon River)</figcaption></figure><h3>TL;DR:</h3><p>I made an LSTM neural network model that uses 30+ years of weather and streamflow data to quite accurately predict what the streamflow will be tomorrow.</p><h3>The problem with river forecasts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4GpE16WH2eL8Fh71L0Z-A.jpeg" /><figcaption>Water meets Idaho granite. 📷 Will Stauffer-Norris</figcaption></figure><p>The main reason I practice data science is to apply it to real-world problems. As a kayaker, I have spent many, many hours poring over weather forecasts, hydrologic forecasts, and SNOTEL station data to make a prediction about a river’s flow. There are good places out there that make this prediction- NOAA runs prediction centers throughout each major river basin in the country, <a href="https://www.nwrfc.noaa.gov/river/station/flowplot/flowplot.cgi?lid=PRLI1">including the South Fork.</a></p><p>But these forecasts often fall short. In particular, I’ve noticed that the forecasts are susceptible to major rain events (flashy rivers in the Pacific Northwest are notoriously hard to predict), and the forecasts are typically only put out once or twice per day, which is often not frequent enough to react to rapidly changing mountain weather forecasts. NOAA also only gives forecasts on a select group of rivers. If you want a forecast for a smaller or more remote drainage, even if it’s gauged, you’re out of luck.</p><p>So I’m setting out to create a model that will meet or exceed NOAA’s forecasts, and build models for some drainages that are not covered by NOAA.</p><p>To start out, I’m benchmarking my model against an industry-standard model created by <a href="https://hydroforecast.com/case-study-south-payette">Upstream Tech</a>.</p><p>The South Fork Payette is a great place to start, for several reasons:</p><ol><li>The South Fork above Lowman is undammed, so the confounding variables of reservoirs are avoided.</li><li>The USGS operates a gauge on the South Fork, NOAA has weather stations and a river forecast, and there are SNOTEL sites in the basin. There is a lot of easily accessible data to start with.</li><li>I used to teach kayaking on the Payette and I’ve paddled almost every section of the river system, so I know the region and its hydrology well!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n9JdBGu-BVpDvX_rvCGJpg.jpeg" /><figcaption>The North Fork of the Payette is legendary among kayakers. 📷 Will Stauffer-Norris</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SdSmuOpuctrLqvMbW64Emg.jpeg" /><figcaption>Idaho’s rivers are always in flux. 📷 Will Stauffer-Norris</figcaption></figure><h3>The data</h3><p>The Upstream Tech model I’m benchmarking against uses meteorological as well as remote sensing data to build the model. I haven’t incorporated any satellite imagery yet, although this is the next development in my model.</p><p>To start, I <a href="https://www.ncdc.noaa.gov/cdo-web/datasets#GHCND">downloaded daily meteorological data from NOAA </a>from a weather station on Banner Summit, which is at the headwaters of the South Fork. Eventually, I will incorporate more stations into my forecast, but I wanted to keep it simple for this first iteration. The metrics measured are:</p><ul><li>Precipitation</li><li>Temperature (min and max)</li><li>Snow Depth</li><li>Snow Water Equivalent</li><li>Day of Year.</li></ul><p>These are my predictive features. The data go back to 1987.</p><p>Next, I went to the <a href="https://waterdata.usgs.gov/usa/nwis/uv?13235000">USGS gauge at Lowman, Idaho</a>, and grabbed the daily discharge for every day since 1987. In a more refined model, I might get hourly data, but I decided daily was good enough for this iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Ylarc0MNRvdUCa70MFd5Q.png" /><figcaption>Discharge in CFS at the South Fork Payette at Lowman, 1987–2020</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-QnKK0S2kdM8sECYGg_hg.jpeg" /><figcaption>Rocky Mountain rivers are used for recreation as well as hydropower and irrigation. 📷 Will Stauffer-Norris</figcaption></figure><h3>Wrangling</h3><p>I merged the two datasets using pandas, creating a dataframe with features and a target variable (discharge).</p><p>There were a few missing values in the meteorological data, so I imputed some values to replace the NaNs. I created a correlation matrix to see if any values were correlated and could be dropped. I decided to get rid of the average temperature reading, as there were already min and max temperature features.</p><p>With the data cleaned up, it was time to start modeling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oyR25YRTVhm0twgdFoqWJg.jpeg" /><figcaption>Water in the American West is measured down to the last drop. 📷 Will Stauffer-Norris</figcaption></figure><h3>The model</h3><p>I started with just a baseline- what would happen if you just guessed the average discharge — about 800 CFS — of the South Fork every time? It turns out that the average error is about 600 CFS. This is unacceptably large, as it’s almost the flow of the river itself!</p><p>I knew I could do better- a lot better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1RsSnnvefQmrLhPv7_bZQQ.png" /><figcaption>The red line is the baseline prediction of about 800 CFS. Period is the year 2019.</figcaption></figure><h3>Linear regression</h3><p>Linear regressions are very simple, but not a bad place to start getting my hands dirty. I used one, then two, then all the features to see how well they would predict the flow of the South Fork. The answer is- pretty badly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HsF3rx2ptDdlNDYBORN4WQ.png" /><figcaption>A single feature linear regression based on the “Day of year” feature is just a sloped line that resets each year. Not too useful.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0H6B_hzsIWfiHEs0x_hlOA.png" /><figcaption>A two feature linear regression (based on “Day of year” and “Temperature” is slightly more nuanced.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*roWMA6fsWX0jVeJOuN5M_g.png" /><figcaption>Using all eight features in a linear regression isn’t that much better.</figcaption></figure><h3>Random forest</h3><p>OK, so linear regressions aren’t known to be the most powerful machine learning models out there. Time to bring out some more complicated stuff. I put all the features in a random forest model. I could have spent longer tweaking the hyperparameters, but I decided to just use the stock scikit-learn settings, with the exception of using 100 estimators.</p><p>The results were a striking improvement- the random forest didn’t quite capture the nuances of the runoff, but it did track the general seasonal trend much better than a linear regression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U9TgVFg_Sy6Gp8mJTaXKIw.png" /><figcaption>A random forest model- getting closer to a decent prediction!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RasfdFUCXjssVorIHZ4CTQ.jpeg" /><figcaption>The Sawtooth Mountains, headwaters of the South Fork Payette. 📷 Will Stauffer-Norris</figcaption></figure><h3>LSTM neural network</h3><p>Now time for the newest, biggest and baddest model- the neural network. LSTM neural networks can be useful for time series prediction, although they have some limitations. I used the Keras LSTM model.</p><p>The model has some quirks- you must wrangle data in a very specific way to make it fit- and I found a few tutorials that were invaluable (the <a href="https://keras.io/examples/timeseries/timeseries_weather_forecasting/">Keras documentation</a> and <a href="https://machinelearningmastery.com/multivariate-time-series-forecasting-lstms-keras/">Machine Learning Mastery</a>).</p><p>I trained the model on the period 1987–2015 and evaluated it on the years 2016–2020. In later iterations, I will look more into better validation techniques for time series data, such as nested cross-validation.</p><p>Eventually, I managed to get a model that had a 98% R² value and a mean absolute error of only ~50 cfs! This is head and shoulders better than the other (quite simple) models I tried.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KLOxIFLf49r2WlfaQ3fhFw.png" /><figcaption>My model performance over time. The LSTM is a clear winner!</figcaption></figure><p>The craziest part is that I haven’t even incorporated any other weather stations or remote sensing data into the neural network.</p><p>I suspect that the previous day’s flow is contributing most to the prediction because the predicted peaks seem to lag the actual peaks by about a day.</p><p>I’d like to do more investigation into how exactly the LSTM is coming up with the prediction, and visualize the feature importances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NNBOVTxs86HiDESM8VhgIg.png" /><figcaption>My LSTM model for the 2019 spring runoff (lead time one day).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBqCYGMsWb93b1YZYPVgMA.jpeg" /><figcaption>Like the Idaho backcountry, there is always something more to explore with machine learning. 📷 Will Stauffer-Norris</figcaption></figure><h3>Next steps</h3><p>Although my model performed decently well a day in advance, I’d like to model the flow in a longer forecast range (2–10 days out). I’ve started doing this with the LSTM, but I need to spend some more time on it.</p><p>I also want to incorporate more weather stations. NOAA operates several more stations in the area, and it will be quite interesting to see how the position of the station in the watershed changes the prediction.</p><p>I also want to incorporate satellite imagery as a feature. This is quite a bit more complicated, due to the large file sizes and acquiring the images in the first place. I’ve started building a pipeline to ingest Google Earth Engine data into my machine learning models.</p><p>Finally, looking at the model, it’s able to predict very well the down-legs of the hydrograph- but so can I, just intuitively. The model is less able to predict abrupt upswings due to rapid snowmelt or a rain event. These are the kinds of events where prediction is critically important for hydropower, flood control, and public safety.</p><p>As always, there is more work to do!</p><p>Thanks for reading, and stay tuned for Part 2, where I will go through some of these next steps, especially incorporating satellite imagery.</p><p>For the latest on my predictions, check out <a href="http://www.rivers.fyi/">rivers.fyi,</a> where I’m putting LSTM neural networks into production for multiple rivers.</p><p>You can view the notebooks I used on Github <a href="https://github.com/willstauffernorris/streamflow_predictions">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65292eadf6a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/predicting-the-flow-of-the-south-fork-payette-river-using-an-lstm-neural-network-65292eadf6a6">Predicting the flow of the South Fork Payette River using an LSTM neural network</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Naive Bayes Classifier from scratch]]></title>
            <link>https://medium.com/@willstauffernorris/creating-a-naive-bayes-classifier-from-scratch-f3df2b398d0e?source=rss-2bebc4143b5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3df2b398d0e</guid>
            <dc:creator><![CDATA[Will Stauffer-Norris]]></dc:creator>
            <pubDate>Thu, 30 Jul 2020 22:26:02 GMT</pubDate>
            <atom:updated>2020-07-30T23:44:23.859Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lhErprYdNmM7KnKjnRZXPw.jpeg" /><figcaption>It can be used to classify stars!</figcaption></figure><p>As a data scientist, it’s fairly simple to bring in a huge number of tools with one very simple line of code. If I want to try running a simple classifier on a dataset, I quickly type:</p><pre>from sklearn.naive_bayes import GaussianNB</pre><p>This is one of the best features of using Python for data science- taking advantage of the massive open-source libraries available. But what’s actually going on under the hood? I set out to write this Naive Bayes Classifier from scratch to better understand it.</p><p>The first step was to understand what’s actually going on.</p><h4>Understand</h4><p>The Naive Bayes Classifier is a simple supervised machine learning algorithm that can predict which class a given data point will belong to. Its simplicity means that it’s fast, so it works well on a large dataset. It also generalizes well (underfits). The “naive” is due to its assumption of independence of the features in a dataset. This is not usually true in real life, but it simplifies the algorithm and tends to work well in real datasets.</p><pre>P(class|data) = (P(data|class) * P(class)) / P(data)</pre><p>P(class|data) is the probability that the given data point is in a certain class. Eventually, we want to find the class with the highest probability.</p><p>P(data|class) is the probability that the data exists in the given class.</p><p>P(class) is the prior probability. Regardless of the given data, if that class represents 30% of the data, then this will be 30%.</p><p>P(data) is the probability of observing the data. For this classifier, we’ll ignore this denominator because it’s constant as we compare one data point across different classes.</p><p>I understand it better with examples. Say you have symptoms of a rare cancer, and everyone who has this cancer has this symptom. How likely is it that you have the cancer?</p><pre>P(Cancer|Symptoms) = P(Symptoms|Cancer)*P(Cancer)/P(Symptoms)</pre><p>P(Symptoms|Cancer) = 1. The probability that you have symptoms given that you have the rare cancer is 100%</p><p>P(Cancer) = 1/1000. This is a rare cancer, so chances are you don’t have it.</p><p>P(Symptoms) = P(Symptoms|Cancer) * P(Cancer) + P(Symptoms|Non-cancer) * P(Non-cancer)</p><p>The first part is the same as above, then we must add the probability that you have the symptoms if you don’t have cancer (1/100) multiplied by the probability that you don’t have the rare cancer (999/1000)</p><p>This adds up to:</p><pre>1 * .001 / 1 * .001 + .01 * .999</pre><pre>== .001 / .01099</pre><pre>== .09 ## Nine percent</pre><p>We will use this theorem to figure out the probability that a data point belongs to a certain class.</p><h4>Plan</h4><p>After reading through the conceptual ideas behind the Naive Bayes Classifier, I was ready to dive into the planning process.</p><p>In this ‘Plan’ phase, I focused on translating the abstract math into pseudocode to form an outline of my algorithm.</p><p>I wrote out all the concepts and tried to think of the Python implementation. This proved to be trickier than I originally thought because I was trying not to use any other libraries except NumPy.</p><p>After wrestling with the problem for a while, I also looked up the source code for the scikit-learn implementation as well as a few other implementations. This proved to be extremely helpful, especially for the Gaussian element of the algorithm.</p><p>Time to jump into writing real Python code!</p><h4>Execute, Part 1</h4><p>There are several parts to this problem:</p><h4>1. Separate the data by class.</h4><p>This allows the algorithm to see how the attributes of each class differ.</p><h4>2. Get summary statistics.</h4><p>After separating the classes, the algorithm can calculate the mean and standard deviation for each class.</p><h4>3. Calculate summary statistics for each class.</h4><p>Now the algorithm has mean and standard deviation for each attribute of each class.</p><h4>4. Create a Gaussian probability function.</h4><p>This takes in a data point and estimates how likely it is to occur, given a normal distribution of data. This is best explained with an example:</p><p>If the mean is 0 and the standard deviation is 1, and you’re estimating the probability of a -1 occurring, the probability is .24. A 1 would have the same probability as -1. A 0 has a .39 chance of occurring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*tBF9lMwbdvX4QxZyEyWltQ.png" /><figcaption>If you look at the red line (with a standard deviation of 1), you can see that the mean has a 39% chance of occurring, and a 1 has a 24% chance.</figcaption></figure><p>This normal distribution of probability will help in our final step.</p><h4>5. Calculate the probability that a given data point belongs in each class.</h4><p>Remember Baye’s Theorem above? We’re going to put it in code.</p><pre>P(class=1|attribute=A, attribute=B) = P(attribute=A|class=1) * P(attribute=B|class=1)* P(class=1)</pre><p>This is slightly different from the first formula because we’re comparing the probability that the data belongs to each class to each other class, rather than the raw probability (i.e. we remove the denominator).</p><p>This formula also calls out specific attributes. In most datasets, there is more than one attribute — there can be hundreds. We have to calculate the probabilities for each attribute in each class.</p><p>This is just doing the same steps above for each data point instead of a single data point. This becomes the .predict method in the class and returns a list of predictions.</p><p>Now, let’s plug in a dataset into this algorithm.</p><p>I started with the very simple (and overused) Iris dataset to test my implementation of the Naive Bayes Classifier against the Scikit learn version.</p><p>After preprocessing the data to turn categorical variables into numeric variables, and splitting the dataset into an X_train, X_test, y_train, and y_test pieces, I was ready to test the classifier.</p><p>Given the lack of hyperparameters to tune, it’s only a few lines of code to run the classifier.</p><p>The sci-kit learn version:</p><pre>gnb = GaussianNB()<br>gnb.fit(X_train, y_train)<br>y_pred = gnb.predict(X_test)</pre><p>I instantiate the object, call the .fit and .predict statements, and it returns a list of predicted values.</p><p>I set up my Naive Bayes class to take the same inputs as the sklearn version, so the code looks very similar:</p><pre>wills_gaussian = Gaussian_Naive_Bayes()<br>wills_gaussian.fit(X_train, y_train)<br>y_pred = wills_gaussian.predict(X_test)</pre><p>Depending on the random seed picked in the train/test split, my classifier performed the same or slightly worse on the data. I’m still investigating what the difference is, but it does prove the point that it’s usually better to use an algorithm that has been extensively tested and modified by the open-source community, rather than one that was written in a day or two!</p><p>After figuring out the basics using the Iris dataset, I tried with a harder dataset: classifying stars based on a large number of features.</p><p><a href="https://www.kaggle.com/deepu1109/star-dataset">https://www.kaggle.com/deepu1109/star-dataset</a></p><p>This dataset has six possible classifications- but only 240 data points, which is a tiny dataset for training. The Naive Bayes classifier still managed to classify most of the test data correctly, with an 85% accuracy.</p><p>I haven’t tested this dataset on a neural network, but my intuition is that a NN would perform worse, due to the lack of training data.</p><p>Github repo: <a href="https://github.com/willstauffernorris/Naive_Bayes_Classifier">https://github.com/willstauffernorris/Naive_Bayes_Classifier</a></p><p><em>Originally published at </em><a href="https://github.com/willstauffernorris/Naive_Bayes_Classifier/blob/master/README.md"><em>https://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3df2b398d0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Street Smarts-  Price and  CO2 of any car]]></title>
            <link>https://medium.com/@willstauffernorris/street-smarts-price-and-co2-of-any-car-2937ee2f169f?source=rss-2bebc4143b5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2937ee2f169f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Will Stauffer-Norris]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 19:57:10 GMT</pubDate>
            <atom:updated>2020-07-28T19:57:10.425Z</atom:updated>
            <content:encoded><![CDATA[<h3>Street Smarts</h3><p>Street Smarts was my biggest data science project to date. In this post, I’ll lay out some of the challenges in successes that we had during eight weeks of building Street Smarts. <a href="https://www.streetsmarts.online/">https://www.streetsmarts.online/</a></p><h3>The product</h3><p>Street Smarts is a website that allows a user to input the make, model, and year of a car, and learn about the cost to own and carbon emissions of that vehicle. You can also compare up to three different vehicles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*6QsrMfEjGQQD4UDA.gif" /></figure><h3>The team</h3><p>We had a cross-functional team of nine people- web developers, data scientists, a UX designer, and a team lead. This was the first major coding project that most of us had worked on, and we were all thrown together as a team for the first time. Additionally, most of us had just learned to code four months prior, as we were all at a similar stage in Lambda School.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GEoBu9vae_0pfp7G.png" /></figure><h3>Research &amp; Planning</h3><p>We began this project from scratch, with input from a Lambda School stakeholder who guided the vision for the project. After doing some research into existing car price websites like Kelley Blue Book and Cars.com, we realized that these websites didn’t have any metric for the carbon emissions of vehicles. We decided that price and carbon emissions were the most important metrics to display on Street Smarts, as we were filling a gap in the market.</p><p>We broke the project down into the web team (front and back end), UX, and my team, data science.</p><h3>Data</h3><p>The first challenge for the data science team was to source our data. We wanted a wide variety of cars for a user to choose from, so we found a dataset created by the U.S. Environmental Protection Agency (EPA). This dataset contained over 40K models of vehicles from the last 40+ years, along with attributes such as miles per gallon, fuel type, number of engine cylinders, and more. The one thing it was missing is the price.</p><p>To get price estimates for each vehicle, we sourced a dataset from Kaggle that contained a half million Craigslist car listings. This had a big advantage in that it was scraped just a few months prior, so we knew the prices were about as accurate as we could get. The huge disadvantage, however, was that the car models from the EPA dataset and the car models from the Craigslist dataset didn’t match exactly.</p><h3>Machine Learning Model</h3><p>We wanted to predict the price of a car based on the make, model, and year. We used our Craigslist dataset with 500K rows.</p><p>To start, we took the mean average error of the mean price of our whole dataset- around $8k. If you just guessed the mean value, you would be off on average by $8000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TVH-79aOZOhKXyxp.png" /></figure><p>As we iterated on the model, we tried linear regressions, random forests, and neural networks. Ultimately, we arrived at an MAE of around $2k using a random forest. Another consideration was our model size- for example, we were unable to deploy giant 1GB neural networks to AWS. When considering technical limitations, user load times, and performance, the random forest was our best performer.</p><h3>Heroku and Flask</h3><p>Now that we had a model, we needed to deploy it live to production. The team was experienced with Heroku and Flask, so for our first iteration, we chose a Flask app to create an API that would return data to the web team. We got inputs of make, model, and year, and we would return a predicted price.</p><p>To get those inputs, however, we needed a database of all the possible makes, models, and years. To do this, we created a Postgres database on Heroku that we populated with the data from the EPA dataset.</p><h3>AWS Elastic Beanstalk and FastAPI</h3><p>But there were a few limitations to the free tier of Heroku that we were using, and we wanted to learn AWS systems, so we decided to transition our project over to AWS. We created a database in AWS Relational Database Service (RDS) and populated it with our EPA dataset. We also deployed to production using AWS Elastic Beanstalk and FastAPI, which has some great built-in documentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HhRRqdhcyKaMSexX.png" /></figure><p>The auto-generated documentation of FastAPI allows you to test different inputs and make sure the API is functioning properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-3rutK616o6OaDaC.png" /></figure><p>The data science API returned these values for each car that a user selects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jPO1QUkFEmYLLPG8.png" /></figure><p>The Elastic Beanstalk deployment came with many challenges, such as trying to deploy larger machine learning models and environment issues. We closely monitored the health of the application as well as dug through the logs to troubleshoot.</p><h3>Challenges</h3><p>The biggest challenge of our project came when trying to merge the two datasets. The EPA data was very complete and well structured but lacked price. The Craigslist data had the real-world price, but due to varying user inputs, was messy.</p><p>The solution came in the form of a magic library called Rapid Fuzz. This would take the make, model, and year that a user selected from the drop-down menus (populated from the EPA dataset) and try and find the closest match in the Craigslist dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_mEWytMNvhug0ksf.png" /></figure><p>The Rapid Fuzz library does this with a process called fuzzy string matching that uses the Levenshtein Distance to calculate the differences between strings. <a href="https://en.wikipedia.org/wiki/Levenshtein_distance">https://en.wikipedia.org/wiki/Levenshtein_distance</a></p><p>The results are not always perfect, but it was the best way we could find to merge these two datasets.</p><p>Another major challenge was selecting a limited range of inputs. Our model was better when using all the available features, such as location, odometer mileage, and condition, but these data had a lot of missing values and ultimately only improved the model by about 12–15%. We decided to limit our inputs to just make, model, and year, mainly to improve the user experience and increase the speed at which a user could find the information they were looking for.</p><h3>Conclusion</h3><p>Street Smarts was an incredible eight-week project with a fantastic team. We learned a ton, solved real problems, and got our hands dirty in the AWS ecosystem.</p><h3>Street Smarts Demo</h3><p>Click to view YouTube video.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*0ge-s2xll-A9Yw_7.jpg" /></figure><p><em>Originally published at </em><a href="https://willstauffernorris.github.io/2020-06-24-Streetsmarts/"><em>https://willstauffernorris.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2937ee2f169f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ DeepTunes- Incognito Tab For Your Spotify]]></title>
            <link>https://medium.com/@willstauffernorris/deeptunes-incognito-tab-for-your-spotify-b8cdc815eaef?source=rss-2bebc4143b5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8cdc815eaef</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <dc:creator><![CDATA[Will Stauffer-Norris]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 19:54:43 GMT</pubDate>
            <atom:updated>2020-07-28T19:54:43.874Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OF55Z77J5KqAbn8M6tkhaA.png" /><figcaption>Deeptunes home page</figcaption></figure><p>DeepTunes was the first cross-functional build week project at Lambda School. We had only four days to work with a brand new team of web developers and data scientists and create a fully functional web app.</p><p>We were one of two teams selected out of 15+ to present at “Shark Tank,” a school-wide presentation of 300+ people.</p><p>Check out the Shark Tank demo here: <a href="https://youtu.be/5P3oDO8v0Sc">https://youtu.be/5P3oDO8v0Sc</a></p><h3>The app</h3><p>Have you ever listened to a track on Spotify, then had your Discover Weekly populate with similar tracks? That’s what it’s designed to do. But sometimes your partner listens to a track on your account, or you go down a rabbit hole of a single artist- and your Discover Weekly reflects this, perhaps not in a way you want.</p><p>We created DeepTunes to take the personalization out of recommendations- an incognito tab for your Spotify. We took a database of hundreds of thousands of songs and created a recommendation engine that gives you similar songs based on the song’s attributes, not on your listening history.</p><p>A user inputs a single song that they like, and we generate a list of similar songs based on the features of our dataset: Duration, Key, Mode, Time Signature, Danceability, Instrumentalness, Liveness, Speechiness, and Valence.</p><p>We also visualize these attributes, something that Spotify doesn’t allow you to do.</p><h3>Conclusion</h3><p>Street Smarts was an incredible week-long project with a great team. We learned a ton about recommender systems and working cross-functionally.</p><p><a href="https://deeptunes.now.sh/">https://deeptunes.now.sh/</a></p><p><em>Originally published at </em><a href="https://willstauffernorris.github.io/2020-05-01-DeepTunes-Spotify/"><em>https://willstauffernorris.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8cdc815eaef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What kind of web traffic generates the most money?]]></title>
            <link>https://medium.com/@willstauffernorris/what-kind-of-web-traffic-generates-the-most-money-9cf6d082bfc4?source=rss-2bebc4143b5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cf6d082bfc4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Will Stauffer-Norris]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 19:50:43 GMT</pubDate>
            <atom:updated>2020-07-28T19:50:43.409Z</atom:updated>
            <content:encoded><![CDATA[<p>Google Analytics is a valuable tool for any business, but it’s a challenge to do any in-depth analysis using Google’s simple dashboard. I wanted to build a robust model that would predict revenue based on over a dozen attributes, such as how many pages a user visits on the website, user location, and the time of year.</p><p>I looked at two years of website data for a business that sells boats.</p><h3>Wrangling my data</h3><p>As soon as I began, I hit my first major Google Analytics limitation: You are only allowed to export .csv files that are five features and five metrics wide, and five thousand rows long. This means that I was forced to export these maximum sized .csv’s quite a few times and then merge them in a Jupyter notebook. There is a way to get a somewhat larger .csv using the Google Analytics API, but given the size of my data, it wasn’t worth it to set that up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KVA-TMTQ3qpp_4vG.png" /></figure><p><strong>This is what the Google Analytics reporting looks like.</strong></p><p>Another problem with this specific data set is that I only had usable data from the last two years, even though I could access the website data going back seven years. This is due to the way that the Google Analytics account was reconfigured two years ago. There is probably a workaround to get more years of data, but it would require a level of data wrangling that I decided was outside the scope of this project.</p><h3>Creating a model</h3><p>Initially, my goal was to predict the type of product that was being purchased. However, I found this extremely difficult to do, given my smaller data size (~7000 rows) and a high variety of products. Even after binning down the product types, my model tended to just guess the majority class, barely beating the baseline in the best cases and underperforming the baseline in the worst cases. I was also limited by what features I could choose to eliminate leakage. For example, using the revenue to predict product type gave me 99%+ accuracy, so revenue was dropped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/0*RXfjQZoMYPP10KL1.png" /></figure><p><strong>This confusion matrix shows that my model mostly just guessed the majority class, only predicting the other categories a few times.</strong></p><p>So I pivoted. Instead of trying to predict the type of product, I tried predicting the revenue generated per transaction. This left me with an even smaller number of observations (~3500), but a continuous target variable. It also allowed me to export a larger number of potential predicting features from Google Analytics, because Google Analytics is quite picky with what combinations of data it allows.</p><p>This new goal meant that I was able to beat the baseline in just a few model iterations. It still wasn’t great- only coming up with an R-squared of around .1, meaning my model only explained 10% of the variation in the data- but it beats guessing!</p><p>Part of the problem with my target variable, revenue, is that it has a bimodal distribution. Transactions tend to be either quite small, or quite large.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/0*d6jLyYsCrzsDv-kn.png" /></figure><p><strong>People are usually either purchasing accessories (~$100) or boats (~$1000).</strong></p><p>This explains the high mean absolute error I was able to achieve with my model- just over $700. If my model takes a guess at the price, it’s off by $700 on average. That’s quite a lot when some of the products on the website are only $50 or so!</p><p>My model does beat the baseline, however- just guessing, the mean absolute error is over $800.</p><p>I wanted to see how the model was arriving at its conclusions, and determine what the most important factors are in predicting revenue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/0*205qVN79e_E6ZbWO.png" /></figure><p><strong>The top features by permutation importance.</strong></p><p>One factor that I had assumed would be important is the day of the year. People are buying more boats in the summer and over the holidays, as shown by this revenue vs time graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zxf4fFODR8N-Hl_y.png" /></figure><p><strong>Note the spikes in summer and over the holidays.</strong></p><p>Indeed, when this “Day of Year” feature is isolated, it does have an effect on the model during those times:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gixTCoInSUADjqPf.png" /></figure><p><strong>Partial dependence plot of how “day of year” affects the XGBoost model.</strong></p><p>These Partial Dependence plots show how the Page Depth and Session Duration impact the revenue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P1vtf_Tvsh1YOtVR.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QS3Xp5Gdfg6LWxmx.png" /></figure><p>And these are the feature importances as described by the XGBoost model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*STGnoWdfUPyJKkPV.png" /></figure><h3>Deploying my web app</h3><p>Even though my model is imperfect, it still has some valuable insights.</p><p>I decided it was time to deploy a web app to allow for other people to explore the model. I used Heroku, a (relatively) simple platform for creating web apps. I’ve built simple websites since the early 2000’s, but this was my first try at building a website with interactive modeling.</p><p>For simplicity’s sake, I built a new model using only the top three most important features as described above. A user only has three inputs instead of over a dozen.</p><p><strong>You can </strong><a href="https://boatdata.herokuapp.com/"><strong>try for yourself</strong></a><strong>- just adjust the inputs and see how the revenue changes!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uLVnXjwyz5hrJgij.jpg" /></figure><p><em>Originally published at </em><a href="https://willstauffernorris.github.io/2020-03-05-Predicting-Boat-Prices/"><em>https://willstauffernorris.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cf6d082bfc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How bad can droughts in the American West get?]]></title>
            <link>https://medium.com/@willstauffernorris/how-bad-can-droughts-in-the-american-west-get-f728ed53a8ca?source=rss-2bebc4143b5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f728ed53a8ca</guid>
            <category><![CDATA[climate-change]]></category>
            <category><![CDATA[colorado-river]]></category>
            <category><![CDATA[water]]></category>
            <dc:creator><![CDATA[Will Stauffer-Norris]]></dc:creator>
            <pubDate>Fri, 07 Feb 2020 22:12:19 GMT</pubDate>
            <atom:updated>2020-02-07T22:12:19.938Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Millennium of River Flows.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JL32RGk30BhIZDfijeI3pA.jpeg" /><figcaption>The Colorado River through Grand Canyon</figcaption></figure><h3>Introduction</h3><p>In the American West, we wait in anticipation every winter for the precipitation that will dictate how full the rivers and reservoirs will be, the intensity of the wildflower blooms, and the severity of the fire season. These anticipations often take the form of phrases like:</p><blockquote>“It’s such a dry January.”</blockquote><p>or</p><blockquote>“This February is one of the wettest on record!”</blockquote><p>or, most commonly,</p><blockquote>“It’s so warm/cold/wet/dry compared to last year!”</blockquote><p>As humans, our perception of the climate is heavily influenced by recent events. This has a name in psychology: <em>recency bias</em>.</p><p>We have at most 100+ personal data points to draw on for how seasonal patterns of precipitation “should” look, and about 150 data points for modern climate records and streamflow gauges. This is great, but the American West has had a somewhat similar climate for the last 12,000 years since the last Ice Age, and 150 years may not be enough time to capture all the possible variance in climate events.</p><p>This is where teams of creative and dedicated scientists have stepped in. The scientists have traveled all around the West, boring small holes in ancient trees and extracting <a href="https://en.wikipedia.org/wiki/Dendrochronology">tree cores</a>. By measuring the size of each years’ tree rings, it’s possible to infer how wet the climate was that year, and from there, the amount of streamflow in the rivers of the watershed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fz9_C-bTipuKZ2W_.jpg" /><figcaption><em>Hannes Grobe/AWI </em><a href="https://creativecommons.org/licenses/by-sa/2.5"><em>CC BY-SA</em></a><em>]</em></figcaption></figure><p>This gives us an unprecedented look at several major river basins in the West over more than a millenium, vastly increasing our understanding of the region’s climate. <strong>Understanding the events of the past is crucial in planning for future climate variability</strong>.</p><h3>Historical Record of three major rivers in the West</h3><p><strong>The Sacramento, San Joaquin, and Colorado are three of the West’s most important rivers. Reconstructed gauging stations marked with green circles.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XcXU6To8J3nff5eb.png" /></figure><p>Tens of millions of people rely on the Sacramento, San Joaquin, and Colorado Rivers for drinking water, agricultural irrigation, and recreation. I used the datasets available from the <a href="https://data.cnra.ca.gov/dataset/paleo-dendrochronology-tree-ring-hyrdo-climatic-reconstructions">California Natural Resources Agency</a> to build visualizations of these three rivers. I chose these rivers from a sample of about 20 rivers around the West, partly because they had a longer historical flow reconstruction.</p><p><strong>Figure: Historical flow over time in the Sacramento River, San Joaquin River, and the Colorado River.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KMccY8akaXQH3fYf.jpg" /></figure><p>A 10 year running average of the flows of the three rivers over a millennium. There is considerable natural variability in the flow.</p><h3>Floods and Droughts</h3><p>The tree ring data gives us a much coarser picture of the past than modern stream gauges. The tree rings can tell us how much water there was in a season, but it can’t tell us if that water came in a sudden torrential storm or gradually, over a season.</p><p><strong>Floods</strong> usually happen over a short duration: There’s too much water in too short of a timespan. Therefore it’s tougher to infer what kinds of flooding happened in the past.</p><p><strong>Droughts</strong>, however, occur over a long duration. Even if there were intense storms during a drought, the problem is one of too little water over too long of a timespan. Droughts are easier to identify using historical tree ring data.</p><h3>Drought in the West</h3><p><strong>Figure: Droughts over time</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QP_ohmgHcCQvwj42.png" /></figure><p><strong>Each of the three rivers has experienced a wide variety of wet and dry years over the past millennium.</strong></p><p>In this figure, the river flows have been normalized to compare between rivers. Positive values are the number of standard deviations above the mean flow for each river, and negative values are standard deviations below the mean. The filled in line is the 10 year rolling average, and the lighter bars are individual years.</p><p><strong>It’s easier to look at each river individually; below, you can see the history of each river’s flow.</strong></p><h3>Sacramento River</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yGca0ltaRKeNTTJl.png" /></figure><h3>San Joaquin River</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*70mx8WPzOqk-3i9C.png" /></figure><h3>Colorado River</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ddi58ghZ3GdW18Zk.png" /></figure><p>One of the more striking thing about these figures is that there have historically been as bad or even more severe droughts than we’ve seen in the 20th and 21st centuries. Particularly on the Colorado, there have historically been very severe droughts.</p><h3>How often have bad droughts occurred?</h3><p>I wanted to see if there was much of a difference in river basins between how often really bad droughts have occurred.</p><p><strong>Figure: Percentage of Years in Moderate and Severe Drought</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/0*0yd_xTJw-lSQdm1X.png" /></figure><p>It turns out that the rivers have fairly similar frequency of moderate droughts (defined as a standard deviation of &gt; 1.5), but the Colorado has had considerably more time in severe drought (standard deviation of &gt;2).</p><p><strong>Looking again at the Colorado River over time, we can see 3–4 instances of very severe drought.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_V5samAjklFF8q9o.png" /></figure><p>Interestingly, archaeologists have connected the <a href="https://en.wikipedia.org/wiki/Mesa_Verde_National_Park#Pueblo_III:_1150_to_1300">abandonment of Mesa Verde</a> around the end of the 1200s to one of the droughts I’ve marked as “Moderate.” This shows that it’s not just the severity (aka how low the 10 year rolling average) is, it’s also the duration of the drought that is important.</p><h3>Conclusion</h3><p>The climate that we’ve experienced in the 20th and 21st century in the West isn’t necessarily the norm for these major rivers.</p><p>As anthropogenic climate change starts to kick in, we should expect higher temperatures, which can intensify droughts. This could be balanced by an increase in precipitation, but the timing of this precipitation and runoff may be altered. Another cause for concern is the enlargement of Hadley cells, which drive bands of deserts around the world. However climate change unfolds, <strong>we need to keep the past in mind and plan for the entirely plausible scenario of a drought unlike anything the modern West has experienced.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wwpRu9NvIZV1ILNg.jpg" /></figure><p><em>The end of the Colorado River: Irrigation canal in Mexico</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f728ed53a8ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>