<?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 William Yee on Medium]]></title>
        <description><![CDATA[Stories by William Yee on Medium]]></description>
        <link>https://medium.com/@williamwahyee?source=rss-b899c7dba259------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4ayuQsCQ_I95D7bL.jpg</url>
            <title>Stories by William Yee on Medium</title>
            <link>https://medium.com/@williamwahyee?source=rss-b899c7dba259------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 06:34:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@williamwahyee/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[Monte Carlo Simulations: The Intersection of Probabilistic and Deterministic]]></title>
            <link>https://medium.com/data-science/monte-carlo-simulations-the-intersection-of-probabilistic-and-deterministic-2720a0b541b1?source=rss-b899c7dba259------2</link>
            <guid isPermaLink="false">https://medium.com/p/2720a0b541b1</guid>
            <category><![CDATA[determinism]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[monte-carlo-method]]></category>
            <dc:creator><![CDATA[William Yee]]></dc:creator>
            <pubDate>Tue, 25 Jun 2019 13:20:33 GMT</pubDate>
            <atom:updated>2019-06-25T14:19:29.071Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi welcome to my blog, I hope you find this helpful as an introduction to Monte Carlo Simulations. What this is, a minimal mathematical approach to Monte Carlo Simulations with simple graphics to illustrate my various points. What this is not, a deep dive into Monte Carlo simulations for very specific and well defined industry problems.</p><p>This data and premise of this Monte Carlo Simulation comes from <a href="https://www.coursera.org/specializations/data-analytics-business">Coursera’s Advance Business Analytics</a> course taught by the faculty at the University of Colorado. Originally, the calculation was performed on Analytic Solver, but I decided to bring the process into an environment that I’m (and hopefully you) more comfortable in, Python.</p><p>First, I used the words probabilistic and deterministic, I should define them in the context of this article.</p><p>Probabilistic: something that can be quantified by a probability distribution. E.G. How many people show up for their flight?</p><p>Deterministic: something that can be calculated from parameters. E.G. If 150 people show up for a flight that has 134 seats, how many people are bumped to the next flight?</p><p>A Monte Carlo Simulation can account for the uncertainty (probabilistic nature) in the parameters of a Deterministic model yielding a probability distribution of possible results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fa9aYaaqqiNfG8ip17-BSA.jpeg" /></figure><h3>The Problem</h3><p>On any given flight, not all passengers complete the process to utilize their purchased seats. In response, airlines typically overbook flights to maximize occupied seats and revenue. However, if the overbooking rate is too high bumped passengers will have to reschedule flights and the overall reputation of the airline will be damaged.</p><h4>Goals:</h4><ul><li>Determine an appropriate overbooking rate, using bumped passengers and revenue cost</li><li>Determine the revenue of any given flight</li></ul><h4>Givens:</h4><ul><li>Historical Data for this specific</li><li>Booking Capacity of Plane: 134 passengers</li><li>Price of ticket: 314USD</li><li>Cost to bump passenger: 400USD</li></ul><p>At this point you maybe tempted to use the expected values of the historical data, or the max/min values, to calculate the expected values for overbooking rate, bumped passengers, and revenue. However, it is possible to have a distribution where the expected value is not a good approximation of the distribution. Such as something multimodal or something with heavy skew.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*2HnoOui8Qi1OVEgOf9bjfQ.png" /><figcaption>Both distributions have a mean of zero and a variance of 5</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*DLjA6aoiLgl3Ywz4LCs0Hg.png" /><figcaption>Both distributions have a mean of 1 and variance of 1</figcaption></figure><h3>The Solution</h3><p>To tackle this problem we need to break it into the follow steps.</p><ol><li>Fit the distributions of the supplied historical data (Probabilistic Inputs)</li><li>Build a mathematical model for flight overbooking process (Deterministic)</li><li>Choose at random from the historical distributions, calculate the results, and repeat (Probabilistic Output)</li></ol><h4>Distribution Fitting of Historical Data</h4><pre>#############<br>###IMPORTS###<br>#############</pre><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import fitter</pre><pre>from scipy.stats import exponnorm , genlogistic</pre><p>Import historical data to python using pandas and view a quick summary</p><pre>hData = pd.read_csv(&#39;data/historicalData.csv&#39;)<br>hData.describe()<br>hData.shape</pre><p>730 observations of 3 features, with zero missing data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*z19dgqYww0UTm0yzhb6z8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WeYXhwOFUJTb0d40Df2hEA.png" /><figcaption>Flight Demand, Historical</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XipbG62A4t14an9x8eOFOw.png" /><figcaption>Number of People that are Ready to Board, Historical</figcaption></figure><p>Let’s use the Fitter Package to model the distribution. Fitter uses 80 distributions from scipy to fit distributions and allows you to plot the results for a visual check.</p><pre>f_demand = fitter.Fitter(hData.Demand, timeout= 100)<br>f_demand.fit()<br>f_demand.get_best()</pre><pre>demand_params = list(f_demand.get_best().values())[0]</pre><pre>f_shows = fitter.Fitter(hData.Shows, timeout =100)<br>f_shows.fit()<br>f_shows.get_best()</pre><pre>shows_params = list(f_shows.get_best().values())[0]</pre><p>The demand fitter output from f_demand.get_best() and f_shows.get_best() are presented below as a python dictionary. The best scipy distribution is the key and the parameters are the stored in the value tuple.</p><pre>{&#39;exponnorm&#39;: (0.4319945610366508, 145.53002093494484, 11.26683008052343)}</pre><pre>{‘genlogistic’: (0.03148397254846405, 144.0118676463261, 0.3243429345277982)}</pre><h4>Mathematical Model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7aplFK1FeyVD_GKybrj6A.png" /><figcaption>Graphical Representation of the Deterministic Model</figcaption></figure><p>The yellow boxes in the above model are inputs. If historical data exists for the inputs, probabilistic distributions will be sampled from randomly and independently.</p><pre>def Planesim(OverbookingLimit =20):<br>    PlaneCap = 134<br>    TicketCost = 314<br>    BumpCost = 400</pre><pre>    BookingCap = OverbookingLimit + PlaneCap<br>    AcutalDemand =int(exponnorm.rvs(*demand_params))<br>    Booked = min(BookingCap,AcutalDemand)</pre><pre>    ReadytoBoard = int(genlogistic.rvs(*shows_params))<br>    NoShows = Booked - ReadytoBoard</pre><pre>    Flying = min(ReadytoBoard,Booked,PlaneCap)<br>    Bumped = max(ReadytoBoard - PlaneCap , 0)</pre><pre>    Sold = Booked * TicketCost<br>    Costs = Bumped * BumpCost<br>    Revenue = Sold - Costs</pre><pre>    return Flying, Bumped, Revenue</pre><h4>Simulate 100,000 Flights</h4><p>Now that we have both the modeled distributions and the mathematical formula we can start simulating plane rides to determine the distributions of the outcomes.</p><pre>flyingPassengers = []<br>bumpedPassengers = []<br>revenue = []</pre><pre>for i in range(100000):<br> output = Planesim(10)<br> flyingPassengers.append(output[0])<br> bumpedPassengers.append(output[1])<br> revenue.append(output[2])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NsixhOgQj1Fcs-ORS1NWlw.png" /></figure><p>The above figure is the result of an overbooking limit of 10 passengers. The average Revenue for this flight is $43,121.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ux-K5qlL4uLLwL7GVHRjsQ.png" /></figure><p>The above figure is the result of an overbooking limit of 30 passengers. The average Revenue for this flight is $45,487.</p><h4>Finding the Overbooking Limit for Max Revenue</h4><p>Let’s find the max revenue by iterating through an overbooking limit of 1 to 100. We can accomplish this by running putting our overbooking simulation in a for loop.</p><pre>expected_rev = []<br>overbooking_rate = []<br>for j in range(100):<br>    flyingPassengers = []<br>    bumpedPassengers = []<br>    revenue = []</pre><pre>for i in range(100000):<br>        output = Planesim(j)<br>        flyingPassengers.append(output[0])<br>        bumpedPassengers.append(output[1])<br>        revenue.append(output[2])<br>    overbooking_rate.append(j)<br>    expected_rev.append(np.mean(revenue))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*a5tUoB_m0tMEsx8wFlKw6g.png" /></figure><p>Hmm, looks like there is no maximum solution for Revenue as a Function of Overbooking Limit. Most likely the decision will be made on how tolerant the airline is to rebooking flights.</p><h3>Conclusion</h3><p>We walked through how to build a mathematical model based on a deterministic situation, then added probabilistic parameters where necessary. The historical data was fitted on various scipy distributions to facilitate random selection. Finally, we simulated various levels of overbooking to maximize revenue for this specific situation.</p><p>To see my code for this project, check out my <a href="https://github.com/yeewill/monte_carlo_blog">github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2720a0b541b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/monte-carlo-simulations-the-intersection-of-probabilistic-and-deterministic-2720a0b541b1">Monte Carlo Simulations: The Intersection of Probabilistic and Deterministic</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[A Gentle Introduction to IoT/GPS Trajectory Clustering and Geospatial Clustering]]></title>
            <link>https://medium.com/data-science/a-gentle-introduction-to-iot-gps-trajectory-clustering-and-geospatial-clustering-daba8da8c41e?source=rss-b899c7dba259------2</link>
            <guid isPermaLink="false">https://medium.com/p/daba8da8c41e</guid>
            <category><![CDATA[gps]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <dc:creator><![CDATA[William Yee]]></dc:creator>
            <pubDate>Wed, 19 Jun 2019 21:26:03 GMT</pubDate>
            <atom:updated>2019-06-20T01:15:44.364Z</atom:updated>
            <content:encoded><![CDATA[<p>Internet of things, connected devices, and geospatial data are all hot topics when it comes to developing value-added propositions. In this article, I will provide a gentle introduction to unsupervised learning techniques applied to GPS Trajectories.</p><p>The data comes from <a href="https://www.microsoft.com/en-us/download/details.aspx?id=52367&amp;from=https%3A%2F%2Fresearch.microsoft.com%2Fen-us%2Fdownloads%2Fb16d359d-d164-469e-9fd4-daa38f2b2e13%2F">Microsoft Research Asia</a>, containing data from 182 users and 17,621 trips between April 2007 and August 2012. The data is mostly densely populated with a longitude and latitude recording every 1 to 5 seconds.</p><h3>Data Preparation and Cleaning</h3><p>Now let’s take a look at the data files themselves. Hmm ‘.plt’ format, a format I have never seen before, but let’s open it in text edit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-FFk160TtkYRV_DgBsvjxQ.png" /></figure><p>Okay great, looks like pandas read_csv function will work well with the .plt file format, and the accompanying documentation about the data structure looks accurate.</p><pre>import pandas as pd</pre><pre>colnames = [&#39;lat&#39;,&#39;long&#39;, &#39;null&#39;, &#39;alt&#39; ,&#39;DateTime&#39;,&#39;Date&#39;,&#39;Time&#39;]</pre><pre>df = pd.read_csv(&#39;20090724005608.plt&#39;, skiprows=6, names = colnames)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EClXmwO_-7uwPCYioYu0Og.png" /></figure><p>Having the time series in a data frame is great, but we need to convert each data frame into a single observation with multiple features. Doing so will format the data for loading into clustering algorithm. Let’s aggregate the 10th 25th 50th 75th 90th and average values for speed, acceleration, and jerk . To do so, we are going to write a few python function to apply to each file.</p><pre>def add_feat(df_input):<br>    &quot;&quot;&quot;<br>    This function takes in raw lat long time series from the microsoft geolife data.</pre><pre>Preprocessing notes: skip the first six lines before doing pandas read csv , expecting columns in [&#39;lat&#39;,&#39;long&#39;, &#39;null&#39;, &#39;alt&#39; ,&#39;DateTime&#39;,&#39;Date&#39;,&#39;Time&#39;]</pre><pre>Requres: pandas imported as pd<br>             from vincenty import vincenty<br>         <br>    Adds:<br>        speed<br>        acceleration<br>        jerk<br>        bearing rate<br>        distance travelled<br>    &quot;&quot;&quot;<br>    df = df_input<br>    # add some initial shifts<br>    df[&#39;lat_shift&#39;] = df.lat.shift(-1)<br>    df[&#39;long_shift&#39;] = df.long.shift(-1)<br>    df[&#39;time_shift&#39;] = df.DateTime.shift(-1)<br>    # add speed<br>    def speed(x):<br>        try:<br>            s = vincenty((x[-3],x[-2]),(x[0],x[1]), miles = True) / ((x[-1]-x[4]) * 24)<br>        except:<br>            s= np.nan<br>        return s<br>    df[&#39;speed_mph&#39;] = df.apply(speed,axis =1)<br>    df[&#39;speed_shift&#39;] = df.speed_mph.shift(-1)<br>    # add acceleration<br>    def accel(x):<br>        try:<br>            a = (x[-1] - x[-2]) / ((x[9] - x[4]) *24*60*60)<br>        except:<br>            a = np.nan<br>        return a<br>    df[&#39;acceleration&#39;] = df.apply(accel, axis =1)<br>    df[&#39;acceleration_shift&#39;] = df.acceleration.shift(-1)<br>    # add jerk<br>    def jerk(x):<br>        try:<br>            j = (x[-1] - x[-2]) / ((x[9] - x[4]) *24*60*60)<br>        except:<br>            j = np.nan<br>        return a<br>    df[&#39;jerk&#39;] = df.apply(accel, axis =1)<br>    df[&#39;jerk_shift&#39;] = df.jerk.shift(-1)<br>    # add y for bearing calculator<br>    def y(x):<br>        try:<br>            yy = np.sin((x[8] - x[0]) * np.pi/180) *np.cos( x[7]* np.pi/180)<br>        except:<br>            yy= np.nan<br>        return yy<br>    df[&#39;y&#39;] = df.apply(y, axis =1)<br>    # add x for bearing calculator <br>    def x(x):<br>        try:<br>            xx = np.cos(x[0] * np.pi/180) *np.sin(x[7]* np.pi/180) - np.sin(x[0]* np.pi/180) * np.cos(x[7]* np.pi/180)*np.cos((x[8]-x[1])* np.pi/180)<br>        except:<br>            xx = np.nan<br>        return xx<br>    df[&#39;x&#39;] = df.apply(x,axis =1)<br>    # calculate bearing<br>    def bearing(x):<br>        try:<br>            b = np.arctan2(x[-2],x[-1])*180/np.pi<br>        except:<br>            b = np.nan<br>        return b<br>    df[&#39;bearing&#39;] = df.apply(bearing,axis=1)</pre><pre>df[&#39;brearing_shift&#39;] = df.bearing.shift(-1)<br>    # calculate bearing rate (rate of change of direction)<br>    def bearing_rate(x):<br>        try:<br>            br = abs(x[-1]-x[-2])<br>        except:<br>            br = np.nan<br>        return br<br>    df[&#39;bearing_rate&#39;] = df.apply(bearing_rate,axis=1)<br>    # calculate distance travelled<br>    def distance(x):<br>        try:<br>            dist = vincenty((x[7],x[8]),(x[0],x[1]), miles = True)<br>        except:<br>            dist= np.nan<br>        return dist<br>    df[&#39;distance&#39;] = df.apply(distance,axis = 1)<br>    <br>    df.drop(df.tail(4).index,inplace=True)<br>    return df</pre><pre>def list_df_summary(input_df):<br>    &#39;&#39;&#39;<br>    Converts output from add_feat function into an observation for machine learning<br>    &#39;&#39;&#39;<br>    names = [&#39;speed_10&#39;,&#39;speed_25&#39;,&#39;speed_50&#39;,&#39;speed_75&#39;,&#39;speed_90&#39;,&#39;speed_ave&#39;,<br>            &#39;accel_10&#39;,&#39;accel_25&#39;,&#39;accel_50&#39;,&#39;accel_75&#39;,&#39;accel_90&#39;,&#39;accel_ave&#39;,<br>            &#39;jerk_10&#39;,&#39;jerk_25&#39;,&#39;jerk_50&#39;,&#39;jerk_75&#39;,&#39;jerk_90&#39;,&#39;jerk_ave&#39;,<br>            &#39;bearingRate_10&#39;,&#39;bearingRate_25&#39;,&#39;bearingRate_50&#39;,&#39;bearingRate_75&#39;,&#39;bearingRate_90&#39;,&#39;bearingRate_ave&#39;,<br>            &#39;distance_traveled&#39;,&#39;time_traveled&#39; ,&#39;last_lat&#39;,&#39;last_long&#39;,&#39;start_lat&#39;,&#39;start_long&#39;<br>            <br>            ]<br>    values = list()<br>    #speed<br>    values.append(input_df.quantile(.10)[8])<br>    values.append(input_df.quantile(.25)[8])<br>    values.append(input_df.quantile(.50)[8])<br>    values.append(input_df.quantile(.75)[8])<br>    values.append(input_df.quantile(.90)[8])<br>    values.append(input_df.mean()[8])<br>    #accel<br>    values.append(input_df.quantile(.10)[10])<br>    values.append(input_df.quantile(.25)[10])<br>    values.append(input_df.quantile(.50)[10])<br>    values.append(input_df.quantile(.75)[10])<br>    values.append(input_df.quantile(.90)[10])<br>    values.append(input_df.mean()[10])<br>    #jerk<br>    values.append(input_df.quantile(.10)[12])<br>    values.append(input_df.quantile(.25)[12])<br>    values.append(input_df.quantile(.50)[12])<br>    values.append(input_df.quantile(.75)[12])<br>    values.append(input_df.quantile(.90)[12])<br>    values.append(input_df.mean()[12])<br>    #bearing<br>    values.append(input_df.quantile(.10)[18])<br>    values.append(input_df.quantile(.25)[18])<br>    values.append(input_df.quantile(.50)[18])<br>    values.append(input_df.quantile(.75)[18])<br>    values.append(input_df.quantile(.90)[18])<br>    values.append(input_df.mean()[18])<br>    #distance travelled<br>    values.append(input_df.distance.sum())<br>    #time travelled<br>    values.append((input_df.iloc[-1,4] - input_df.iloc[0,4])*24*60)<br>    #lat long<br>    values.append(input_df.iloc[-1,0])<br>    values.append(input_df.iloc[-1,1])<br>    values.append(input_df.iloc[0,0])<br>    values.append(input_df.iloc[0,1])<br>    <br>    <br>    return pd.DataFrame([values],columns=names)</pre><p>To loop through the file directory, I used a package called glob. Below is the code that accomplishes creating a list of pathnames for every .plt file in the GeoLife directory. Then runs a for loop through the .plt list and applies the previous function to get us ready for machine learning!</p><pre>plts = []<br>for folder in glob(&#39;Geolife Trajectories 1.3/Data/*/Trajectory&#39;):<br>    for file in glob(folder +&#39;/*.plt&#39;):<br>        plts.append(file)</pre><pre>large_df = []<br>for i, file in enumerate(plts):<br>    print( int(i*100 / len(plts)))<br>    try:<br>        large_df.append(list_df_summary(add_feat(pd.read_csv(file, skiprows=6,names=colnames))))<br>    except:<br>        print(&#39;error at: &#39; + file)<br>df = pd.concat(large_df)</pre><p>For my example, I am going to take a subset of the modeling_df features to create clusters. Not every feature has useful information(<a href="https://en.wikipedia.org/wiki/Curse_of_dimensionality">read more on the curse of dimensionality</a>). It’s a bit of an iterative process, you can try different subsets to develop different clusters. Initially, I looked at the distributions of each feature to guess if it would be valuable inclusion to the unsupervised learning algorithm.</p><h3>GPS Trajectory Clustering</h3><pre>from sklearn.cluster import KMeans<br>from sklearn.preprocessing import StandardScaler<br>import seaborn as sns<br>from collections import Counter</pre><pre>## Remove longer trips<br>df_local_all_feat=df[(df.time_traveled &lt; 300) &amp; (df.distance_traveled &lt; 100)&amp; (df.speed_90&lt;75)]</pre><pre>## Select Features with unique distributions<br>df_local = df_local_all_feat[[&#39;speed_90&#39;,&#39;speed_ave&#39;,&#39;accel_75&#39;,&#39;speed_50&#39;,&#39;accel_ave&#39;,&#39;distance_traveled&#39;,&#39;time_traveled&#39;]]</pre><pre>## Scale Data for KMeans<br>X = StandardScaler()<br>X = X.fit_transform(df_local)</pre><pre>#################################<br>### PERFORM KMeans CLUSTERING ###<br>#################################</pre><pre>Sum_of_squared_distances = []<br>scores = []<br>cluster_count = []<br>K= range(2,15,1)<br>for i in K:<br>    km = KMeans(n_clusters=i)<br>    km.fit(X)<br>    pred =km.predict(X)<br>    Sum_of_squared_distances.append(km.inertia_)<br>    scores.append(silhouette_score(X, pred))<br>    cluster_count.append(i)<br>    print(Counter(pred))<br>    print(str(silhouette_score(X, pred)) + &#39; clusters:&#39; +str(i))<br>    print(&#39;------&#39;)</pre><pre>########################################<br>### Elbow plot with silhouette score ###<br>########################################</pre><pre>sns.set_context(&#39;talk&#39;)<br>sns.lineplot(cluster_count,scores)<br>plt.xlabel(&#39;Cluster Count&#39;)<br>plt.ylabel(&#39;Silhouette Score&#39;)<br>plt.title(&#39;Elbow Method For Optimal Cluster Count&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*siRC_JH1cXbXIe_Ku915nQ.png" /><figcaption>The elbow plot is telling us to investigate either 6 or 7 clusters.</figcaption></figure><pre>df_local_all_feat[&#39;cluster&#39;] = KMeans(n_clusters=7).fit_predict(X)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*HZX5SQ9DCHRmgJE_2wHeNg.png" /><figcaption>Trajectory Clusters</figcaption></figure><p>Clusters 4,5 contain very few number of observations therefore, are not included in this analysis.</p><p>Let’s take a look at the final destination and the Trajectory clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JzSA7c19oOG-VJITJHKYKQ.png" /><figcaption>Tsinghua University, Trajectory Cluster</figcaption></figure><p>Looking at Tsinghua University we can see a significant amount of clusters 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_SNHIyFD7GazWu0eDjvBcw.png" /><figcaption>Tencent Office, Trajectory Cluster</figcaption></figure><p>Looking at Tecent offices we can start to see significantly more subway rides, clusters 5 and 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4ah1hQpMVuVbB4apuww0g.png" /></figure><p>Looking at a local shopping district a less subway/train trips, but train trips typically travel longer distances (size is total distance travelled).</p><h3>Destination Geospatial Clustering</h3><p>The larger “zoom-out” map of the above section, can be found below. We have identified 3 general points of interest, it’s time to cluster them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJdwsI3nJ2wnBrLhzA3Axw.png" /><figcaption>Tsinghua University on top, shopping center on lower left, and Tencent on lower right</figcaption></figure><p>Looks like we need algorithm that can combine distance with proximity, while giving the capability to exclude noise. It sounds like DB Scan would be algorithm for this application.</p><pre>from sklearn.cluster import DBSCAN</pre><pre># pull out the only the location metrics<br>df_cluster = df_local_all_feat[[&#39;Last Lat&#39;, &#39;Last Long&#39;]]</pre><pre>X = StandardScaler()<br>X = X.fit_transform(df_cluster)</pre><pre>scores = []<br>EP =[]<br>number =[]<br>eps= [.08,.10,.15,.20,.25,.30,.40,.50,.60]<br>size= [200,250,300]<br>for ep in eps:<br>    for siz in size:<br>        db = DBSCAN(eps=ep, min_samples=siz)   <br>        pred = db.fit_predict(X)<br>        <br>        print(&#39;ep:&#39;+ str(ep) + &#39; size:&#39;+ str(siz))<br>        print(Counter(pred))<br>        try:<br>            scores.append(silhouette_score(X, pred))<br>        except:<br>            scores.append(np.nan)<br>        EP.append(ep)<br>        number.append(siz)</pre><p>The variable eps and size will allow you to grid search the appropriate hyperparameters for your application. In the end I, landed on the following values.</p><pre>db = DBSCAN(eps= 0.37, min_samples = 250)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*t7LeSEcHvR_532JH7hW0Rg.png" /></figure><h3>Combing Both Clustering Algorithms</h3><p>By combing both clustering algorithms, we can filter specific trips based on point of interest to determine where people are coming from and the method of transportation used to arrive at the said point of interest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V5Y8qW1TPpW9vTwXpc4GJA.png" /></figure><p>For Tsinghua University, we can see people are generally taking shorts trip from nearby.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*89RYU2xDb0-tMfcIDzGt6g.png" /></figure><p>For the shopping district, we can see people are traveling a bit further and are mostly using transportation mode 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zMnLcvWTF0_FqGmTE2huoQ.png" /></figure><p>For the Tencent office, people are traveling from the furtherest away. However, people commuting from nearby are typically taking transportation mode 0, while people commuting from further away are taking transportation mode 6.</p><h3>Conclusion</h3><p>Using various unsupervised learning algorithms, we are able to determine how people travel to specific locations, how to bound points of interest, and where people originated.</p><p>With adjustments, in the data collection architecture, it would be interesting to determine how people dwell stay at a location, based on the factors of distance travelled and method of transportation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daba8da8c41e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-gentle-introduction-to-iot-gps-trajectory-clustering-and-geospatial-clustering-daba8da8c41e">A Gentle Introduction to IoT/GPS Trajectory Clustering and Geospatial Clustering</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>