<?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 Salih Salih on Medium]]></title>
        <description><![CDATA[Stories by Salih Salih on Medium]]></description>
        <link>https://medium.com/@salih.salih?source=rss-2037cbb08e24------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RZlJ5vTLIQxUcd95ZE2eHQ.png</url>
            <title>Stories by Salih Salih on Medium</title>
            <link>https://medium.com/@salih.salih?source=rss-2037cbb08e24------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:56:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@salih.salih/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[The Many Pillars of Getting the Most Value From Your Organization’s Data]]></title>
            <link>https://medium.com/data-science/the-many-pillars-of-getting-the-most-value-from-your-organizations-data-836b9e712001?source=rss-2037cbb08e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/836b9e712001</guid>
            <category><![CDATA[data-management]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[aiken-pyramid]]></category>
            <dc:creator><![CDATA[Salih Salih]]></dc:creator>
            <pubDate>Sat, 30 Mar 2024 15:23:30 GMT</pubDate>
            <atom:updated>2024-03-30T18:38:43.966Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cTSJ2xnvEeUg4PXlMWkaFw.jpeg" /><figcaption>Photo by Choong Deng Xiang on Unsplash</figcaption></figure><h3>A Story of a Data Scientist</h3><p>Let me introduce you to Sarah, a talented and passionate data scientist, who just landed her dream job at GreenEnv, a large company that makes eco-friendly cleaning products. GreenEnv has tons of data on customers, products, and other areas of the business. They hired Sarah to unlock the hidden potential within this data, uncovering market trends, competitive advantages, and more.</p><p>Her first task: analyze customer demographics and buying habits to create targeted marketing campaigns. Confident in her abilities and excited to apply data science methods, Sarah dived into the customer database. But her initial excitement quickly faded. The data was a mess — inconsistent formatting, misspelled names, and duplicate entries everywhere.<strong> Data quality</strong> was terrible. There were variations of names like “Jhon Smith” and “Micheal Brown” alongside entries like “Jhonn Smtih” and “Michealw Brown.” Emails had extra spaces and even typos like “gnail.com” instead of “gmail.com.” along with many other inaccuracies. Sarah realized the hard job ahead of her — data cleaning.</p><p>Inconsistent formatting, missing values, and duplicates would lead to skewed results, giving an inaccurate picture of GreenEnv’s customer base. Days turned into weeks as Sarah tirelessly cleaned the data, fixing inconsistencies, filling in gaps, and eliminating duplicates. It was a tedious process, but essential to ensure her analysis was built on a solid foundation.</p><blockquote><strong>Who cares about data quality?</strong></blockquote><blockquote>Every year, poor data quality costs organizations an average of $12.9 million. [1]</blockquote><p>Thankfully, after weeks of cleaning and organizing this messy data, Sarah was able to get the job done…or at least for this part..</p><p>Her next challenge came when she ventured into product data, aiming to identify top-selling items and recommend future opportunities. However, she encountered a different problem — a complete lack of <strong>metadata</strong>. Product descriptions were absent, and categories were ambiguous. Basically, there wasn’t enough data to help Sarah to understand the product’s data. Sarah realized the importance of <strong>metadata management </strong>— structured information about the data itself. Without it, understanding and analyzing the data was almost impossible.</p><blockquote><strong>Research Shows Most Data Has Inaccuracies</strong></blockquote><blockquote>Research by Experian reveals that businesses believe around 29% of their data is inaccurate in some way. [2]</blockquote><p>Frustrated but determined, Sarah reached out to different departments to piece together information about the products. She discovered that each department used its own internal jargon and classification systems. Marketing and sales refer to the same cleaning product with different names.</p><p>As Sarah delved deeper, she found that datasets were kept in separate applications by different departments, outdated storage systems struggling to handle the growing volume of data, and Sarah had to wait for a long time for her queries to be executed. Sarah noticed also there are no clear rules on who can access what data and under what terms, without centralized control and proper access controls, the risk of unauthorized access to sensitive information increases, potentially leading to data breaches and compliance violations. The lack of <strong>data governance</strong>, a set of rules and procedures for managing data, was evident.</p><blockquote>Data Breaches Can Be Costly</blockquote><blockquote>According to the Ponemon Institute, the average cost of a data breach in 2023 is $4.45 million globally, an all-time high record, with costs varying by industry and location. [3]</blockquote><p>Each of the above issues and hurdles in Sarah’s story highlighted the interconnectedness of many pillars — <strong>data quality</strong>, <strong>metadata management</strong>, and <strong>data governance</strong> all played a crucial role in accessing and utilizing valuable insights at GreenEnv.</p><p>Sarah’s journey is a common one for data scientists and analysts. Many organizations have massive amounts of data, and everyone knows the saying: “Data is the new electricity.” Every organization wants to make the most of their data, as it’s a very valuable asset. But most people mistakenly (and practically) believe that simply hiring a data analyst or data scientist is enough to unlock this value. There are many pillars to getting the most value from data, and organizations need to account for and pay attention to these. The keyword here is <strong>data management</strong>.</p><blockquote>Did you know..</blockquote><blockquote>86% of organizations say they believe investing in data management directly impacts their business growth[4]</blockquote><h3><strong>What Exactly is Data Management?</strong></h3><blockquote>Generally speaking, data management is the overall practice of handling the organization’s data. from acquiring and storing the data to processing, securing, and analyzing it. The goal is to ensure the data is a<strong>ccessible, usable, accurate, reliable, </strong>and of<strong> high quality</strong> to achieve the state of <strong>data-informed organization</strong> and ultimately achieve our organizational objectives.</blockquote><p><strong>The Pillars of Data Management</strong></p><p>There are several key dimensions that work together to achieve successful data utilization, and while these pillars might be slightly different from one framework to another, the underlying concepts are the same.</p><p>In addition to <strong>data security</strong> and <strong>data integration</strong> as pillars we also have:</p><ul><li><strong>Data Quality:</strong> This ensures the data is <strong>accurate</strong>, <strong>consistent</strong>, <strong>complete</strong>, and <strong>timely</strong>. It involves identifying and fixing errors, managing missing values, and establishing <strong>data cleaning and validation processes</strong>.</li><li><strong>Metadata Management:</strong> This focuses on organizing and cataloging information about the data itself.</li><li><strong>Data Governance:</strong> This establishes the framework and rules for managing data assets throughout their lifecycle. It involves setting policies, and processes, and assigning roles to ensure data accuracy, security, and compliance with regulations.</li><li><strong>Data Architecture:</strong> This defines the structure and organization of data assets. It includes defining data models, storage solutions, and data flows, ensuring efficient data storage, retrieval, and utilization.</li><li><strong>Data Lifecycle Management:</strong> This focuses on managing data throughout its entire lifespan, from creation to archiving or deletion. It involves implementing processes for data capture, storage, transformation, use, and disposal.</li></ul><p>You can notice that these dimensions are interconnected and also closely related. Addressing weaknesses in one area can often impact others. Some frameworks have been developed to address the relationship between the different dimensions of data management and how they interact and affect each other.</p><p><strong>Data Management Frameworks: The Aiken’s Pyramid</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HTT2Khr2SIIJuM0jQ8S6yg.png" /><figcaption>Aiken’s Pyramid: Image by Author</figcaption></figure><p>Many established frameworks like DAMA-DMBOK2, IGF, and EDM offer structured guidance, standardized terminology, and maturity assessments for data management</p><p>One conceptual framework worth mentioning here, and the one I like the most, is Aiken’s pyramid of Data Management. It outlines the different stages of data management processes. Developed by Peter Aiken, a data management pioneer, this framework describes the situation in which many organizations find themselves. In trying to leverage the full potential of their data, many organizations go through a similar progression of steps:</p><ul><li><strong>Phase 1:</strong> This focuses on establishing the basic building blocks, like data modeling, storage solutions, and security measures.</li><li><strong>Phase 2:</strong> As data usage increases, this level addresses challenges arising from poor data quality and activities like metadata management and data architecture.</li><li><strong>Phase 3:</strong> The previous activities from Phase 2 require <strong>data governance</strong>. data governance also enables activities like <strong>document and content management</strong>, <strong>reference and master data management, data warehousing, and business intelligence</strong>, all in turn allowing for advanced analytics in Phase 4.</li><li><strong>Phase 4:</strong> This is the stage where the organization truly unlock the full potential of their data. Here, organizations leverage high-quality data for advanced analytics and data science and extract valuable insights to inform decision-making.</li></ul><p>The Aiken Pyramid helps organizations understand how data management activities interconnect, how each one builds on the others, and how to prioritize their efforts for effective data utilization.</p><h3><strong>My Reflections and Takeaways on Data Management Best Practices</strong></h3><p>Reflecting on learning and experience with data management(although I’m not a data management expert XD), I’ve come to appreciate and favor the following points regarding data management and its best practices, especially if we are focusing on data quality.</p><ol><li>There’s no one-size-fits-all solution to data management. While frameworks exist to guide organizations towards data management maturity, the full process remains unique for each entity. Each organization prioritizes different aspects of data management and faces distinct challenges.</li><li>My approach would be to start simple. Apply data management best practices or enhancements to a targeted portion of the organization’s data, focusing on what matters most. This allows for gradual growth in maturity, eventually encompassing all data. This phased approach can be very beneficial for dimensions like data quality and metadata management.</li><li>If a process consistently generates bad data, even the best efforts in other areas of data management won’t prevent it. These processes can be technical or non-technical. A proactive approach is crucial here.<br> <br>- For example, a non-technical process that generates bad data might involve database creation by developers who solely focus on the technical aspects. There might be a lack of documentation or column descriptions for instance. A good practice in my opinion would be to engage data analysts and other relevant stakeholders in the design process to ensure adherence to data management best practices. The data management team can decide if we would go forward with a certain application design or not.<br><br>- An application’s design can also be a technical process for bad data generation. A well-designed application should enforce data quality proactively during data entry. For instance, instead of a text box for entering gender, a dropdown menu could be used. Another example might be predefining email types, where the user only needs to add their username before automatically receiving “@gmail.com” or another domain extension.</li><li>Standardization is key: Inconsistency in data can be a nightmare. Imagine customer names stored differently across departments, dates in conflicting formats, or teams using their own abbreviations. but more than that within a single organization or a company there might be different processes that generate the same type of data, and different data collection tools. Standardization combats this chaos by establishing common formats, definitions, and processes for data handling. This ensures data quality, simplifies integration across applications, fosters collaboration through a shared data language, and boosts efficiency by streamlining data workflows. This process is also iterative and agile, the organization can gradually achieve more levels of maturity in it. This one can also be part of the previous data management process of validation of applications that generate data: adherence to standards. i.e. any application to be approved should comply to the standards first.</li><li>Finally, data management is a comprehensive process that requires collaboration across different teams within the organization, with the need to define the data management strategy and align it with the business or institute’s objectives and strategies. This would typically start with assessing the current and desired data management maturity levels, analyzing the gap, prioritizing data management tasks, and remaining agile. The process is iterative, and clear solutions rarely exist in advance.</li></ol><h3><strong>Data Management Professional Career</strong></h3><p>There are many data management certifications out there you might consider. The best choice depends on your specific goals and experience but here are a few ones I came across:</p><ul><li><strong>Certified Data Management Professional (CDMP):</strong> Offered by the Data Management Association (DAMA) International, this covers a wide range of topics, from data governance and quality to modeling.</li><li><strong>Certified Information Management Professional (CIMP):</strong> This program, offered by the Institute for Information Management (IIM), focuses on information management disciplines like governance, quality, security, and more.</li><li><strong>Data Governance and Stewardship Professional (DGSP):</strong> This certification, from the Data Governance Institute, focuses on the skills needed to develop and implement a data governance program, along with ensuring data quality, compliance with regulations, and so on.</li><li><strong>Certified Clinical Data Manager (CCDM):</strong> This one, offered by the Society for Clinical Data Management (SCDM), is for professionals in clinical research who manage data collected during trials.</li></ul><p>Ultimately the choice of which one is worth the time and effort requires a more in-depth analysis of the credibility, content, and purpose of each certification.</p><h3>Looking Ahead: Data Management Tools</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3gGH2_1JJhKKW2V8Dw1XwQ.jpeg" /><figcaption>Image by author</figcaption></figure><p>As you would guess, there is an endless number of tools available to address different aspects of data management, and it would be impractical to talk about all these tools, each tool would have pros and cons, and situations where it might be effective, or specific data management dimensions where it would be helpful.</p><p>In my next article, I will delve deeper into two open-source tools for data management, DataHub and Great Expectations(GX), and provide a step-by-step guide on how to integrate them to create a robust, cost-effective, scalable, and unified environment for data discovery, metadata management, data quality, data governance, data lineage, and impact analysis.</p><h3>Conclusion</h3><p>Data is arguably an organization’s most valuable asset these days. However, many still lack proper data management, limiting their ability to leverage its true potential. Issues like data quality, governance, security, and metadata management are all central pillars to get the most value out of your organization’s data.</p><p>Remember Sarah’s story at the beginning? Hiring a data scientist isn’t enough. They often spend a significant amount of time cleaning and organizing messy data before they can even begin analysis. Thankfully, frameworks like the Aiken Pyramid can guide organizations on their data management journey, and help in communicating data management initiatives across the different teams and different stakeholders easily and regardless of their technical level.</p><p>Thanks for reading all the way here! I hope you found this informative and enjoyable. Please feel free to point out any mistakes or share your thoughts — your feedback is always appreciated.</p><h3>References</h3><ol><li>Gartner. (2021). “How to Improve Your Data Quality.” Smarter With Gartner, Gartner”</li><li>Experian. (2019). “Global Data Management Research Report.”</li><li>Ponemon Institute. (2023). “Cost of a Data Breach Report.”</li><li>Experian. (2021), “Data experience The data-driven strategy behind business growth report”</li></ol><h3>Further Readings</h3><h4>Books</h4><ul><li>Data Management Body of Knowledge (DAMA-DMBOK): The DAMA-DMBOK 2nd edition, this one serves as a comprehensive guide to data management practices and principles. It provides a detailed overview of various aspects of data management. [my favorite reference for data management!]</li><li>“Data Governance: How to Design, Deploy and Sustain an Effective Data Governance Program” by John Ladley.</li><li>“The Case for the Chief Data Officer: Recasting the C-Suite to Leverage Your Most Valuable Asset”, by Peter Aiken, Michael M. Gorman</li><li>“Data Management for Researchers: Organize, Maintain and Share Your Data for Research Success” by Kristin Briney.</li></ul><h4>Online Resources:</h4><ul><li><a href="https://www.dama.org/cpages/home">Data Management Association (DAMA) International:</a> DAMA International offers a wealth of resources on data management, including articles, webinars, and whitepapers. Their website is a valuable resource for both beginners and experienced professionals.</li><li><a href="https://tdan.com/">The Data Administration Newsletter</a>: TDAN.com is an online publication dedicated to data management and data administration topics.</li><li><a href="https://www.facebook.com/groups/346145433213551">CDMP Study Group on Facebook</a>: Here you can find many data practitioners and others who are interested in the CDMP exam, you can ask questions, seek a study partner, or join them in their regular webinars and discussions about data management based on the CDMP topics. personally, this one is one of my favorites, thanks to <a href="https://medium.com/u/2caa691701c0">Nicole Janeway Bills</a> for her efforts in this group.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=836b9e712001" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-many-pillars-of-getting-the-most-value-from-your-organizations-data-836b9e712001">The Many Pillars of Getting the Most Value From Your Organization’s Data</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning Algorithms as a Mapping Between Spaces: From SVMs to Manifold Learning]]></title>
            <link>https://medium.com/data-science/machine-learning-algorithms-as-a-mapping-between-spaces-from-svms-to-manifold-learning-b1dfe1046e4f?source=rss-2037cbb08e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1dfe1046e4f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[support-vector-machine]]></category>
            <category><![CDATA[manifold-learning]]></category>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[high-dimensional-data]]></category>
            <dc:creator><![CDATA[Salih Salih]]></dc:creator>
            <pubDate>Wed, 07 Feb 2024 17:48:01 GMT</pubDate>
            <atom:updated>2024-02-07T17:48:01.858Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring the beauty of mapping between spaces in SVMs, autoencoders, and manifold learning (isomaps) algorithms</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VVhUflIpoCFfelz2RKMdPA.jpeg" /><figcaption>Photo by Evgeni Tcherkasski on Unsplash</figcaption></figure><h3>Introduction</h3><p>In machine learning, understanding how algorithms process, interpret, and classify data relies heavily on the concept of “spaces.” In this context, a space is a mathematical construct where data points are positioned based on their features. Each dimension in the space represents a specific attribute or feature of the data, allowing algorithms to navigate a structured representation.</p><h4>Feature Space and Input Space</h4><p>The journey begins in the feature or input space, where each data point is a vector representing an instance in the dataset. To simplify, imagine an image where each pixel is a dimension in this space. The complexity and dimensionality of the space depend on the number and nature of the features. Working with high-dimensional spaces can be either enjoyable or frustrating for data practitioners.</p><h4>Challenges in Low-dimensional Spaces</h4><p>In low-dimensional spaces, not all relationships or patterns in the data are easily identifiable. Linear separability, which is the ability to divide classes with a simple linear boundary, is often unachievable. This limitation becomes more apparent in complex datasets where the interaction of features creates non-linear patterns that cannot be captured by simple linear models.</p><p>In this article, we will explore machine learning algorithms in the perspective of mapping and interaction between different spaces. We will start with support vector machines (SVMs) as an example of simplicity, then move on to autoencoders, and finally, we will discuss manifold learning and Isomaps.</p><p><strong>Please note that the code examples in this article are for demonstration and may not be optimized. I encourage you to modify, improve and try the code with different datasets to deepen your understanding and gain further insights.</strong></p><h3>Support Vector Machines</h3><p>Support Vector Machines (SVMs) are known machine learning algorithms that excel at classifying data. As we mentioned at the beginning:</p><blockquote>In lower dimensions, linear separability is often impossible, which means it’s difficult to divide classes with a simple linear boundary.</blockquote><p>SVMs overcomes this difficulty by transforming data into a higher-dimensional space, making it easier to separate and classify. To illustrate this, let’s look at an example. The code below generates synthetic data that is clearly not linearly separable in its original space.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.datasets import make_circles<br><br># Generate synthetic data that is not linearly separable<br>X, y = make_circles(n_samples=100, factor=0.5, noise=0.05)<br><br># Visualize the data<br>plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.coolwarm, edgecolors=&#39;k&#39;)<br>plt.xlabel(&#39;Feature 1&#39;)<br>plt.ylabel(&#39;Feature 2&#39;)<br>plt.title(&#39;Original 2D Data&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*amE3_Ad-T5yvns4__k8jLg.png" /><figcaption>Image by Author</figcaption></figure><p>SVMs use a mapping between spaces to separate different classes. They lift the data from a lower dimensional space to a higher dimensional one. In this new space, SVMs find the optimal hyperplane, which is a decision boundary that separates the classes. It’s like finding the perfect line that divides groups in a two-dimensional graph, but in a more complex, multidimensional universe.</p><p>In the provided data, one class is close to the origin and another class is far from the origin. Let’s look at a typical example to understand how this data becomes separable when transformed into higher dimensions.</p><p>We will transform each 2D point (x, y) to a 3D point (x, y, z), where z = x² + y². The transformation adds a new third dimension based on the squared distance from the origin in the 2D space. Points that are farther from the origin in the 2D space will be higher in the 3D space because their squared distance is larger.</p><pre>from mpl_toolkits.mplot3d import Axes3D<br><br># Transform the 2D data to 3D for visualization<br>Z = X[:, 0]**2 + X[:, 1]**2  # Use squared distance from the origin as the third dimension<br><br># Visualize the 3D data<br>fig = plt.figure()<br>ax = fig.add_subplot(111, projection=&#39;3d&#39;)<br>ax.scatter(X[:, 0], X[:, 1], Z, c=y, cmap=plt.cm.coolwarm)<br><br># Set labels<br>ax.set_xlabel(&#39;Feature 1&#39;)<br>ax.set_ylabel(&#39;Feature 2&#39;)<br>ax.set_zlabel(&#39;Transformed Feature&#39;)<br><br># Set the viewpoint<br>elevation_angle = 15  # Adjust this to change the up/down angle<br>azimuth_angle = 45  # Adjust this to rotate the plot<br>ax.view_init(elev=elevation_angle, azim=azimuth_angle)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*CoTkYZy5H2Jy2ciCPzZovQ.png" /><figcaption>Image by Author</figcaption></figure><p>You can notice from the output above that after this transformation, our data becomes linearly separable by a 2D hyperplane.</p><p>Another example is the effectiveness of drug dosages. A patient is only cured if the dosage falls within a certain range. Dosages that are too low or too high are ineffective. This scenario naturally creates a dataset that is not linearly separable, making it a good candidate for demonstrating how a polynomial kernel can help.</p><pre># Train the SVM model on the 2D data<br>svc = SVC(kernel=&#39;linear&#39;, C=1.0)<br>svc.fit(X, y)<br><br># Create a function to plot decision boundary<br>def plot_svc_decision_function(model, plot_support=True):<br>    &quot;&quot;&quot;Plot the decision function for a 2D SVC&quot;&quot;&quot;<br>    ax = plt.gca()<br>    xlim = ax.get_xlim()<br>    ylim = ax.get_ylim()<br><br>    # create grid to evaluate model<br>    xx = np.linspace(xlim[0], xlim[1], 30)<br>    yy = np.linspace(ylim[0], ylim[1], 30)<br>    YY, XX = np.meshgrid(yy, xx)<br>    xy = np.vstack([XX.ravel(), YY.ravel()]).T<br>    Z = model.decision_function(xy).reshape(XX.shape)<br><br>    # plot decision boundary and margins<br>    ax.contour(XX, YY, Z, colors=&#39;k&#39;, levels=[-1, 0, 1], alpha=0.5,<br>               linestyles=[&#39;--&#39;, &#39;-&#39;, &#39;--&#39;])<br>    # plot support vectors<br>    if plot_support:<br>        ax.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1],<br>                   s=300, linewidth=1, facecolors=&#39;none&#39;, edgecolors=&#39;k&#39;)<br><br># Adjust the figure size for better visualization<br>plt.figure(figsize=(8, 5))<br><br># Scatter plot for original dosage points<br>plt.scatter(dosages, np.zeros_like(dosages), c=y, cmap=&#39;bwr&#39;, marker=&#39;s&#39;, s=50, label=&#39;Original Dosages&#39;)<br><br># Scatter plot for dosage squared points<br>plt.scatter(dosages, squared_dosages, c=y, cmap=&#39;bwr&#39;, marker=&#39;^&#39;, s=50, label=&#39;Squared Dosages&#39;)<br><br># Calling the function to plot the SVM decision boundary<br>plot_svc_decision_function(svc)<br><br># Expanding the limits to ensure all points are visible<br>plt.xlim(min(dosages) - 1, max(dosages) + 1)<br>plt.ylim(min(squared_dosages) - 10, max(squared_dosages) + 10)<br><br># Adding labels, title and legend<br>plt.xlabel(&#39;Dosage&#39;)<br>plt.ylabel(&#39;Dosage Squared&#39;)<br>plt.title(&#39;SVM Decision Boundary with Original and Squared Dosages&#39;)<br>plt.legend()<br><br># Display the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*esmoNshbLTeToOCFx_fEcw.png" /><figcaption>Image by Author</figcaption></figure><blockquote>In the two examples above, we take advantage of our knowledge about the data. For instance, in first example we know that we have two classes: one close to the origin and another far from the origin. This is what the algorithm does through training and fine-tuning — it finds a suitable space where the data can be linearly separated.</blockquote><p>The great thing here is that SVMs don’t map data into higher dimensions as this would be very complex computationally. Instead, they compute the relationship between the data as if it were in higher dimensions using the dot product. This is called the “Kernel trick.” I will explain SVM kernels in another article.</p><h3>Autoencoders</h3><p>Autoencoders are truly amazing and beautiful architectures that capture my imagination. They have a wide range of applications across various domains, utilizing diverse types of autoencoders.</p><p>They basically consist of an <strong>encoder </strong>and a <strong>decoder</strong>, the encoder takes your input and encode/compress it, a process in which we move from a high-dimensional space to a more compact, lower-dimensional one. What’s truly interesting is how the decoder then takes this condensed representation and reconstructs the original data in the higher-dimensional space. The natural question is: how is it possible to go back to the original space from a significantly reduced dimension?</p><p>Let’s consider an HD image with a resolution of 720x720 pixels. Storing and transmitting this image requires a lot of memory and bandwidth. Autoencoders solve this problem by compressing the image into a lower-dimensional space, like a 32x32 representation called the ‘bottleneck’. The encoder’s job is done at this point. The decoder takes over, trying to rebuild the original image from this compressed form.</p><p>This process is similar to sharing images on platforms like WhatsApp. The image is encoded to a lower quality for transmission and then decoded on the receiver’s end. The difference in quality between the original and received image is called ‘reconstruction error’, which is common in autoencoders.</p><p>In autoencoders, we can think of it as an interaction between 3 spaces:</p><ol><li>The input space.</li><li>The latent representation space (the bottleneck).</li><li>The output space.</li></ol><p>The beauty here is that we can see the autoencoder as something that operates in these 3 spaces. It takes advantage of the latent spaces to remove any noisy or unnecessary information from the input space, resulting in a very compact representation with core information about the input space. It does this by trying to mirror the input space in the output space, reducing the difference between the two spaces or the reconstruction error.</p><h4>Convolutional Autoencoders: Encoding Complexity into Simplicity</h4><p>The code below shows an example of a convolutional autoencoder, which is a type of autoencoders that works well with images. We will use the popular MNIST dataset[LeCun, Y., Cortes, C., &amp; Burges, C.J. (1998). The MNIST Database of Handwritten Digits. <a href="https://www.tensorflow.org/datasets/catalog/mnist">Retrieved from TensorFlow</a>, CC BY 4.0], which contains 28x28 pixel grayscale images of handwritten digits. The encoder plays a crucial role by reducing the dimensionality of the data from 784 elements to a smaller, more condensed form. The decoder then aims to reconstruct the original high-dimensional data from this lower-dimensional representation. However, this reconstruction is not perfect and some information is lost. The autoencoder overcomes this challenge by learning to prioritize the most important features of the data.</p><pre>import tensorflow as tf<br>from tensorflow.keras import layers<br>from tensorflow.keras.datasets import mnist<br>import matplotlib.pyplot as plt<br><br># Load MNIST dataset<br>(x_train, _), (x_test, _) = mnist.load_data()<br>x_train = x_train.astype(&#39;float32&#39;) / 255.<br>x_test = x_test.astype(&#39;float32&#39;) / 255.<br>x_train = x_train.reshape((len(x_train), 28, 28, 1))<br>x_test = x_test.reshape((len(x_test), 28, 28, 1))<br><br># Define the convolutional autoencoder architecture<br>input_img = layers.Input(shape=(28, 28, 1))<br><br># Encoder<br>x = layers.Conv2D(16, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(input_img)<br>x = layers.MaxPooling2D((2, 2), padding=&#39;same&#39;)(x)<br>x = layers.Conv2D(8, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(x)<br>encoded = layers.MaxPooling2D((2, 2), padding=&#39;same&#39;)(x)<br><br># Decoder<br>x = layers.Conv2D(8, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(encoded)<br>x = layers.UpSampling2D((2, 2))(x)<br>x = layers.Conv2D(16, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(x)<br>x = layers.UpSampling2D((2, 2))(x)<br>decoded = layers.Conv2D(1, (3, 3), activation=&#39;sigmoid&#39;, padding=&#39;same&#39;)(x)<br><br># Autoencoder model<br>autoencoder = tf.keras.Model(input_img, decoded)<br>autoencoder.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;)<br>autoencoder.fit(x_train, x_train, epochs=10, batch_size=64, validation_data=(x_test, x_test))<br><br># Visualization<br># Sample images<br>sample_images = x_test[:8]<br># Reconstruct images<br>reconstructed_images = autoencoder.predict(sample_images)<br><br># Plot original images and reconstructed images<br>fig, axes = plt.subplots(nrows=2, ncols=8, figsize=(14, 4))<br>for i in range(8):<br>    axes[0, i].imshow(sample_images[i].squeeze(), cmap=&#39;gray&#39;)<br>    axes[0, i].set_title(&quot;Original&quot;)<br>    axes[0, i].axis(&#39;off&#39;)<br>    axes[1, i].imshow(reconstructed_images[i].squeeze(), cmap=&#39;gray&#39;)<br>    axes[1, i].set_title(&quot;Reconstructed&quot;)<br>    axes[1, i].axis(&#39;off&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zaMjtvR1oqoEIlNnbg0GOw.png" /><figcaption>Image by Author</figcaption></figure><p>The output above shows how well the autoencoder works. It displays pairs of images: the original digit images and their reconstructions after encoding and decoding. This example proves that the encoder captures the essence of the data in a smaller form and the decoder can approximate the original image, even though some information is lost during compression.</p><p>Now, let’s go further and visualize the learned latent space (the bottleneck). We will use PCA and t-SNE, two techniques to reduce dimensions, to show the compressed data points on a 2D plane. This step is important because it helps us see how the autoencoder organizes the data in the latent space and shows any natural clusters of similar digits. We used PCA and t-SNE together just to compare how well they work.</p><pre># Encode all the test data<br>encoded_imgs = encoder.predict(x_test)<br><br># Reduce dimensionality using PCA<br>pca = PCA(n_components=2)<br>pca_result = pca.fit_transform(encoded_imgs)<br><br># Reduce dimensionality using t-SNE<br>tsne = TSNE(n_components=2, perplexity=30, n_iter=300)<br>tsne_result = tsne.fit_transform(encoded_imgs)<br><br><br><br># Visualization using PCA<br>plt.figure(figsize=(20, 10))<br>plt.subplot(1, 2, 1)<br>plt.scatter(pca_result[:, 0], pca_result[:, 1], c=y_test, cmap=plt.cm.get_cmap(&quot;jet&quot;, 10))<br>plt.colorbar(ticks=range(10))<br>plt.title(&#39;PCA Visualization of Latent Space&#39;)<br><br># Visualization using t-SNE<br>plt.subplot(1, 2, 2)<br>plt.scatter(tsne_result[:, 0], tsne_result[:, 1], c=y_test, cmap=plt.cm.get_cmap(&quot;jet&quot;, 10))<br>plt.colorbar(ticks=range(10))<br>plt.title(&#39;t-SNE Visualization of Latent Space&#39;)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KScDWhVN1uRYCN9bFtw9Lw.png" /><figcaption>Image by Author</figcaption></figure><p>Comparing the two resulted graphs, t-SNE is better than PCA at separating different classes of digits in the latent space visualization(it captures non-linearity). It creates distinct clusters with minimal overlap between classes. The autoencoder compresses images into a lower dimensional space but still captures enough information to distinguish between different digits, as shown in the t-SNE graph.</p><blockquote>An important note here is that t-SNE is a non-linear technique used for visualizing high-dimensional data. It preserves local data structures, making it useful for identifying clusters and patterns visually. However, it is not typically used for feature reduction in machine learning.</blockquote><p><strong>But what does this autoencoder probably learn?</strong></p><p>Generally speaking, one can say that an autoencoder like this learns the basic and simple edges and textures, moving to parts of the digits like loops and lines and how they are arranged, and finally understanding whole digits(hierarchical characteristics), all this while capturing the unique essence of each digit in a compact form. It can guess missing parts of an image and recognizes common patterns in how digits are written.</p><h3>Manifold learning: The Blessing of Non-Uniformity</h3><p>In a previous article titled <a href="https://towardsdatascience.com/curse-of-dimensionality-an-intuitive-exploration-1fbf155e1411">Curse of Dimensionality: An Intuitive Exploration</a>, I explored the concept of the “Curse of dimensionality”, which refers to the problems and challenges that arises when working with data in higher dimensions, making the job of ML algorithms harder in many ways.</p><p>Here come the manifold learning algorithms, driven by the blessing of non-uniformity, the uneven distribution or variation of data points within a given space or dataset.</p><blockquote>The fundamental assumption underlying manifold learning is that high-dimensional data actually lies on or near a lower-dimensional manifold within the high-dimensional space. This concept is based on the idea that although the data might exist in a high-dimensional space due to the way it’s measured or recorded, the intrinsic dimensions that effectively describe the data and its structure are much lower.</blockquote><p>Let’s generate the famous Swiss roll dataset and use it as an example of non-uniformity in higher-dimensional spaces. In its original form, this dataset looks like a chaotic mess of data points. But beneath this chaos, there is hidden order — a low-dimensional structure that includes the important features of the data. Manifold learning techniques, like Isomaps, take advantage of this non-uniformity. By mapping data points from the high-dimensional space to a lower-dimensional one, Isomap shows us the intrinsic shape of the Swiss roll. It keeps the richness of the original data while revealing the underlying structure — a 2D projection that captures the non-uniformity of the high-dimensional space:</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn import manifold, datasets<br><br># Generate a Swiss Roll dataset<br>X, color = datasets.make_swiss_roll(n_samples=1500)<br><br># Apply Isomap for dimensionality reduction<br>iso = manifold.Isomap(n_neighbors=10, n_components=2)<br>X_iso = iso.fit_transform(X)<br><br># Plot the 3D Swiss Roll<br>fig = plt.figure(figsize=(15, 8))<br><br># Create a 3D subplot<br>ax = fig.add_subplot(121, projection=&#39;3d&#39;)<br>ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=color, cmap=plt.cm.Spectral)<br><br># Set the viewing angle<br>elevation_angle = 30  # adjust this for elevation<br>azimuthal_angle = 45  # adjust this for azimuthal angle<br>ax.view_init(elev=elevation_angle, azim=azimuthal_angle)<br><br>ax.set_title(&quot;Original Swiss Roll&quot;)<br><br># Plot the 2D projection after Isomap<br>ax = fig.add_subplot(122)<br>ax.scatter(X_iso[:, 0], X_iso[:, 1], c=color, cmap=plt.cm.Spectral)<br>plt.axis(&#39;tight&#39;)<br>ax.set_title(&quot;2D projection by Isomap&quot;)<br><br># Show the plots<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eIlllbVUQJAHJFhd9OSpnw.png" /><figcaption>Image by Author</figcaption></figure><p>Let’s look at the output above:</p><p>We have two colorful illustrations. On the left, there’s a 3D Swiss roll with a rainbow of colors that spiral together. It shows how each shade transitions into the next, marking a path through the roll.</p><p>Now, on the right. There’s a 2D spread of the same colors. Even though the shape has changed the order and flow of colors still tell the same story of the original data. The order and connections between points are preserved, as if the Swiss roll was carefully unrolled onto a flat surface so we can see the entire pattern at once.</p><h3><strong>Conclusion</strong></h3><p>This article started by exploring the concept of spaces, which are the mathematical constructs where data points are positioned based on their features/attributes. We examined how <strong>Support Vector Machines (SVMs)</strong> leverage the idea of mapping data into higher-dimensional spaces to address the challenge of <strong>non-linear separability</strong> in lower spaces.</p><p>Then we moved on to <strong>autoencoders</strong>, an elegant and truly beautiful architecture that maps between <strong>3 spaces</strong>, the <strong>input space</strong>, that gets compressed to a much lower<strong> latent representation(the bottleneck)</strong>, and then comes the decoder to take the lead aiming to reconstruct the original input from this lower representation<strong> while minimizing the reconstruction error</strong>.</p><p>We also explored <strong>manifold learning</strong>, and the blessing that we get from non-uniformity as a way to overcome the <strong>curse of dimensionality</strong> by simplifying complex datasets without losing important details.</p><p>If you made it this far, I would like to thank you for your time reading this, I hope you found it enjoyable and useful, please feel free to point out any mistakes or misconceptions in my article, your feedback and suggestions are also greatly appreciated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1dfe1046e4f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/machine-learning-algorithms-as-a-mapping-between-spaces-from-svms-to-manifold-learning-b1dfe1046e4f">Machine Learning Algorithms as a Mapping Between Spaces: From SVMs to Manifold Learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Curse of Dimensionality: An Intuitive Exploration]]></title>
            <link>https://medium.com/data-science/curse-of-dimensionality-an-intuitive-exploration-1fbf155e1411?source=rss-2037cbb08e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fbf155e1411</guid>
            <category><![CDATA[dimensionality-reduction]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[high-dimensional-data]]></category>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[curse-of-dimensionality]]></category>
            <dc:creator><![CDATA[Salih Salih]]></dc:creator>
            <pubDate>Sat, 30 Dec 2023 17:02:30 GMT</pubDate>
            <atom:updated>2023-12-30T17:02:30.877Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1sfM8HlPslMNalP0dtRFVw.jpeg" /><figcaption>Photo by Mathew Schwartz on Unsplash</figcaption></figure><h3><strong>Introduction</strong></h3><p>In the previous article, we discussed the<a href="https://towardsdatascience.com/the-surprising-behavior-of-data-in-higher-dimensions-1c49bca9bbee"> surprising behavior of data in higher dimensions</a>. We found that volume tends to accumulate in the corners of spaces in a strange way, and we simulated a hypersphere inscribed inside a hypercube to investigate this, observing an interesting decrease in their volume ratio as the dimensions grew. Examples that demonstrated the advantages of multi-dimensional thinking were the DVD-paper experiment and the kernel trick in support vector machines(SVMs).</p><p>Today, we will be looking at some of the difficult aspects of high-dimensional data which is referred to as curse of dimensionality. Our goal is to have an intuitive understanding of this concept and its practical implications. The diagram below outlines how our article is structured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*cZgs5ifa0fXlXWhxCAF_bQ.png" /><figcaption>Image by Author</figcaption></figure><h4>Understanding the Curse of Dimensionality</h4><p>“Curse of dimensionality” is a term that was first used by Richard E. Bellman back in the 1960s. It began as Bellman’s idea from dynamic optimization and it turned out to be a fundamental concept for understanding complexity in high-dimensional spaces.</p><p>Good, but what is “curse of dimensionality”?</p><blockquote>It is at its core the difficulties and unique characteristics one faces when working with data in high-dimensional spaces( in our case this refers to having many features, columns or attributes in datasets). These spaces go far beyond our experience of everyday life in three-dimensional space.</blockquote><p>When we increase the number of dimensions on a dataset, the volume it occupies expands exponentially. This might appear initially as an advantage — more space could mean more data and probably more insights? However, that is not the case because having many dimensions comes with a number of challenges which change how we need to deal with and understand these high-dimensional data.</p><h3>Key Challenges</h3><p>The shift from low-dimensional to high-dimensional data faces several harsh challenges. There are two, which stand out because they have the most significant effects: 1) sparsity of data; 2) the issue with distance metric. Each of them makes analysis in higher dimensions even more complex.</p><h4>Data Sparsity: Islands in an Ocean of Emptiness</h4><p>Data sparsity in highly dimensional spaces is like few small islands lost within a vast ocean. When dimensionality increases, data points that were close together in lower dimensions become increasingly separated. This is due to the fact that the amount of space expands exponentially with each new addition of another dimension. Just imagine a cube becoming a hypercube; its corners move further away from its center and make it more empty inside. This growing emptiness is what we refer to as data sparsity.</p><p>Many data analysis techniques struggle with sparsity. For example, many clustering algorithms depend on closely situated data points to form meaningful clusters. However, when data points become too dispersed, these algorithms face difficulties.</p><h4>Distance Metric Problems: When Proximity Loses Meaning</h4><p>In high-dimensional spaces, distance metrics encounter significant challenges. Metrics like Euclidean or Manhattan distances, which are useful for measuring proximity between data points in lower dimensions, lose their effectiveness. In these expanded spaces, distances start to converge. This means that most pairs of points become nearly equidistant from each other and from a reference point. This convergence makes it harder to distinguish between close neighbors and distant ones.</p><p>In tasks like classification, where distance measurements are crucial for categorizing new data points, these metrics become less effective. As a result, algorithm performance drops, leading to less accurate predictions and analyses.</p><p>To better understand how distance behavior changes in higher dimensions, let’s perform a simple simulation. We will generate random points in both low and high-dimensional spaces. This will allow us to observe and compare the distribution of distances, showing us how these distances evolve as we move to higher dimensions.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.spatial.distance import pdist<br><br>def generate_points(dimensions, num_points, range_min, range_max):<br>    return np.random.uniform(range_min, range_max, (num_points, dimensions))<br><br>def calculate_pairwise_distances(points):<br>    distances = np.sqrt(((points[:, np.newaxis, :] - points[np.newaxis, :, :]) ** 2).sum(axis=-1))<br>    np.fill_diagonal(distances, np.nan)  # Ignore self-distances by setting them to NaN<br>    return distances<br><br>def calculate_distances_from_reference(points, reference_point):<br>    distances = np.sqrt(((points - reference_point) ** 2).sum(axis=1))<br>    return distances<br><br>def calculate_stats_for_dimensions(num_points, dimensions_range, range_min, range_max):<br>    means_pairwise = []<br>    stds_pairwise = []<br>    means_ref = []<br>    stds_ref = []<br><br>    for dim in dimensions_range:<br>        points = generate_points(dim, num_points, range_min, range_max)<br>        pairwise_distances = calculate_pairwise_distances(points)<br>        reference_point = generate_points(dim, 1, range_min, range_max)<br>        distances_from_ref = calculate_distances_from_reference(points, reference_point)<br><br>        means_pairwise.append(np.nanmean(pairwise_distances))<br>        stds_pairwise.append(np.nanstd(pairwise_distances))<br>        means_ref.append(np.mean(distances_from_ref))<br>        stds_ref.append(np.std(distances_from_ref))<br><br>    return means_pairwise, stds_pairwise, means_ref, stds_ref<br><br>def plot_histograms_and_stats(num_points, dimensions_range, range_min, range_max):<br>    fig, axs = plt.subplots(2, 3, figsize=(12, 7), tight_layout=True)<br><br>    # Plotting histograms for 3D and 100D<br>    for i, dim in enumerate([3, 100]):<br>        points = generate_points(dim, num_points, range_min, range_max)<br>        pairwise_distances = calculate_pairwise_distances(points)<br>        reference_point = generate_points(dim, 1, range_min, range_max)<br>        distances_from_ref = calculate_distances_from_reference(points, reference_point)<br><br>        axs[i, 0].hist(pairwise_distances[~np.isnan(pairwise_distances)], bins=50, alpha=0.7, color=&#39;blue&#39;, edgecolor=&#39;black&#39;)<br>        axs[i, 0].set_title(f&#39;Pairwise Distances in {dim}D&#39;)<br>        axs[i, 1].hist(distances_from_ref, bins=30, alpha=0.7, color=&#39;green&#39;, edgecolor=&#39;black&#39;, range=(0, max(distances_from_ref)))<br>        axs[i, 1].set_title(f&#39;Distances to Reference in {dim}D&#39;)<br><br>    # Calculating and plotting mean and std deviation trends across dimensions<br>    means_pairwise, stds_pairwise, means_ref, stds_ref = calculate_stats_for_dimensions(num_points, dimensions_range, range_min, range_max)<br><br>    # Plotting mean and std deviation graphs for pairwise distances<br>    axs[0, 2].plot(dimensions_range, means_pairwise, label=&#39;Mean Pairwise&#39;, marker=&#39;o&#39;, color=&#39;blue&#39;)<br>    axs[0, 2].plot(dimensions_range, stds_pairwise, label=&#39;Std Dev Pairwise&#39;, marker=&#39;x&#39;, color=&#39;cyan&#39;)<br>    axs[0, 2].set_title(&#39;Pairwise Distances Stats&#39;)<br><br>    # Plotting mean and std deviation graphs for distances to reference point<br>    axs[1, 2].plot(dimensions_range, means_ref, label=&#39;Mean Reference&#39;, marker=&#39;o&#39;, color=&#39;green&#39;)<br>    axs[1, 2].plot(dimensions_range, stds_ref, label=&#39;Std Dev Reference&#39;, marker=&#39;x&#39;, color=&#39;lime&#39;)<br>    axs[1, 2].set_title(&#39;Reference Point Distances Stats&#39;)<br><br>    axs[0, 2].legend()<br>    axs[1, 2].legend()<br><br>    plt.show()<br><br>plot_histograms_and_stats(1000, range(1, 101), 1, 100)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSCbxVtV4F6dCkcAL1-y-A.png" /><figcaption>Image by Author</figcaption></figure><p>The code output shows how distances change across dimensions. In 3D, there are different distances between points. In 100D, distances between points tend to be similar. Graphs to the right also show that as dimensions increase, the mean distance between points gets bigger, but the standard deviation stays roughly the same as it was on 2D or 3D space.</p><p>Another note here is that as dimensions increase, the mean distance between points gets bigger and approaches the maximum distance. This happens because most of the space is concentrated in the corners.</p><p>To better understand this, we can simulate random points in dimensions up to 100D. This will let us compare the average distance to the maximum distance.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.spatial.distance import pdist<br><br>def generate_points(dimensions, num_points, range_min, range_max):<br>    return np.random.uniform(range_min, range_max, (num_points, dimensions))<br><br>def calculate_distances_stats(points):<br>    # Compute pairwise distances<br>    distances = pdist(points)<br>    <br>    # Calculate average and maximum distance<br>    average_distance = np.mean(distances)<br>    max_distance = np.max(distances)<br><br>    return average_distance, max_distance<br>def plot_normalized_difference(num_points, dimensions_range, range_min, range_max):<br>    normalized_differences = []<br><br>    for dim in dimensions_range:<br>        points = generate_points(dim, num_points, range_min, range_max)<br>        average_distance, max_distance = calculate_distances_stats(points)<br>        normalized_difference = (max_distance - average_distance) / max_distance<br>        normalized_differences.append(normalized_difference)<br><br>    plt.figure(figsize=(8, 6))<br>    plt.plot(dimensions_range, normalized_differences, label=&#39;Normalized Difference&#39;, marker=&#39;o&#39;, color=&#39;blue&#39;)<br>    plt.xlabel(&#39;Number of Dimensions&#39;)<br>    plt.ylabel(&#39;Normalized Difference&#39;)<br>    plt.title(&#39;Normalized Difference Between Max and Average Distances Across Dimensions&#39;)<br>    plt.legend()<br>    plt.show()<br>plot_normalized_difference(500, range(1, 101), 0, 1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*osG6ro9g4UnKI1wrFT_gLw.png" /><figcaption>Image by Author</figcaption></figure><p>The graph shows that as we go into higher dimensions, the average distance gets closer to the maximum distance. We used normalization in here to make sure the scales were accurate.</p><blockquote>It’s important to understand the difference between absolute and relative distances. While absolute distances generally increase with more dimensions, it’s the relative differences that matter more. Clustering algorithms like K-means or DBSCAN work by looking at how points are positioned compared to each other, not their exact distances. This lets us find patterns and relationships that we might miss if we only looked at the distances.</blockquote><p>But this leads to an interesting question: why do pairs of points in high-dimensional spaces tend to be roughly the same distance apart as we add more dimensions? What causes this to happen?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DjNaQx_OIjrUs8Sy4SWaxQ.jpeg" /><figcaption>Photo by Aakash Dhage on Unsplash</figcaption></figure><p>To understand why pairs of points in high-dimensional spaces become equidistant, we can look at the Law of Large Numbers (LLN). This statistical principle suggests that as we increase our sample size or the number of dimensions, the average of our observations gets closer to the expected value.</p><p>Let’s consider the example of rolling a fair six-sided dice. The expected mean of a roll is 3.5, which is the average of all possible outcomes. Initially, with just a few rolls, like 5 or 10, the average might be significantly different from 3.5 due to randomness. But as we increase the number of rolls to hundreds or thousands, the average roll value gets closer to 3.5. This phenomenon, where the average of many trials aligns with the expected value, shows the essence of the LLN. It demonstrates that while individual outcomes are unpredictable, the average becomes highly predictable over many trials.</p><p>Now, how does this relate to distances in high-dimensional spaces?</p><p>The Euclidean distance between two points in an n-dimensional space is calculated by summing the squared differences across each dimension. We can think of each squared difference as a random variable, similar to a roll of a dice. As the number of dimensions (or rolls) increases, the sum of these ‘rolls’ gets closer to an expected value.</p><p>A crucial requirement for the LLN is the independence of random variables. In high-dimensional vectors, this independence might be shown through an interesting geometric property:<strong> the vectors tend to be almost orthogonal to each other.</strong></p><pre>import numpy as np<br><br>def test_orthogonality(dimensions, n_trials):<br>    for i in range(n_trials):<br>        # Generate two random vectors<br>        v1 = np.random.randn(dimensions)<br>        v2 = np.random.randn(dimensions)<br><br>        # Calculate dot product<br>        dot_product = np.dot(v1, v2)<br><br>        # Calculate magnitudes<br>        magnitude_v1 = np.linalg.norm(v1)<br>        magnitude_v2 = np.linalg.norm(v2)<br><br>        # Calculate the cosine of the angle<br>        cos_theta = dot_product / (magnitude_v1 * magnitude_v2)<br><br>        # Check if vectors are almost orthogonal<br>        if np.abs(cos_theta) &lt; 0.1:  # Adjust this threshold as needed<br>            orthogonality = &quot;Almost Orthogonal&quot;<br>        else:<br>            orthogonality = &quot;Not Orthogonal&quot;<br><br>        # Calculate angle in degrees<br>        theta = np.arccos(cos_theta) * (180 / np.pi)  # Convert to degrees<br><br>        print(f&quot;Trial {i+1}:&quot;)<br>        print(f&quot;  Dot Product: {dot_product}&quot;)<br>        print(f&quot;  Cosine of Angle: {cos_theta}&quot;)<br>        print(f&quot;  Angle: {theta} degrees&quot;)<br>        print(f&quot;  Status: {orthogonality}&quot;)<br>        print(&quot;--------------------------------&quot;)<br><br># Try to edit this and notice the near-orthogonality of vectors in higher dimensions<br>dimensions = 100  # Number of dimensions<br>n_trials = 10     # Number of trials<br><br>test_orthogonality(dimensions, n_trials)</pre><p>Try running the code above and editing the number of dimensions/ trials, and you can notice that vectors in higher dimensions are almost orthogonal.</p><p>The angle between two vectors, A and B, is determined by the cosine of the angle, which is derived from their dot product and magnitudes. The formula is expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*XxlyINhTLz9RXhfrwDjwWw.png" /></figure><p>Here, <em>A</em>⋅<em>B</em> represents the dot product of vectors A and B, and ∥<em>A</em>∥ and ∥<em>B</em>∥ are their respective magnitudes. For two vectors to be orthogonal, the angle between them must be 90 degrees, making cos(<em>θ</em>) equal to zero. Typically, this is achieved when the dot product <em>A</em>⋅<em>B</em> is zero, a condition familiar in lower dimensions.</p><p>However, in high-dimensional spaces, another phenomenon emerges. <strong>The ratio of the dot product to the magnitude of the vectors becomes so small that we can consider the vectors to be ‘almost orthogonal.’</strong></p><p>But what does it mean for two vectors to be ‘independent’ in this context?</p><h4>Navigating a Grid City: An Analogy for Independence in High Dimensions</h4><p>Imagine you are in a city laid out in a grid, like Manhattan’s streets. Picture yourself at an intersection, trying to reach another point in this city. In this analogy, each street represents a dimension in a high-dimensional space. Moving along a street is like changing the value in one dimension of a high-dimensional vector. Moving along one street doesn’t affect your position on another street, just like changing one dimension doesn’t affect the others.</p><p>To reach a specific intersection, you make a series of independent decisions, like calculating distance in high-dimensional space. Each decision contributes independently but leads you to your destination.</p><p>This analogy also applies to the concept of orthogonality in high-dimensional vectors. When vectors are almost orthogonal, they follow their own paths without significantly influencing each other. This condition complements the need for statistical independence for the LLN.</p><p>An important note: while this analogy of LLN offers a helpful perspective, it may not capture all the idea or causes behind this behavior. However, it serves as a useful proxy, providing an understanding of what the reason <strong>might</strong> be for pairs of point to be almost equidistant.</p><h3>Practical Implications</h3><p>One way the curse of dimensionality problems show up is overfitting. Overfitting happens when a complex model learns noise instead of the patterns in the data. This is especially true in high-dimensional spaces where there are many features. The model can make false connections or correlations and perform poorly when it sees new data(failing to generalize).</p><p>The curse also makes it hard to find patterns in big datasets. High-dimensional data is spread out and sparse, so it’s challenging for traditional analysis methods to find meaningful insights. Some changes or specialized methods are needed to navigate and understand this type of data.</p><p>Another implication is that processing high-dimensional data takes a lot of computational power and memory. Algorithms that work well in lower dimensions become much more complex and resource-heavy as the number of dimensions increases. This means either having more powerful hardware or optimizing algorithms to handle the increased computational load efficiently.</p><h3><strong>How to address curse of dimensionality?</strong></h3><p>There are several strategies to deal with the curse of dimensionality. One way is to reduce the dimensionality while keeping the important information(ex. PCA algorithm). Another method is manifold learning(can be considered as a type of dimensionality reduction).which uncovers the structure within the high-dimensional data. The key idea behind manifold learning is that many high-dimensional datasets actually lie on a lower-dimensional manifold within the high-dimensional space(ex. Isomaps)</p><blockquote>Note here that -generally speaking- traditional dimensionality reduction techniques like PCA (Principal Component Analysis) focus on preserving global data structure and variance in a linear fashion. In contrast, manifold learning techniques like Isomap(Isometric Mapping) emphasize uncovering the underlying non-linear structure(manifold) of data, aiming to preserve local relationships and geometrical features.</blockquote><p>Feature selection is also an option, where relevant features are chosen to improve model performance. Regularization techniques prevent overfitting by shrinking less important features. Increasing the sample size can also help, although it may not always be possible. These methods can help us analyze high-dimensional data more accurately and efficiently.</p><h3>Conclusion</h3><p>The curse of dimensionality is one of the most important problems in data science and machine learning. It happens when dealing with high-dimensional spaces. Two significant challenges that arise are data sparsity and issues with distance metrics. These challenges can cause overfitting in machine learning models and make computations more complex. To tackle these challenges, strategies like dimensionality reduction, feature selection, and regularization techniques can be used.</p><p>If you have made it this far, I would like to thank you for spending time reading this! I hope you found the topic enjoyable and at least inspiring enough to delve deeper into the world of high-dimensional data. Please feel free to suggest any edits or point out any mistakes or inaccuracies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fbf155e1411" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/curse-of-dimensionality-an-intuitive-exploration-1fbf155e1411">Curse of Dimensionality: An Intuitive Exploration</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Surprising Behavior of Data in Higher Dimensions]]></title>
            <link>https://medium.com/data-science/the-surprising-behavior-of-data-in-higher-dimensions-1c49bca9bbee?source=rss-2037cbb08e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c49bca9bbee</guid>
            <category><![CDATA[high-dimensional-data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[svm-algorithm]]></category>
            <category><![CDATA[curse-of-dimensionality]]></category>
            <category><![CDATA[thoughts-and-theory]]></category>
            <dc:creator><![CDATA[Salih Salih]]></dc:creator>
            <pubDate>Fri, 15 Dec 2023 07:46:14 GMT</pubDate>
            <atom:updated>2023-12-15T07:46:14.395Z</atom:updated>
            <content:encoded><![CDATA[<h4>A journey into the surprising world of high-dimensional data: the blessings and the challenges</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L7JCyXWEBHvseZ2FzZl3cw.jpeg" /><figcaption>Photo by Guillermo Ferla on Unsplash</figcaption></figure><p>Richard Feynman, the renowned physicist, once said, “I can safely say that nobody understands quantum mechanics.” In his interview titled “<a href="https://youtu.be/P1ww1IXRfTA">Fun to Imagine with Richard Feynman</a>”, he touched on the strange behavior of things at the atomic and subatomic particles level, noting how they often defy our common sense. Interestingly, we can notice a similar behavior at the level of higher-dimensional data. It’s not exactly like quantum mechanics, but there’s a similar element of surprise and beauty — mixed with a few/a lot of challenges — when we transition from lower to higher dimensions.</p><p>In this and future articles, I want to provide some insights into this fascinating topic. My goal is to pique the interest and encourage learning about the world of higher-dimensional data, especially by those who are unfamiliar with it.</p><blockquote>High-dimensional data, or data in higher dimensions, in the context of data analysis and ML, generally refers to datasets that have a large number of variables, features, or attributes. Each of those represents a different “dimension” in our data.</blockquote><p>To begin, let’s examine some basic examples that highlight the distinctions that arise when we go from lower-dimensional spaces to higher-dimensional ones.</p><h4><strong>Volume Concentration in High-Dimensional Spaces</strong></h4><p>First, let’s explore the concept of volume concentration in high-dimensional spaces. Consider generating random points within a hypercube whose sides range from 0 to 1. How likely is it that these points fall in the middle region of this hypercube as its dimensions increase?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*WhqUE5cCtpngLm4bVvDD1w.jpeg" /><figcaption>Image by author</figcaption></figure><p>In the image above, let’s assume x is a small value, such as 0.1. We aim to determine how the probability of a point randomly falling in this middle region (not on the edge) varies with increasing dimensions.</p><ol><li>One-Dimensional Space (Line)</li></ol><p>Think of a line segment from 0 to 1. The middle part is between 0.1 and 0.9, The chance of a random point landing here is simply the length of this middle segment over the total length, which is 0.8.</p><p>2. Two-Dimensional Space (Square)</p><p>Now, envision a square where each side ranges from 0 to 1. The middle region is a smaller square with each side from 0.1 to 0.9. The probability calculation involves comparing the area of this smaller square to the total area, giving us a probability of 0.64.</p><p>3. Three-Dimensional Space (Cube)</p><p>For a cube with each edge measuring 1, the middle region is a smaller cube with each edge from 0.1 to 0.9. Here, the probability is the volume of this smaller cube divided by the total volume, resulting in 0.512.</p><p>4. Higher Dimensions (Hypercube)</p><p>In a hypercube of n dimensions, the ‘volume’ of the middle region shrinks drastically as dimensions increase. For instance, in 4D, the probability is 0.4096; in 5D, it’s 0.32768; and in 10D, it drops to approximately 0.10737.</p><p>The generalization of this idea starts with considering the edge to be of a small distance x, as shown in the image above. For a line, the probability of a point falling in the middle region is 1–2x. For a square, it’s (1–2x)*(1–2x), as a point must fall in the middle of both dimensions.</p><p>This pattern continues in n dimensions, where the probability of falling in the middle region is (1–2x)^n, becoming very small in higher dimensions.</p><p>Note that here, we simplify by considering the length of each side as 1.</p><h4>Inscribing a Hypersphere within a Hypercube</h4><p>To further illustrate the concept of volume concentration, I performed a simple simulation using python, where we inscribe a hypersphere within a hypercube, and then compare the ratio of the volume of the hypersphere to the hypercube as the dimensions increase.</p><p>What’s a Hypercube Anyway?</p><p>Picture a square. Now, puff it out into a cube. That’s the jump from 2D to 3D. Now, take a leap of imagination into the fourth dimension and beyond — that’s where hypercubes come in. A hypercube is essentially a cube extended into higher dimensions. It’s a shape with equal sides, and in our simulation, we’re considering hypercubes with side lengths of 2. The formula for its volume? just 2^<em>n(2 to the power n) </em>for an n-dimensional hypercube.</p><p>And a Hypersphere?</p><p>A hypersphere, the higher-dimensional equivalent of a sphere, emerges when you extend a 2D circle into 3D (forming a sphere) and then continue into higher dimensions. The catch? Its volume isn’t as straightforward to calculate. It involves pi (yes, the famous 3.14159…) and the gamma function, which is like a factorial on steroids. In a nutshell, the volume of a hypersphere with a radius of 1 in an n-dimensional space is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*FqQzLlfV1W0pcNKv3G0aqg.png" /></figure><p>The Gamma function Γ(<em>n</em>) extends the factorial function to real and complex numbers. For positive integers <em>n</em>, Γ(n)=(n−1)!, and for non-integer values, it is computed numerically.</p><p>To calculate this ratio using python we can use the following code:</p><pre>import math<br>import matplotlib.pyplot as plt<br><br>def hypersphere_volume(dim):<br>    &quot;&quot;&quot; Calculate the volume of a hypersphere with radius 1 in &#39;dim&#39; dimensions. &quot;&quot;&quot;<br>    return math.pi ** (dim / 2) / math.gamma(dim / 2 + 1)<br><br>def hypercube_volume(dim):<br>    &quot;&quot;&quot; Calculate the volume of a hypercube with side length 2 in &#39;dim&#39; dimensions. &quot;&quot;&quot;<br>    return 2 ** dim<br><br># Number of dimensions to consider<br>max_dim = 20<br><br># Lists to hold volumes and dimension values<br>dimensions = range(1, max_dim + 1)<br>sphere_volumes = [hypersphere_volume(dim) for dim in dimensions]<br>cube_volumes = [hypercube_volume(dim) for dim in dimensions]<br>ratios = [sphere_volumes[i] / cube_volumes[i] for i in range(max_dim)]<br><br># Plotting the results<br>plt.figure(figsize=(10, 6))<br>plt.plot(dimensions, ratios, marker=&#39;o&#39;)<br>plt.xlabel(&#39;Number of Dimensions&#39;)<br>plt.ylabel(&#39;Ratio of Volumes (Hypersphere/Hypercube)&#39;)<br>plt.title(&#39;Volume Concentration in Higher Dimensions&#39;)<br>plt.grid(True)<br>plt.show()</pre><p>The output of the above code is the following graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*cYiQAIE98AtpKfmQElwVEA.png" /><figcaption>Image by author</figcaption></figure><p>We can clearly see that as we go to higher dimensions the ratio decreases rapidly, leaving the most volume concentrated in the corners of the hypercube.</p><p>These examples demonstrate that in higher dimensions, the volume of the middle region becomes a progressively smaller fraction of the total volume, highlighting the counterintuitive nature of high-dimensional spaces.</p><blockquote>Q: What are some of the implications of this volume concentration phenomenon on the performance of ML algorithms?</blockquote><p><strong>The Paper and DVD Experiment</strong></p><p>Consider the experiment where you try to fit a DVD through a paper piece with a square hole. Initially, it seems impossible as the square’s diagonal is smaller than the DVD’s diameter. However, folding the paper allows the DVD to pass through.</p><p>The folding of the paper, a small yet effective adjustment of spatial dimensions, holds the key to the puzzle. An intriguing analogy for comprehending the complexity of higher-dimensional landscapes can be found in this experiment.</p><p>When the paper is first laid out, it forms a two-dimensional plane. The square slot seems too narrow to let the DVD through because of its set dimensions.</p><p>This hypothetical situation is consistent with our daily experiences in a three-dimensional environment, where length, width, and height are the units of measurement for size and distance. But the instant we begin to fold the paper, we add another dimension. The hole and the DVD’s spatial connection are completely altered by this folding action.</p><p>In this new three-dimensional setting, the concept of distance, which was so inflexible and clear-cut in two dimensions, becomes more flexible and less intuitive. The paper is folded, which effectively modifies the angles generated by the paper’s edges and the distances between points surrounding the hole.</p><p>The hole in this new three-dimensional form can fit the DVD, demonstrating how the inclusion of a third dimension can make an apparently hopeless task in a two-dimensional space achievable.<br>The mathematics underlying this experiment is explained in full in an intriguing study by Weiwei Lin et al.</p><p><a href="https://ms.copernicus.org/articles/12/933/2021/">A toy-inspired kirigami pattern and its kinematic performance by applying mechanisms and machine theory</a></p><p>You can also watch this beautiful video by “The Action Lab” that demonstrates the idea intuitively:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8jE-ATI8utA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8jE-ATI8utA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8jE-ATI8utA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/17633ea6662482fbb91404df87abe05b/href">https://medium.com/media/17633ea6662482fbb91404df87abe05b/href</a></iframe><p>This shift in perspective has significant implications, especially in the fields of mathematics, physics, and machine learning. This idea is reflected in machine learning methods like Support Vector Machines (SVMs).</p><p><strong>SVM and the Kernel Trick</strong></p><p>The kernel trick in Support Vector Machines (SVMs) shows a similar idea. In SVMs, we often encounter data that isn’t linearly separable. The kernel trick overcomes this by transforming the data into a higher-dimensional space, akin to how folding the paper changed its spatial properties. (In reality, SVMs don’t actually transform data into higher dimensions, as this is computationally expensive. Instead, they compute relationships between data points as if they were in a higher dimension using the kernel trick).</p><p>In simpler terms, SVMs normally find a separating line (or hyperplane) in lower dimensions. But with non-linear data, this isn’t possible. The kernel trick, like folding the paper, adds dimensions, making it easier to find a hyperplane that does the job.</p><p>The kernel trick doesn’t just shift dimensions; it also simplifies complex problems. It’s really a great example of how higher-dimensional thinking can provide solutions to problems that seem impossible in lower dimensions.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.svm import SVC<br><br># Here I manullay entered a data that is not linearly seperable in 1D<br>x = np.array([1,2,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,20,21,23,24,25,26,27,28,29,30]).reshape(-1, 1)  # Replace YOUR_X_VALUES with your data<br>y = np.array([1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1])                 # Replace YOUR_Y_VALUES with your class labels<br><br># Non-linear transformation to 2D, (squaring)<br>def transform_to_2d(X):<br>    return np.c_[X, X**2]<br><br># Transforming data to 2D<br>X_transformed = transform_to_2d(x)<br><br># Fitting SVM with a linear kernel in the transformed 2D space<br>svm = SVC(kernel=&#39;linear&#39;)<br>svm.fit(X_transformed, y)<br><br>fig, axes = plt.subplots(1, 2, figsize=(12, 5))<br><br># 1D data plot<br>axes[0].scatter(x, np.zeros_like(x), c=y, cmap=&#39;bwr&#39;, edgecolors=&#39;k&#39;)<br>axes[0].set_title(&#39;Original 1D Data&#39;)<br>axes[0].set_xlabel(&#39;Feature&#39;)<br>axes[0].set_yticks([])<br><br># 2D transformed data plot<br>axes[1].scatter(X_transformed[:, 0], X_transformed[:, 1], c=y, cmap=&#39;bwr&#39;, edgecolors=&#39;k&#39;)<br>axes[1].set_title(&#39;Transformed 2D Data&#39;)<br>axes[1].set_xlabel(&#39;Original Feature&#39;)<br>axes[1].set_ylabel(&#39;Transformed Feature (X^2)&#39;)<br><br># Plotting the decision boundary in 2D<br>ax = axes[1]<br>xlim = ax.get_xlim()<br>ylim = ax.get_ylim()<br><br>xx = np.linspace(xlim[0], xlim[1], 30)<br>yy = np.linspace(ylim[0], ylim[1], 30)<br>YY, XX = np.meshgrid(yy, xx)<br>xy = np.vstack([XX.ravel(), YY.ravel()]).T<br><br># Getting the separating hyperplane<br>Z = svm.decision_function(xy).reshape(XX.shape)<br><br># Plotting decision boundary and margins<br>ax.contour(XX, YY, Z, colors=&#39;k&#39;, levels=[-1, 0, 1], alpha=0.5,<br>           linestyles=[&#39;--&#39;, &#39;-&#39;, &#39;--&#39;])<br><br>plt.tight_layout()<br>plt.show()</pre><p>The result of the above code is the following graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2axkmogT5Z9kJAO0WTSkkw.png" /><figcaption>Image by Author</figcaption></figure><p>It’s clear that the data, initially non-linearly separable on the left, becomes separable in 2D. This transformation, as shown in the graph to the right, effectively solves our problem. Isn’t this amazing?</p><p><strong>Wrapping Up</strong></p><p>In this article, we have explored some ideas about the world of high-dimensional data. We have shown how entering higher dimensions can greatly alter our viewpoints and methods of approaching problems, starting with volume concentration and continuing with the real-life example of the paper and DVD experiment and, lastly, the kernel trick in SVMs.</p><p>In the upcoming article, we will discuss the “curse of dimensionality,” which refers to the difficulties and complications involved in navigating high-dimensional spaces. We’ll examine how this impacts machine learning and data analysis, as well as strategies for mitigating its effects.</p><p>Thank you for making it this far! I really appreciate your time in reading this, and I hope you found the topic engaging. Please feel free to share any suggestions or possible edits for future articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c49bca9bbee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-surprising-behavior-of-data-in-higher-dimensions-1c49bca9bbee">The Surprising Behavior of Data in Higher Dimensions</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Three Interpretability Methods to Consider When Developing Your Machine Learning Model]]></title>
            <link>https://medium.com/data-science/three-interpretability-methods-to-consider-when-developing-your-machine-learning-model-5bf368b47fac?source=rss-2037cbb08e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bf368b47fac</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ml-interpretability]]></category>
            <category><![CDATA[shap]]></category>
            <category><![CDATA[lime]]></category>
            <category><![CDATA[anchor]]></category>
            <dc:creator><![CDATA[Salih Salih]]></dc:creator>
            <pubDate>Fri, 04 Mar 2022 22:00:30 GMT</pubDate>
            <atom:updated>2022-03-04T22:00:30.679Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2wA1H3RHwDVTVHZw" /><figcaption>Photo by <a href="https://unsplash.com/@mitchel3uo?utm_source=medium&amp;utm_medium=referral">Mitchell Luo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Following my last article, <a href="https://towardsdatascience.com/understanding-machine-learning-interpretability-168fd7562a1a">Understanding Machine Learning Interpretability</a>, which presented an introductory overview of machine learning interpretability taxonomy, driving forces, and importance- this article presents 3 interpretability techniques that you might need to consider when developing your machine learning model. These methods are SHAP(SHapley Additive exPlanations), LIME( Local Interpretable Model-agnostic Explanations), and Anchors. In addition to providing examples for each method, we compare and contrast the three methods, discuss their limitations and provide papers and references for further readings.</p><p>Notes:</p><ol><li>This article is not about the theoretical details of these methods or how they precisely work, rather I will provide a short intuition about each method and focus on how to make use of it.</li><li>A lot of the content in this article is based on this amazing book by Christoph Molnar: Interpretable Machine Learning: A Guide for Making Black Box Models Explainable. <strong>I highly recommend reading it.</strong></li></ol><h4>Content</h4><ol><li>Brief intuition</li><li>Example</li><li>Comparison</li><li>Further readings</li><li>Conclusion</li><li>References and bibliography</li></ol><h4>1. Brief intuition</h4><h4>1.1 SHAP</h4><p>SHAP explains the prediction of the instance by determining how much each feature has contributed to the final prediction.</p><p>This method is an approach from game theory based on Shapley values, each feature value is considered as a “player” in a game, and Shapley values determine how to distribute this payout fairly among the different features.[1]</p><h4>1.2 LIME</h4><p>LIME explains the model’s prediction of an instance by approximating the model with an intrinsically interpretable one like decision trees. Roughly what LIME does is that it takes the model and calls (probes) it many times to understand how or why the model makes its predictions, by comparing how the model acts to different variations of the data, from this probing we will have a new dataset, LIME then train a new interpretable model by nature like decision trees, and each instance is weighted by how close it is to the sample instances of the newly generated dataset.[2]</p><h4>1.3 Anchors</h4><p>Like SHAP and LIME, the anchors approach a similar strategy to generate local explanations. “ <em>But instead of interpretable models employed by LIME, the explanations are expressed as simple, easy-to-understand IF-THEN rules</em>”[3], called anchors. The idea of “anchors” is that changes in other features values that are not in the anchor rule don’t affect or change the prediction, so the rule is said to “anchor” the prediction.[3]</p><h4>2. Example</h4><h4>Problem description</h4><p>To illustrate how you can utilize these methods, here is an example of loan approval, we will be working with this dataset from <a href="https://github.com/mridulrb/Predict-loan-eligibility-using-IBM-Watson-Studio/blob/master/Dataset/Dataset.csv">GitHub</a>, the 5 top rows of the data are provided in the figure below to understand how the data looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7-x8-3hVITiznuO_yZ5mDw.jpeg" /></figure><p>This dataset represents a loan approval dataset, consisting of 13 columns(12 features and 1 target variable which is loan_status).</p><p>For the purpose of this article, I have developed a simple XGBoost classifier with an accuracy of 86.67%. What these interpretability methods do, is that it takes the black-box model variable “model” and try to interpret it. What we need to understand here is that we have built an XGBoost classifier model, we apply our interpretability techniques to this model.[Note that all code in this article is carried out on Google Colab platform]</p><p>Kindly download the dataset from GitHub and save it as loan_approval.csv. The code for building the model is below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af786cd06ccc46849d3e4f895b4a0ce0/href">https://medium.com/media/af786cd06ccc46849d3e4f895b4a0ce0/href</a></iframe><p>Let’s install and import our 3 libraries</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab030fd925d2d23cbbf8f6b311acebce/href">https://medium.com/media/ab030fd925d2d23cbbf8f6b311acebce/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c906d5356abcb9933871c0dd0a35f75c/href">https://medium.com/media/c906d5356abcb9933871c0dd0a35f75c/href</a></iframe><h4>2.1 Interpreting with SHAP</h4><p>First, we need to extract the features(columns) of the dataset that are used in the prediction</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d32ee638b17c14054195d70aeb6b75a0/href">https://medium.com/media/d32ee638b17c14054195d70aeb6b75a0/href</a></iframe><p>The next cell will initialize, apply, and show SHAP interpretation for the first instance in the test set. We pass the model and the X_test( test set).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e05bf5f6339ba21db6c5a40827c0df63/href">https://medium.com/media/e05bf5f6339ba21db6c5a40827c0df63/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T0zVHaFgf36cqM_BpXc2hQ.jpeg" /><figcaption>Cell output</figcaption></figure><p>The red color in the figure above represents features that have contributed positively to the prediction, i.e loan getting approved, while features in blue have contributed negatively towards loan not getting approved.</p><p>After showing the interpretation of a single instance, the next cell can be used to plot a summary of the overall features importance of the model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3460698f41e2d55d960b3fe1664f114/href">https://medium.com/media/b3460698f41e2d55d960b3fe1664f114/href</a></iframe><p>The output will be as below, this plot summaries the overall importance of each feature, the x-axis represents SHAP values, positive values contribute positively towards loan approval and vice versa, the y-axis represents each feature, red color mean high values for the feature, and blue colors indicate lower values, so how to read this graph?</p><p>For example, we can notice that status of the applicant being married(married=1) has always contributed positively, while LoanAmount being high almost contributed negatively on loan approval, and so on, look at each feature, see the color indication and read the SHAP values accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*IxqbX7BJ5ZS6TIzAYweVEQ.jpeg" /><figcaption>Cell output</figcaption></figure><h4>2.2 Interpreting with LIME</h4><p>With LIME, a similar process applies, we initiate a tabular explainer, LIME has a specific explainer for each type of data, eg text, tabular, images, etc). LIME explainer accepts 4 parameters: training data, features names, classes names, and mode( classification in our case)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4dc0f7025b8a35af97151c2850fc58c/href">https://medium.com/media/a4dc0f7025b8a35af97151c2850fc58c/href</a></iframe><p>The next cell will show LIME’s explanation of the first instance of the test set</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e2a3e44c371e0e7ab4138e4428dd7a9/href">https://medium.com/media/0e2a3e44c371e0e7ab4138e4428dd7a9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*FX1lg9Eh3l2Jc3QGhBi0ow.jpeg" /><figcaption>Cell output</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*q_-HSq8CTOhdIaVVT555-g.jpeg" /><figcaption>Cell output</figcaption></figure><h4>2.3 Interpreting with Anchors</h4><p>Similar to SHAP and LIME, Anchors takes some parameters like class names, features names, and the training data, in addition to one more parameter which is categorical_name. For anchors to deal with categorical features, you need to create a dictionary that maps each categorical feature to its corresponding categories, each key in the dictionary is the index of the feature(column) in the training data, and values at each dictionary is a string representing each category. For example, if you have one categorical feature as the third column in your training data, and its values are: Employed, Student-then your category map will look like {2:[“Employed”, “Student”]}</p><p>If you are using one-hot encoding instead, you can write it as in the next cell {2:[“0”,”1&quot;]}. ( Make sure to write 0 and 1 as strings or it will raise an error)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eadf020ad9ef7d667b12e9ade40dde5f/href">https://medium.com/media/eadf020ad9ef7d667b12e9ade40dde5f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec1aa3a6f41de226268ec98021ef7328/href">https://medium.com/media/ec1aa3a6f41de226268ec98021ef7328/href</a></iframe><p>The next cell will print the prediction of the first instance of the test set</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3622fc036cb2b1f679c3a1935357e712/href">https://medium.com/media/3622fc036cb2b1f679c3a1935357e712/href</a></iframe><pre>Output:<br>Prediction: Approved</pre><p>The next cell will print the anchors for the first instance of the test set</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99c8d9ff17d85668ed3e4d08070dfde6/href">https://medium.com/media/99c8d9ff17d85668ed3e4d08070dfde6/href</a></iframe><pre>Output:<br>Anchor: ApplicantIncome &gt; 0.67 AND Married = 1 AND LoanAmount &lt;= 0.63 AND Property_Area_Urban = 1<br>Precision: 0.99<br>Coverage: 0.01</pre><p>Instead of looking at the complete anchor, you can look at just part of the anchor(the first 2 or 3 clauses)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edb1ad7562de59db6766121b6c8f142d/href">https://medium.com/media/edb1ad7562de59db6766121b6c8f142d/href</a></iframe><pre>Output:<br>Partial anchor: ApplicantIncome &gt; 0.67 AND Married = 1</pre><pre>Partial precision: 0.82</pre><pre>Partial coverage: 0.11</pre><p>Finally, the cell below will output a visualization of anchor explanations</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e67e8722245bacef5acedfa1d36cc65/href">https://medium.com/media/9e67e8722245bacef5acedfa1d36cc65/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*azUakbBf0Dl0H2oENBR9LQ.jpeg" /><figcaption>Cell output</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*ZPsCl7nOxAyU8ALW32zvhw.jpeg" /><figcaption>Cell output</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*VyF9XHOT07D04kfvBd6BfQ.jpeg" /><figcaption>Cell output</figcaption></figure><h4>3. comparison</h4><h4>3.1 Similarities</h4><ol><li>All of the 3 methods: SHAP, LIME, and Anchors, provide local, model-agnostic interpretability methods. Local means it explains individual instances, SHAP can provide global interpretability by summing individual predictions’ absolute SHAP values. Model-agnostic means it is model-independent, i.e, it can interpret any black-box machine learning model.</li><li>The three methods can be applied to different data types( tabular data, text, and images)</li></ol><h4>3.2 Pros and cons</h4><h4>3.2.1 SHAP</h4><h4>Pros</h4><ol><li>“SHAP has solid theoretical foundations in game theory”[1]</li><li>The explanations are contrastive because the prediction is fairly distributed among the feature values[1].</li></ol><h4>Cons</h4><ol><li>SHAP, in general, is computationally expensive unless for tree-based machine learning models like Decision Tree, Random Forest, and XGBoost, for which SHAP has a fast implementation[1]</li><li>One can create misleading explanations( SHAP can hide biases)[15]</li></ol><h4>3.2.2 LIME</h4><h4>Pros</h4><ol><li>“ LIME has fidelity measure gives a good idea of how reliable the interpretable model is in explaining the black box predictions” [2]</li><li>LIME is easy to use and implemented in both Python and R[2]</li></ol><h4>Cons</h4><ol><li>“ One of the big problems is the instability of the explanations” [2]. In an article [14], “the authors showed that the explanations of two very close points varied greatly in a simulated setting, this Instability means that it is difficult to trust the explanations”[2]</li><li>Similar to SHAP, “LIME explanations can be manipulated by the data scientist to hide biases”[2][refer to article 15]</li></ol><h4>3.2.3 Anchors</h4><h4>Pros</h4><ol><li>The algorithm’s output can be understood very easily as it is written in the form of IF-THEN rules.</li><li>It is highly efficient</li></ol><h4>Cons</h4><ol><li>“ The algorithm suffers from highly configurable settings” [3]( this was not covered in the example we provided, you should try to play with these parameters yourself)</li><li>Constructing anchors requires many calls to the ML model, the algorithm runtime then depends on the model’s performance.[3]</li></ol><h4>4. Further reading</h4><p>For those who are interested in reading more in detail in machine learning interpretability, these are some references that I found useful for me:</p><p>Books:</p><ol><li>Interpretable Machine Learning: A Guide for Making Black Box Models Explainable by Christoph Molnar[4]</li><li>Interpretable Machine Learning with Python: Learn to build interpretable high-performance models with hands-on real-world examples by Serg Masís[5]</li><li>Interpretable AI, building explainable machine learning systems by Ajay Thampi[6]</li></ol><p>Papers:</p><ol><li>Explainable AI: A Review of Machine Learning Interpretability Methods[7]</li><li>Machine Learning Interpretability: A Survey on Methods and Metrics[8]</li><li>Explaining explanations: An overview of interpretability of machine learning[9]</li><li>Explainable ai: A review of machine learning interpretability methods[10]</li><li>A unified approach to interpreting model predictions(SHAP original paper)[11]</li><li>“ Why should I trust you?” Explaining the predictions of any classifier(LIME original paper)[12]</li><li>Anchors: High-precision model-agnostic explanations(Anchors original paper)[13]</li></ol><h4>5. Conclusion</h4><p>This article presented 3 interpretability techniques that are helpful to consider when developing machine learning models: SHAP, LIME, and Anchors. We presented a short intuition of each method, with examples of how to apply them. We compared and briefly discussed the similarities between them, the pros and cons of each method, we finalized the article by referring to some useful references and papers for further readings.</p><p>In the next articles, we will explore more recent interpretability techniques, and discuss the theoretical foundations of these methods.</p><p>If you have any comments, suggestions, or anything else, feel free to leave a comment below or reach out through <a href="https://www.linkedin.com/in/salih-eihab/">LinkedIn</a></p><p>Thanks a lot for reading, I hope you found it useful :)</p><h4>6. References and bibliography</h4><p>[1]Molnar, Christoph. Interpretable machine learning. Lulu. com, 2022. sec 9.6,<a href="https://christophm.github.io/interpretable-ml-book/shap.html">https://christophm.github.io/interpretable-ml-book/shap.html</a></p><p>[2]Molnar, Christoph. Interpretable machine learning. Lulu. com, 2022. sec 9.2,<a href="https://christophm.github.io/interpretable-ml-book/lime.html">https://christophm.github.io/interpretable-ml-book/lime.html</a></p><p>[3]Molnar, Christoph. Interpretable machine learning. Lulu. com, 2022. sec 9.4,<a href="https://christophm.github.io/interpretable-ml-book/anchors.html">https://christophm.github.io/interpretable-ml-book/anchors.html</a></p><p>[4]Molnar, Christoph. Interpretable machine learning. Lulu. com, 2022.,<a href="https://christophm.github.io/interpretable-ml-book/">https://christophm.github.io/interpretable-ml-book/</a></p><p>[5]Masis, Serg. Interpretable Machine Learning with Python: Learn to build interpretable high-performance models with hands-on real-world examples. Packt Publishing Ltd, 2021.,<a href="https://learning.oreilly.com/library/view/interpretable-machine-learning/9781800203907/">https://learning.oreilly.com/library/view/interpretable-machine-learning/9781800203907/</a></p><p>[6]Ajay Thampi,Interpretable AI, building explainable machine learning systems by Ajay Thampihttps(2021)://livebook.manning.com/book/interpretable-ai/</p><p>[7]Linardatos, Pantelis, Vasilis Papastefanopoulos, and Sotiris Kotsiantis. “Explainable ai: A review of machine learning interpretability methods.” Entropy 23.1 (2021): 18.,<a href="https://www.mdpi.com/1099-4300/23/1/18">https://www.mdpi.com/1099-4300/23/1/18</a></p><p>[8]Carvalho, Diogo V., Eduardo M. Pereira, and Jaime S. Cardoso. “Machine learning interpretability: A survey on methods and metrics.” Electronics 8.8 (2019): 832.,<a href="https://www.mdpi.com/2079-9292/8/8/832">https://www.mdpi.com/2079-9292/8/8/832</a></p><p>[9]Gilpin, Leilani H., et al. “Explaining explanations: An overview of interpretability of machine learning.” 2018 IEEE 5th International Conference on data science and advanced analytics (DSAA). IEEE, 2018.,<a href="https://ieeexplore.ieee.org/abstract/document/8631448">https://ieeexplore.ieee.org/abstract/document/8631448</a>.</p><p>[10]Linardatos, Pantelis, Vasilis Papastefanopoulos, and Sotiris Kotsiantis. “Explainable ai: A review of machine learning interpretability methods.” Entropy 23.1 (2021): 18.,<a href="https://www.mdpi.com/1099-4300/23/1/18">https://www.mdpi.com/1099-4300/23/1/18</a></p><p>[11]Lundberg, Scott M., and Su-In Lee. “A unified approach to interpreting model predictions.” Advances in neural information processing systems 30 (2017).,<a href="https://proceedings.neurips.cc/paper/2017/hash/8a20a8621978632d76c43dfd28b67767-Abstract.html">https://proceedings.neurips.cc/paper/2017/hash/8a20a8621978632d76c43dfd28b67767-Abstract.html</a></p><p>[12]Ribeiro, Marco Tulio, Sameer Singh, and Carlos Guestrin. “” Why should i trust you?” Explaining the predictions of any classifier.” Proceedings of the 22nd ACM SIGKDD international conference on knowledge discovery and data mining. 2016.,<a href="https://dl.acm.org/doi/abs/10.1145/2939672.2939778">https://dl.acm.org/doi/abs/10.1145/2939672.2939778</a></p><p>[13]Ribeiro, Marco Tulio, Sameer Singh, and Carlos Guestrin. “Anchors: High-precision model-agnostic explanations.” Proceedings of the AAAI conference on artificial intelligence. Vol. 32. №1. 2018.,<a href="https://ojs.aaai.org/index.php/AAAI/article/view/11491">https://ojs.aaai.org/index.php/AAAI/article/view/11491</a></p><p>[14]Alvarez-Melis, David, and Tommi S. Jaakkola. “On the robustness of interpretability methods.” arXiv preprint arXiv:1806.08049 (2018).,<a href="https://arxiv.org/abs/1806.08049">https://arxiv.org/abs/1806.08049</a></p><p>[15]Slack, Dylan, et al. “Fooling lime and shap: Adversarial attacks on post hoc explanation methods.” Proceedings of the AAAI/ACM Conference on AI, Ethics, and Society. 2020.,<a href="https://dl.acm.org/doi/abs/10.1145/3375627.3375830">https://dl.acm.org/doi/abs/10.1145/3375627.3375830</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bf368b47fac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/three-interpretability-methods-to-consider-when-developing-your-machine-learning-model-5bf368b47fac">Three Interpretability Methods to Consider When Developing Your Machine Learning Model</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Machine Learning Interpretability]]></title>
            <link>https://medium.com/data-science/understanding-machine-learning-interpretability-168fd7562a1a?source=rss-2037cbb08e24------2</link>
            <guid isPermaLink="false">https://medium.com/p/168fd7562a1a</guid>
            <category><![CDATA[ai-fairness]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[ml-interpretability]]></category>
            <category><![CDATA[shap]]></category>
            <dc:creator><![CDATA[Salih Salih]]></dc:creator>
            <pubDate>Wed, 26 Jan 2022 15:18:40 GMT</pubDate>
            <atom:updated>2022-01-26T15:18:40.745Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Introduction to machine learning interpretability, </strong>driving forces, taxonomy, example, and notes on interpretability assessment.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VtVnP6tedRVFXXWk" /><figcaption>Photo by <a href="https://unsplash.com/@danielacuevas?utm_source=medium&amp;utm_medium=referral">Daniela Cuevas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Today, machine learning is everywhere, and although machine learning models have shown a great predictive performance and achieved a notable breakthrough in different applications, those machine learning models are getting complex and in turn, their inner working structure and how they arrive at specific outcomes become unclear and hidden even to experts, which presents a serious question: how do we trust those models?</p><p>Moreover, the applications of machine learning in highly regulated and critical domains like criminal justice, financial services, and healthcare require measuring machine learning models not only based on their accuracy but also their interpretability and transparency.</p><p>This article provides an overview of machine learning interpretability, driving forces, taxonomy, an example of interpretability methods, and a note on the importance of assessing the quality of interpretability methods.</p><p>The structure of this article is as follow:</p><p><strong>1. Driving forces</strong></p><p>1.1 AI incidents</p><p>1.2 Public awareness and regulations</p><p><strong>2. Terminology</strong></p><p><strong>3. Example</strong></p><p><strong>4. Assessing interpretability</strong></p><p><strong>5. Summary and conclusion</strong></p><p><strong>6. References</strong></p><h4><strong>1. Driving forces</strong></h4><p><strong>1.1 AI incidents</strong></p><p>Many incidents have been recorded for imperfect AI and machine learning, which brought attention to how we trust those automated algorithms, one of the early serious incidents was on May 7th, 2016, when a Tesla driver was killed while autopilot is active [1]</p><p>In 2018, Uber self-driving car killed a pedestrian (woman) while the vehicle was in autonomous mode,” Uber discovered that its self-driving software decided not to take any actions after the car’s sensors detected the pedestrian “ [2]</p><p>In November 2019, New York’s State Department of Financial Services issued an investigation of Goldman Sachs’ credit card algorithm after showing discrimination against female customers, after a tweet from David Heinemeier Hansson, a Danish entrepreneur, and developer saying: “My wife and I filed joint tax returns, live in a community-property state, and have been married for a long time. Yet Apple’s black box algorithm thinks I deserve 20x the credit limit she does” [3], the same incident forced Amazon to shut down its AI recruiting tool, which was found to discriminate against female applicants [4].</p><p>In criminal justice, a report by <a href="https://www.propublica.org/"><strong>ProPublica </strong></a>has shown<strong> </strong>that COMPAS, which is a case management and decision support tool used by U.S. courts to assess the likelihood of a defendant becoming a recidivist[15], the report has shown that the software is biased against black people, predicting them as twice as riskier than white people[5].</p><p>Healthcare is not an exception to AI malfunction, many incidents have occurred which bring attention to the trustworthiness of AI in the healthcare domain especially.</p><p>For example, new research shows that software guiding care for tens of millions of people from a major US hospital systematically privileges white patients over black patients[6]</p><p>There’re many incidents to mention, you can find more reports here: <a href="https://incidentdatabase.ai/">https://incidentdatabase.ai/</a></p><p><strong>1.2 Public awareness and regulations­­</strong></p><p>AI incidents and the increased use of AI and machine learning in safety-critical and regulated domains have driven the attention towards the importance of machine learning interpretability as an undeniable requirement for trusting machine learning models and their results.</p><p>In Europe, one of the important projects is the XAI program by DARPA, as stated by the program official website, the program aims to create a suite of machine learning techniques that:</p><ul><li>Produce more explainable models, while maintaining a high level of learning performance (prediction accuracy); and</li><li>Enable human users to understand, appropriately trust, and effectively manage the emerging generation of artificially intelligent partners[7].</li></ul><p>Regarding the US, in October 2016, National Science and Technology Council Committee on Technology published a report titled “ preparing for the future of artificial intelligence”, in which one of the recommendations is that “ Federal agencies that make grants to state and local governments in support of the use of AI-based systems to make consequential decisions about individuals should review the terms of grants to ensure that AI-based products or services purchased with Federal grant funds produce results in a sufficiently transparent fashion and are supported by evidence of efficacy and fairness”[16].</p><p>More recent regulations include a proposal by the European union published on April 2021 [9], titled “ laying down harmonised rules on artificial intelligence (Artificial Intelligence Act) and amending certain union legislative acts “ in which different levels of transparency are stressed and enforced as a requirement for the use and deployment of AI systems is the union market.</p><p>Moreover many countries have published their own proposals for AI strategy including France [10], Germany [11], Portugal[12], United Kingdom[13], United States[14], and many other countries in which transparency and interpretability of AI systems is a mandatory requirement for the future of AI.</p><p><strong>2. Terminology</strong></p><p><strong>2.1 Interpretability:</strong></p><p>There’s no agreed-upon definition for interpretability, and it’s necessary to take the context and domain when defining interpretability, but roughly speaking interpretability is the mean by which a user or expert can understand the rationale behind the model’s decisions and outcomes.</p><p>In general, there are two ways to achieve interpretability [8]:</p><p>2.1.1 Developing intrinsically interpretable models, either by using interpretable models by nature such as linear regression, decision trees, or by imposing other constraints on the model.</p><p>2.1.2 developing explanation methods that are can be applied to the developed models.</p><p><strong>2.2 Pre-Model vs. In-Model vs. Post-Model</strong></p><p>Pre-model refers to the interpretability methods that we use before selecting and developing our model, for this, it is closely related to exploratory data analysis.</p><p>In-model interpretability is about models that are intrinsically (by nature) interpretable.</p><p>Post-models (Post Hoc) refer to interpretability techniques that try to enhance model interpretability after the model has been developed.</p><p><strong>2.3 Model-Specific vs. Model-Agnostic</strong></p><p>Model-specific interpretability techniques are limited to specific types of models while model-agnostic can be applied to any model (post hoc).</p><p><strong>2.4 local VS global</strong></p><p>Local interpretability methods refer to methods that explain a single prediction, while global methods refer to methods that explain the overall model</p><p>The below figure shows a diagram summarizing the relevant taxonomy of machine learning interpretability :</p><p>[Apologize: A high-resolution image of the mind map is available on <a href="https://drive.google.com/file/d/1oGgVSxDE9OP7TopEXKju8AvUnod6ezHl/view?usp=sharing">google drive</a> because this image might not be readable(the quality is auto-decreased)]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kmvey4tku1ur-FpsoYnpVw.png" /><figcaption>Image by author</figcaption></figure><p><strong>3. Interpretability methods example</strong></p><p>To better understand machine learning interpretability and its importance, let’s take a very simple, basic example with one of the famous interpretability techniques: SHapley Additive exPlanations or SHAP for short.</p><p>For now, it’s enough to just understand that “ The goal of SHAP is to explain the prediction of an instance x by computing the contribution of each feature to the prediction “[17], so generally speaking SHAP outputs a value for each feature explaining its importance and effect on the predicted output of the instance.</p><p>First, let’s import the necessary libraries (this example is carried out using Google Colab).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13e6c9973354cb6d35771fdf09e764e4/href">https://medium.com/media/13e6c9973354cb6d35771fdf09e764e4/href</a></iframe><p>Next, we install and import SHAP library</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0ab65f104702bb8851c0b64f251b560/href">https://medium.com/media/f0ab65f104702bb8851c0b64f251b560/href</a></iframe><p>For this example, I’ve created a very simple Salary dataset, which would be enough for the purpose of illustration, you can download it <a href="https://drive.google.com/file/d/1yZOle-CJY1AuM0Y10L6KgcJwdSJ3T5Kg/view?usp=sharing">here</a>, and then upload it using the next code cell:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a64c22403d1857abddc9e1f8c1bf9eb/href">https://medium.com/media/9a64c22403d1857abddc9e1f8c1bf9eb/href</a></iframe><p>The next few lines will read the dataset file and add a Gender column to the dataset (this is to make more features so we can better understand the example).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3787433e6736395a475f9da8437c6863/href">https://medium.com/media/3787433e6736395a475f9da8437c6863/href</a></iframe><p>Fitting the model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e05e96b1e8fcc11baa2a12e0c36aed90/href">https://medium.com/media/e05e96b1e8fcc11baa2a12e0c36aed90/href</a></iframe><p>After we’ve built the model, let’s use Shapley values to understand and interpret our model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d747906133427dcd067f4995d21a67a8/href">https://medium.com/media/d747906133427dcd067f4995d21a67a8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*KXV4tkF98BARfW3wScbC3A.jpeg" /><figcaption>Cell output</figcaption></figure><p>From the image above we can see that for example 10, the most contributing feature to predicting the salary is the years of experience, which seems rational that gender should not affect the salary of the person.</p><p>The next code cell will output an overall summary of the features of the dataset, we can notice that the affecting feature here is the YearsExperience.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/225beb512cc21a2d72bad175da8a7486/href">https://medium.com/media/225beb512cc21a2d72bad175da8a7486/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*v4z55s-9s-oqwpYI4gAllw.jpeg" /><figcaption>Cell output</figcaption></figure><h4><strong>Modeling biased dataset</strong></h4><p>To understand how SHAP can help us detect the bias of our model, I’ve created a simple example with a biased, fake dataset, the dataset represents simple loan approval data, consisting of two columns: income and gender.</p><p>In this dataset the loan approval is totally depending on the gender, meaning if the applicant is male, then the loan is approved, otherwise, it’s declined, if we fit the model and measured it based only on its accuracy we can think that the model is very good, but if we tried to interpret the model, we will find that the model is biased against the female applicants, this simple example is what is happening actually in real-world application with many similar recorded incidents.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c5037d2c85a6360ae86087d6ebf8764/href">https://medium.com/media/1c5037d2c85a6360ae86087d6ebf8764/href</a></iframe><p>Fitting the model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cafc7bbcfda03617443a53dfe2f5e09e/href">https://medium.com/media/cafc7bbcfda03617443a53dfe2f5e09e/href</a></iframe><p>Interpreting the model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/439e88370ada4bb0c9c4e870ef668b25/href">https://medium.com/media/439e88370ada4bb0c9c4e870ef668b25/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*cNxQOs9Ra_3SO0agnAKmjg.jpeg" /><figcaption>Cell output</figcaption></figure><p>From the figure above we can notice that for applicant number 10(Female), the gender feature had the most effect on loan approval, in this case, a negative impact(the blue bar) which ended in the loan not being approved.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ccf0ec62ff39ae8646f5af5c8f4134a/href">https://medium.com/media/9ccf0ec62ff39ae8646f5af5c8f4134a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*rhsUygC3SEJH4qQtgWSoqA.jpeg" /><figcaption>Cell output</figcaption></figure><p>This figure in contrast to the above shows that the Gender feature had a positive impact on loan approval for applicant number 11(Male)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3190ccab19c6b94ad50f8f35468248e5/href">https://medium.com/media/3190ccab19c6b94ad50f8f35468248e5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*i9jUWUxc41ZwhjnL-gETiw.jpeg" /><figcaption>Cell output</figcaption></figure><p>This figure summarized the overall feature importance for the loan approval dataset from which we can conclude that even our model is well-performing when measured in terms of accuracy, it’s actually very bad when it comes to its fairness, having a serious bias against female applicants, while the income feature has no effect in the final decision of loan approval process, which as stated is what happens in real-world problems.</p><h4><strong>4. Methods for evaluating interpretability techniques</strong></h4><p>Many research articles have been published about building methods for explaining and interpreting black-box machine learning models, others on developing intrinsically interpretable models, but a few research has been done assessing and evaluating the quality of interpretability methods.</p><p>For the needs of this article, we will stick to note that it’s important to address and conduct research on how we evaluate and assess the quality of interpretability methods, some of the frameworks and axioms for evaluating interpretability methods are presented by Diogo V. Carvalho et al in their literature review paper[8]. (<strong>I highly recommend reading this paper</strong>).</p><h4><strong>5. Summary and conclusion</strong></h4><p>This article presented an introductory overview of machine learning interpretability, driving forces, public work and regulations on the use and development of machine learning, a summary of interpretability taxonomy, an example using Shapley values which demonstrated the importance of interpretability methods, and finally a note on the importance of assessing and evaluating interpretability techniques.</p><p>One thing to be concluded here: machine learning interpretability is a MUST for the future of machine learning, and it is as important as developing high-performance machine learning models, which is required to have attention to from data scientists, machine learning researchers, and others who work in the field of machine learning- to consider interpretability and transparency questions when developing their models.</p><p>In the next articles, we will go forward towards understanding recent interpretability methods which will be helpful to consider while developing your model.</p><p>Thanks for reading, if you have any questions, suggestions, and other queries, feel free to reach out through <a href="https://www.linkedin.com/in/salih-eihab/">LinkedIn</a> or E-mail: salih.eihab1@gmail.com.</p><h4><strong>6. References:</strong></h4><p>[1] The Guardian, Tesla driver dies in first fatal crash while using autopilot mode(2016),<a href="https://www.theguardian.com/technology/2016/jun/30/tesla-autopilot-death-self-driving-car-elon-musk">https://www.theguardian.com/technology/2016/jun/30/tesla-autopilot-death-self-driving-car-elon-musk</a></p><p>[2] Daisuke Wakabayashi, Self-Driving Uber Car Kills Pedestrian in Arizona, Where Robots Roam(2018), <a href="https://www.nytimes.com/2018/03/19/technology/uber-driverless-fatality.html">https://www.nytimes.com/2018/03/19/technology/uber-driverless-fatality.html</a></p><p>[3] Taylor Telford, Apple Card algorithm sparks gender bias allegations against Goldman Sachs(2019), <a href="https://www.washingtonpost.com/business/2019/11/11/apple-card-algorithm-sparks-gender-bias-allegations-against-goldman-sachs/">https://www.washingtonpost.com/business/2019/11/11/apple-card-algorithm-sparks-gender-bias-allegations-against-goldman-sachs/</a></p><p>[4] Anonymous. (2016) Incident Number 37. in McGregor, S. (ed.) Artificial Intelligence Incident Database. Partnership on AI. Retrieved on January 25, 2022 from incidentdatabase.ai/cite/37.</p><p>[5] Anonymous. (2016) Incident Number 40. in McGregor, S. (ed.) Artificial Intelligence Incident Database. Partnership on AI. Retrieved on January 25, 2022 from incidentdatabase.ai/cite/40.</p><p>[6] Lutz, Roman. (2019) Incident Number 124. in McGregor, S. (ed.) Artificial Intelligence Incident Database. Partnership on AI. Retrieved on January 25, 2022 from incidentdatabase.ai/cite/124.</p><p>[7] Dr. Matt Turek, Explainable Artificial Intelligence (XAI), <a href="https://www.darpa.mil/program/explainable-artificial-intelligence">https://www.darpa.mil/program/explainable-artificial-intelligence</a></p><p>[8] Carvalho, Diogo V., Eduardo M. Pereira, and Jaime S. Cardoso. “Machine Learning Interpretability: A Survey on Methods and Metrics” Electronics 8(2019) no. 8: 832. <a href="https://doi.org/10.3390/electronics8080832">https://doi.org/10.3390/electronics8080832</a></p><p>[9] EUROPEAN COMMISSION, REGULATION OF THE EUROPEAN PARLIAMENT AND OF THE COUNCIL LAYING DOWN HARMONISED RULES ON ARTIFICIAL INTELLIGENCE (ARTIFICIAL INTELLIGENCE ACT) AND AMENDING CERTAIN UNION LEGISLATIVE ACTS(2021), <a href="https://eur-lex.europa.eu/legal-content/EN/TXT/?qid=1623335154975&amp;uri=CELEX%3A52021PC0206">https://eur-lex.europa.eu/legal-content/EN/TXT/?qid=1623335154975&amp;uri=CELEX%3A52021PC0206</a></p><p>[10] France AI Strategy Report(2018), <a href="https://knowledge4policy.ec.europa.eu/ai-watch/france-ai-strategy-report_en">https://knowledge4policy.ec.europa.eu/ai-watch/france-ai-strategy-report_en</a></p><p>[11] Germany AI Strategy Report(2018), <a href="https://knowledge4policy.ec.europa.eu/ai-watch/germany-ai-strategy-report_en">https://knowledge4policy.ec.europa.eu/ai-watch/germany-ai-strategy-report_en</a></p><p>[12] Portugal AI Strategy Report(2019), <a href="https://knowledge4policy.ec.europa.eu/ai-watch/portugal-ai-strategy-report_en">https://knowledge4policy.ec.europa.eu/ai-watch/portugal-ai-strategy-report_en</a></p><p>[13] United Kingdom AI Strategy Report(2018), <a href="https://knowledge4policy.ec.europa.eu/ai-watch/united-kingdom-ai-strategy-report_en">https://knowledge4policy.ec.europa.eu/ai-watch/united-kingdom-ai-strategy-report_en</a></p><p>[14] National Security Commission on Artificial Intelligence(2021), <a href="https://www.nscai.gov/wp-content/uploads/2021/03/Full-Report-Digital-1.pdf">https://www.nscai.gov/wp-content/uploads/2021/03/Full-Report-Digital-1.pdf</a></p><p>[15] COMPAS (software), <a href="https://en.wikipedia.org/wiki/COMPAS_(software)">https://en.wikipedia.org/wiki/COMPAS_(software)</a></p><p>[16] National Science and Technology Council Committee on Technology, PREPARING FOR THE FUTURE OF ARTIFICIAL INTELLIGENCE(2016), <a href="https://obamawhitehouse.archives.gov/sites/default/files/whitehouse_files/microsites/ostp/NSTC/preparing_for_the_future_of_ai.pdf">https://obamawhitehouse.archives.gov/sites/default/files/whitehouse_files/microsites/ostp/NSTC/preparing_for_the_future_of_ai.pdf</a></p><p>[17] Christoph Molnar, Interpretable Machine Learning, A Guide for Making Black Box Models Explainable(2022), <a href="https://christophm.github.io/interpretable-ml-book/">https://christophm.github.io/interpretable-ml-book/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=168fd7562a1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/understanding-machine-learning-interpretability-168fd7562a1a">Understanding Machine Learning Interpretability</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>