<?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 Benjamin Stager on Medium]]></title>
        <description><![CDATA[Stories by Benjamin Stager on Medium]]></description>
        <link>https://medium.com/@bstager?source=rss-3cbc3887b6e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rcFjct_LZILA0KzLDbjbRw.png</url>
            <title>Stories by Benjamin Stager on Medium</title>
            <link>https://medium.com/@bstager?source=rss-3cbc3887b6e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 02:14:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bstager/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[STRAVAFY]]></title>
            <link>https://medium.com/@bstager/stravafy-2e75f0163301?source=rss-3cbc3887b6e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e75f0163301</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Benjamin Stager]]></dc:creator>
            <pubDate>Sun, 28 Dec 2025 19:55:51 GMT</pubDate>
            <atom:updated>2025-12-28T19:55:51.642Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Python, APIs, and the principles of Spotify Wrapped to create my own Strava Wrapped for 2025.</h4><p>While I’ve always enjoyed running from time to time, 2025 was a monumental year for my relationship with the sport. I did a fair amount of running in 2024, but not as consistently as I would’ve liked. When I moved to New York City at the end of last year, I quickly learned that the concrete jungle was a fantastic and vast playground to start running more. So I took advantage of that. I ran over 700 miles this year, and just competed in my first half-marathon. Recently, I found out I was admitted into the 2026 New York City Marathon and I could not be more excited.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*7vzb8sZSVWLbvowrmGJ_8g.png" /><figcaption>Me at the Big Apple Half Marathon</figcaption></figure><p>I created my Strava account in June of 2024. For those unfamiliar, Strava is a platform designed to log workouts, with a social media component allowing you to interact with other athletes and friends. It is a fantastic medium to track progress and history, although it is relatively limited in its analysis (you also need a premium subscription to move beyond surface level statistics). So, being the nerd I am, I decided to spend the last week creating a project surrounding my 2025 runs using Python, Strava’s API, and Spotify’s API (more on the last one later).</p><p>I split this project into three distinct pillars:</p><ol><li>StravaAPI class development, data pipelining, and analysis</li><li>Spotify Song OTD analysis (again, more on this later).</li><li>Strava Assistant using Langchain that is capable of interfacing my workout data</li></ol><h3>A disclaimer</h3><p>Before we get into the code, I’d like to make a quick disclaimer. I am increasingly disturbed by how much obviously-AI-generated data science and machine learning content, related to both code and articles, is on Medium. Data scientists “write” articles that are clearly the text output of a ChatGPT prompt, and post code that is well above what the author is capable of. Don’t get me wrong, I think LLMs are a phenomenal tool for learning and I use them to help my understanding with various programming problems and libraries. But to post tightly polished code with no indication that you partially or fully used AI to write it, is deceptive. Therefore, throughout this article, I will make a mention any time I used the assistance of AI to write or debug code. Furthermore, I will briefly say if ChatGPT or Copilot was used (although I am extremely hesitant to use AI IDE tools, like Copilot). If there is no mention<strong>, I did not use generative AI in writing or assistance of writing the code.</strong></p><h3>StravaAPI Development</h3><p>Strava, like many other services, expose various APIs so that developers can create their own applications. So the goal for this project is to pull in all my 2025 running data, and create a dataset that is analysis ready. In order to access your data, you first need to authenticate yourself and go through the usual motions. You can find their developer guide here: <a href="https://developers.strava.com/">https://developers.strava.com/</a></p><p>Here are the libraries I used to create my API connector:</p><pre>import requests<br>import time <br>import datetime<br>import pandas as pd<br>import numpy as np</pre><p>Once I authenticated myself, I began developing a simple Python class that would allow me to connect to their API and start pulling my data in. Shown below is the header of my class:</p><pre>class StravaAPI:<br>    def __init__(self, client_id, client_secret, code=None, file_name=&#39;activity_data.csv&#39;, context_file_name=&#39;formatted_sts&#39;):<br>        self.client_id = client_id<br>        self.client_secret = client_secret<br>        self.code = code<br>        self.read_all_url = f&quot;https://www.strava.com/oauth/authorize?client_id={client_id}&amp;redirect_uri=http://localhost/exchange_token&amp;response_type=code&amp;scope=read,activity:read_all&amp;approval_prompt=force&quot;<br>        self.activies_endpoint = &quot;https://www.strava.com/api/v3/activities&quot;<br>        self.activate_api_url = &quot;https://www.strava.com/oauth/token&quot;<br>        self.file_name = file_name <br>        self.context_file_name = context_file_name</pre><p>Client ids, secrets, and codes can be found in your developer portal. The next part of the class would be to connect to the API, shown below:</p><pre>def connect(self):<br>    payload = {<br>        &quot;client_id&quot;: self.client_id,<br>        &quot;client_secret&quot;: self.client_secret,<br>        &quot;code&quot;: self.code,<br>        &quot;grant_type&quot;: &quot;authorization_code&quot;<br>    }<br><br>    tokens = requests.post(url=self.activate_api_url, data=payload).json() <br>    refresh_token = tokens[&quot;refresh_token&quot;]<br><br>    payload = {<br>        &quot;client_id&quot;: self.client_id,<br>        &quot;client_secret&quot;: self.client_secret,<br>        &quot;grant_type&quot;: &quot;refresh_token&quot;,<br>        &quot;refresh_token&quot;: refresh_token<br>    }<br><br>    refreshed = requests.post(self.activies_endpoint, data=payload).json()<br>    access_token = tokens[&quot;access_token&quot;]<br>    self.headers = {&quot;Authorization&quot;: f&quot;Bearer {access_token}&quot;}</pre><p><strong>AI NOTE: I used ChatGPT to inquire about the best way to pass the payload to the Strava API.</strong></p><p>Before connecting, there is an important quirk. Strava requires that you re-authenticate to “read_all” mode, so you have to run the following:</p><pre>StravaAPI().read_all_url</pre><p>This will print a link. Click on the link and select “allow” in the dialogue. This will take you to a page that looks like an error, but you need to select the code from the resulting url and pass it to the class attribute, like so:</p><pre>StravaAPI().code = &#39;YOUR_CODE_HERE&#39;</pre><p><strong>AI NOTE: I asked ChatGPT about how to do this secondary authentication, as the documentation on Strava’s website regarding this is sparse.</strong></p><p>Once this is done, you are all ready to connect. From here, I developed two ways to make a request to the API:</p><pre>def make_request_nondetailed(self, page, per_page):<br>    r = requests.get(self.activies_endpoint, headers=self.headers, params={&quot;page&quot;:page, &quot;per_page&quot;: per_page})<br>    activities = r.json()<br>    return activities<br><br>def make_request_detailed(self, activity_id):<br>    activities_with_id = f&quot;{self.activies_endpoint}/{activity_id}&quot;<br>    r = requests.get(activities_with_id, headers=self.headers)<br>    specific_activity = r.json()<br>    <br>    setattr(self, f&#39;activity_{activity_id}&#39;, specific_activity)</pre><p>A nondetailed request pulls basic activity data: distance, time, heart rate, and other location metrics. A detailed request pulls more granular and complex statistics. Most importantly, a detailed request allows you to pull the written description you provide in a Strava post (this could be comments, photos, or other things). This will be critical for the Spotify exercise.</p><p>I added an additional helper function that would allow me to make a series of requests, retrieving several activities at one time:</p><pre>def pull_activity_data(self, num_activities=&#39;all&#39;):<br>    activities_list = []<br>    page = 1<br>    <br>    if num_activities == &#39;all&#39;:<br>        for _ in range(12):<br>            response = self.make_request_nondetailed(page=page, per_page=100)<br>            activities_list.extend(response)<br>            page+=1<br>    else:<br>        if num_activities &gt;= 100:<br>            pages = num_activities // 100<br>            remainder = num_activities % 100<br>            for _ in range(pages-1):<br>                response = self.make_request_nondetailed(page=page, per_page=100)<br>                activities_list.extend(response)<br>                page+=1<br>            <br>            response = self.make_request_nondetailed(page=pages, per_page=remainder)<br>            activities_list.extend(response)<br>        else:<br>            page = 1<br>            response = self.make_request_nondetailed(page=1, per_page=num_activities)<br>            activities_list.extend(response)<br><br>    self.activities_list = activities_list</pre><p>Now that we have a way to make requests en masse, we can move on to the more digestible part of this exercise: feature creation and dataset export. Shown below are some helper functions I created to assist in feature engineering:</p><pre>def pull_song(self, string):<br>    try:<br>        if &#39;:&#39; in string:<br>            split = &quot;Song OTD:&quot;<br>        else: <br>            split = &quot;Song OTD&quot;<br>        res = string.split(split)[1].split(&#39;by&#39;)[0].strip()<br>        return res<br>    except:<br>        return &#39;NA&#39;<br>    <br>def pull_artist(self, string):<br>    try:<br>        if &#39;:&#39; in string:<br>            split = &quot;Song OTD:&quot;<br>        else: <br>            split = &quot;Song OTD&quot;<br>        res = string.split(split)[1].split(&#39;by&#39;)[1].strip()<br>        return res<br>    except:<br>        return &#39;NA&#39;<br><br>def pull_artist_and_song(self, string):<br>    try:<br>        if &#39;:&#39; in string:<br>            split = &quot;Song OTD:&quot;<br>        else: <br>            split = &quot;Song OTD&quot;<br>        res = string.split(split)[1]<br>        return res<br>    except:<br>        return &#39;NA&#39;    <br><br>def format_pace(self, x):<br>    if np.isnan(x):<br>        return &#39;NA&#39;<br>    else:<br>        second_frac = x - int(x)<br>        seconds = int((60) * second_frac)<br>        if seconds &lt; 10:<br>            seconds = f&quot;0{seconds}&quot;<br>        return f&quot;{int(x)}:{seconds}&quot;<br>    <br>def extract_lat(self, x):<br>    try:<br>        return x[0]<br>    except:<br>        return &#39;NA&#39;<br><br>def extract_long(self, x):<br>    try:<br>        return x[1]<br>    except:<br>        return &#39;NA&#39;</pre><p>You will see some odd helper functions that relate to extracting certain text related, and as I’ve previously mentioned: more on this later. The final step to get a cleaned dataset of my 2025 runs would be to run the API request function, and add some additional metadata: like formatted pace, speed in MPH, and latitude / longitude. Shown below is that function:</p><pre>def refresh_dataset(self, max_lookback=25):<br>    existing_data = pd.read_csv(self.file_name)<br>    <br>    self.pull_activity_data(num_activities=max_lookback)<br>    <br>    all_keys = set().union(*[dic.keys() for dic in self.activities_list])<br><br>    to_add = pd.DataFrame([{key: dic.get(key, None) for key in all_keys} for dic in self.activities_list])<br>    new_ids = np.setdiff1d(to_add[&#39;id&#39;].tolist(), existing_data[&#39;id&#39;].tolist())<br>    to_add = to_add[to_add[&#39;id&#39;].isin(new_ids)]<br>    to_add[&#39;date_str&#39;] = to_add[&#39;start_date&#39;].apply(lambda x: pd.Timestamp(x).date())<br>    to_add[&#39;time_mins&#39;] = to_add[&#39;elapsed_time&#39;].apply(lambda x: x / 60)<br>    to_add[&#39;distance_miles&#39;] = to_add[&#39;distance&#39;] * 0.000621371<br>    to_add[&#39;pace&#39;] = np.where(to_add[&#39;type&#39;] == &#39;Run&#39;, to_add[&#39;time_mins&#39;] / to_add[&#39;distance_miles&#39;], np.nan)<br>    to_add[&#39;pace_formatted&#39;] = to_add[&#39;pace&#39;].apply(self.format_pace)<br>    to_add[&#39;speed_mph&#39;] = to_add[&#39;distance_miles&#39;] / (to_add[&#39;time_mins&#39;] / 60)<br>    to_add = to_add[(to_add[&#39;pace&#39;] &lt;= 12) &amp; (to_add[&#39;type&#39;] == &#39;Run&#39;)].sort_values(&#39;date_str&#39;, ascending=True)<br><br>    for col in [&#39;start_latlng&#39;, &#39;end_latlng&#39;]:<br>        start_end = col.split(&#39;_&#39;)[0]<br>        to_add[f&#39;{start_end}_lat&#39;] = to_add[col].apply(self.extract_lat)<br>        to_add[f&#39;{start_end}_long&#39;] = to_add[col].apply(self. extract_long)<br><br>    #outdoor_runs = to_add[(to_add[&#39;start_lat&#39;] != &#39;NA&#39;) &amp; (to_add[&#39;end_lat&#39;] != &#39;NA&#39;)]<br><br>    descriptions = []<br>    for id in new_ids:<br>        self.make_request_detailed(activity_id=id)<br>        response = getattr(self, f&quot;activity_{id}&quot;)<br>        description = response[&#39;description&#39;]<br><br>        descriptions.append(description)<br>        time.sleep(15)<br><br><br>    descriptions = pd.DataFrame({<br>        &quot;id&quot; : new_ids,<br>        &quot;description&quot; : descriptions<br>    })<br><br>    to_add = pd.merge(left=to_add, right=descriptions, on=&#39;id&#39;, how=&#39;left&#39;)<br><br>    to_add[&#39;description_music&#39;] = to_add[&#39;description&#39;].apply(self.pull_artist_and_song)<br>    to_add[&#39;song_otd&#39;] = to_add[&#39;description&#39;].apply(self.pull_song)<br>    to_add[&#39;artist&#39;] = to_add[&#39;description&#39;].apply(self.pull_artist)<br>    <br>    self.updated_data = pd.concat([to_add, existing_data])<br><br>    cols_need = {<br>        # &quot;elev_high&quot;,<br>        # &quot;max_speed&quot;,<br>        # &quot;average_watts&quot;,<br>        # &quot;distance&quot;,<br>        # &quot;kilojoules&quot;,<br>        # &quot;max_heartrate&quot;,<br>        # &quot;average_heartrate&quot;,<br>        # &quot;max_watts&quot;,<br>        &quot;date_str&quot;:&quot;Date&quot;,<br>        &quot;time_mins&quot;:&quot;Time (minutes)&quot;,<br>        &quot;distance_miles&quot;:&quot;Distance (miles)&quot;,<br>        &quot;pace_formatted&quot;:&quot;Pace (minutes per mile)&quot;,<br>        # &quot;start_lat&quot;,<br>        # &quot;start_long&quot;,<br>        # &quot;end_lat&quot;,<br>        # &quot;end_long&quot;,<br>        &quot;description&quot;:&quot;Description&quot;,<br>        &quot;description_music&quot;:&quot;Music for the run&quot;,<br>    }<br><br><br>    formatted_strs = []<br>    <br>    for idx, row in self.updated_data[self.updated_data[&#39;start_date&#39;] &gt;= &#39;2025-01-01&#39;].iterrows():<br>        string = &quot;&quot;&quot;<br>        --------------------<br>        &quot;&quot;&quot;<br>        for col in cols_need.keys():<br>            string += f&quot;&quot;&quot;<br>            {cols_need[col]} : {row[col]}<br>            &quot;&quot;&quot;<br>        string += &quot;&quot;&quot;<br>        --------------------<br>        \n<br>        &quot;&quot;&quot;<br>        formatted_strs.append(string)<br>        <br>    self.formatted_strs = formatted_strs</pre><p><strong>AI NOTE: I used ChatGPT to inquire about the best way to align different length dictionaries where their keys would be used as columns of a DataFrame.</strong></p><p>As you can see, I not only export a DataFrame, but a formatted text file of the run data. This is used as simple context for the rudimentary chatbot that I developed.</p><p>Finally, I added two methods to read and write the running data. It is crucial to have an overwrite function as I need to keep my dataset fresh and updated as I continue to run!</p><pre>def overwrite_data(self):<br>    self.updated_data.to_csv(self.file_name)<br>    with open(&quot;formatted_strs.txt&quot;, &quot;w&quot;) as file:<br>        file.write(&quot; &quot;.join(self.formatted_strs))<br><br>def read_data(self):<br>    return pd.read_csv(self.file_name)</pre><h3>2025 Running Analysis</h3><p>Obviously, a huge part of this is actually analyzing how my running went this year! EDA is a critical skill in order to be a successful data scientist, so I always like to practice my skills.</p><p>Again, the libraries:</p><pre>from strava import StravaAPI<br>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from pytz import timezone, UnknownTimeZoneError<br>from geopy.geocoders import Nominatim<br>import seaborn as sns<br>import warnings<br>import spotipy<br>from spotipy.oauth2 import SpotifyOAuth<br>from spotipy.oauth2 import SpotifyClientCredentials<br>import cartopy.crs as ccrs<br>import cartopy.feature as cfeature<br>from langchain.chat_models import ChatOpenAI</pre><p>You may be unfamiliar with some of these libraries, but they will become clearer later on.</p><p>See that now I can call the class I just made like a usual library! Since we’re reading in static dataset, we can just call it like this, sans ID and secret:</p><pre>strava = StravaAPI(client_id=None, client_secret=None)<br>df = strava.read_data()</pre><p>Each row of the DataFrame is a run from 2025. I created some additional bespoke helper functions to add some data breakouts that I wanted to analyze, shown below:</p><pre>def cast_day_part(hour):<br>    if hour in range(0, 10):<br>        return &#39;Morning&#39;<br>    if hour in range(10, 17):<br>        return &#39;Mid-Day&#39;<br>    if hour in range(17, 24):<br>        return &#39;Evening&#39;<br><br>def pull_geo(row, level):<br>    lat, long = row[&#39;start_lat&#39;], row[&#39;start_long&#39;]<br>    if np.isnan(lat):<br>        return &#39;Indoor&#39;<br>    geolocator = Nominatim(user_agent=&#39;geo_api&#39;)<br>    location = geolocator.reverse((str(lat), str(long)))<br>    result = location.raw.get(&#39;address&#39;).get(&#39;city&#39;)<br>    if result is None:<br>        result = location.raw.get(&#39;address&#39;).get(&#39;town&#39;)<br>        if result is None:<br>            result = location.raw.get(&#39;address&#39;).get(&#39;village&#39;)<br>    return result<br><br>def map_timezone(tz_str):<br>    try:<br>        return timezone(tz_str)<br>    except UnknownTimeZoneError:<br>        if tz_str == &#39;(GMT-05:00) America/Atikokan&#39;:<br>            return timezone(&#39;America/Toronto&#39;)  <br>        elif tz_str == &#39;(GMT-05:00) America/New_York&#39;:<br>            return timezone(&#39;America/New_York&#39;)  <br>        elif tz_str == &#39;(GMT-04:00) America/Anguilla&#39;:<br>            return timezone(&#39;America/Puerto_Rico&#39;)  <br>        elif tz_str == &#39;(GMT-07:00) America/Phoenix&#39;:<br>            return timezone(&#39;America/Phoenix&#39;)  <br>        elif tz_str == &#39;(GMT-06:00) America/Chicago&#39;:<br>            return timezone(&#39;America/Chicago&#39;)  <br>        elif tz_str == &#39;(GMT+01:00) Europe/Rome&#39;:<br>            return timezone(&#39;Europe/Rome&#39;)  <br>        elif tz_str == &#39;(GMT+02:00) Africa/Blantyre&#39;:<br>            return timezone(&#39;Africa/Blantyre&#39;)  <br>        else:<br>            return timezone(&#39;UTC&#39;) </pre><p><strong>AI NOTE: I used ChatGPT to inquire about how to extract city names from a latitude and longitude, and to inquire about how to convert a timezone string to a proper timezone() object.</strong></p><p>Apply some of these new features like so:</p><pre>df[&#39;start_date&#39;] = pd.to_datetime(df[&#39;start_date&#39;])<br>df[&#39;start_date_local&#39;] = df.apply(<br>    lambda row: row[&#39;start_date&#39;].tz_convert(map_timezone(row[&#39;timezone&#39;])), axis=1<br>)<br>df = df[df[&#39;date_str&#39;] &gt;= &#39;2025-01-01&#39;].sort_values(&#39;date_str&#39;)<br>df[&#39;mile_cat&#39;] = df[&#39;distance_miles&#39;].round()<br>df[&#39;month&#39;] = df[&#39;date_str&#39;].apply(lambda x: pd.Timestamp(x).date().month)<br>df[&#39;week&#39;] = df[&#39;date_str&#39;].apply(lambda x: pd.Timestamp(x).weekofyear)<br>df[&#39;week_day&#39;] = df[&#39;date_str&#39;].apply(lambda x: pd.Timestamp(x).weekday)<br>df[&#39;hour&#39;] = df[&#39;start_date_local&#39;].apply(lambda x: pd.Timestamp(x).hour)<br>df[&#39;day_part&#39;] = df[&#39;hour&#39;].apply(cast_day_part)<br>df[&#39;city&#39;] = df.apply(lambda row: pull_geo(row, level=&#39;city&#39;),axis=1)</pre><p>We can now dig into the data! To plot, I used a combination of seaborn and matplotlib. For the sake of brevity, I am going to omit the plotting code, as it&#39;s relatively straightforward. If you’d like any of it, please feel free to pull any of it from my Github. I first wanted to evaluate how my running distance changed over time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*iK2uSMkV_vRDG_1UUKOArA.png" /><figcaption>Daily runs and miles per every 7 runs</figcaption></figure><p>While I knew I was increasing my distance, I’m pretty thrilled that I’ve taken my average run distance from 1.5 miles all the way to 6 miles! I also created a monthly graph that better communicates this relationship:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*DBUozeDGBj6GZN3oMpxqSQ.png" /><figcaption>Smoothed and aggregated chart from above</figcaption></figure><p>Additionally, I checked how my mileage stacked up over each month:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*OivXIk7-P52WusWiQaMDVQ.png" /><figcaption>Total mileage in 2025</figcaption></figure><p>I’m glad to see a good upward trend here, although I am a little disappointed by the dip in Decmeber. Due to some Achilles problems’ following my half-marathon, I shut down for a few weeks. I’ll likely wait to start running again until 2026.</p><p>I also wanted to see how my heartrate changed throughout my running journey in 2025, and was able to create the following graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*AQpYsrXyTI77T3QHvhCm2Q.png" /><figcaption>Heartrate over time</figcaption></figure><p>Note that there are some gaps here as I had a few workouts that I had to manually log, due to my watch or phone dying. Not much to analyze here, as my heartrate remained relatively consistent even as I begin to increase distance.</p><p>Strava’s API also provides you with latitude and longitude data for each run, meaning I’d be able to do some geographical level analysis. If you look at the helper functions above, you will see I created a function that allowed me to extract city names from a latitude and longitude. Using Python’s cartopy module, I was able to create a static map of the United States illustrating everywhere that I ran this year. Since this is an unconventional plotting module, I’ve included the code below:</p><pre>points = df[[&#39;start_lat&#39;, &#39;start_long&#39;]].values<br><br>lats = [p[0] for p in points]<br>lons = [p[1] for p in points]<br><br>fig = plt.figure(figsize=(10, 6))<br>ax = plt.axes(projection=ccrs.PlateCarree())<br><br>ax.set_global()<br>ax.add_feature(cfeature.LAND)<br>ax.add_feature(cfeature.OCEAN)<br>ax.add_feature(cfeature.BORDERS, linewidth=0.5)<br>ax.add_feature(cfeature.COASTLINE, linewidth=0.5)<br><br>ax.scatter(<br>    lons,<br>    lats,<br>    color=&quot;red&quot;,<br>    s=20,<br>    transform=ccrs.PlateCarree(),<br>)<br><br>plt.show()</pre><p><strong>AI NOTE: I used ChatGPT to inquire about the best Python module to use for this sort of exercise, which was cartopy.</strong></p><p>Running this gives the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*V_EdmMeJAZT7XkjRATZ9rg.png" /><figcaption>A map of everywhere I ran this year.</figcaption></figure><p>Here are the above locations:</p><ul><li>Indoors</li><li>New York, NY</li><li>Shaker Heights, OH</li><li>Scottsdale, AZ</li><li>Clayton, MO</li><li>Hunter Mountain, NY</li><li>Evanston, IL</li><li>Siracusa, Italy</li><li>Southold (Long Island), NY</li><li>Kansas City, KS</li><li>Cleveland, OH</li></ul><p>Pretty blessed to be able to run in so many different locations this year.</p><p>One last thing I wanted to evaluate was how my runs may have differed depending on the time of day. About halfway through the year, I began running after work, instead of early in the morning, as my body often feels better when I’m fully awake. I day-parted runs into three times of day: morning, mid-day, and evening. I wanted to analyze, pace, miles per run, and total miles, shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*WuG6kk0-ZQFwhMrS5XV45A.png" /><figcaption>Three charts parted by day</figcaption></figure><p>I think there’s some obvious, yet interesting, takeaways here. While I ran the most miles mid-day, I had a much lower miles per run. This is usually due to running mid-day on Saturday and Sunday when I don’t have a lot of time to workout, or going for quick 15 minute (2 mile) jogs on my lunch break at work. Furthermore, I clearly go for my longest runs in the evening, whereas my morning runs are defined by quick, short mile to two mile runs a at a high pace.</p><h3>CREATING STRAVAFY</h3><p>Now, remember when I kept saying “I’ll get to that later”? This is later. I am a massive music fan, and good music is what keeps me going during long runs. I often curate specific song orders before a run so that the best songs come on during the most challenging part of the workout. As my tiny amount of Strava followers are likely already aware, every time I post a run I add a small description of how it went, in addition to a “<strong>Song OTD”:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*W68EB2Gnbyd5hgKP6HiAHQ.png" /><figcaption>Example caption that I wrote for a run</figcaption></figure><p>I started this Song OTD caption idea with the sole intention of capturing how my mood for the run. But now that I have my API connector, I realized there are likely tons of different cool analyses that I could do related to which songs I ran to throughout the year.</p><p>As I already have the description information from when I ran my data pipeline function, <strong>all I had to do was specifically pull the song and artist from the string</strong>. I standardized how I wrote my captions (because I knew in the back of my mind I’d likely want to do something like this later on), so this was relatively easy. Gonna drop the helper functions again:</p><pre>def pull_song(self, string):<br>    try:<br>        if &#39;:&#39; in string:<br>            split = &quot;Song OTD:&quot;<br>        else: <br>            split = &quot;Song OTD&quot;<br>        res = string.split(split)[1].split(&#39;by&#39;)[0].strip()<br>        return res<br>    except:<br>        return &#39;NA&#39;<br>    <br>def pull_artist(self, string):<br>    try:<br>        if &#39;:&#39; in string:<br>            split = &quot;Song OTD:&quot;<br>        else: <br>            split = &quot;Song OTD&quot;<br>        res = string.split(split)[1].split(&#39;by&#39;)[1].strip()<br>        return res<br>    except:<br>        return &#39;NA&#39;<br><br>def pull_artist_and_song(self, string):<br>    try:<br>        if &#39;:&#39; in string:<br>            split = &quot;Song OTD:&quot;<br>        else: <br>            split = &quot;Song OTD&quot;<br>        res = string.split(split)[1]<br>        return res<br>    except:<br>        return &#39;NA&#39;    </pre><p>Now that we have a cleaned song and artist column, I can see what sort of artists I listened to on my runs this year. I tried to log a Song OTD every run, but occasionally forgot. The final count is 155 total unique Song OTDs. Here are the top 10 artists by song count:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*1BggktgKcxCClYDkU91KtA.png" /><figcaption>Top 10 artists for my runs this year</figcaption></figure><p>From here, I wasn’t sure what I wanted to do with my music data. I could do an analysis about how my Song OTD affects my run quality. Unfortunately, my Song OTD is chosen relatively arbitrarily, and I truly just pick it based on what my vibe for the run is. The only criteria I use is that I had to listen to the song at some point during the run. I then realized I could do something really cool, armed with just songs and artists: <strong>pass the songs and artists programmatically to Spotify’s API and its corresponding Python package, Spotipy, and create my own Strava 2025 Wrapped playlist on my profile.</strong></p><p>This is a relatively simple exercise. The first step is to take the songs and artists from my written description and confirm that they are all correct to be passed to to Spotify’s API. To expedite this, I used Langchain and its ChatOpenAI wrapper, which would be able to return a correct list if the songs were misspelled or if I missed artists. This is shown below:</p><pre>llm = ChatOpenAI(<br>    model=&quot;gpt-5.1&quot;,<br>    max_completion_tokens=16000,<br>    streaming=True,<br>)<br><br>vals = df[&#39;description_music&#39;].values<br><br>prompt = f&quot;&quot;&quot;<br>I need you to do only one thing: take the following list of songs and artists, <br>clean them if they have the wrong name.<br>And then return a python matrix where first value is song, second <br>value is artist.<br><br>Here is the list:<br><br>{vals}<br>&quot;&quot;&quot;<br><br>response = llm.invoke(prompt)</pre><p>This worked shockingly well. Here is a sample of the output:</p><pre>tracks = [[&quot;Best Day Ever&quot;, &quot;Mac Miller&quot;],<br>    [&quot;Ladders&quot;, &quot;Mac Miller&quot;],<br>    [&quot;Fancy Footwork&quot;, &quot;Chromeo&quot;],<br>    [&quot;Alright&quot;, &quot;Kendrick Lamar&quot;],<br>    [&quot;Kids&quot;, &quot;MGMT&quot;],<br>    [&quot;Like Him&quot;, &quot;Tyler, The Creator&quot;],<br>    [&quot;She&#39;s a Lady&quot;, &quot;Tom Jones&quot;],<br>    [&quot;Everything I Love&quot;, &quot;Morgan Wallen&quot;],</pre><p>From here, all that is left to do is to call Spotipy’s API. We need to get the URIs of each track, iterate over them, and add them to a playlist. Similarly to Strava, you need to create a developer profile in order to access Spotify’s API, <a href="https://developer.spotify.com/">https://developer.spotify.com/</a>. Once authenticated, we first need to get all URIs for all 155 tracks:</p><pre>sp = spotipy.Spotify(<br>    auth_manager=SpotifyClientCredentials(<br>        client_id=&quot;REDACTED_ID&quot;,<br>        client_secret=&quot;REDACTED_SECRET&quot;<br>    )<br>)<br><br>uris = []<br>for title, artist in tracks:<br>    q = f&quot;track:{title} artist:{artist}&quot;<br>    result = sp.search(q, type=&quot;track&quot;, limit=1)<br><br>    if result[&quot;tracks&quot;][&quot;items&quot;]:<br>        track = result[&quot;tracks&quot;][&quot;items&quot;][0]<br>        uri = track[&#39;uri&#39;]<br>        print({<br>            &quot;track&quot;: track[&quot;name&quot;],<br>            &quot;artist&quot;: track[&quot;artists&quot;][0][&quot;name&quot;],<br>            &quot;album&quot;: track[&quot;album&quot;][&quot;name&quot;],<br>            &quot;popularity&quot;: track[&quot;popularity&quot;],<br>        })<br>        uris.append(uri)</pre><p><strong>AI NOTE: I used ChatGPT to ask about how to use Spotipy. I did not directly copy any code that was written by generative AI.</strong></p><p>This worked remarkably well. Spotipy uses a regex-like algorithm to search for songs, so names do not need to be perfect. Finally, I created an iteration to create a playlist and add the songs:</p><pre>sp = spotipy.Spotify(auth_manager=SpotifyOAuth(<br>    client_id=&quot;REDACTED_ID&quot;,<br>    client_secret=&quot;REDACTED_SECRET&quot;,<br>    redirect_uri=&quot;REDACTED_REDIRECT&quot;,  <br>    scope=&quot;playlist-modify-public playlist-modify-private&quot;<br>))<br><br>user_id = sp.current_user()[&quot;id&quot;]<br><br>playlist = sp.user_playlist_create(<br>    user=user_id,<br>    name=&quot;STRAVAFY&quot;,<br>    public=True,<br>    description=&quot;Created using Spotipy and Strava&quot;<br>)<br>playlist_id = playlist[&quot;id&quot;]<br>print(f&quot;Created playlist with ID: {playlist_id}&quot;)<br><br>for i in range(11):<br>    sp.playlist_add_items(playlist_id, uris[i*15:(i+1)*15])<br>print(&quot;Tracks added!&quot;)</pre><p>I had to use batch iteration as Spotipy rate limits how many URIs you can add to a playlist in one call. I ran the code and voila: check it out!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phbrpL9qPocXPRDzqMR_Hg.png" /></figure><p>It is so awesome to have all of my Song OTDs from 2025 in a playlist created from simple Python code. This is truly one of my favorite projects I’ve ever worked on. If you wanna jam out to what I listened to on my runs this year: <a href="https://open.spotify.com/playlist/6cj1AQmEhlfDaXdQLlACzJ?si=551a6dc0a0aa427c">STRAVAFY</a></p><h3>Strava LLM Assistant</h3><p>Ever popular are LLMs, and I try to do a little dev work related to language modeling in any project that I work on, even if it&#39;s not production ready. Historically, my favorite way to create a lightweight custom ChatBot demo is to use LangChain + Streamlit. It’s an accessible and simple way to create strong MVPs. I really just wanted to see how capable GPT was of analyzing my lightweight dataset out of the box.</p><p>Recall this code snippet from above:</p><pre>    formatted_strs = []<br>    <br>    for idx, row in self.updated_data[self.updated_data[&#39;start_date&#39;] &gt;= &#39;2025-01-01&#39;].iterrows():<br>        string = &quot;&quot;&quot;<br>        --------------------<br>        &quot;&quot;&quot;<br>        for col in cols_need.keys():<br>            string += f&quot;&quot;&quot;<br>            {cols_need[col]} : {row[col]}<br>            &quot;&quot;&quot;<br>        string += &quot;&quot;&quot;<br>        --------------------<br>        \n<br>        &quot;&quot;&quot;<br>        formatted_strs.append(string)<br>        <br>    self.formatted_strs = formatted_strs<br><br>def overwrite_data(self):<br>    self.updated_data.to_csv(self.file_name)<br>    with open(&quot;formatted_strs.txt&quot;, &quot;w&quot;) as file:<br>        file.write(&quot; &quot;.join(self.formatted_strs))</pre><p>In addition to saving my runs as tabular data, I also cached them as formatted strings in order to pass them to a LLM. Historically, LLMs struggle mightily with csv’s, so I saved the data I needed as a formatted string for each run. From here, creating a deployable chatbot was relatively simple.</p><p>The imports, as usual:</p><pre>import streamlit as st<br>from langchain.chat_models import ChatOpenAI<br>from langchain.schema import SystemMessage, HumanMessage</pre><p>For those unfamiliar, Streamlit is a Python framework that streamlines frontend development, allowing for simple creation of web-apps with little front-end dev knowledge. I will present each portion of the app, and then post the full script below.</p><p>First, define headers and the LLM call via LangChain:</p><pre>st.set_page_config(page_title=&quot;Chat&quot;, layout=&quot;centered&quot;)<br><br>st.header(&quot;Strava Analyst&quot;)<br>st.subheader(&quot;An app designed by Benjamin Stager to communicate with his 2025 running data.&quot;)<br><br>with open(&quot;formatted_strs.txt&quot;, &quot;r&quot;) as file:<br>    context = file.read()<br><br>llm = ChatOpenAI(<br>    model=&quot;gpt-5.1&quot;,<br>    max_completion_tokens=16000,<br>    streaming=True,<br>)</pre><p>Next, define a function to stream the responses and save history. Streaming allows for sequential text generation, similar to how ChatGPTs interface renders its text:</p><pre>if &quot;messages&quot; not in st.session_state:<br>    st.session_state.messages = []<br><br>def stream_response(messages):<br>    for chunk in llm.stream(messages):<br>        if chunk.content:<br>            yield chunk.content<br><br>for msg in st.session_state.messages:<br>    with st.chat_message(msg[&quot;role&quot;]):<br>        st.markdown(msg[&quot;content&quot;])<br></pre><p>Finally, define a system-user prompt system and call the LLM:</p><pre>user_input = st.chat_input(&quot;Type your message&quot;)<br><br>if user_input:<br>    st.session_state.messages.append(<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_input}<br>    )<br><br>    with st.chat_message(&quot;user&quot;):<br>        st.markdown(user_input)<br><br>    messages = [<br>        SystemMessage(<br>            content=(<br>                &quot;You are a Strava workout analysis assistant. &quot;<br>                &quot;Don&#39;t tell me how detailed my runs are or anything. JUST BE READY TO ASSIST. DO NOT TELL ME HOW GREAT THE LOG IS JUST BE READY TO ANSWER ANY QUESTION&quot;<br>                &quot;The user&#39;s name is Ben.&quot;<br>                &quot;Answer concisely and factually.\n\n&quot;<br>                &quot;You are to serve every request accurately. You are not to suggest additional analysis or suggestions.&quot;<br>                &quot;Often times there will be a song of the day and description. Try to reference this as well&quot;<br>                &quot;Don&#39;t just spit out the data, try to do an analysis with it, or craft some sort of narrative around it.&quot;<br>                f&quot;Dataset:\n{context}&quot;<br>            )<br>        ),<br>        HumanMessage(content=user_input),<br>    ]<br><br>    with st.chat_message(&quot;assistant&quot;):<br>        placeholder = st.empty()<br>        streamed_text = &quot;&quot;<br><br>        for chunk in stream_response(messages):<br>            streamed_text += chunk<br>            placeholder.markdown(streamed_text)<br><br>    st.session_state.messages.append(<br>        {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: streamed_text}<br>    )<br><br><br>    st.session_state.messages = st.session_state.messages[-8:]</pre><p>Since our text file is relatively small in terms of tokens, we can just pass it as context via the system prompt, as opposed to using a Retrieval Augmented Generation (RAG) system. We are now ready to go. Below are some screenshots of me interacting with my new Strava Analyst:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZuVx-9nYOKlyT_v_FZlLaA.png" /><figcaption>My Streamlit Strava Assistant</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*maeTDShBR0cqS7TEKLrlUg.png" /><figcaption>My Streamlit Strava Assistant</figcaption></figure><p>It is pretty remarkable how well it handled context being passed directly. I also find it funny that it takes my descriptions I write for the run and gives a bit of a story behind them. I’ll likely use this in the future of there’s specific runs I want to recall at a moments notice. There’s definitely a lot more I’d like to flesh out here, but I’m pretty thrilled about how well it’s working out of the box.</p><p>Full app code:</p><pre>import streamlit as st<br>from langchain.chat_models import ChatOpenAI<br>from langchain.schema import SystemMessage, HumanMessage<br><br>st.set_page_config(page_title=&quot;Chat&quot;, layout=&quot;centered&quot;)<br><br>st.header(&quot;Strava Analyst&quot;)<br>st.subheader(&quot;An app designed by Benjamin Stager to communicate with his 2025 running data.&quot;)<br><br>with open(&quot;formatted_strs.txt&quot;, &quot;r&quot;) as file:<br>    context = file.read()<br><br>llm = ChatOpenAI(<br>    model=&quot;gpt-5.1&quot;,<br>    max_completion_tokens=16000,<br>    streaming=True,<br>)<br><br>if &quot;messages&quot; not in st.session_state:<br>    st.session_state.messages = []<br><br>def stream_response(messages):<br>    for chunk in llm.stream(messages):<br>        if chunk.content:<br>            yield chunk.content<br><br># render history<br>for msg in st.session_state.messages:<br>    with st.chat_message(msg[&quot;role&quot;]):<br>        st.markdown(msg[&quot;content&quot;])<br><br>user_input = st.chat_input(&quot;Type your message&quot;)<br><br>if user_input:<br>    st.session_state.messages.append(<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_input}<br>    )<br><br>    with st.chat_message(&quot;user&quot;):<br>        st.markdown(user_input)<br><br>    messages = [<br>        SystemMessage(<br>            content=(<br>                &quot;You are a Strava workout analysis assistant. &quot;<br>                &quot;Don&#39;t tell me how detailed my runs are or anything. JUST BE READY TO ASSIST. DO NOT TELL ME HOW GREAT THE LOG IS JUST BE READY TO ANSWER ANY QUESTION&quot;<br>                &quot;The user&#39;s name is Ben.&quot;<br>                &quot;Answer concisely and factually.\n\n&quot;<br>                &quot;You are to serve every request accurately. You are not to suggest additional analysis or suggestions.&quot;<br>                &quot;Often times there will be a song of the day and description. Try to reference this as well&quot;<br>                &quot;Don&#39;t just spit out the data, try to do an analysis with it, or craft some sort of narrative around it.&quot;<br>                f&quot;Dataset:\n{context}&quot;<br>            )<br>        ),<br>        HumanMessage(content=user_input),<br>    ]<br><br>    with st.chat_message(&quot;assistant&quot;):<br>        placeholder = st.empty()<br>        streamed_text = &quot;&quot;<br><br>        for chunk in stream_response(messages):<br>            streamed_text += chunk<br>            placeholder.markdown(streamed_text)<br><br>    st.session_state.messages.append(<br>        {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: streamed_text}<br>    )<br><br>    # keep last 4 turns<br>    st.session_state.messages = st.session_state.messages[-8:]</pre><h3>Conclusion</h3><p>This has been one of my favorite projects to work on. Typically, when working on a data science or machine learning project, I am overwhelmed by the possibilities. Compartmentalizing this one into three specific pillars was significantly beneficial. And especially, being able to create a custom playlist simply using captions from runs and Spotify’s API is a memento I can hold forever, and reminds me why I love data science so much.</p><p>I hope you enjoyed this article! If anyone would like to take a gander at my code, you can find it on my GitHub here: <a href="https://github.com/benstager/strava">repo</a>. Furthermore, if you have any questions or comments feel free to reach out to me on <a href="https://www.linkedin.com/in/ben-stager-802b141a5/">LinkedIn</a> or shoot me an email at bstager@tulane.edu.</p><p>Here’s to more Song OTDs in 2026!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e75f0163301" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Takeaways From My Journey into Industry Data Science]]></title>
            <link>https://medium.com/@bstager/10-takeaways-from-my-journey-into-industry-data-science-71d7463d9813?source=rss-3cbc3887b6e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/71d7463d9813</guid>
            <category><![CDATA[career-advice]]></category>
            <category><![CDATA[advice]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Benjamin Stager]]></dc:creator>
            <pubDate>Wed, 03 Sep 2025 17:26:08 GMT</pubDate>
            <atom:updated>2025-09-03T17:26:08.951Z</atom:updated>
            <content:encoded><![CDATA[<h3>10 Takeaways From My Journey Into Industry Data Science</h3><p>Recently, I had the pleasure of sharing some insights into my data science journey at a mathematics conference. As I thought they might be helpful to anyone looking to become a data scientist, I figured I’d jot my notes down here.</p><h3>1. The Data Science Skill Tree</h3><p>Data science is not a uniform field — it is a discipline that is supported by a myriad of different skills. While you don’t have to master all of them, you should feel comfortable enough in each skillset that you are able to communicate it to others. Listed below are what I think the most important skills to succeed in the field.</p><h4>The Mathematics of Data Science</h4><p>Understanding the mathematics that drives exploratory data analysis, machine learning models, and statistical analysis are paramount. Linear algebra and calculus III are used relentlessly in the derivation of models. Even complex architectures like transformers and RNNs are underpinned by partial derivatives and matrix multiplication. If linear algebra and calculus III are the tools to build the house, then probability and statistics are the blueprint for the house. Many machine learning models are, fundamentally, probabilistic models. A good resource for this: <em>Mathematics for Machine Learning </em>by Deisenroth, Faisal, and Ong</p><h4>Computer Science</h4><p>Learning computer science is non-negotiable for data science. You don’t need to be a master of data structures and algorithms, nor do you need to grind Leetcode, but you do need to understand basic control flows, data types and abstract data types, code modularization, and source control. Python is a popular choice, and will forever be my go-to. Get comfortable with pandas and numpy, then start to integrate things like sklearn and scipy in. Good resources: Geeksforgeeks, Kaggle</p><h4>DevOps/MLOps</h4><p>This has certainly become more relevant in recent years, but having a basic to moderate understanding of machine learning engineering is definitely good to have. Learning how to move from notebooks, to Python files, to Docker containers and virtual machines is a worthwhile investment. Tools like Github, Docker, Kubernetes, MLflow, DigitalOcean are king here. Good resources: <em>Machine Learning Engineering </em>by McMahon</p><h4>Analytics</h4><p>While some may roll their eyes at how pedantic the differences between data analysts and data scientists are, they truly do differ. Your time in data science will be governed more by your ability to build computational systems that can parse, explain, and model data, more than it will be governed by your ability to draw conclusions from said data. However, you will almost certainly be asked to do the latter. When I began to get into data science, I found myself so focused on modeling and computer science, that I initially struggled to actually explain the story the data was telling. Make sure that you are not only able to work with the data, but explain the data as well.</p><h4>Business understanding and communication</h4><p>This ties back to the previous point. This is a highly technical field, and a good portion of your communication will be with those aren’t working in data science. For everything you build, have mental conversations with yourself at each step architecting how you would explain this to non-technical stakeholders. As powerful as data science is, it is useless if you can not communicate your work to everyone.</p><h4>Computer architecture and CLI tools</h4><p>Understanding how the hardware that drives your data science work is paramount. You don’t need to be a master of the Linux kernel, but you should have a good grasp on what exactly is going on under the hood. Be aware of how many CPU cores are at your disposal, as there will be times where using parallel processing will aid in your workflow. Furthermore, tools like Github and AWS have command line tools that make life a lot easier. A good starting point is usually by using GitHub’s CLI.</p><h4>ETL</h4><p>It is <strong>data </strong>science after all. Developing a good sense of extract, transform, and load will make your life a lot easier. For example, if you are interfacing a SQL database from Python, encapsulate your read-in function from the beginning so you are not constantly reinstantiating connection parameters each time you want to pipe data in. If you have data that is updated on a regular cadence, define some functions that can preview and analyze the data simply with one function call.</p><h3><strong>2. Business Solutions Are Different Than Academia</strong></h3><p>Throughout your career, you will find yourself posed with a problem that you have the keys to solve. Let’s say you’re a toy company, and you’re asked to determine high, medium, and low performing products. It could be tempting to create a myriad of different features, and run something like K-Means clustering to determine which products are in which tiers. While this is certainly a viable solution, you may encounter some trouble when you have to explain how it’s actually clustering products. It may be too difficult to try and explain how Euclidean distance and the Elbow-Test works. Instead, you could choose a heuristic like share of revenue or unit sales for each product, and divide them into percentiles. This is a much simpler and explainable solution, and will likely yield reliable and repeatable results.</p><p>I don’t say this to deter data scientists from employing complex solutions, but data science is about striking a balance between complexity and explainability. If you’re building a framework that seeks to model a continuous variable, start with a linear regression model. From there, if you need to introduce non-linearity or more complexity, then it is best to derive a more complex framework. Simplicity is always key, and slowly mix-in more nuance as needed.</p><h3><strong>3. When Learning, Use LLMs Wisely</strong></h3><p>This takeaway has become increasingly relevant. Large language models have led to a massive increase in people attempting to learn how to code. While it can be a fantastic tool to encourage learning, it should not be your only tool. Use resources like textbooks, Github repos, Stack Overflow, Kaggle, and Reddit to study first-hand accounts of data science projects. LLMs, while trained on nearly all of this content, are diluted and can lead to a lessened understanding. Don’t copy code from an LLM, use documentation to fuel your understanding and write it yourself.</p><p>I find that the best place to use an LLM like ChatGPT for studies is when you are building something and want to challenge an assumption. One of my favorite things to do is pass an equation or code snippet and say “hey, can you challenge me on the assumptions I’m making? What do you think are good areas for betterment?” This way, I have already built something and am merely trying to make incremental improvements.</p><h3><strong>4. Master the Cloud Services</strong></h3><p>While the classic duo of Jupyter and your laptop is always a great foundation, you will never, <em>ever</em>, host a model on your local machine. Cloud platforms like DigitalOcean, AWS, and GCP are necessities when you want to deploy a model. I understand the hesitation for many, as these services currently boast dozens of different functionalities. For AWS, a good data science stack could be:</p><ul><li>AWS S3 (data lake for flat files, raw data)</li><li>AWS Redshift (data warehouse)</li><li>AWS Sagemaker (modeling)</li><li>AWS EC2 (virtual machine for deployment)</li></ul><p>A good starting point is to build an extremely simple model and try to deploy it to a small DigitalOcean VM. You could read in daily stock market data, and train a dummy linear regression model that is updated and retrained daily. But doing this will be a gentle introduction to services that exponentially become more complex.</p><h3><strong>5: Kaggle is Great, but Data Science Does Not Live in Notebooks</strong></h3><p>Similarly to my previous point, exploration is only part of the data science puzzle. Kaggle is primarily comprised of demonstrations on how to analyze data and build models, but it doesn’t really show you how to deploy them. To better understand how to analyze, build, train, and select models, Kaggle is a great resource. To actually understand how to deploy them, you will have to move outside of the Jupyter notebook and start to read on how you can encapsulate your code and pickle your models to prepare them for production.</p><p>Most production models are never run through Jupyter notebooks. If you are working on a modeling problem, you should be thinking throughout the exploration process: “how will each of these steps be prepared for deployment?”</p><h3><strong>6. Follow the Hype, but Classical ML Runs Everything</strong></h3><p>Large language models and natural language processing are the hot topics of modern data science — and rightfully so. These models are limitless in their power and prowess, but that should not be where your journey starts. Transformers are the foundational model that fuel large language models. Under the hood of transformers, are a series of neural networks and linear algebra operations. Under the hood of neural networks are more linear algebra operations and some Calculus III. I draw this path to illustrate that all of machine learning is underpinned by advanced mathematics and classical machine learning principles.</p><p>Use these more complex frameworks to better drive your understanding of the mathematics behind them. Study how backpropagation and partial derivatives work, then move forward to understand how neural networks can be reshaped to be recurrent, generative, or convolutional (once again, all built on these principles). It gets lost in translation quite a bit today, but classical machine learning principles will always be king.</p><h3><strong>7: Building Projects</strong></h3><p>Having a strong portfolio is obviously a necessity when searching for a job in data science. Researching and developing your own projects is a great way to make yourself stand out amongst candidates. Coming from someone who has many projects that live in the Jupyter notebook graveyard, I can attest that there is a better way to be building projects.</p><p>I think the best way to showcase your skills as a data scientist is a demonstration of all necessary tools, on a simple dataset. Start with Kaggle and find any dataset. Create a notebook that explores the data and define an objective. Show you’re development process in this notebook. Once you’ve built all the necessary functions, put them into a Python file so that you can prepare it for deployment. Then, create a pipeline that can repeatably complete your objective. Build a simple frontend using Streamlit (it could literally be a button click that runs the pipeline and displays the output). Then deploy it. You’ve now built an end to end machine learning project that not only demonstrates your data science chops, but also some MLOps understanding as well.</p><h3><strong>8. Mathematics of ML</strong></h3><p>Arguably what got me into data science, a strong understanding of mathematics is necessary in order to become a prosperous data scientist. It’s hard to say which discipline is the most prevalent, but there’s a few that are everywhere:</p><p><strong>Linear algebra</strong> is used to compute linear combinations of features and weights. It’s also used to generalize problems like least squares and support vector machines. Matrix-vector notation is literally everywhere in literature, so it will be key to understand how they generate problems to datasets. The subject is tricky, but the actual principles that are used in data science are quite simple if you take the time to learn it.</p><p><strong>Calculus III</strong> appears when using partial derivatives. Most commonly, you use partial derivatives to in Gradient Descent to optimize a loss function, or to calculate a neuron’s gradient during Backpropagation. Actually, learning backpropagation is a fantastic exercise to test your knowledge of linear algebra AND calculus III.</p><p><strong>Probability and statistics</strong> (admittedly my least favorite) is also everywhere, and arguably the most important. Linear models are driven by probabilistic viewpoints and assumptions. Furthermore, a whole class of data science models are driven by statistical inference.</p><h3><strong>9. Encourage Socialization</strong></h3><p>Computer science and mathematics are often seen as isolated, “heads-down” fields. Because they are so technically intense, a lot of a practitioner’s time can be spent pencil on paper or hands on keys. It doesn’t have to strictly be this way, though. Having dialogues with others about subjects and topics that interest you can significantly increase understanding. Move away from the textbook and talk out loud about it! During my Master’s, one of my favorite things to do would be to stroll into a professor’s office, pick up a piece of chalk, and write out a problem that was conceptually confusing me. We would have dialogues while I solved it, discussing each step in detail. I attribute much of my mathematical understanding to these chats.</p><p>It doesn’t have to be in person, either! Go on Reddit, Cross Validated (Data Science’s Stack Overflow), and post a question. People are active everyday, and are usually more friendly than you may think.</p><p>Finally, encourage kindness and lift others up. Unfortunately, there is a competitive spirit in computer and data science that can often be unkind and destructive. The more experienced you become, start to turn outwards and help others getting into the field — because one day they will thank you for your assistance in their success.</p><h3><strong>10. Be Annoying, Be Proud, and Self-Advertise</strong></h3><p>I’m sure you’re thinking, how is it productive to be annoying? Let me explain further — be annoying in the way that you are relentlessly proud of the work that you do. When building something, post on LinkedIn and be vocal about what you’re doing. People will take notice, and it will get your name as a data scientist out there. Make connections, and seek dialogues with people inside and outside of data science. It is a beautifully vast and complex field that is supported by those with a desire to continuously learn.</p><p>I hope anyone reading this truly resonates with some of these takeaways. When I began my data science journey around 5 years ago, I felt daunted by the scale. But by focusing on these core values, I found myself ever improving and with a curiosity that only continued to grow.</p><p>I hope anyone reading this truly resonates with some of these takeaways. When I began my data science journey around 5 years ago, I felt daunted by the scale. But by focusing on these core values, I found myself ever improving and with a curiosity that only continued to grow.</p><p>If you want to chat about anything data science or math related, feel free to email <a href="/service/mailto:bstager@tulane.edu">bstager@tulane.edu</a>, and I will be happy to chat! You can also find my projects on <a href="https://github.com/benstager">https://github.com/benstager</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71d7463d9813" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MfL: Predicting the Success of 2025 Quarterback Prospects]]></title>
            <link>https://medium.com/@bstager/mfl-predicting-the-2025-quarterback-draft-future-7fbab9a1992f?source=rss-3cbc3887b6e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fbab9a1992f</guid>
            <category><![CDATA[football-analytics]]></category>
            <category><![CDATA[sports-data]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Benjamin Stager]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 02:22:32 GMT</pubDate>
            <atom:updated>2025-04-24T02:31:30.589Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fdPvL3cGDC5fcQ1m" /></figure><p>Every year, owners across the National Football League are faced with an almost possible challenge: if, and when, they should draft a quarterback. As the position continually evolves, it has only become more difficult to try and determine the best spot to draft a signal caller. Therefore, attempted to build a binary classification model that would try and predict the best spots to be picked for this year’s quarterbacks. This article will serve as a demonstration of how to build a model pipeline, as well as a meta-analysis of this year’s draft class.</p><h4>Outline</h4><p>The purpose of this article is to demonstrate how you can build a modeling pipeline in Python related to professional sports prediction. My ultimate goal was to build a binary classification model in advance of the 2025 NFL Draft. As this is a draft model, I restricted myself to only using data that would be readily available before the draft — college data, historical draft data, and franchise related pick data. The workflow for developing such a model is listed below:</p><ol><li>Data Collection</li><li>Exploratory Data Analysis</li><li>Model Development</li><li>Model Evaluation and Results</li><li>2025 Out of Sample Predictions</li><li>Limitations and Further Work</li></ol><h4>Data Collection</h4><p>Football data, both NFL and, especially, College Football, is notoriously not readily available. Due to this limitation, I first chose to evaluate the existing data that I had access to and from there judge how much more data I would need. Beginning with my imports…</p><pre># NFL data<br>import mfl as mfl<br>import pandas as pd<br>import numpy as np<br>import mfl.api.data_loaders as mfldata<br>import nfl_data_py as nfl<br><br># Linear modeling <br>from sklearn.linear_model import LogisticRegression<br>from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier<br>from sklearn.svm import SVC<br>from sklearn.model_selection import train_test_split, StratifiedKFold<br>from sklearn.metrics import accuracy_score, f1_score, roc_auc_score, recall_score, precision_score, precision_recall_curve, mean_squared_error, mean_absolute_error<br><br># Gradient boosted trees<br>from xgboost import XGBClassifier, XGBRFClassifier<br>from catboost import CatBoostClassifier, CatBoostRegressor<br><br># Deep learning<br>import keras<br>from keras.layers import Dense, ReLU, Bidirectional, Normalization, Dropout, Input<br>from keras.models import Sequential<br><br># Clustering<br>from sklearn.cluster import KMeans<br><br># Webscraping<br>import requests<br>from bs4 import BeautifulSoup<br>import time<br><br># Plotting<br>import seaborn as sns<br>import matplotlib.pyplot as plt</pre><p>The first step is to judge how much readily available data I have, using the nfldatapy package. This API provides week-by-week historical NFL data, as well as some basic information about each draft pick, since 1999. For simplicity sake, I will only include 2010–2022 draft data, as many quarterback’s careers post 2022 are still panning out. Profiling this gives…</p><pre><br>years = range(2010, 2023)<br>data = nfl.import_weekly_data(years)<br>draft = nfl.import_draft_picks(years)<br><br>print(draft.columns)<br><br>Index([&#39;season&#39;, &#39;round&#39;, &#39;pick&#39;, &#39;team&#39;, &#39;gsis_id&#39;, &#39;pfr_player_id&#39;,<br>       &#39;cfb_player_id&#39;, &#39;pfr_player_name&#39;, &#39;hof&#39;, &#39;position&#39;, &#39;category&#39;,<br>       &#39;side&#39;, &#39;college&#39;, &#39;age&#39;, &#39;to&#39;, &#39;allpro&#39;, &#39;probowls&#39;, &#39;seasons_started&#39;,<br>       &#39;w_av&#39;, &#39;car_av&#39;, &#39;dr_av&#39;, &#39;games&#39;, &#39;pass_completions&#39;, &#39;pass_attempts&#39;,<br>       &#39;pass_yards&#39;, &#39;pass_tds&#39;, &#39;pass_ints&#39;, &#39;rush_atts&#39;, &#39;rush_yards&#39;,<br>       &#39;rush_tds&#39;, &#39;receptions&#39;, &#39;rec_yards&#39;, &#39;rec_tds&#39;, &#39;def_solo_tackles&#39;,<br>       &#39;def_ints&#39;, &#39;def_sacks&#39;],<br>      dtype=&#39;object&#39;)<br><br>print(data.columns)<br><br>Index([&#39;player_id&#39;, &#39;player_name&#39;, &#39;player_display_name&#39;, &#39;position&#39;,<br>       &#39;position_group&#39;, &#39;headshot_url&#39;, &#39;recent_team&#39;, &#39;season&#39;, &#39;week&#39;,<br>       &#39;season_type&#39;, &#39;opponent_team&#39;, &#39;completions&#39;, &#39;attempts&#39;,<br>       &#39;passing_yards&#39;, &#39;passing_tds&#39;, &#39;interceptions&#39;, &#39;sacks&#39;, &#39;sack_yards&#39;,<br>       &#39;sack_fumbles&#39;, &#39;sack_fumbles_lost&#39;, &#39;passing_air_yards&#39;,<br>       &#39;passing_yards_after_catch&#39;, &#39;passing_first_downs&#39;, &#39;passing_epa&#39;,<br>       &#39;passing_2pt_conversions&#39;, &#39;pacr&#39;, &#39;dakota&#39;, &#39;carries&#39;, &#39;rushing_yards&#39;,<br>       &#39;rushing_tds&#39;, &#39;rushing_fumbles&#39;, &#39;rushing_fumbles_lost&#39;,<br>       &#39;rushing_first_downs&#39;, &#39;rushing_epa&#39;, &#39;rushing_2pt_conversions&#39;,<br>       &#39;receptions&#39;, &#39;targets&#39;, &#39;receiving_yards&#39;, &#39;receiving_tds&#39;,<br>       &#39;receiving_fumbles&#39;, &#39;receiving_fumbles_lost&#39;, &#39;receiving_air_yards&#39;,<br>       &#39;receiving_yards_after_catch&#39;, &#39;receiving_first_downs&#39;, &#39;receiving_epa&#39;,<br>       &#39;receiving_2pt_conversions&#39;, &#39;racr&#39;, &#39;target_share&#39;, &#39;air_yards_share&#39;,<br>       &#39;wopr&#39;, &#39;special_teams_tds&#39;, &#39;fantasy_points&#39;, &#39;fantasy_points_ppr&#39;],<br>      dtype=&#39;object&#39;)<br><br></pre><p>As previously mentioned, while these datasets provide good professional data, the college statistics are rather limited. Therefore, I built a webscraper that could parse information on Sports Reference College Football, shown below:</p><pre>def scrape_NFL_REF_QB(player_name):<br><br>    first_name = player_name.split(&#39; &#39;)[0].lower()<br>    last_name = player_name.split(&#39; &#39;)[1].lower()<br>    player_url = f&#39;https://www.sports-reference.com/cfb/players/{first_name}-{last_name}-1.html&#39;<br>    html_content = requests.get(player_url).text<br><br>    if len(player_name.split(&#39; &#39;)) &gt; 2:<br>        first_name = player_name.split(&#39; &#39;)[0].lower()<br>        last_name = player_name.split(&#39; &#39;)[1].lower()<br>        suffix = player_name.split(&#39; &#39;)[2].lower()<br>        player_url = f&#39;https://www.sports-reference.com/cfb/players/{first_name}-{last_name}-{suffix}-1.html&#39;<br>        html_content = requests.get(player_url).text<br><br><br>    soup = BeautifulSoup(html_content, &#39;html.parser&#39;)<br>    table = soup.find(&#39;table&#39;, {&#39;id&#39;: &#39;passing_standard&#39;})<br><br>    if not table:<br>        for idx in range(2, 6):<br>            time.sleep(3)<br>            first_name = player_name.split(&#39; &#39;)[0].lower()<br>            last_name = player_name.split(&#39; &#39;)[1].lower()<br>            player_url = f&#39;https://www.sports-reference.com/cfb/players/{first_name}-{last_name}-{idx}.html&#39;<br>            html_content = requests.get(player_url).text<br>            <br>            soup = BeautifulSoup(html_content, &#39;html.parser&#39;)<br>            table = soup.find(&#39;table&#39;, {&#39;id&#39;: &#39;passing_standard&#39;})<br>            <br>            if not table:<br>                print(f&quot;Passing stats table not found for {player_name}. Failed on index {idx}&quot;)<br>            else:<br>                print(f&quot;Player found on index {idx}&quot;)<br>                break<br>    <br>    try:<br>        table.find_all(&#39;th&#39;)<br>        headers = [th.getText() for th in table.find_all(&#39;th&#39;)]<br>        yrs = [i for i in headers if (&#39;2&#39; in i) &amp; (len(i) == 4 or len(i) == 5)]<br>        career_idx = headers.index(yrs[-1]) + 1<br>        baseline_headers = []<br>        headers = [th.getText() for th in table.find_all(&#39;th&#39;)]<br>        rows = []<br><br>        for tr in table.find_all(&#39;tr&#39;)[1:]:<br>            cells = [td.getText() for td in tr.find_all(&#39;td&#39;)]<br>            if cells: <br>                rows.append(cells)<br><br>        career_stats = []<br><br>        for row in rows:<br>            if row.count(&#39;&#39;) == 2:<br>                career_stats.extend(row)<br>                break<br><br>        career_stats.remove(&#39;&#39;)<br>        career_stats.remove(&#39;&#39;)<br><br>        career_stats.append(len(yrs))<br>        career_stats.append(player_name)<br><br>        column_names = [<br>        &#39;G&#39;,        <br>        &#39;Cmp&#39;,      <br>        &#39;Att&#39;,      <br>        &#39;Cmp%&#39;,     <br>        &#39;Yds&#39;,      <br>        &#39;TD&#39;,       <br>        &#39;TD%&#39;,      <br>        &#39;Int&#39;,      <br>        &#39;Int%&#39;,     <br>        &#39;Y/A&#39;,      <br>        &#39;AY/A&#39;,     <br>        &#39;Y/C&#39;,      <br>        &#39;Y/G&#39;,      <br>        &#39;Rate&#39;,<br>        &#39;seasons&#39;,<br>        &#39;name&#39;<br>        ]<br><br>        final = pd.DataFrame({name: [value] for name, value in zip(column_names, career_stats)})<br><br>        if len(career_stats) == len(column_names):<br>            final = pd.DataFrame({name: [value] for name, value in zip(column_names, career_stats)})<br>        else:<br>            print(&quot;Error: Number of stats does not match number of column names.&quot;)<br><br>        return final    <br>    except:<br>        print(f&quot;FAILED: On {player_name}&quot;)</pre><p>This webscraper was extremely effective in providing aggregate college statistics like TD’s, INT’s, Seasons Played, and more. As this is often a frowned upon procedure, I had to proceed with rate limiting caution. (Sorry Sports Ref!)</p><p>Once this was completed, I began by scraping college data for each NFL quarterback. A limitation with this scraper is that it can not locate non-FBS player data, so there were some gaps in my final dataset. From here, I performed some data merging to loop in other static statistics like round picked, year picked and more.</p><pre>all_qbs = draft[draft[&#39;position&#39;] == &#39;QB&#39;]<br>all_qb_names = all_qbs[&#39;pfr_player_name&#39;].unique().tolist()<br><br>raw_data = []<br>for name in all_qb_names:<br>    print(name)<br>    raw_data.append(scrape_NFL_REF_QB(player_name=name))<br>    time.sleep(3)<br><br>extracted_data = pd.concat([i for i in raw_data if i is not None])<br>processing = data[data[&#39;player_display_name&#39;].isin(all_qb_names)].sort_values([&#39;player_display_name&#39;, &#39;season&#39;]).groupby([&#39;player_display_name&#39;, &#39;recent_team&#39;], sort=False).agg({&#39;season&#39;:&#39;nunique&#39;}).reset_index()<br>final_years_1st_team = processing.groupby(&#39;player_display_name&#39;).agg({&#39;season&#39;:&#39;first&#39;})<br><br>draft_teams = data[data[&#39;player_display_name&#39;].isin(all_qb_names)].groupby([&#39;player_display_name&#39;]).agg({&#39;recent_team&#39;:&#39;first&#39;})<br><br>df_with_teams = pd.merge(left=extracted_data, <br>                         right=draft_teams, <br>                         left_on=&#39;name&#39;,<br>                         right_on=&#39;player_display_name&#39;,<br>                         how=&#39;left&#39;)<br><br>df_with_draft_teams = pd.merge(left=all_qbs[[&#39;pfr_player_name&#39;, &#39;round&#39;, &#39;pick&#39;, &#39;season&#39;, &#39;allpro&#39;, &#39;seasons_started&#39;]],<br>                               right=df_with_teams,<br>                               left_on=&#39;pfr_player_name&#39;,<br>                               right_on=&#39;name&#39;,<br>                               how=&#39;left&#39;<br>                               )<br><br>final_years_1st_team = final_years_1st_team.rename(columns={&#39;season&#39;:&#39;seasons_with_draft_team&#39;})<br><br>final = final[[&#39;pfr_player_name&#39;, &#39;round&#39;, &#39;pick&#39;, &#39;season&#39;, &#39;G&#39;, &#39;Cmp&#39;, &#39;Att&#39;, &#39;Cmp%&#39;,<br>       &#39;Yds&#39;, &#39;TD&#39;, &#39;TD%&#39;, &#39;Int&#39;, &#39;Int%&#39;, &#39;Y/A&#39;, &#39;AY/A&#39;, &#39;Y/C&#39;, &#39;Y/G&#39;, &#39;Rate&#39;,<br>       &#39;seasons&#39;,&#39;recent_team&#39;, &#39;seasons_with_draft_team&#39;]]<br><br>final = final.rename(columns={&#39;season&#39;:&#39;draft_year&#39;,&#39;pfr_player_name&#39;:&#39;player_name&#39;, &#39;seasons&#39;:&#39;college_seasons&#39;})<br><br>final.to_csv(&quot;~/Desktop/mfl_project/mfl/data/full_qb_dataset_v2.csv&quot;,index=False)</pre><p>Note that in the modeling process I ultimately determine what the best response variable for the binary classification model will be.</p><p><strong>Exploratory Data Analysis (FINISH)</strong></p><p>Part of any modeling process is Exploratory Data Analysis (or EDA). There are some interesting things that have happened in the last decade in the draft — below are some of my favorite things that I’ve found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*0Qdc65tKzf26Uyys43flYA.png" /><figcaption>Browns leading the charge as always</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*_90M4DuQR-ECV_5r3G03Nw.png" /><figcaption>Significant longevity drop-off after the 2nd round</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*brqVhazDd-T-auyeyDx2Gw.png" /><figcaption>Top prospects over the years</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*AIkiGNQ_nIOaU-PrzOhi8w.png" /><figcaption>Only about 30% of Quarterbacks drafted since 2010 have started more than 3 years</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*g_UH9nlPYb_0t533MzQyNQ.png" /><figcaption>Quarterback quality, round agnostic, has significantly increased over the years</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*w634hSIiAxuyqxXrdjUsYQ.png" /><figcaption>Feature correlation. Notice how you are clearly more likely to start more the higher you are picked</figcaption></figure><h4>Model Development</h4><p>I wanted to make the modeling process for this as simple as possible — as I spent a significant amount of time pulling in the data itself. As I’ve said, the goal of this is to just show a routine pipeline.</p><p>My choice of model was “CatBoostClassifier” from Python package ‘catboost’. This is an extremely effective gradient boosted tree model, that supports things like feature encoding and automatic scaling. As for the response variable, I<strong> </strong>chose<strong> positive samples to be quarterbacks who started for 3 or more years, and negative samples to be those who started less than 3 years. </strong>Naturally, this approach has serious limitations — as teams are often more inclined to trot out a higher round investment for longer, than a lower round investment. But my indicator of a successful pick will be if, at any point, they started more than 3 years in their career.</p><p>Helper functions:</p><pre>def map_years_with_draft_team(x):<br>        if x &gt;= 4:<br>            return 1<br>        else: <br>            return 0<br>        <br>def map_seasons_started(x):<br>     if x &gt;=3: <br>          return 1<br>     else:<br>          return 0<br><br>    <br>def score(y_test, y_probs, y_preds):<br>    accuracy = accuracy_score(y_test, y_preds)<br>    f1 = f1_score(y_test, y_preds)<br>    roc_auc = roc_auc_score(y_test, y_probs)<br>    recall = recall_score(y_test, y_preds)<br>    precision = precision_score(y_test, y_preds)<br><br>    metric_dict = {<br>        &#39;accuracy&#39; : accuracy,<br>        &#39;f1&#39; : f1,<br>        &#39;roc_auc&#39;: roc_auc,<br>        &#39;recall&#39;: recall,<br>        &#39;precision&#39;: precision<br>    }<br><br>    return metric_dict</pre><p>To model, I used all features and excluded ones that were irrelevant or could cause data leakage: player names, seasons with draft team, etc.</p><p>The model driver code is shown below:</p><pre>def catboost(df, year_cutoff=2019, feature_set=None, kfold=False, folds=2):<br><br>    df = df.dropna()<br>    df = df[df[&#39;draft_year&#39;] &lt;= year_cutoff]<br><br>    if feature_set is None:<br>        X = df.drop([&#39;player_name&#39;, &#39;pfr_player_name&#39;, &#39;seasons_with_draft_team&#39;, &#39;seasons_started&#39;],axis=1)<br>        y = df[&#39;seasons_started&#39;]<br>    elif feature_set is not None:<br>        pass # didn&#39;t build t<br>    <br>    X = X<br>    y = y<br>    y_mapped = y.apply(map_years_with_draft_team)<br>    y_mapped = y.apply(map_seasons_started)<br><br>    X_train, X_test, y_train, y_test = train_test_split(X, y_mapped, test_size=.25, stratify=y_mapped, shuffle=True)<br><br>    model = CatBoostClassifier(one_hot_max_size=15,<br>                                iterations=500, <br>                                cat_features=X.select_dtypes(include=&#39;object&#39;).columns.tolist())<br>    <br>    model.fit(X_train, y_train)<br><br>    y_preds = model.predict(X_test)<br>    y_probs = model.predict_proba(X_test)[:,1]<br><br>    metrics = score(y_test, y_probs, y_preds)<br>    <br>    model.fit(X, y_mapped)<br>    fit_model = model<br>    model_results = pd.DataFrame(metrics, index=[0])<br><br>    return model, model_results</pre><p>There are clear limitations to this approach — which I will discuss a little bit later. The main workflow is governed by passing a DataFrame object, and creating training and validation sets off of that. All features are used for this classifier — another clear limitation. Since seasons started are initially encoded as an ordinal variable, I had to apply a mapping function to conver them into a binary response variable. I used a typical 75–25 training-testing split, and some rudimentary hyperparameters for the classifier.</p><h4><strong>Model Evaluation and Results</strong></h4><p>The models results are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*KEeNoRDUz_5GbyIX-ncWlA.png" /></figure><h4><strong>Out Of Sample Prediction</strong></h4><p>Now that the model is trained, we can see which QB’s are most likely to succeed in the NFL at their likely draft position. Since we don’t actually know who will be picked where and when yet (sans Cam Ward), I predicted out each quarterback at every pick and team of the draft, and took note where the relative spikes were. Due to the nature of NFL franchises, a quarterback picked in the 1st vs. 4th, regardless of who it is, will have a much higher chance of starting more seasons due to the sunk cost fallacy. But, a quarterback picked at the 15th vs. 16th pick of the 1st round could have very interesting differences in probability.</p><p>The out of sample predictive algorithm I used is shown below:</p><pre>def predict_2025_qb(model, player_name, round, pick, recent_team, predictors, season=2025):<br>    season = season<br>    variant_features = [&#39;round&#39;, &#39;pick&#39;, &#39;draft_year&#39;]<br>    available_features = np.setdiff1d(model.feature_names_[:-1], variant_features).tolist()<br>    predictors = predictors[available_features]<br>    <br>    initial_features = pd.DataFrame({<br>        &#39;round&#39; : round,<br>        &#39;pick&#39; : pick,<br>        &#39;draft_year&#39; : season<br>    }, index=[0])<br>    <br>    processing = pd.concat([initial_features, predictors], axis=1)<br>    processing[&#39;recent_team&#39;] = recent_team<br>    prediction = model.predict_proba(processing).tolist()[0][1]<br><br>    result_dict = {<br>         &#39;player_name&#39; : player_name,<br>         &#39;round&#39; : round,<br>         &#39;pick&#39; : pick,<br>         &#39;prob&#39; : prediction<br>    }<br>    <br>    return pd.DataFrame(result_dict, index=[0])</pre><p>Then iterate over 2025 draft position to get the final modeled dataset:</p><pre>draft_order = pd.read_excel(&quot;~/Downloads/Top Prospects for the 2025 NFL Draft-2.xlsx&quot;, sheet_name=&#39;2025 NFL Draft Order&#39;, skiprows=1)<br><br>abbreviations = [&#39;TEN&#39;, &#39;CLE&#39;, &#39;NYG&#39;, &#39;NE&#39;, &#39;JAX&#39;, &#39;LV&#39;, &#39;NYJ&#39;, &#39;CAR&#39;, &#39;NO&#39;, &#39;CHI&#39;, &#39;SF&#39;, &#39;DAL&#39;, &#39;MIA&#39;, &#39;IND&#39;, &#39;ATL&#39;, &#39;ARI&#39;, &#39;CIN&#39;, &#39;SEA&#39;, &#39;TB&#39;, &#39;DEN&#39;, &#39;PIT&#39;, &#39;LAC&#39;, &#39;GB&#39;, &#39;MIN&#39;, &#39;HOU&#39;, &#39;LAR&#39;, &#39;BAL&#39;, &#39;DET&#39;, &#39;WAS&#39;, &#39;BUF&#39;, &#39;KC&#39;, &#39;PHI&#39;]<br>teams = draft_order[&#39;Team&#39;].unique()<br><br>team_mapping = {i:j for i,j in zip(teams, abbreviations)}<br><br>draft_order[&#39;abbrev&#39;] = draft_order[&#39;Team&#39;].apply(lambda team: team_mapping[team])</pre><pre>def predict_full_draft(player_name, draft_order):<br>    season = 2025<br>    player_data = mfldata.scrape_NFL_REF_QB(player_name)<br>    results = []<br>    for pick, team in zip(draft_order[&#39;Pick&#39;], draft_order[&#39;abbrev&#39;]):<br>        if pick &lt;= 224:<br>            round = math.ceil(pick/32)<br>        else:<br>            round = 7<br>        result = predict_2025_qb(model=model, <br>                                 player_name=player_name, <br>                                 round=round, <br>                                 pick=pick,<br>                                 recent_team=team,<br>                                 predictors=player_data,<br>                                 season=season)<br>        results.append(result)<br>    final = pd.concat(results)<br><br>    return final<br><br>modeled_results = pd.concat([predict_full_draft(player_name=qb, draft_order=draft_order) for qb in qbs_of_interest])</pre><p>The quarterbacks of interest to me (and many other NFL franchises) are going to be:</p><ol><li>Cam Ward</li><li>Shedeur Sanders</li><li>Jalen Milroe</li></ol><p>After prediction, across 257 pick spots, here are the compared probabilities for Cam Ward, Shedeur Sanders, and Jalen Milroe:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*vJ96Lk4BngEo_EssDnJAKQ.png" /></figure><p>Listed below is an analysis of some of the highest mocked quarterbacks in this draft, where dots indicate their likely draft positions. The green dot indicates the best landing spot for that specific quarterback.</p><p><strong>Cam Ward (Miami, Likely 1st Overall Pick)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*H1WBqX2DRKiYRfy30R-Zgg.png" /><figcaption>Cam Ward from Miami will likely be picked 1st overall, with a roughly <strong>83% chance </strong>to start for 3 years or more</figcaption></figure><p><strong>Shedeur Sanders (Colorado, Likely 1st Rounder)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*s8W29C__B-5WvrepjjBg0A.png" /><figcaption>As expected, Shedeur Sanders best landing spot is the Giants at 3rd overall, with an<strong> 85% chance </strong>to start for 3 years or more</figcaption></figure><p><strong>Jalen Milroe (Alabama, Late 1st to Early 2nd Rounder)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*LBlg3d2broayerSBJFqInQ.png" /><figcaption>Maybe surprisingly, the Giants are the best landing spot for Jalen Milroe in his expected draft range — with a <strong>58% chance</strong> of starting 3 or more years for them</figcaption></figure><p><strong>My Cleveland Browns!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*gwOz_q_cJT6a5gUflsqWdw.png" /><figcaption>The model says that the best quarterback for Cleveland, my favorite team, at 2.33 is Jaxson Dart from Ole Miss (<strong>48% chance</strong> to start for 3 years or more)</figcaption></figure><h4>Limitations</h4><p>Below are some clear limitations I recognize with my approach, and some words about the direction I’d like to take this project in.</p><p><strong>Training Data (Samples and Features)</strong></p><p>I was extremely limited in the data I had. Using primarily aggregate college statistical data, it prioritized players who had lengthy careers with good stats. <strong>Jaxson Dart</strong> had the highest average probability across the first two rounds, which many draft experts would laugh at it. <strong>Dillon Gabriel</strong>, a talented but physically limited and older QB from Oregon, also performed extremely well. On the next iteration of this model, I plan on including temporal college statistics — tracking things like top 5, and top 25 wins over time, injury history, strength of schedule, and more. While it may just be too hard to statistically predict quarterbacks without the “Eye Test”, I know that I can improve performance — even marginally. I also would like to include data about the team that plans on drafting them at the hypothetical position, such as if they are actively seeking quarterback (perhaps makes them more likely to reach and put the QB in a precarious situation).</p><p>I also only extended my dataset back to 2010 — although I have readily available data from 1999. By simply adding more training examples, I could’ve easily introduced a lot more nuance and depth into the model.</p><p><strong>Model Development</strong></p><p>I rushed and used a relatively out of the box framework in CatBoost, and think that investing more time in running simulations with non-parametric models, deep learning frameworks, and even rudimentary logistic regression models would be better.</p><p>I had little consideration for hyperparameter tuning, which would likely offer some incremental increase in performance.</p><p>I also believe that being more considerate of feature selection, in addition to the aforementioned feature engineering, would provide considerable increases in accuracy and out of sample prediction.</p><p><strong>Inclusion of Domain Knowledge</strong></p><p>While I consider myself an avid NFL and College Football fan, it is hard to speak directly to a machine learning model. Pundits, analysts, and draft experts often have significant influence on draft positioning and QB success, and by introducing some of the rhetoric revolving around these quarterbacks, I believe that the model can be considerably improved. Perhaps adding NLP features may be paramount to the success of the model.</p><p><strong>Response Variable</strong></p><h4>Further Work</h4><p>I plan on continuing to develop this model in a myriad of ways. By including the suggestions above, as well as researching, historically, the best ways to model future professional success, I think there is room for genuine improvement to this project. I’d also like to encapsulate this into an open-source package (something I’ve already begun doing locally).</p><p>If you have any questions or comments, please email bstager@tulane.edu.</p><p>Go Browns!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fbab9a1992f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>