<?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 Alex Belengeanu on Medium]]></title>
        <description><![CDATA[Stories by Alex Belengeanu on Medium]]></description>
        <link>https://medium.com/@alexbelengeanu?source=rss-39d6de6f7471------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*AOdP4-cdVEt46Oy0</url>
            <title>Stories by Alex Belengeanu on Medium</title>
            <link>https://medium.com/@alexbelengeanu?source=rss-39d6de6f7471------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:20:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexbelengeanu/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[Getting started with Raincloud plots in Python]]></title>
            <link>https://medium.com/@alexbelengeanu/getting-started-with-raincloud-plots-in-python-2ea5c2d01c11?source=rss-39d6de6f7471------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ea5c2d01c11</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Alex Belengeanu]]></dc:creator>
            <pubDate>Mon, 05 Dec 2022 15:33:06 GMT</pubDate>
            <atom:updated>2022-12-05T15:33:06.897Z</atom:updated>
            <content:encoded><![CDATA[<p>A powerful data visualization method which consists of a combination between violin, scatter and box plots.</p><p>Taken individually, each of the abovementioned visualization methods have their own <strong>advantages</strong> and <strong>disadvantages</strong>. But what if we could combine them together and get to a more robust data visualization technique, namely <em>Raincloud plots </em>?</p><h4>What are Raincloud plots?</h4><p>Raincloud plots are a more<strong><em> robust and intuitive</em></strong> form of <em>data visualization</em>. As I mentioned earlier, they are a <em>blend</em> of multiple methods that put together provide a great overview on most of the <strong>statistics and patterns</strong> we need to know about our observations in the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*an2cBo2fYiU9aaoli_zD6Q.png" /><figcaption>Figure 1. Allen M, Poggiali D, Whitaker K <em>et al.</em> Raincloud plots: a multi-platform tool for robust data visualization (<a href="https://doi.org/10.12688/wellcomeopenres.15191.2">https://doi.org/10.12688/wellcomeopenres.15191.2</a>). Image from the paper.</figcaption></figure><p>In this article we will learn how to use and implement such type of plots in Python using <em>numpy </em>and <em>matplotlib</em> libraries.</p><h4>Loading the dataset</h4><p>For the sake of simplicity, for this example we will generate two random distributions in a given range of values.</p><p>Let’s import the required libraries</p><pre># Imports<br>import numpy as np<br>import matplotlib.pyplot as plt</pre><p>Next, the following code snippet will generate us two distributions of numbers that we will later use to visualize the data in a raincloud plot</p><pre># Generate random distribution of integers between 0-10 as the first feature<br>x1 = np.random.choice([0,1,2,3,4,5,6,7,8,9,10], p=[0.01, 0.01, 0.15, 0.19, 0.05, 0.11, 0.2, 0.16, 0.10, 0.01, 0.01], size=(500))<br><br># Apply random noise on each sample so they don&#39;t overlap on the x-axis in scatter plot<br>idxs = np.arange(len(x1))<br>out = x1.astype(float)<br>out.flat[idxs] += np.random.uniform(low=-1, high=1, size=len(idxs))<br>x1 = out<br><br># Generate random distribution of integers between 6-17 as the second feature<br>x2 = np.random.choice([6,7,8,9,10,11,12,13,14,15,16,17], p=[0.01, 0.01, 0.15, 0.23, 0.14, 0.06, 0.05, 0.10, 0.12, 0.11, 0.01, 0.01], size=(500))<br><br># Apply random noise on each sample so they don&#39;t overlap on the y-axis in scatter plot<br>idxs = np.arange(len(x2))<br>out = x2.astype(float)<br>out.flat[idxs] += np.random.uniform(low=-1, high=1, size=len(idxs))<br>x2 = out<br><br># Combine features in a list<br>data_x = [x1, x2]</pre><p>Great. Now that we have something to visualize, let’s see how we can build a raincloud plot</p><h4>Data visualization</h4><pre>fig, ax = plt.subplots(figsize=(8, 4))<br><br># Create a list of colors for the boxplots based on the number of features you have<br>boxplots_colors = [&#39;yellowgreen&#39;, &#39;olivedrab&#39;]<br><br># Boxplot data<br>bp = ax.boxplot(data_x, patch_artist = True, vert = False)<br><br># Change to the desired color and add transparency<br>for patch, color in zip(bp[&#39;boxes&#39;], boxplots_colors):<br>    patch.set_facecolor(color)<br>    patch.set_alpha(0.4)<br><br># Create a list of colors for the violin plots based on the number of features you have<br>violin_colors = [&#39;thistle&#39;, &#39;orchid&#39;]<br><br># Violinplot data<br>vp = ax.violinplot(data_x, points=500, <br>               showmeans=False, showextrema=False, showmedians=False, vert=False)<br><br>for idx, b in enumerate(vp[&#39;bodies&#39;]):<br>    # Get the center of the plot<br>    m = np.mean(b.get_paths()[0].vertices[:, 0])<br>    # Modify it so we only see the upper half of the violin plot<br>    b.get_paths()[0].vertices[:, 1] = np.clip(b.get_paths()[0].vertices[:, 1], idx+1, idx+2)<br>    # Change to the desired color<br>    b.set_color(violin_colors[idx])<br><br># Create a list of colors for the scatter plots based on the number of features you have<br>scatter_colors = [&#39;tomato&#39;, &#39;darksalmon&#39;]<br><br># Scatterplot data<br>for idx, features in enumerate(data_x):<br>    # Add jitter effect so the features do not overlap on the y-axis<br>    y = np.full(len(features), idx + .8)<br>    idxs = np.arange(len(y))<br>    out = y.astype(float)<br>    out.flat[idxs] += np.random.uniform(low=-.05, high=.05, size=len(idxs))<br>    y = out<br>    plt.scatter(features, y, s=.3, c=scatter_colors[idx])<br><br>plt.yticks(np.arange(1,3,1), [&#39;Feature 1&#39;, &#39;Feature 2&#39;])  # Set text labels.<br>plt.xlabel(&#39;Values&#39;)<br>plt.title(&quot;Raincloud plot&quot;)<br>plt.show()</pre><p>The result of the above code snippet will be the following plot :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*_-7tXycFIfP0_yGBnQ8WIw.png" /><figcaption>Figure 2. Representation of the Raincloud plot. Image by the autor</figcaption></figure><p>As you can see, this provides us <em>almost everything</em> we need to know about our dataset in an <strong>initial</strong> data exploration <strong>phase</strong>. We have some insights about the overall distributions, individual trend, median, quartiles and outliers.</p><p>Furthermore, it could be even <em>considerably easier</em> to read by people with little to no background in statistics / data science as it is <strong>highly intuitive</strong>.</p><h4>About me</h4><p>Hi, my name is Alex and I’m a young and passionate student about Machine Learning and Data Science.</p><p>If you liked the content please consider dropping a follow and claps as they are really appreciated. Also feel free to connect with me on <a href="https://www.linkedin.com/in/alexandru-florin-belengeanu-74b1a3128/">LinkedIn</a> in order to get some weekly insights on machine learning related topics.</p><h4>References</h4><p>[1] Allen M, Poggiali D, Whitaker K <em>et al.</em> <a href="https://wellcomeopenresearch.org/articles/4-63/v2">Raincloud plots: a multi-platform tool for robust data visualization</a> (2019) <a href="https://wellcomeopenresearch.org/articles/4-63/v2">https://wellcomeopenresearch.org/articles/4-63/v2</a></p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ea5c2d01c11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Build Your Own K-Means Algorithm Implementation in Python From Scratch With K-Means++…]]></title>
            <link>https://pub.towardsai.net/how-to-build-your-own-k-means-algorithm-implementation-in-python-from-scratch-with-k-means-f652ed08ea31?source=rss-39d6de6f7471------2</link>
            <guid isPermaLink="false">https://medium.com/p/f652ed08ea31</guid>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[Alex Belengeanu]]></dc:creator>
            <pubDate>Tue, 29 Nov 2022 20:01:41 GMT</pubDate>
            <atom:updated>2022-11-29T20:01:41.831Z</atom:updated>
            <content:encoded><![CDATA[<h3>How To Build Your Own K-Means Algorithm Implementation in Python From Scratch With K-Means++ Initialization</h3><h4>What’s a better method to deepen your knowledge about algorithm principles than implementing it from 0 by yourself?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQ8rwmJy7wtyOZl8m-toSA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/es/@melpoole?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mel Poole</a> on <a href="https://unsplash.com/s/photos/clusters?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4><strong>What is K-Means?</strong></h4><p>K-Means is an <strong>unsupervised machine learning technique</strong><em> </em>used to split up a number of <em>‘n’ observations</em> into <em>‘k’ different clusters</em>, where each observation belongs to the cluster with the closest centroid. The result will be a partition of the dataset into <em>Voronoi Cells</em>.</p><p>Suppose we have a dataset that consists of two features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*L8qEHPIlEOMjvYA1JxI1iw.png" /><figcaption>Figure 1. Randomly generated 2-dimensional unlabeled dataset. Illustration by the author.</figcaption></figure><p>As you can notice in <em>Figure 1</em>, it’s easily distinguishable by the eye that this dataset can be partitioned into six different clusters <em>(or groups)</em>. But how does the algorithm determine which observation belongs to which cluster?</p><p>In order to assign each sample a specific group, the K-Means algorithm follows the following steps :</p><ol><li>Initialize ‘k’ centroids, one for each cluster.</li><li>Assign each sample a cluster based on the closest centroid.</li><li>Recompute cluster centers based on the assigned points.</li><li>Repeat steps 2 and 3 until the centroids do not change anymore.</li></ol><p>Voilà, that’s how K-Means reaches the final result.</p><h4>K-Means use cases</h4><p>Some of the most common use cases for this clustering algorithm include topics such as <strong><em>search engines, anomaly detection</em></strong>, and <strong><em>segmentation of customers</em></strong> based of previous behavior (interests, purchases etc.)</p><h4><strong>Initialization method for centroids</strong></h4><p>One important thing we should take into consideration is that <strong>the final results will depend</strong> on <strong>the initialization</strong> <strong>method</strong> of the cluster centers. Two of the most used initialization methods are <em>‘random’</em> and <em>‘k-means++’</em>. The main difference between those two is that ‘k-means++’ is trying to push the centroids as far from one another as possible, which means that <strong>it will converge faster</strong> to the final solution.</p><p>For this implementation, we will be using <em>‘k-means++’</em> as the initialization method.</p><h4><strong>Implementation</strong></h4><pre>class myKMeans:<br>    def __init__(self, n_clusters, iters):<br>        &quot;&quot;&quot;<br>        KMeans Class constructor.<br><br>        Args:<br>          n_clusters (int) : Number of clusters used for partitioning.<br>          iters (int) : Number of iterations until the algorithm stops.<br><br>        &quot;&quot;&quot;<br>        self.n_clusters = n_clusters<br>        self.iters = iters<br>        <br>    def kmeans_plus_plus(self, X, n_clusters):<br>        pass<br><br>    def find_closest_centroids(self, X, centroids):<br>        pass<br><br>    def compute_centroids(self, X, idx, K):<br>        pass<br><br>    def fit_predict(self, X):<br>        pass</pre><p>This is the structure of the class that we will build. The <em>‘kmeans_plus_plus()’, ‘find_closest_centroids()’ </em>and <em>‘compute_centroids()’ </em>methods will implement the 1st, 2nd and 3rd steps of the algorithm respectively. The <em>‘fit_predict()’ </em>method will take the dataset and make a prediction on the labels.</p><pre>def kmeans_plus_plus(self, X, n_clusters):<br>    &quot;&quot;&quot;<br>    My implementation of the KMeans++ initialization method for computing the centroids.<br><br>    Args:<br>        X (ndarray): Dataset samples<br>        n_clusters (int): Number of clusters<br><br>    Returns:<br>        centroids (ndarray): Initial position of centroids<br>    &quot;&quot;&quot;<br>    # Assign the first centroid to a random sample from the dataset.<br>    idx = random.randrange(len(X))<br>    centroids = [X[idx]]<br><br>    # For each cluster<br>    for _ in range(1, n_clusters):<br><br>        # Get the squared distance between that centroid and each sample in the dataset<br>        squared_distances = np.array([min([np.inner(centroid - sample,centroid - sample) for centroid in centroids]) for sample in X])<br><br>        # Convert the distances into probabilities that a specific sample could be the center of a new centroid<br>        proba = squared_distances / squared_distances.sum()<br><br>        for point, probability in enumerate(proba):<br>            # The farthest point from the previous computed centroids will be assigned as the new centroid as it has the highest probability.<br>            if probability == proba.max():<br>                centroid = point<br>                break<br><br>        centroids.append(X[centroid])<br><br>    return np.array(centroids)</pre><p>The function above <em>implements</em> the first step<strong> (the initialization method) </strong>of the K-Means algorithm.</p><p>We take a random sample from the dataset and assign it as <strong><em>the first centroid</em></strong>. After that, we <em>repeatedly compute</em> the distance between <em>each sample and all centroids</em> and assign all the remaining centroids to the <em>farthest points</em> from the previously computed centers.</p><pre>def find_closest_centroids(self, X, centroids):<br>    &quot;&quot;&quot;<br>    Computes the distance to the centroids and assigns the new label to each sample in the dataset.<br><br>    Args:<br>        X (ndarray): Dataset samples  <br>        centroids (ndarray): Number of clusters<br><br>    Returns:<br>        idx (ndarray): Closest centroids for each observation<br><br>    &quot;&quot;&quot;<br><br>    # Set K as number of centroids<br>    K = centroids.shape[0]<br><br>    # Initialize the labels array to 0<br>    label = np.zeros(X.shape[0], dtype=int)<br><br>    # For each sample in the dataset<br>    for sample in range(len(X)):<br>        distance = []<br>        # Take every centroid<br>        for centroid in range(len(centroids)):<br>            # Compute Euclidean norm between a specific sample and a centroid<br>            norm = np.linalg.norm(X[sample] - centroids[centroid])<br>            distance.append(norm)<br><br>        # Assign the closest centroid as it&#39;s label<br>        label[sample] = distance.index(min(distance))<br><br>    return label</pre><p>The function above <em>implements</em> the second step <strong>(finding the closest centroids)</strong> of the K-Means algorithm.</p><p>For <em>each sample</em> in the dataset, we take <em>each centroid</em> and <strong>compute the Euclidean norm</strong> between them. We store that in a list, and at the end, we assign the observation to <em>the closest centroid</em>.</p><pre>def compute_centroids(self, X, idx, K):<br>    &quot;&quot;&quot;<br>    Returns the new centroids by computing the mean of the data points assigned to each centroid.<br><br>    Args:<br>        X (ndarray): Dataset samples <br>        idx (ndarray): Closest centroids for each observation <br>        K (int): Number of clusters<br><br>    Returns:<br>        centroids (ndarray): New centroids computed<br>    &quot;&quot;&quot;<br><br>    # Number of samples and features<br>    m, n = X.shape<br><br>    # Initialize centroids to 0<br>    centroids = np.zeros((K, n))<br><br>    # For each centroid<br>    for k in range(K):   <br>        # Take all samples assigned to that specific centroid<br>        points = X[idx == k]<br>        # Compute their mean<br>        centroids[k] = np.mean(points, axis=0)<br><br>    return centroids</pre><p>The function above <em>implements</em> the third step <strong>(recomputing the new cluster centers)</strong> of the K-Means algorithm.</p><p>For <em>each centroid</em>, we take<em> all the assigned points</em> to that <em>specific group</em> and <strong>calculate their mean</strong>. The result will give us the <em>new center of the cluster</em>.</p><pre>def fit_predict(self, X):<br>    &quot;&quot;&quot;<br>    My implementation of the KMeans algorithm.<br><br>    Args:<br>        X (ndarray): Dataset samples<br><br>    Returns:<br>        centroids (ndarray):  Computed centroids<br>        labels (ndarray):     Predicts for each sample in the dataset.<br>    &quot;&quot;&quot;<br>    # Number of samples and features<br>    m, n = X.shape<br><br>    # Compute initial position of the centroids<br>    initial_centroids = self.kmeans_plus_plus(X, self.n_clusters)<br><br>    centroids = initial_centroids   <br>    labels = np.zeros(m)<br><br>    prev_centroids = centroids<br><br>    # Run K-Means<br>    for i in range(self.iters):<br>        # For each example in X, assign it to the closest centroid<br>        labels = self.find_closest_centroids(X, centroids)<br><br>        # Given the memberships, compute new centroids<br>        centroids = self.compute_centroids(X, labels, self.n_clusters)<br>        <br>        # Check if centroids stopped changing positions<br>        if centroids.tolist() == prev_centroids.tolist():<br>            print(f&#39;K-Means converged at {i+1} iterations&#39;)<br>            break<br>        else:<br>            prev_centroids = centroids<br><br>    return centroids, labels</pre><p>Last but not least, the <em>‘fit_predict()’ </em>function will be called to make a prediction on the samples in our dataset.</p><p>Finally<em>,</em> your <em>K-Means class</em> should look something <strong>like this</strong> <strong>:</strong></p><pre>class myKMeans:<br>    def __init__(self, n_clusters, iters):<br>        &quot;&quot;&quot;<br>        KMeans Class constructor.<br>  <br>        Args:<br>          n_clusters (int) : Number of clusters used for partitioning.<br>          iters (int) : Number of iterations until the algorithm stops.<br>  <br>        &quot;&quot;&quot;<br>        self.n_clusters = n_clusters<br>        self.iters = iters<br>        <br>    def kmeans_plus_plus(self, X, n_clusters):<br>        &quot;&quot;&quot;<br>        My implementation of the KMeans++ initialization method for computing the centroids.<br>  <br>        Args:<br>            X (ndarray): Dataset samples<br>            n_clusters (int): Number of clusters<br>  <br>        Returns:<br>            centroids (ndarray): Initial position of centroids<br>        &quot;&quot;&quot;<br>        # Assign the first centroid to a random sample from the dataset.<br>        idx = random.randrange(len(X))<br>        centroids = [X[idx]]<br>  <br>        # For each cluster<br>        for _ in range(1, n_clusters):<br>  <br>            # Get the squared distance between that centroid and each sample in the dataset<br>            squared_distances = np.array([min([np.inner(centroid - sample,centroid - sample) for centroid in centroids]) for sample in X])<br>  <br>            # Convert the distances into probabilities that a specific sample could be the center of a new centroid<br>            proba = squared_distances / squared_distances.sum()<br>  <br>            for point, probability in enumerate(proba):<br>                # The farthest point from the previous computed centroids will be assigned as the new centroid as it has the highest probability.<br>                if probability == proba.max():<br>                    centroid = point<br>                    break<br>  <br>            centroids.append(X[centroid])<br>  <br>        return np.array(centroids)<br>  <br>    def find_closest_centroids(self, X, centroids):<br>        &quot;&quot;&quot;<br>        Computes the distance to the centroids and assigns the new label to each sample in the dataset.<br>  <br>        Args:<br>            X (ndarray): Dataset samples  <br>            centroids (ndarray): Number of clusters<br>  <br>        Returns:<br>            idx (ndarray): Closest centroids for each observation<br>  <br>        &quot;&quot;&quot;<br>  <br>        # Set K as number of centroids<br>        K = centroids.shape[0]<br>  <br>        # Initialize the labels array to 0<br>        label = np.zeros(X.shape[0], dtype=int)<br>  <br>        # For each sample in the dataset<br>        for sample in range(len(X)):<br>            distance = []<br>            # Take every centroid<br>            for centroid in range(len(centroids)):<br>                # Compute Euclidean norm between a specific sample and a centroid<br>                norm = np.linalg.norm(X[sample] - centroids[centroid])<br>                distance.append(norm)<br>  <br>            # Assign the closest centroid as it&#39;s label<br>            label[sample] = distance.index(min(distance))<br>  <br>        return label<br>  <br>    def compute_centroids(self, X, idx, K):<br>        &quot;&quot;&quot;<br>        Returns the new centroids by computing the mean of the data points assigned to each centroid.<br>  <br>        Args:<br>            X (ndarray): Dataset samples <br>            idx (ndarray): Closest centroids for each observation <br>            K (int): Number of clusters<br>  <br>        Returns:<br>            centroids (ndarray): New centroids computed<br>        &quot;&quot;&quot;<br>  <br>        # Number of samples and features<br>        m, n = X.shape<br>  <br>        # Initialize centroids to 0<br>        centroids = np.zeros((K, n))<br>  <br>        # For each centroid<br>        for k in range(K):   <br>            # Take all samples assigned to that specific centroid<br>            points = X[idx == k]<br>            # Compute their mean<br>            centroids[k] = np.mean(points, axis=0)<br>  <br>        return centroids<br>  <br>    def fit_predict(self, X):<br>        &quot;&quot;&quot;<br>        My implementation of the KMeans algorithm.<br>  <br>        Args:<br>            X (ndarray): Dataset samples<br>  <br>        Returns:<br>            centroids (ndarray):  Computed centroids<br>            labels (ndarray):     Predicts for each sample in the dataset.<br>        &quot;&quot;&quot;<br>        # Number of samples and features<br>        m, n = X.shape<br>  <br>        # Compute initial position of the centroids<br>        initial_centroids = self.kmeans_plus_plus(X, self.n_clusters)<br>  <br>        centroids = initial_centroids   <br>        labels = np.zeros(m)<br>        <br>        prev_centroids = centroids<br>  <br>        # Run K-Means<br>        for i in range(self.iters):<br>            # For each example in X, assign it to the closest centroid<br>            labels = self.find_closest_centroids(X, centroids)<br>  <br>            # Given the memberships, compute new centroids<br>            centroids = self.compute_centroids(X, labels, self.n_clusters)<br>            <br>            # Check if centroids stopped changing positions<br>            if centroids.tolist() == prev_centroids.tolist():<br>                print(f&#39;K-Means converged at {i+1} iterations&#39;)<br>                break<br>            else:<br>                prev_centroids = centroids<br>  <br>        return labels, centroids</pre><p>Cool. Now let’s see how <strong>the results</strong> of <em>our implementation</em> look like <strong>compared</strong> to the <em>sklearn</em> version of K-Means :) For that, we need to import the following dependencies :</p><pre>import random<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.cluster import KMeans</pre><p>Next, we need a dataset on which we will perform the clustering. For the sake of simplicity, I will generate a dummy dataset using <em>‘make_blobs()’</em> function from <em>sklearn.datasets.</em></p><pre>from sklearn.datasets import make_blobs<br><br># Generate 2D classification dataset<br>X, y = make_blobs(n_samples=1500, centers=6, n_features=2, random_state=67)</pre><p>The code snippet from above will generate us the following dataset :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*fyLT1fCoA_pqZWsa0VLjuQ.png" /><figcaption>Figure 2. Randomly generated 2-dimensional labeled dataset. Illustration by the author.</figcaption></figure><p>Now, let’s run both versions of K-Means (<em>own</em> and <em>sklearn</em> implementations) and see how they perform.</p><pre># sklearn version of KMeans<br>kmeans = KMeans(n_clusters=5)<br>sklearn_labels = kmeans.fit_predict(X)<br>sklearn_centers = kmeans.cluster_centers_<br><br># own implementation of KMeans<br>my_kmeans = myKMeans(5, 50)<br>mykmeans_labels, mykmeans_centers = my_kmeans.fit_predict(X)</pre><p>Great. Now that we have the inferences let’s visualize them together with the Voronoi Cells.😁</p><pre>plt.figure(figsize=(12,4)) <br>vor = Voronoi(sklearn_centers)<br>fig = voronoi_plot_2d(vor, plt.subplot(1, 2, 1))<br>plt.subplot(1, 2, 1)<br>plt.title(&quot;sklearn KMeans Predicts&quot;)<br>plt.xlabel(&quot;Feature 1&quot;)<br>plt.ylabel(&quot;Feature 2&quot;)<br>plt.xlim([-13, 11])<br>plt.ylim([-14, 13])<br>plt.scatter(X[:, 0], X[:, 1], 4, c=sklearn_labels) <br>plt.scatter(sklearn_centers[:, 0], sklearn_centers[:, 1], marker=&#39;x&#39;, c=&#39;red&#39;, s=50)<br>vor = Voronoi(mykmeans_centers)<br>fig = voronoi_plot_2d(vor, plt.subplot(1, 2, 2))<br>plt.subplot(1, 2, 2)<br>plt.title(&quot;My KMeans Predicts&quot;)<br>plt.xlabel(&quot;Feature 1&quot;)<br>plt.ylabel(&quot;Feature 2&quot;)<br>plt.xlim([-13, 11])<br>plt.ylim([-14, 13])<br>plt.scatter(X[:, 0], X[:, 1], 4, c=mykmeans_labels) <br>plt.scatter(mykmeans_centers[:, 0], mykmeans_centers[:, 1], marker=&#39;x&#39;, c=&#39;red&#39;, s=50)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*CT9zwS0m5I67RO0v2blRFg.png" /><figcaption>Figure 3. Comparison between our implementation of K-Means from scratch and the sklearn version. Illustration by the author.</figcaption></figure><p>Wow. That looks <strong><em>really impressive</em></strong> if you ask me. The results are pretty much the same.</p><h4>Conclusions</h4><p>To sum up, this is more or less everything that you need to know about this powerful clustering algorithm. I hope that this article helped you get a glance at K-Means principles. Thanks for reading!</p><p>If you have any observations about the article, write them in the comments! I’d love to read them 😋</p><h4>About me</h4><p>Hi, my name is Alex, and I’m a young and passionate student in Machine Learning and Data Science.</p><p>If you liked the content, please consider dropping a follow and claps, as they are really appreciated. Also, feel free to connect with me on <a href="https://www.linkedin.com/in/alexandru-florin-belengeanu-74b1a3128/">LinkedIn</a> in order to get some weekly insights on machine learning-related topics.</p><h4>References</h4><p>[1] David Arthur and Sergei Vassilvitskii, <a href="http://ilpubs.stanford.edu:8090/778/1/2006-13.pdf">k-means++: The Advantages of Careful Seeding</a> (2007), <a href="http://ilpubs.stanford.edu:8090/778/1/2006-13.pdf">http://ilpubs.stanford.edu:8090/778/1/2006-13.pdf</a></p><p>[2] <a href="https://en.wikipedia.org/wiki/K-means_clustering#Applications">https://en.wikipedia.org/wiki/K-means_clustering#Applications</a></p><p>[3] <a href="https://www.kdnuggets.com/2020/06/centroid-initialization-k-means-clustering.html">https://www.kdnuggets.com/2020/06/centroid-initialization-k-means-clustering.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f652ed08ea31" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/how-to-build-your-own-k-means-algorithm-implementation-in-python-from-scratch-with-k-means-f652ed08ea31">How To Build Your Own K-Means Algorithm Implementation in Python From Scratch With K-Means++…</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>