<?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 Benny Friedman on Medium]]></title>
        <description><![CDATA[Stories by Benny Friedman on Medium]]></description>
        <link>https://medium.com/@benny-friedman2?source=rss-4f6cfeaab93b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Benny Friedman on Medium</title>
            <link>https://medium.com/@benny-friedman2?source=rss-4f6cfeaab93b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 18:22:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@benny-friedman2/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[Unmasking Motion AI Assistant: Under the Hood — AI Scheduling]]></title>
            <link>https://benny-friedman2.medium.com/unmasking-motion-ai-assistant-under-the-hood-ai-scheduling-ac86fff1e26e?source=rss-4f6cfeaab93b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac86fff1e26e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[google-or-tools]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[scheduling]]></category>
            <dc:creator><![CDATA[Benny Friedman]]></dc:creator>
            <pubDate>Wed, 30 Oct 2024 12:36:19 GMT</pubDate>
            <atom:updated>2024-10-30T12:36:19.414Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unmasking Motion AI Assistant: Under the Hood — AI Scheduling</h3><p><em>This is an entry from the Not Magic, Just Math newsletter, published 10/29/2024</em></p><p><a href="https://nmjm.beehiiv.com/subscribe">Not Magic, Just Math</a></p><p>This week, I thought I’d take a break from our deep dive into ML Typologies and try something new. I want to introduce a fresh “field note” series called <strong>Under the Hood</strong>, where we take an “AI software” and try to deduce how the system works — and how I would build it from scratch. To kick things off, let’s look at a tool I love and use daily: <strong>Motion</strong>.</p><h3>🕰️ Meet Motion</h3><p>Motion brands itself as your “AI assistant.” According to their website:</p><p><em>“Motion takes all of your projects and tasks, prioritizes and time-blocks them on your calendar, and dynamically optimizes your schedule dozens of times a day, all done automatically. Your plan will always be perfect and up-to-date.”</em></p><p>The primary “AI” component is its auto-scheduling and prioritization system. Here’s how it works:</p><ol><li><strong>Set your working hours.</strong></li><li><strong>Connect your events calendar</strong> (work calendar, for example).</li><li><strong>Define your current tasks</strong>, specifying:</li></ol><ul><li>Estimated time to complete.</li><li>Due date.</li></ul><p>Once you’ve done this, Motion fits your tasks into open time slots in your calendar between meetings, all within your specified working hours. Neat, right?</p><p>Interested?</p><p>Check out the fully featured Motion app here: <a href="https://get.usemotion.com/34nmt4f5cg5x"><em>https://get.usemotion.com/34nmt4f5cg5x</em></a></p><h3>🕵️‍♂️ Under the Hood: How Does Motion Work?</h3><p>To figure out how Motion works, let’s start by categorizing it in terms of an ML typology.</p><h4>🔍 Typology Check:</h4><p>I’d describe the problem as follows:</p><p><em>“Given defined tasks with time, decomposition constraints, and due dates, place them on a timeline (schedule) that maximizes the number of tasks completed on time, without violating working window constraints or interfering with pre-existing events.”</em></p><p>Sounds like an <strong>optimization problem</strong>! Keywords like “maximize” and “constraint” are telltale signs.</p><h4>🛠️ Solving the Problem:</h4><p>Now that we know it’s an optimization problem, how might we approach it? In our optimization deep dive, we explored two methods:</p><ul><li><a href="https://nmjm.beehiiv.com/p/digging-into-rl"><strong>Reinforcement Learning (RL)</strong></a></li><li><a href="https://nmjm.beehiiv.com/p/nmjm-6-mathematical-optimization"><strong>Mathematical Optimization</strong></a></li></ul><p>I often use RL when the system can’t be fully described with known equations. But in this case, we can represent the constraints mathematically, making <strong>Mathematical Optimization</strong> our tool of choice.</p><h4>If you’ve made it this far you might like other field notes from Not Magic, Just Math!</h4><p>I write a new field note each week as a part of my weekly free newsletter “Not Magic, Just Math” our goal is to create a community of people interested in the practicalities of Data Science, ML and AI. We share insights, lessons learned, and tricks of the trade — both from my experience and those of other practitioners!</p><p>Join here: <a href="https://nmjm.beehiiv.com/subscribe">https://nmjm.beehiiv.com/subscribe</a></p><h4>✏️ Representing Motion as a Mathematical Optimization:</h4><p>To solve this as a Mathematical Optimization problem, we have a few options:</p><ul><li><strong>Linear Programming (LP)</strong></li><li><strong>Mixed Integer Programming (MIP)</strong></li></ul><p>For this problem, I’d use <strong>Mixed Integer Programming</strong> because we need boolean (yes/no) variables to represent task scheduling.</p><p>Let’s break it down simply:</p><ul><li>We assume a 1-week schedule and represent it using 15-minute increments.</li><li>The system schedules tasks in available slots that align with working hours and pre-existing events.</li></ul><h4>📅 Setting Up the Data:</h4><ol><li><strong>A boolean list of work hours</strong>: True for working periods (e.g., 9–5, M–F), False otherwise.</li><li><strong>A boolean list of pre-existing events</strong>: True for available slots, except where events already exist.</li><li><strong>An initial availability list</strong> that’s True when within work hours and not blocked by other events.</li></ol><h4>🔨 Variables for Task Scheduling:</h4><ul><li><strong>Task lists</strong>: One list per task, with boolean values for each time slot.</li><li><strong>Tracking variables</strong> for whether a task is successfully scheduled.</li></ul><h4>📏 Defining Constraints:</h4><p>We introduce constraints to ensure:</p><ol><li><strong>Task Duration</strong>: Each task occupies consecutive time slots according to its duration.</li><li><strong>Task Scheduling &amp; Completion</strong>: A task is considered scheduled when its required duration is met.</li><li><strong>No Overlap</strong>: Only one task can be scheduled per time slot.</li><li><strong>Within Working Hours</strong>: Tasks are only scheduled within defined work hours.</li><li><strong>No Conflict with Pre-Existing Events</strong>: Tasks cannot overlap with events on your calendar.</li></ol><h4>🎯 Objective Function:</h4><p>The objective is to <strong>maximize the number of successfully scheduled tasks</strong>.</p><h3>🖥 In Code:</h3><p>To validate my approach, I developed a simple <strong>Motion clone</strong> using <strong>OR-Tools</strong> (Google’s mathematical optimization package). Here’s how I brought this to life:</p><p>1) Set up our initial information</p><pre>HORIZON_WEEKS = 1<br>START_DATE = &#39;2024-10-01&#39;<br>WORKING_DAYS = &quot;M-F&quot;  # Workdays: Monday to Friday<br>WORKING_HOURS = (9, 17)  # Working hours: 9 AM to 5 PM</pre><pre>## Create our task definitions<br>tasks = {<br>    &#39;Complete Budget Draft&#39;: {&#39;time_to_complete&#39;: 30, &#39;due_date&#39;: Timestamp(&#39;2024-10-02 11:00:00&#39;)},<br>    ...<br>}<br></pre><pre># Create our event definitions<br>events = {<br>    &#39;Team Alignment Meeting&#39;: {&#39;date_time&#39;: Timestamp(&#39;2024-10-01 09:00:00&#39;), &#39;length&#39;: 60},<br>    &#39;Sales Review Session&#39;: {&#39;date_time&#39;: Timestamp(&#39;2024-10-01 15:00:00&#39;), &#39;length&#39;: 90},<br>    ...<br>}</pre><p>2) Set up our schedule dataset</p><pre>#Calculate the end date based on the scheduling horizon in weeks<br>end_date = pd.to_datetime(START_DATE) + pd.Timedelta(weeks=HORIZON_WEEKS)</pre><pre># Create a date range with 15-minute increments to represent all possible time slots in the schedule<br>date_range = pd.date_range(start=START_DATE, end=end_date, freq=&#39;15min&#39;)</pre><pre># Create a DataFrame to store the schedule, using the generated date range as the index<br>df_schedule = pd.DataFrame(index=date_range)</pre><pre># Add a column to track the day of the week for each time slot<br>df_schedule[&#39;dow&#39;] = df_schedule.index.dayofweek  # Monday=0, Sunday=6</pre><pre># Create a column to determine if each 15-minute slot falls within working hours and on a working day<br>df_schedule[&#39;working_hour&#39;] = df_schedule.index.to_series().apply(<br>    lambda x: 1 if (x.weekday() &lt; 5 and WORKING_HOURS[0] &lt;= x.hour &lt; WORKING_HOURS[1]) else 0<br>)<br></pre><pre># Initialize a column in the DataFrame to track time slots that are occupied by existing events<br>df_schedule[&#39;scheduled&#39;] = 0</pre><pre># Mark time slots occupied by pre-existing events as &quot;scheduled&quot; in the DataFrame<br>for event, details in events.items():<br>    start_time = details[&#39;date_time&#39;]<br>    duration_minutes = details[&#39;length&#39;]<br>    end_time = start_time + pd.Timedelta(minutes=duration_minutes)</pre><pre>    # Mark the event slots as unavailable by setting `scheduled` to 1<br>    df_schedule.loc[start_time:end_time, &#39;scheduled&#39;] = 1</pre><pre># Create a boolean column `available` to identify time slots that are within working hours and not scheduled<br>df_schedule[&#39;available&#39;] = (df_schedule[&#39;working_hour&#39;] == 1) &amp; (df_schedule[&#39;scheduled&#39;] == 0)</pre><pre># Create a numerical index to reference the time slots for easy access later<br>df_schedule[&#39;time_index&#39;] = range(len(df_schedule))</pre><p>This creates a dataset that looks like:</p><p>3) Write our optimization code including:</p><ul><li>variables</li><li>constraints</li><li>objective</li></ul><pre># Initialize the CP-SAT model for scheduling optimization<br>model = cp_model.CpModel()<br><br>...<br><br># Loop through all tasks to set up variables and constraints for each<br>for task in tasks:<br>    details = tasks[task]<br>    due_time = details[&#39;due_date&#39;]<br>    duration = details[&#39;time_to_complete&#39;] // 15  # Duration in 15-minute increments<br>    task_increment_vars = increment_vars[task_i]<br>    # Find the maximum index up to which the task can be scheduled based on its due date<br>    max_due_index = df_schedule[df_schedule.index &lt;= due_time][&#39;time_index&#39;].max()<br>    # Boolean variables to track the task&#39;s schedule across all time slots<br>    task_timesteps = [model.NewBoolVar(f&#39;scheduled_step_{task}_{ts}&#39;) for ts in range(0, max_index)]<br>    # Integer variable to store the start time of the task<br>    start_timestep = model.NewIntVar(name=f&#39;scheduled_start_step_{task}&#39;, ub=max_index, lb=0)<br>    # Variable to track the count of scheduled slots for the task<br>    scheduled_itterator = model.NewIntVar(name=f&quot;scheduled_iter_{task}&quot;, lb=0, ub=duration + 1)<br>    # Boolean variable indicating if the task is fully scheduled<br>    scheduled = model.NewBoolVar(f&quot;{task}_scheduled&quot;)<br> ...<br><br><br># Constraints for ensuring that each slot is not double-booked and follows availability rules<br>for i in range(0, max_index):<br>    availability = available[i]<br>    indexed_increments = []<br>    for t in increment_vars:<br>        indexed_increments.append(t[i])<br>    # Ensure only one task can occupy each slot<br>    model.Add(master_timestep_vars[i] == sum(indexed_increments))<br>    # Ensure tasks are only scheduled within available slots<br>    if availability == False:<br>        model.Add(master_timestep_vars[i] == 0)<br># Objective function: maximize the number of fully scheduled tasks<br>total_scheduled = model.NewIntVar(name=&quot;Total_Scheduled&quot;, lb=0, ub=1000)<br>model.add(total_scheduled == sum(scheduled_vars))<br>model.Maximize(total_scheduled)<br># Solve the model and check for an optimal or feasible solution<br>solver = cp_model.CpSolver()<br>status = solver.Solve(model)</pre><h3>📝 Notes on the Code:</h3><p>Constraint optimization can be quite an art! One of my favorite “inventions” I developed in this code is using a <strong>“master” timestep variable</strong> for overlap, working hours, and pre-existing events. Instead of multiple constraints, we link time slots to boolean variables and set constraints on these “master” timestep variables:</p><ul><li>1 if available.</li><li>0 if outside work hours or pre-occupied.</li></ul><p>With these simple constraints, we ensure no overlap and adherence to work hours and event constraints!</p><h3>💻 Try it Yourself!</h3><p>Check out my GitHub for a full implementation of this <strong>Motion clone</strong> <a href="https://github.com/benjaminwfriedman/motion-clone">[GitHub link]</a>. It’s a great way to experiment with the concept! Here are the results from the example settings, events, and tasks.</p><p>Highlighted sections are work hours, the gray line indicates previously scheduled events and the colored horizontal lines are scheduled tasks. You’ll notice that the scheduled tasks avoid conflicting events and fall within working hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RuE9BS-NMyjJxKEUOooRmQ.png" /></figure><h3>🚀 Conclusion:</h3><p>So, as you can see, we can indeed develop the capabilities of tools like Motion using <strong>Mathematical Optimization</strong>! 🥳 If you enjoyed this peek “Under the Hood,” let me know by replying to this email or commenting on the field note.</p><p>Oh, and do check out <strong>Motion</strong> for a polished experience — they’ve got a great UI, and you can connect it to your Google or Outlook calendar for seamless scheduling!</p><p><a href="https://get.usemotion.com/34nmt4f5cg5x"><em>https://get.usemotion.com/34nmt4f5cg5x</em></a></p><p>Thanks for coming along on this new type of field note! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac86fff1e26e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Measuring Urban Similarities in Los Angeles (Open Data, ArcGIS, Sklearn).]]></title>
            <link>https://medium.com/analytics-vidhya/measuring-urban-similarities-in-los-angeles-open-data-arcgis-sklearn-71b3bef53ea6?source=rss-4f6cfeaab93b------2</link>
            <guid isPermaLink="false">https://medium.com/p/71b3bef53ea6</guid>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[spatial-analysis]]></category>
            <category><![CDATA[urban-planning]]></category>
            <category><![CDATA[cities]]></category>
            <dc:creator><![CDATA[Benny Friedman]]></dc:creator>
            <pubDate>Tue, 02 Mar 2021 18:27:21 GMT</pubDate>
            <atom:updated>2021-03-03T16:21:44.825Z</atom:updated>
            <content:encoded><![CDATA[<h3>Measuring Urban Similarities in Los Angeles using, Open Data, ArcGIS, and Sklearn.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xeE92MpPuOhZQ4o0K0HlGg.jpeg" /></figure><h4>Finding similar places</h4><p>After exploring ways to measure happiness in cities, <a href="https://medium.com/analytics-vidhya/a-look-at-spatial-happiness-in-cities-using-tweepy-text-blob-and-arcgis-c60c50cb64b0"><em>A Look at Spatial Happiness in Cities, using Tweepy, Text Blob, and ArcGIS</em></a><em>, </em>I continued to look for ways to use spatial data to glean important information about our urban surroundings. I was intrigued when a friend mentioned that, as an urban planner, she spent a lot of time identifying places similar to her project sites to serve as precedents. A precedent study is usually conducted as one of the first steps in urban planning projects. The goal is to identify applicable ideas from similar projects. If we could quantify the similarity between places, that would help urban planners find new and similar locations to serve as precedents. But its uses are not limited to urban planning. It would also help businesses and real estate. A retailer may want to find areas like those it has succeeded in already. A real estate agent may be interested in quickly identify areas that clients might like.</p><p>I decided to quickly build a proof of concept for such a tool. Since my friend’s use case piqued my interest, I began by thinking about the aspects of place that would define similarity for her precedent searches. When looking for precedent examples, urban planners want to find places that have similar urban structures (street network, built structure, land-use types, population density) and demographics (income, culture, age). In this article, I’ll walk through the methods and decisions I settled on to quantify neighborhood similarity, and demonstrate how data science methods can deliver helpful insights about our cities.</p><h4>Measuring a Neighborhood</h4><p>To identify similarities between neighborhoods, we must define a neighborhood. People know what a neighborhood is, but a consistent definition is elusive. For this project, I borrowed the 10-minute walk/ 1/2 mile radius frequently used in urban planning, and created a 1/2 SQMI grid to serve as my neighborhood unit. It is somewhat crude but is fine-grained enough to derive some helpful insights.</p><p>The next question to answer: what features should be similar for two neighborhoods to be considered similar? Do we care if both places have similar types of restaurants? Do we care about how the streets are laid out, e.g., in a grid or not? How about the politics of a place? Or something else? In this case, urban structure and demographics are the most important features to measure. If someplace has a similar structure and people, it is similar enough to use as a high-quality precedent. If you are looking for similarity in real estate, e.g., to identify places someone may want to buy a home, the important features will likely be different. Maybe you would care about school quality or park space. I don’t know so, if you work in real estate, please let me know!</p><p>Having decided to focus on similarities in structure and demographics, I set out to collect the needed data. To keep the workload manageable and avoid potential data inconsistencies, I focused my tool on Los Angeles County only. It’s the most populous county in the country and has a very deep catalog of open GIS data; it is a good place to start.</p><p><strong>Urban Structure Data</strong></p><p>Based on my experience with urban planning, I selected four features that speak to urban structure: population density, intersection density, parcel density, and commercial land use density. Places that differ significantly in any of these features will likely feel structurally different from each other. Population density speaks to urban or rural character, intersection density speaks to active vs automotive transportation priorities, parcel density speaks to urban scale, and commercial density speaks to local function.</p><p>To engineer the structural features, I pulled census and open urban data from the LA County Geohub into ArcGIS. Population density is derived using ESRI’s enrichment tool using population estimates from the 2018 American Community Survey (ACS), parcel density was created from the LA County Tax Assessors Parcel dataset, intersection density was derived from the LA County Countywide Address Management System (CAMS) street dataset, and commercial land use density was pulled from a subset of the Assessors Parcel dataset. All features were analyzed on the 1/2 SQMI grid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*JsZVVJVY2hgmecTdv7iyQA.png" /><figcaption>LA County Population Density on a 1/2 mile grid</figcaption></figure><p><strong>Demographic Data</strong></p><p>To assess the demographic similarity between neighborhoods, I settled on four features that I thought exemplified cultural and experiential similarities between neighborhoods: median household income (MHHI), average age, percent of the local population identified as white, and the percent of the local population identified as Hispanic. Income significantly affects how a neighborhood behaves; therefore controlling for MHHI is important in finding neighborhoods that have similar behavior. Like MHHI, age can dictate how a neighborhood feels; a neighborhood with a lot of 20-year-olds feels very different from one filled with families or retirees. Finally, race can impact a neighborhood’s behavior and culture. I included two race features because neighborhood culture is affected, by both the size of different populations and especially the control each may exert over the community. A neighborhood with many white people and few minorities will feel different than one with an equal distribution of cultures, both those neighborhoods will feel different than a majority-minority neighborhood. This is a very complex relationship that is hard to fully distill from data but is important enough to neighborhood similarity to include.</p><p>All demographic features were pulled from the ESRI enrichment tool in ArcGIS and summarized to the 1/2 SQMI grid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*XoUBytKm5rYzBVIYjJXApA.png" /><figcaption>LA County Average Age on a 1/2 SQMI grid</figcaption></figure><h4>Quantifying Similarity</h4><p>Now that the structural and demographic features are selected and derived for each 1/2 SQMI neighborhood in the LA County grid, it’s time to talk about exactly how to quantify similarity. Broadly there are two common methods used in data science to understand the similarity between samples: clustering algorithms can intelligently identify groups of similar samples in a dataset, and distance measurements that quantify the multi-dimensional distance between samples. Clustering is best if we are looking to group neighborhoods by similarity, and distance measures are better if we want a way to quantify how similar or dissimilar any two neighborhoods are. Both have their advantages, but for my friend’s situation, where we want to find the N most similar neighborhoods, distance measures will work better.</p><p>There are two common methods for measuring distance-based similarity: Euclidian distance and cosine distance. You probably met Euclidian distance in geometry class. Using the Pythagorean theorem, you can measure how far point A is from point B; we can extend that same concept to multiple dimensions. Cosine distance is another mathematical approach. It works best when the magnitude of the features may not be important. In our case, the magnitude is likely quite important. A neighborhood with a MHHI of $120,000 is very different from one with a MHHI of $50,000, size matters. With this in mind, we will use Euclidian distance to measure similarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*UO3juhGTHvRwI4czt06qfQ.png" /><figcaption>Simplified multi-dimensional Euclidian distance formula for data with k features.</figcaption></figure><h4>Building the tool</h4><p>Now that we have engineered our features and settled on a method for quantifying the similarity between samples, we can begin building the tool itself! For simplicity, I built the tool in a Jupyter Notebook, but I intend to move it into an interactive Dash/Plotly web app in the future.</p><p>The tool should work as follows:</p><ol><li>The user selects a 1/2 SQMI neighborhood that they would like to compare with other neighborhoods, in order to find similar neighborhoods.</li><li>The tool finds N number of similar 1/2 SQMI neighborhoods in LA County in list and map form.</li></ol><p>First, let’s take a look at our data and features to get an idea of what we are dealing with. I’ll load the data as a geopandas dataframe and then generate distribution histograms for each feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTpEyMyM71sCL3EHzxHUyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*At4fDiQnf8wPk7GCrl4tFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1cB-o48CEO4IAJq_0aONfQ.png" /><figcaption>Sample distributions for the four structural features</figcaption></figure><p>Looking at our urban form structural features, we can immediately see that all our structural data is skewed to the right. Meaning that there are far more small values than large ones. Interestingly, this tends to hold true for almost any urban characteristic and is one of the only hard and fast laws of cities. For more on this phenomenon check out Zipf’s law and Geoffrey West’s book <a href="https://www.amazon.com/Scale-Universal-Innovation-Sustainability-Organisms/dp/1594205582"><strong>Scale</strong></a><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Tc-Cf9x6hYzU5IaADRgCA.png" /><figcaption>Sample distributions for the four demographic features</figcaption></figure><p>Looking at our demographic features, we notice that MHHI and age are far more normally distributed than the structural features were. This makes sense since we are dealing with data regarding humans, where, in biology, we expect to find normal distributions. However, the race features exhibit some of the skewness we observed in the structural features, which may indicate a structural aspect to race distributions. All of the features have significant numbers of zero instances. This can be explained by neighborhood areas without regular populations. There are a few communities in LA County that are specialized industrial areas, like Vernon and the City of Commerce that might account for some portion of the zero instances, and swaths of low-density areas in the far north of the county, that could account for more. We will keep them in the dataset, despite their appearance as outliers, because they represent true on the ground conditions and there is no requirement for normality for this analysis.</p><p><strong>Scaling and weighting</strong></p><p>Before we compute our similarities, we need to scale our data. Since we plan to use Euclidian distances to quantify similarity, we need to be mindful of differences in scale between our features. Let’s use the pandas describe method to get a quick understanding of how our datasets differ in scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GaXHaRJfTv_q1-Oowovwlw.png" /></figure><p>By inspecting the descriptive statistics of each feature, we can see how the ranges of each vary vastly from one another. This is a problem when using Euclidian distances because the formula assumes consistent units in all dimensions. To illustrate this, let’s assume we are only finding the similarity between 2D points with a population density and age value. Sample 1 has a population density of 7000 and an age of 60 and Sample 2 has a population density of 7500 and an age of 36. Using the formula described earlier, the Euclidian distance is 500.57. You’ll notice that if we disregarded age completely, we would have found a distance of 500. The reason these are both so similar, even though we know that a place with an average age of 60 would be quite different than one with an average age of 36, is because the scale of the population density feature is so much larger. It completely washes out the important differences in age. Thus, we must scale our data so that all our dimensions have consistent units. We will use the SKLearn Standard Scaler method to do this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*XYWkivVdk2jMX-_kRrYCKA.png" /></figure><p>You’ll notice that I also included a weights input for MHHI and ethnicity. This is because, once you scale your data, you can control the impact each variable has on your analysis. After scaling, each feature will have the same impact on similarity as every other feature. This may be what you want, but sometimes, like in our case, there are a few features that you want to make sure are heavily considered. In this case, I felt that dissimilarity in MHHI and ethnicity, in regard to neighborhood behavior, might overpower similarities present in other features. Two places with similar commercial and population densities, for example, would behave similarly only if ethnicities and MHHI were similar as well, if they were structurally similar, but had different ethnicities and incomes, I would not expect them to behave all that similarly. So to account for this, we can choose to weigh income and ethnicity higher than other variables. At present, I have given them both a 5X weight, meaning that a one-unit change in either is only offset by at least a five-unit change in an unweighted variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*4PJNzbgqy_qaCr6BVdBF5g.png" /><figcaption>Adding weights to the scaled data with lambda expressions</figcaption></figure><p><strong>Computing Similarities</strong></p><p>Once our inputs are scaled and weighted, we can calculate Euclidian distance similarities. First, we must take the input neighborhood that we wish to find similar neighborhoods to. Since this is built in a Jupyter Notebook, I just take the neighborhood of interest as the Object ID referencing the selected Neighborhood in the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*8lw4u_gOsbtumS-XSW9rbA.png" /><figcaption>Input OID for analysis</figcaption></figure><p>Then we compute the Euclidian distances between the specified neighborhood and all other 1/2 SQMI neighborhoods in the dataset. To do this we use the SKLearn paired_distances method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*WQHUKuWjKuYl1qRX10Yezg.png" /><figcaption>Code to find the 100 most similar neighborhoods.</figcaption></figure><p>The code above returns the 100 most similar neighborhoods to the neighborhood selected. With this data in hand, we can use geopandas to plot them on a map with only a few lines of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*j87XOd9t3HYccliDK0semg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*WhXLWf6azMI5UteWUJxBnA.png" /><figcaption>A map of the 100 most similar areas to a selected neighborhood</figcaption></figure><p>On the map, you can quickly see the areas most similar to the selected neighborhood. You can further interrogate the results by looking at the returned data frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*c761hLEvHvXb-BMlYBvPzg.png" /></figure><p>Looking at the similarity data frame we can see how well our Euclidian distance similarities work. At the top of the image, you can see the feature values for our input neighborhood, and below, the top 10 most similar neighborhoods. The first is the selected neighborhood, so it should be ignored. But starting with the second we can see how our similarity quantities, “sim” line up with the similarity of our structural and demographic features. The most similar, with a Euclidian distance similarity of 2.68, OID: 3228, is a little less dense but has a fairly similar intersection density and is extremely similar in terms of MHHI, ethnicities, and age. When we inspect the output, we can see that, as designed, the tool weighted income and ethnicity more than the structural features. Weights, in the future, would be likely best determined by the user. But overall, it seems to have done a good job finding similar neighborhoods!</p><h4>Next Steps</h4><p>This was certainly just a proof of concept, but it provides a valuable starting place for further work. In the future, I think that the feature set can be expanded to include far more structural and demographic features. The tool could be packaged in a web app to improve usability and enable the user to tune the analysis for their specific use. It will also be important to expand the tool beyond the LA Region. However, further analysis will have to be undertaken to determine how well one can compare neighborhoods across diverse regions.</p><p>As always, I love getting feedback. I hope to start a discussion about how we can better measure and analyze our cities!</p><p>Please feel free to comment on this article, send me an email, or connect with me on LinkedIn. I’d love to hear your comments and suggestions!</p><p>Email: benny.friedman2@gmail.com</p><p>LinkedIn: <a href="https://www.linkedin.com/in/benjaminfriedman2/">https://www.linkedin.com/in/benjaminfriedman2/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71b3bef53ea6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/measuring-urban-similarities-in-los-angeles-open-data-arcgis-sklearn-71b3bef53ea6">Measuring Urban Similarities in Los Angeles (Open Data, ArcGIS, Sklearn).</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Look at Spatial Happiness in Cities, using Tweepy, Text Blob, and ArcGIS.]]></title>
            <link>https://medium.com/analytics-vidhya/a-look-at-spatial-happiness-in-cities-using-tweepy-text-blob-and-arcgis-c60c50cb64b0?source=rss-4f6cfeaab93b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c60c50cb64b0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[sentiment]]></category>
            <category><![CDATA[urban-planning]]></category>
            <category><![CDATA[gis]]></category>
            <dc:creator><![CDATA[Benny Friedman]]></dc:creator>
            <pubDate>Sun, 27 Dec 2020 21:51:40 GMT</pubDate>
            <atom:updated>2021-01-03T16:49:53.816Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*rsy9mCZTB5Nhm07Y9uL52Q.png" /></figure><h3>How can we measure the built environment with social media?</h3><p>Understanding the effects of the built environment has always been a fascination for me. How do we judge great development? How can we know urban planning is succeeding in making life better? Can we be data-driven in our analysis?</p><p>To find out how people feel about a place, architects often spend months convening community meetings and conducting surveys to gain a detailed understanding. But if we are looking for a much quicker, less exact view, Twitter sentiment analysis can perhaps provide a standardized, high volume way to understand how people feel at any given time in any given place. Well, at least how their social media selves feel.</p><p>The kind of Twitter sentiment analysis I am thinking of marries knowledge about the tone of tweets with placing those tweets geographically. To conduct the investigation I sampled random points in two different cities: Los Angeles and Chicago. I used the Tweepy API to pull tweets, Text Blob to analyze sentiment, and ArcGIS to interpolate the sentiments between the sample points.</p><h3>The Analysis.</h3><p>The first hill to climb was to build a simple script to understand the sentiment of tweets near any given point on earth. My input would be a lat/long coordinate, and I wanted the output to be the average sentiment of tweets within 1 mile of that point. The code is below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*9TD_0x3QYymvGU1N6d-1cQ.png" /><figcaption>Methods utilizing TextBlob and Tweepy to derive subjectivity and polarity of tweets</figcaption></figure><p>For each point, the final function makes use of Tweepy to search for tweets within a specified radius. The API returns up to 100 tweets from the last day or so from within a given radius. Each tweet is evaluated for “Polarity” and “Subjectivity” using Text Blob. Polarity is returned as a float between -1 and 1, negative to positive. Subjectivity is returned as a float between 0 and 1. Using pandas, the polarities are averaged to get a polarity score for the point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*OUuinsltOWBce9JPupRq8A.png" /><figcaption>Tweet content and their polarity scores</figcaption></figure><p>Once we know how to capture and understand sentiment around a point, the next step is to generate sample points for each city. I wanted to evaluate spatial twitter sentiment at around 95% confidence and a 5% margin of error. That means, for example, for my LA County AOI, I needed 294 random samples. In order to make sure not to sample underpopulated areas, I first erased all areas specified as “Parks and Openspace” in the “LA County Parks and Openspace” dataset provided by the county. Then using the parkless dataset I created 294 random points with the ArcGIS “Create Random Points” tool. These points were fed into the script outlined earlier to get sample average sentiments.</p><p>In order to interpolate the spatial Twitter sentiment for the full urban areas, I made use of the “Ordinary Kriging” tool. Kriging looks at the relationship between sample point distance and sentiment values, to build linear equations to predict average Twitter sentiment between known samples. Kriging enables us to get good predictions for full AOIs.</p><h3>Examining Spatial Twitter Sentiment</h3><p>After running this analysis on LA and Chicago, it is possible to see how Twitter sentiment varies throughout each city.</p><p><strong>Los Angeles, </strong>11/28/2020</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*fkwnUd71OQ8bGq0LadRwwQ.png" /><figcaption>Los Angeles spatial sentiment on 11/28/2020</figcaption></figure><p>I ran my Los Angeles analysis on 11/28/2020 and the results can be examined in the above map. The map is symbolized by z-score, so areas that show up as having positive and negative sentiment are particularly that way. Most areas are expected to fall close to the mean and be symbolized as neither particularly positive nor negative. Looking at the map, there are some interesting patterns. The Malibu area is particularly happy compared to the rest of the LA area. Through this analysis, it is hard to know what that is, although I would guess it has something to do with living close to beautiful beaches, natural parks, and being particularly affluent. Although, based on this analysis, it&#39;s hard to say that the wealthier you are, the happier you are. Many other affluent areas of the city are not particularly happy. See the Beverly and Hollywood Hills areas.</p><p><strong>Chicago,</strong> 11/28/2020</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*GvxVjjOCanaQ-O6hKGiEgA.png" /><figcaption>Chicago spatial sentiment on 11/28/2020</figcaption></figure><p>I ran the Chicago analysis on 11/28/2020 as well. The maps for both LA and Chicago are symbolized in the same way and on the same data distribution so they can be directly compared. Unlike LA there are three particularly happy areas of the Cook County/Chicago area. In the north, there are the broad Hoffman Estates and Glenview/Skokie areas, and in the south, an area near Calumet City on the Illinois-Indiana border. It also seems clear that, at least on this day, the southern part of Cook County, represents higher negative sentiment.</p><h3>Conclusions</h3><p>I will be the first to say that there are many things wrong with this analysis. First, I only take into account a snapshot of information. If we wanted to more accurately understand how Twitter sentiment varies over space, it would be helpful to collect data for a longer period of time. Maybe a month&#39;s worth of data or even several years. Second, I think that broad-based Twitter sentiment is not particularly correlated with a person’s happiness, and a more elegant classification model is in order. Finally, there is a lot of self-selection that comes along with using Twitter data. Only some people use Twitter, and people who use it a lot will be over considered. For example. if you sampled tweets around 1600 Pennsylvania Ave. in Washington, DC, between 2016 and 2020, you might get too many tweets from one individual, and not enough from the rest of the local population.</p><p>Though, flawed, I think this analysis shows the potential power of Twitter sentiment data. Using tweets, it becomes possible to compare and contrast sentiment across time and space, quickly and cheaply, in a standardized way. And this kind of analysis is not restricted to looking at positive vs negative sentiment. More targeted models can be made to look for more interesting trends in tweets. Where are people talking about a specific thing? How far away does knowledge of some change travel? It is really an open box for analysis.</p><h3><strong>Next Steps</strong></h3><p>My main goal in publishing this is to start a conversation about evaluating the places we live in powerful and scalable ways. Please feel free to comment on this article, send me an email, or connect with me on LinkedIn. I’d love to hear your comments and suggestions!</p><p>Email: benny.friedman2@gmail.com</p><p>LinkedIn: <a href="https://www.linkedin.com/in/benjaminfriedman2/">https://www.linkedin.com/in/benjaminfriedman2/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c60c50cb64b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/a-look-at-spatial-happiness-in-cities-using-tweepy-text-blob-and-arcgis-c60c50cb64b0">A Look at Spatial Happiness in Cities, using Tweepy, Text Blob, and ArcGIS.</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>