<?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 Jennifer Banks on Medium]]></title>
        <description><![CDATA[Stories by Jennifer Banks on Medium]]></description>
        <link>https://medium.com/@jennifer-banks8585?source=rss-a4a4f088f95a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5PyW-HyFfU6D18e6ZK5Bew.png</url>
            <title>Stories by Jennifer Banks on Medium</title>
            <link>https://medium.com/@jennifer-banks8585?source=rss-a4a4f088f95a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 00:14:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jennifer-banks8585/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[How to Embed Interactive Plotly Visualizations on Medium Blogs]]></title>
            <link>https://jennifer-banks8585.medium.com/how-to-embed-interactive-plotly-visualizations-on-medium-blogs-710209f93bd?source=rss-a4a4f088f95a------2</link>
            <guid isPermaLink="false">https://medium.com/p/710209f93bd</guid>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[plotly]]></category>
            <category><![CDATA[embed]]></category>
            <category><![CDATA[plotly-express]]></category>
            <category><![CDATA[plotly-go]]></category>
            <dc:creator><![CDATA[Jennifer Banks]]></dc:creator>
            <pubDate>Sun, 28 Feb 2021 20:56:23 GMT</pubDate>
            <atom:updated>2021-03-04T14:49:17.276Z</atom:updated>
            <content:encoded><![CDATA[<p>I think graphs and other types of visualization products are amazingly effective in conveying your story with limited to no words. Making them interactive just adds value to your product.</p><p>In this post we will learn about how to embed Plotly interactive graphs on your Medium articles. For the first example, we will use a graph from Plotly’s Python Open Source Graphing Library. See link for <a href="https://plotly.com/python/">reference</a>.</p><h4>Here are the steps that we need to do:</h4><p>A. Create an account in <a href="https://chart-studio.plotly.com/feed/#/">https://chart-studio.plotly.com/feed/#/</a></p><p>B. Get your username and API key. To do this, click on the dropdown next to your profile name on the upper left hand corner. Go to <strong>Settings</strong>. Then on the left side of the page, click on <strong>API keys</strong>. <strong>Generate an API key</strong>. Copy your <strong>username</strong> and your <strong>API key</strong>. We will use this later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qrsu6N9IWvzlcJgwNcF8Vg.png" /><figcaption>Accessing Plotly Credentials</figcaption></figure><p>C. This is the time to open your IDE or wherever you housed your code. For this exercise, I am going to use <strong>Google Colab</strong>, and as for the codes, I will borrow from Plotly’s gallery as mentioned above. Since we are using <strong>Google Colab</strong>, we need to install chart-studio with this:</p><pre>!pip install chart-studio</pre><p>Once it’s install you can start importing libraries, define credential variables and set credential on Plotly server.</p><pre>import chart_studio<br>username=&#39;your_username&#39;<br>api_key=&#39;your_api_key&#39;</pre><pre>chart_studio.tools.set_credentials_file(username=username,<br>                                        api_key=api_key)</pre><p>Now, in the fist example below, we will use Plotly Express:</p><pre>import chart_studio.plotly as py<br>import chart_studio.tools as tls</pre><pre>import plotly.express as px</pre><pre>df = px.data.iris()<br>fig = px.scatter(df, x=&quot;sepal_width&quot;, y=&quot;sepal_length&quot;,  <br>                     color=&quot;species&quot;, size=&#39;petal_length&#39;,<br>                     size=&#39;petal_length&#39;, hover_data=[&#39;petal_width&#39;]<br>                  )<br>fig.show()</pre><p>Once the code above is activated, a scatter plot will render on your <strong>Google Colab</strong>. We want to host this graph live on Plotly by using this:</p><pre>py.plot(fig, filename=&quot;plotly_scatter&quot;, auto_open = True)</pre><p>D. Visit your Plotly account, go to <strong>My Files</strong> under your profile dropdown, and then you should find the same graph in your list. Hover over it and click <strong>Viewer.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8eHjPOEQzLykI5fROR5dQ.png" /><figcaption>Click<strong> Viewer</strong> to get the link address</figcaption></figure><p>Now copy the url and paste it in your Medium blog. For instance, this is the url generated by our example above, and accordingly, the graph is shown below.</p><pre><a href="https://chart-studio.plotly.com/~jennifer.banks8585/3">https://chart-studio.plotly.com/~jennifer.banks8585/3</a></pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fchart-studio.plotly.com%2F%7Ejennifer.banks8585%2F3.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7Ejennifer.banks8585%2F3%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/41306e9c542b9f924ef8cbabaaf75df0/href">https://medium.com/media/41306e9c542b9f924ef8cbabaaf75df0/href</a></iframe><p>The next example below is a forecasting visualization for rent prices in Boston, MA. In this example, I used Plotly Graph_Objects instead of Plotly Express. The complete code can be found <a href="https://github.com/JenBanks8585/Randomdata/blob/main/Medium/Plotly_on_Medium.ipynb">here</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7Ejennifer.banks8585%2F1.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7Ejennifer.banks8585%2F1%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6a63c66463b7619b08be31f593cbf95/href">https://medium.com/media/f6a63c66463b7619b08be31f593cbf95/href</a></iframe><p>Now, it is your turn to try this fun skill!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=710209f93bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Data Science API as a Part of a Cross-Functional Team]]></title>
            <link>https://jennifer-banks8585.medium.com/creating-a-data-science-api-as-a-part-of-a-cross-functional-team-b99592efc26d?source=rss-a4a4f088f95a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b99592efc26d</guid>
            <category><![CDATA[plotly]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[aws-ebs]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Jennifer Banks]]></dc:creator>
            <pubDate>Sat, 27 Feb 2021 19:57:12 GMT</pubDate>
            <atom:updated>2021-03-04T14:13:51.650Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*3p4Sy0BEUAuyJrLoqzl-lw.png" /></figure><blockquote>As I am sure there will be more challenging, more useful and more efficient project that a new developer or data scientist will be a part of in the future, the first cross-functional project is no doubt one of the most impactful towards your own professional development.</blockquote><p><strong>The Team.</strong> Headed by a project team lead, our team consists of 3 sub-groups of data science, web and iOS development students. Except for a fellow DS student, this instance is the first time I have met and collaborated with everyone else. I can tell that despite this, everyone was excited and looked forward to this experience. Check the team members <a href="https://github.com/Lambda-School-Labs/cityspire-ds-h/blob/main/README.md">here</a>.</p><figure><a href="https://www.linkedin.com/in/bobbyhalljr/"><img alt="" src="https://cdn-images-1.medium.com/max/400/1*UwCNg8JycHkRV0APkChNMw.jpeg" /></a></figure><figure><a href="https://www.linkedin.com/in/jarrencampos/"><img alt="" src="https://cdn-images-1.medium.com/max/512/1*mfyFngn2jd8fPkZ1bgDbVQ.jpeg" /></a></figure><figure><a href="https://www.linkedin.com/in/fabiolasaga/"><img alt="" src="https://cdn-images-1.medium.com/max/200/1*1QvRErcN8gaK8okojZK7dA.jpeg" /></a><figcaption><strong>Project Lead and iOS sub-group</strong></figcaption></figure><figure><a href="https://www.linkedin.com/in/jenniferobanks/"><img alt="" src="https://cdn-images-1.medium.com/max/400/1*FeiUM4unJinF7S8pY_kA_g.jpeg" /></a></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*N1lYQDGSGD09laxtyeFjeA.png" /></figure><figure><a href="https://www.linkedin.com/in/zacharyleehamilton/"><img alt="" src="https://cdn-images-1.medium.com/max/400/1*ijgtYUKxFPOnrnvN2fhkPA.jpeg" /></a><figcaption><strong>Data Science sub-group</strong></figcaption></figure><figure><a href="https://www.linkedin.com/in/jordan-shehane-b2807a196/"><img alt="" src="https://cdn-images-1.medium.com/max/400/1*h5vPAXxjRbYLptFhyB-Oiw.jpeg" /></a></figure><figure><a href="https://www.linkedin.com/in/aidandang/"><img alt="" src="https://cdn-images-1.medium.com/max/400/1*rFm2EfwzKvsh3vewpbUV9w.jpeg" /></a></figure><figure><a href="https://www.linkedin.com/in/daniel-gipson/"><img alt="" src="https://cdn-images-1.medium.com/max/189/1*guiQ30kV_9dqBRc8peSTow.jpeg" /></a><figcaption><strong>Web Frontend and Backend sub-group</strong></figcaption></figure><p><strong>The Task.</strong> We were tasked to create a web application called CitySpire that provides information and analyzes data about a given location. Information such as population, crime rate, housing cost, pollution and other aspects that add value to a location such as accessibility. Other indices such as livability score are also computed to compare one location against another. Additionally, other than providing these information, we were also tasked to create a predictive model on these aspects, such as forecasted rental cost.</p><p><strong>Sample Use Cas</strong>e. Imagine you are looking into moving to a new state but would like to find out housing or rental rate to gauge affordability. You may also need to consider accessibility of various establishment, is there an efficient public transportation system or will you need your own vehicles to get around. You would want to know the safety index of this location in comparison to other nearby locations of similar potential.</p><p><strong>The Plan.</strong> With the guidance of our project lead, as a team we meet regularly to plan out the role of each sub-group. A draft of the project architecture was created. As the project progressed, regular meetings were conducted to update each sub-group about respective development. See progression of the project in this <a href="https://trello.com/b/wfqYS9vD">Trello Board</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*NLz0gR_BydZ5CbzXNTG6Bg.png" /><figcaption>Project Architecture</figcaption></figure><p><strong>Data Science Section</strong>. The Data Science(DS) API will provide the data for our web and IOS counterparts. Initially there were four members of this sub-group. We planned it out based on this, and assigned each one different sections. For instance, I was initially assigned to the housing cost portion of the project. With each portion, one is expected to:</p><ul><li><em>Find an appropriate dataset</em></li><li><em>Do the necessary cleaning and feature engineering</em></li><li><em>Create a predictive model for a defined problem</em></li><li><em>Update the group database accordingly.</em></li><li><em>Create endpoints for the results</em></li><li><em>Ensure to cover for potential errors and do necessary solutions.</em></li></ul><p>Unfortunately, two of our DS teammates decided not to pursue with the project, so we have to adjust our assignments and plan. Having said that, we used two main resources to accomplish this:<em> </em><strong><em>a) Get data accessible from private and government sectors</em></strong> such as <a href="https://www.huduser.gov/portal/pdrdatas_landing.html">HUD</a> and <a href="https://www2.census.gov/programs-surveys/popest/tables/1980-1990/counties/asrh/">Census</a>. We processed these datasets and created a database for it. Below is a simple schema for our database.</p><figure><a href="https://sqlspy.io/guest/schemas/q2l0evnwaxjl"><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ucjIratom4Sk5Wu4n7z7iw.png" /></a><figcaption>Database Scheme. Click on image to see documentation.</figcaption></figure><p>Secondly,<strong> <em>b) access Application Programming Interface (API)</em></strong> softwares for information that we deemed better off to get real time such as current rental prices and pollution particulate composition. Below is the list of APIs that we used for this purpose:</p><ul><li>RapidAPI.com</li><li>Walkscore.com</li><li><a href="https://aqicn.org/api/">https://aqicn.org/api/</a></li><li><a href="https://openweathermap.org/">https://openweathermap.org</a></li></ul><p>To illustrate the process, I am going to use the rental cost section and talk about how the forecasting values were computed. The source of the data was taken from <a href="https://www.zillow.com/research/data/">Zillow</a>. In this dataset shows rental prices of different cities throughout time. By initial inspection, a tinge of seasonality can be detected. I decided to use SARIMAX time series to create the forecasted values per cities.</p><p>My biggest challenge here is my limited capacity to process, run, call and save all models for each city. In the function below, I decided partition these tasks by indexing different models.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b92e6a0cf6cfc272864b6a5fba7a2376/href">https://medium.com/media/b92e6a0cf6cfc272864b6a5fba7a2376/href</a></iframe><p>Shown below are examples of rental price projections with low and high range for the next five months.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7Ejennifer.banks8585%2F1.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7Ejennifer.banks8585%2F1%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d24ad74d99a368175b752db36d6c969d/href">https://medium.com/media/d24ad74d99a368175b752db36d6c969d/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7Ejennifer.banks8585%2F6.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7Ejennifer.banks8585%2F6%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/40993f04ccf9a974d5110fb04df8ef19/href">https://medium.com/media/40993f04ccf9a974d5110fb04df8ef19/href</a></iframe><p>Below shows pollution particulates in Ada, Idaho. The sample function that calls for a countyand state and returns the visualization of pollution particulates of the given location can be accessed <a href="https://github.com/JenBanks8585/cityspire-ds-h/blob/main/notebooks/pollution.py">here</a>. It shows how to visualize it on Plotly and create a live link for interactive embedding.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7Ejennifer.banks8585%2F8.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7Ejennifer.banks8585%2F8%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/623c5f6b5485e90069113b54ff921cf2/href">https://medium.com/media/623c5f6b5485e90069113b54ff921cf2/href</a></iframe><p>All other aspects such as pollution and crime rate were processed in a similar manner, while the rest as mentioned before were accessed though APIs.</p><p><strong>The Framework.</strong> We used fastAPI framework to deploy our API on AWS Elastic Beanstalk. Our data were saved on AWS RDS Postgres database instance. I have not used any of these technologies in any of my past projects, thus, I was somewhat hesitant albeit excited to learn something new. Luckily, my DS teammate has been superbly helpful and made the transition surprisingly easier than I thought. See below for reference on our main file that creates the fastAPI instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1a7243f0e2463d5557e6709c4124a57/href">https://medium.com/media/c1a7243f0e2463d5557e6709c4124a57/href</a></iframe><p><strong>Potential Enhancements.</strong> Some of the future improvements of our DS API are, but not limited to:</p><ul><li>Refactoring the code where multiple functions were used.</li><li>Use different models for forecasting such as LSTM.</li><li>Perform predictive models on other datasets</li><li>Redeploy this app on another platform, as our AWS source can only house it temporarily.</li><li>Fully connect our API to both iOS and web group.</li></ul><p><strong>The Takeaways.</strong> Overall, this project has been a very enlightening experience with plenty of learning opportunities not only technically but also collaboratively. One of my favorite learning experience if working with git commands and practicing the work process within the team. Below is a sample work flow that I learned from this project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4DE-DSLvFcS6gKV3STA4qA.png" /><figcaption>Simple Git Work Flow</figcaption></figure><p>Another lesson that I learned is how to create a descriptive pull request. Below is my first one, it is descriptive as it provides all <strong><em>a.) links to Trello Board, b) files where these actions can be found in the repository, and c) the list of actions associated with it.</em></strong> However, another important factor that I didn’t realize is that this particular pull request is quite massive with more than 3000 lines of code. It would probably be better if this was chunked into smaller segments.</p><figure><a href="https://github.com/Lambda-School-Labs/cityspire-ds-h/pull/7"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YV4WhJLfNoV-hdKRhWGK1A.png" /></a><figcaption>Sample Pull Request</figcaption></figure><blockquote>For me though, the greatest takeaway from this experience is the chance to work with a group of people of different strengths, skill levels, backgrounds, tracks, and come up with a product close to what was initially defined. I will always value all the collaboration, questions thrown, situations presented, constructive feedback and assistance provided throughout this short period of time.</blockquote><p>This project has given a template for project planning, implementation and deployment, as well as a guide on how to act, work and collaborate in a cross-functional group.</p><p>For the complete reference of the project, use <a href="https://github.com/JenBanks8585/cityspire-ds-h">this</a>.</p><p><strong>Links:</strong></p><ul><li><a href="https://www.linkedin.com/in/jenniferobanks/">LinkedIn</a></li><li><a href="https://github.com/JenBanks8585/cityspire-ds-h">Github</a></li><li><a href="https://h-ds2.cityspire.dev/">API</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b99592efc26d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K Means Clustering: Behind the Scenes]]></title>
            <link>https://jennifer-banks8585.medium.com/k-means-clustering-behind-the-scenes-bf8675a132c8?source=rss-a4a4f088f95a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf8675a132c8</guid>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[clustering-algorithm]]></category>
            <category><![CDATA[k-means]]></category>
            <dc:creator><![CDATA[Jennifer Banks]]></dc:creator>
            <pubDate>Tue, 20 Oct 2020 01:07:02 GMT</pubDate>
            <atom:updated>2020-10-23T02:45:00.015Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is K Means Clustering?</strong> When I try to learn a new concept or field, it always helps me to understand where this particular concept is oriented in the bigger scheme of things. In this post, we will learn about K Means Clustering, a type of machine learning algorithm. So in the big field of machine learning, where does K Means clustering fall?</p><p>As shown in the figure below, there are three types of machine learning techniques. In general, the difference between supervised and unsupervised is the lack of label on the latter one. Having said that, this post will cover one way to deal with unsupervised learning and that is by clustering. There are multiple ways to implement a clustering algorithm, we will mainly focus on K Means Clustering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*ft_LlyBWZjigqHVOD-ZOHA.png" /><figcaption>fig A: Where is K Means Clustering in Machine Learning Map?</figcaption></figure><p>As mentioned above, unsupervised data is not labeled. This means, that there is not a specific value to predict, or a classification to determine. K Means Clustering is an algorithm that groups unlabeled data points that are similar to each other in terms of the available and defined features. Picture a bunch of Skittles. They come in many different colors, flavors, weight, prices and maybe sizes. These are called attributes of the Skittles object. In tabular form, each attribute can be represented by a column. To perform a clustering algorithm on this example, the objective is to group them together based on their most common attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qj3BhM1iXFaurawCb_SCTw.jpeg" /><figcaption>fig B: A bunch of Skittles!</figcaption></figure><p>Here are two potential clustering results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*y_3qWj18O64qI5XJhCEyNA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I2D7anZKAOFcl04jJBzMsQ.jpeg" /><figcaption>fig C: Two different types of clustering results</figcaption></figure><p>Going back to implementation of K Means Clustering, you might wonder how do we measure proximity of attributes? How can one decide if green is closer to black than with another color? How can one measure a sweet flavor from that of a sour one? Unlike price and weight which are numerically represented, categorical data such as flavor can be encoded into numerical form. For this post, we will assume that all attributes had been encoded and that we are dealing with full quantitative data. The measure of proximity of one instance or point from another is implemented by finding the distances between them. We will talk about this more further down in this post. The ‘K’ in K Means Clustering stands for the number of clusters. For instance in fig D below, the left scatter plot has a K = 3, while the one on the right has a K = 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*p32KDQVN4izrgECAp-nVxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*Uoc3cea0Gl5zrKts5mFaMw.png" /><figcaption>fig D: Two different cluster values, K</figcaption></figure><h4><strong>K Means clustering is an iterative process with the basic concept of each step shown as follows:</strong></h4><ol><li>Define the number of clusters, K</li><li>Randomly assign K number of centroids</li><li>Assign each data point to the cluster with the closest centroid.</li><li>Get the average or center-most location of all points belonging in each cluster. This becomes the new updated centroid.</li><li>Just like in step 3, the distances of each point from all new updated centroids is computed. Each point will be reassigned to a new updated cluster with the closest updated centroid.</li><li>Step 3–5 is repeated until each point is permanently assigned to a cluster.</li></ol><p>The iteration happens between steps 3 to 5 and this is broken when a certain tolerance level is attained. To illustrate this process, a sample generator from sklearn called make_blobs will be used. Since we will use clustering, we do not need the labels. In the example code below, we will only use the datapoints denoted by X . There are 400 points in this example denoted by the parameter n_samples . For the purposes of visualization we will use a dummy dataset with two dimensions denoted by the parameter n_features .</p><pre><strong>from sklearn.datasets import make_blobs</strong></pre><pre><strong># generate dummy data<br>X, _ = make_blobs(n_samples=400, n_features=2, centers=2, random_state=42)</strong></pre><p>Visualizing these points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*-TTPCs9XvXfvrnl_0bG_Iw.png" /><figcaption>fig E: Data points distribution</figcaption></figure><p>Before implementing, we need to make a class of this K Means algorithm with the following attributes: data , K clusters and maximum iteration. There are many ways to do this and this class can be designed with different combinations of attributes. This is just one way to implement this.</p><pre><strong>class KMClusters:<br>  def __init__(self, data, K, max_iter = 100):<br>    self.K = K    <br>    self.max_iter = max_iter<br>    self.rows = data.shape[0]<br>    self.columns = data.shape[1]</strong></pre><p><strong>Step 1:</strong> Define the number of clusters, K. For this example, we will set the value of K = 4. This is not necessarily arbitrary. There is a way to find the best K value but this will not be covered in this post. Having a value of K = 4 means the data above will be grouped into four clusters. Each cluster will have a centroid.</p><p>A centroid is a point that represents the coordinates of the center of all points the same cluster. In other words, if we have a 2-dimensional dataset, considering all the points in one cluster, the x- and y-coordinates of the centroid is the average of all x- and y- values in that cluster. One of the purposes of KMeans clustering is to determine the centroids of each cluster.</p><p><strong>Step 2:</strong> To initialize, randomly assign K number of centroids. Since we have chosen K = 4, we will randomly generate four coordinates for these centroids denoted by the star markers below, with a list of coordinates at [[0,4], [4,2], [1,3], [2,6]]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*L5cngWNWhC4gzDfV0Mzs4g.png" /><figcaption>fig F: Data scatter plot with 4 initialized centroids</figcaption></figure><pre><strong>def random_centroids(self, data):<br>    random_idx = np.random.permutation(self.rows)[:self.K]<br>    centroids = data[random_idx]<br>    return centroids</strong></pre><p><strong>Step 3:</strong> Assign each data point to the cluster with the closest centroid. For each point in the dataset the distance from each of the 4 centroids will be computed using the Euclidean distance. There are other types of distance parameters that are available, but we will use Euclidean distance for this post. Each point is associated with the centroid closest to it. All points associated with a particular centroid constitute a cluster. In the figure below, each cluster is shown in different colors. The centroid of each cluster denoted by a star marker. All points that belong to each cluster are represented by the circular dots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*Og91m7pkSCVGeF_jOLaCqw.png" /><figcaption>fig G: Initial clustering based on randomized centroids</figcaption></figure><pre><strong> def create_clusters(self, data):<br>   clusters = [[] for _ in range(self.K)]</strong></pre><pre><strong>   for point_idx, point in enumerate(data):<br>     closest_idx =np.argmin([np.linalg.norm(data-centroid) for centroid in self.random_centroids(data)])<br>     clusters[closest_idx].append(point_idx)<br>    <br>   return clusters</strong></pre><p><strong>Step 4:</strong> Get the mean or center-most location of all points belonging in each cluster. This becomes the new updated centroid. In fig G above, consider the purple-colored cluster with initial centroid located at (0,4). To update the new centroid, all x- and y- values will correspondingly be averaged out. The results will be the new location of the updated centroid for the first iteration. Looking at the figure below, the new purple centroid is located at about (0.2, 4.4). This process is repeated on the rest of the clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*78rNE09tkzHNfmTQjagI0w.png" /><figcaption>fig H: recalculated centroids, first iteration</figcaption></figure><pre><strong>def new_centroids(self, data):<br>  updated_centroid = []<br>  for i in range(len(self.create_clusters(data))):<br>    z = list(np.mean(data[clusters[i]], axis = 0))<br>    updated_centroid.append(z)<br>    new_centroids = np.array(updated_centroid)<br>    <br>  return new_centroids</strong></pre><p><strong>Step 5:</strong> Just like in step 3, the distances of each point from all new updated centroids is computed. Each point will be reassigned to a new updated cluster with the closest updated centroid. In the figure below, notice that the centroids have been relocated and some of the points had been reassigned to a different cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*FpvkAr2CNppJAD2xibBGXw.png" /><figcaption>fig I: Clustering after 1 iteration.</figcaption></figure><p><strong>Step 6: </strong>Step 3–5 is repeated until each point is permanently assigned to a cluster. The movement of centroids and reassignment of clusters become more subtle as the model iterates further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*Brl2_neae5Bn4FOJi6jD1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*HkmXpRTxPAcEesH1N6Zsgw.png" /><figcaption>From left to right figures, there is a slight readjustment of centroids and cluster groupings.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*j8lpeZpIVKVvAzPkJCLoGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*v557vjxAN_hQ8JlC8A1DQg.png" /><figcaption>From left to right all points had been permanently assigned to a cluster. Iteration stops.</figcaption></figure><p>Let’s visualize the same process with a smaller data set and with K = 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*6rXDwSynEU3Eaf5-jQBzqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*ccH0caHA55x01cSisDczQQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*pHHg-XK8PGWZadmmqmeieg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*876ZtCRzbXHLI2t3FwFBOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*EeydC2SliXu6V8IBQtIQNg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*6Y3xdgEUCoj-GlQpz3-87Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*NgvtWhjR7V9kXtR7IQ_iLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*Qu4BtcpYEOVGa5Vxo0BQTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*NgvtWhjR7V9kXtR7IQ_iLA.png" /><figcaption>Clustering algorithm with five iterations</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*Qu4BtcpYEOVGa5Vxo0BQTg.png" /><figcaption>Final cluster assignment</figcaption></figure><p>In the above figures, it can be noted that the last two ‘cluster assignments’ had the same points in each cluster. This means that the algorithm has been optimized, thus iteration is broken.</p><p>To perform the optimization, a fit method will be used, that will take in data in array form, initialize random centroids, assign points to cluster, update centroids, update cluster until iteration is broken.</p><pre><strong>def fit(self, data):<br>    centroids = self.random_centroids(data)<br>    <br>    optimized = True<br>    for i in range(self.max_iter):<br>      clusters = self.create_clusters(data)</strong></pre><pre><strong>    prev_centroids = centroids<br>    centroids = self.new_centroids(data)</strong></pre><pre><strong>      if np.sum((centroids - prev_centroids)/prev_centroids * 100) &gt;   self.tolerance:<br>        optimized = False</strong></pre><pre><strong>      if optimized:<br>        break</strong></pre><pre><strong>    y_preds = self.predict(data)<br>    return y_preds, clusters, centroids</strong></pre><p>There are a few things to consider in clustering. I have mentioned above about encoding when some of the features might be categorical. In the same light, it is also important to standardize the data before feeding it into the model because this is distance based algorithm. By stardardizing, differences in feature units is dealt with, thus essentially scaling it and lowering possibility of bias. Secondly, due to the nature of random initialization of centroids, final clustering will likely provide different results. Running the algorithm multiple times with different initial centroids would be useful.</p><p>Photo sources:</p><ul><li>fig b — <a href="https://www.cnn.com/videos/business/2019/10/25/how-skittles-are-made-candy-factory-orig.cnn">https://www.cnn.com/videos/business/2019/10/25/how-skittles-are-made-candy-factory-orig.cnn</a></li><li>fig c right — <a href="https://everydayanalytics.ca/2015/05/data-visualization-fundamentals-with-skittles.html">https://everydayanalytics.ca/2015/05/data-visualization-fundamentals-with-skittles.html</a></li><li>fig c left — <a href="https://everydayanalytics.ca/category/bar-charts">https://everydayanalytics.ca/category/bar-charts</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf8675a132c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>