<?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 Murali Kashaboina on Medium]]></title>
        <description><![CDATA[Stories by Murali Kashaboina on Medium]]></description>
        <link>https://medium.com/@murali-kashaboina?source=rss-2d02cbc7d153------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fnrlkootg9_M6D05x511lw.jpeg</url>
            <title>Stories by Murali Kashaboina on Medium</title>
            <link>https://medium.com/@murali-kashaboina?source=rss-2d02cbc7d153------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:50:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@murali-kashaboina/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[A Handy Compendium of Common Terms Used In The Context Of LLMs — Part 1]]></title>
            <link>https://murali-kashaboina.medium.com/a-handy-compendium-of-common-terms-used-in-the-context-of-llms-part-1-d9f8730a092a?source=rss-2d02cbc7d153------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9f8730a092a</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[llm-basic-concepts]]></category>
            <category><![CDATA[compendium-on-llms]]></category>
            <category><![CDATA[generative-ai-concepts]]></category>
            <category><![CDATA[llm-glossary-of-terms]]></category>
            <dc:creator><![CDATA[Murali Kashaboina]]></dc:creator>
            <pubDate>Sun, 21 Apr 2024 01:59:36 GMT</pubDate>
            <atom:updated>2024-04-21T01:59:36.874Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Handy Compendium of Common Terms Used In The Context Of LLMs — Part 1</h3><p>Glossary of LLM terms for handy reference…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mc04VmSqz1b6pdmx" /><figcaption>Photo by <a href="https://unsplash.com/@amadorloureiro?utm_source=medium&amp;utm_medium=referral">Amador Loureiro</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’ve put together a handy compendium of basic terms commonly used in the context of large language models (LLM) that I thought could be helpful for anyone interested. Initially, I created it for my own reference, but then I realized that it could benefit many others.</p><p>This Part 1 includes Series 1, 2, and 3 of frequently used terms in the context of LLMs. I’ll be releasing subsequent parts as I compile more information. While these series mainly focus on LLM terms, I’ve also created a separate compendium for multi-modal Gen-AI models that I’m yet to format. I’ll publish it under a different title later.</p><p>Without further ado, here they are. I must mention that the descriptions are kept intentionally simple and concise, in plain English, so that everyone can benefit from the concepts, minimizing the technical explanations.</p><h4>Series 1</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qin5xesbSS23xh3GoSz9Xg.png" /><figcaption>Series 1 of the Glossary of LLM Terms — Image By Author</figcaption></figure><h4>Series 2</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Gptcwi8TS-9nU4MmNF_6g.png" /><figcaption>Series 2 of the Glossary of LLM Terms — Image By Author</figcaption></figure><h4>Series 3</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*okB1DzU11zdQMaiCIeAjIA.png" /><figcaption>Series 3 of the Glossary of LLM Terms — Image By Author</figcaption></figure><p>I hope you found part 1 of the compendium helpful. Stay tuned for part 2 which I will publish shortly! Please leave comments accordingly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9f8730a092a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Emerging Role Of A Chief AI Officer — A Practical Perspective]]></title>
            <link>https://medium.datadriveninvestor.com/the-emerging-role-of-a-chief-ai-officer-a-practical-perspective-68d724a0c2fe?source=rss-2d02cbc7d153------2</link>
            <guid isPermaLink="false">https://medium.com/p/68d724a0c2fe</guid>
            <category><![CDATA[ai-transformation]]></category>
            <category><![CDATA[gen-ai-for-business]]></category>
            <category><![CDATA[chief-ai-officer]]></category>
            <category><![CDATA[disruptive-technologies]]></category>
            <category><![CDATA[gen-ai-revolution]]></category>
            <dc:creator><![CDATA[Murali Kashaboina]]></dc:creator>
            <pubDate>Thu, 11 Apr 2024 00:24:54 GMT</pubDate>
            <atom:updated>2024-04-11T09:59:33.123Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Emerging Role Of A Chief AI Officer — A Practical Perspective</h3><p>A dedicated and accountable executive to drive and deliver on AI promises…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jYYlOndi110qvRzy" /><figcaption>Photo by <a href="https://unsplash.com/@omilaev?utm_source=medium&amp;utm_medium=referral">Igor Omilaev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Have you ever wondered about the emerging role of a Chief AI Officer (CAIO) and what it takes to succeed in this position? Well, let’s dive in! In this practical perspective, we’ll explore the crucial needs of a CAIO and how a CAIO can help organizations harness the power of Artificial Intelligence (AI) for success.</p><p>One of my colleagues recently posed a similar question: is it necessary for organizations to hire an executive-level CAIO to oversee the company’s AI strategies and initiatives? Unfortunately, there is no simple yes or no answer to this question, as various business drivers and circumstances vary from one organization to another. Furthermore, many organizations already have executive positions, such as Chief Information Officer (CIO), Chief Technology Officer (CTO), and Chief Data Officer (CDO), which can add to the confusion surrounding the role of a CAIO.</p><p>The need for a CAIO is becoming increasingly evident for several key business reasons. In this write-up, I will examine AI’s impact on the business landscape and its socio-economic and socio-technological implications. I will also discuss the latest breakthroughs and developments in AI, particularly in Generative AI (Gen-AI), and the imperative for organizations to pursue and adopt AI-driven business models, which highlights the necessity for the emergence of a new CAIO role.</p><h4>The Role of CAIO</h4><p>The CAIO role is not just another executive position. It is a unique and pivotal role rapidly gaining importance in organizations with significant AI investments. A CAIO’s responsibilities are diverse and extensive. They encompass overseeing the development, implementation, and management of AI initiatives across the organization. Additionally, they collaborate with external entities such as AI technology vendors, government regulatory agencies, and other suppliers. A CAIO formulates the AI strategy, ensuring the practice of ethical and responsible AI, managing data privacy and security, and fostering innovation through AI applications.</p><p>However, the exact role and responsibilities of a CAIO can vary depending on the organization’s size, industry, and AI maturity. The questions and confusion around the necessity for a separate CAIO role stem from the fact that, typically, every organization has incumbent roles such as CIO, CTO, or CDO, and most organizations integrate AI leadership into one of these existing roles. Such folding of responsibilities into existing executive roles may work in the case of small-to-medium-scale investments but may not be effective in all cases for the reasons I explain in the following sections.</p><h4>Gen-AI’s Impact On Business And Economy</h4><p>To understand the crucial role of a CAIO, especially in the case of significant AI investments spanning multiple years, it is essential to comprehend AI’s impacts on business and the economy.</p><p>The International Monetary Fund’s (IMF) report from January 2024 predicts that AI will profoundly impact the global economy, with some experts comparing it to a new industrial revolution. The report highlights that nearly 40% of jobs worldwide are at risk of being transformed by AI. Meanwhile, a study by the University of Pennsylvania in August 2023 examined the effect of Gen-AI on the US labor market. The research revealed that around 20% of the US workforce might experience at least 50% of their responsibilities affected, while 80% could see at least a 10% impact due to the emergence of Gen-AI capabilities.</p><p>A similar report published in August 2023 by McKinsey &amp; Company on the future of generative AI opined that the precise impact of Gen-AI will depend on various factors, such as the importance of different business functions and the scale of an industry’s revenue. The report also highlighted that nearly all industries will benefit significantly from implementing the technology in their marketing and sales departments.</p><p>Likewise, a recent report titled “From Potential To Profit With GenAI,” published by the Boston Consulting Group (BCG), highlighted the immense potential of Gen-AI in transforming businesses. The report emphasized that the time to act is now because the genie is out of the bottle. BCG suggested deploying Gen-AI solutions in everyday tasks could achieve a 10% to 20% increase in productivity. Furthermore, the report suggested that reshaping critical functions with Gen-AI could result in a 30% to 50% improvement in efficiencies, and inventing and incorporating new Gen-AI-driven business models could result in significant long-term competitive advantage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*ZJLig6JAdvi3URcMvqyh4w.jpeg" /><figcaption>Source: Gartner, Inc. (<a href="https://www.gartner.com/en/articles/30-emerging-technologies-that-will-guide-your-business-decisions">https://www.gartner.com/en/articles/30-emerging-technologies-that-will-guide-your-business-decisions</a>)</figcaption></figure><p>In their latest report, Gartner highlighted the top 30 emerging technologies in 2024 that will guide and impact business decisions. As shown in the infographic above, Gartner placed Gen-AI and related technologies at the center stage as the top-most technologies organizations must prioritize immediately by developing prevalent and impactful use cases that can enhance their competitive edge and boost productivity gains.</p><p>The above reports clearly show compelling reasons for organizations to strategize and adopt Gen-AI to stay ahead of the curve as soon as possible. Reports also suggest that early adopters who develop a strategic understanding of Gen-AI will be better positioned to leverage its capabilities and gain a competitive advantage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mZCo4C4mcdQGap3TRr2Mmw.png" /><figcaption>Various Forces On A Business Corporate— Image by Author</figcaption></figure><p>Another way to understand Gen-AI’s transformative impact is to examine how market forces triggered by Gen-AI technological advancements exert fierce pressure on the market economy and business outlook, compelling organizations to transform their businesses to sustain and survive in the market.</p><p>The diagram above shows how various forces, including transformative technological, social, and societal change, evolving market, global economic, and competitive business forces, continuously affect an organization’s business outlook. These forces are not independent but are symbiotically interdependent. Triggering one can trigger several others, collectively applying intense pressure on a business to compete, adapt its business model if necessary, and sustain its viability continuously.</p><p>So, how might Gen-AI change an organization’s business landscape? Well, as described in several reports, Gen-AI is a business-disruptive technology trend. Its tech ecosystem has other associated technologies evolving, which could have a force multiplier effect in terms of technological advancement. This could trigger ripple effects on other dimensions of the market.</p><p>Competitors might be the first to leverage this technology to develop better products and services. New entrants could also make inroads into innovation, establishing brand-new value chains and attracting consumers by offering novel products, services, and user experiences. With such innovation possibilities, new substitute products, perhaps unheard of before, could be introduced in the market, diminishing the value of the incumbent products. This could lead to legacy product suppliers potentially becoming competitors offering new substitute products to new and incumbent consumer segments. These changes could impact consumers and their choices, significantly shifting the demand and supply equation and altering the consumer market segments. The organization’s existing consumers will start expecting similar products and services matching what they are seeing from the other competitors.</p><p>As new products and services attain traction in the market, new entrants and incumbent competitors would create new jobs to build and sustain the new promising value chains, as pointed out by several reports. Such profound changes in the entire value chain spectrum would impact society’s socio-economic, socio-technological, and even socio-cultural fabric, affecting the way of general life. Several reports have pointed out these changes. Because of the globalization of economies, the change that started in local markets can trigger global effects regarding the new supply chain demands, global resources, and commodities, significantly altering the global macroeconomic parameters.</p><p>With all such sudden changes in the business landscape, an organization could abruptly find itself in a precarious situation with unexpected competition for which it was unprepared. The bottom line is that even if an organization isn’t ready yet to invest in Gen-AI initiatives, it should start exploring Gen-AI capabilities and the types of problems Gen-AI can solve for the company. Such exploration can help the organization develop a strategy now that can position it to act swiftly when market dynamics change.</p><h4>Incumbent Roles Versus CAIO Role</h4><p>As mentioned earlier, adopting Gen-AI technologies can have a cascading impact on an organization’s business outlook. While it promises continued business sustenance and substantial competitive advantage, it is undoubtedly disruptive and risky for businesses. However, to reap the benefits of Gen-AI, organizations must display an unwavering commitment, meticulous change management within and beyond their walls, explicable accountability, and entrepreneurial perseverance, even in the face of unexpected headwinds. Large investments in Gen-AI require immeasurably more commitments, and those willing to take the plunge will have much greater value at stake.</p><p>As projected by several reports, companies that seize AI opportunities, take early risks, and transform the opportunities into business profitability, viability, and survivability will emerge as winners in the long run. However, today, most organizations typically weigh the risks against the rewards, placing greater emphasis on risk mitigation to minimize disruption to business operations and continuity because making changes to incumbent business processes and systems entails ingrained risks. As a result, executives in the current accountable roles, such as CIO, CTO, and CDO, tend to prioritize and strategize opportunities with minimal business risks but with incremental business value. They are very much risk averse.</p><p>It is important to note that Gen-AI opportunities inherently come with risks, including data security risks, risks associated with ethics, and equity, besides operational risks. While it is imperative to be risk-aware, risk-averse strategies may become counter-intuitive when the goal is to reap maximum benefits. Instead, strategies must be intrinsically risk-taking, and organizations must aim to maximize the rewards expected with Gen-AI opportunities while calculating and controlling the associated risks. Large-scale adoption of Gen-AI is more like a quantum leap in business transformation and sustenance, so attempting to reap the maximum rewards and benefits might as well outweigh the risks.</p><p>Besides, unprecedented research and development are underway in Gen-AI disciplines, such as natural language processing, computer vision, and multi-modality-driven AI models that simultaneously consume text, images, audio, and video to predict and generate content and intelligence of tangible business value. Driving game-changing adoption of such technologies to strategically and surgically reshape the business outlook requires a specialized, AI-savvy, and visionary leader who can quickly latch onto business opportunities, tap the right AI capabilities for business scenarios, and map AI integrations to chart the organization’s transformative AI journey swiftly. As suggested by several reports, the journey should start now. There is no lead time for the rest of the executive leaders to master the required skills and play catchup while still focusing on their core “business-as-usual” responsibilities because while the transformative journey may span multiple years, depending on the extent of AI investments, investments in sustaining existing business will continue.</p><p>In addition, enterprise-focused, cross-portfolio, and cross-disciplinary design thinking becomes crucial to execute AI-fueled transformation. Without such coherent oversight and single-aperture vision, an organization’s Gen-AI agenda may fall on its own weight, where opportunities do not crystallize, and fragmented AI solutions proliferate into disjointed silos.</p><p>The point to note here is that as organizations embark on a transformative AI journey, a CAIO becomes a strategist and a captain steering the ship. Beyond technical know-how, CAIOs champion ethical AI development, addressing concerns about bias and data privacy. They also manage risks associated with AI projects, ensuring responsible implementation. Besides, they prioritize investments, ensuring resources go towards impactful projects and bridge the gap between tech teams and business leaders.</p><p>When an organization successfully transforms its business model and its transformed business operations become normal over time, the CAIO role may no longer be needed. The CAIO’s responsibilities could be taken over by either the CIO or the CTO, because future initiatives will follow standard procedures for managing change.</p><h4>CAIO Qualifications</h4><p>The CAIO role is still emerging, and no clear set of established qualifications exists. However, at the moment, business-oriented and delivery-focused technology executives with solid familiarity with Gen-AI, machine learning, data science, engineering, and hands-on experience leading business transformative initiatives could qualify for such CAIO roles.</p><h4>Key Takeaways</h4><p>Here are my key takeaways about the CAIO role vis-a-vis incumbent executive roles:</p><ol><li>The seismic rise of Gen-AI capabilities is disrupting domestic and global economies and having a groundbreaking impact on how organizations conduct their business. Organizations caught unaware or that do not get their act together fast could suddenly find themselves in a precarious situation of losing business to their competitors and new entrants.</li><li>Significant multi-year investments in Gen-AI require immeasurably more commitment, substantial risk mitigation, extensive collaboration, and meticulous change management both within and outside the organization. Traditional risk-averse strategies will be counter-intuitive. Having a CAIO as a dedicated, accountable, AI-savvy executive to oversee the multi-year transformative AI agenda would help crystallize the opportunities and deliver on the anticipated return on investment. The CAIO, in this scenario, should also report directly to the CEO to ensure continuous executive focus and oversee the multi-year transformative journey, overcoming any business headwinds en route.</li><li>The incumbent executive leaders have no lead time to master the required skills and play catchup since the transformative AI journey should start now. Instead, the incumbent leaders should support the CAIO on the significant AI investments while focusing on sustaining the current business and strategizing risk mitigation initiatives. Of course, fully CAIO-qualified incumbent leaders can move into CAIO roles and drive the AI agenda.</li><li>Organizations should be meticulous in designing the Gen-AI roadmap and strategies. Enterprise-focused, cross-portfolio, and cross-disciplinary thought leadership becomes mandatory to orchestrate AI-driven solutions seamlessly and prevent siloed proliferation.</li><li>It is a no-brainer for an organization aspiring to chart a game-changing Gen-AI-fueled business transformative journey to recruit a dedicated AI-savvy visionary CAIO as an accountable executive. Once the transformation is complete, the CAIO’s responsibilities can be integrated into other IT leadership roles. From then on, future initiatives will follow normal change management processes.</li></ol><p>I hope you found this article insightful and informative. Please leave a note in the comments section.</p><h3>References</h3><ul><li><a href="https://www.imf.org/en/Publications/Staff-Discussion-Notes/Issues/2024/01/14/Gen-AI-Artificial-Intelligence-and-the-Future-of-Work-542379">Gen-AI: Artificial Intelligence and the Future of Work</a></li><li><a href="https://arxiv.org/abs/2303.10130">GPTs are GPTs: An Early Look at the Labor Market Impact Potential of Large Language Models</a></li><li><a href="https://www.mckinsey.com/featured-insights/mckinsey-explainers/whats-the-future-of-generative-ai-an-early-view-in-15-charts">What&#39;s the future of generative AI? An early view in 15 charts</a></li><li><a href="https://www.bcg.com/publications/2024/from-potential-to-profit-with-genai">BCG AI Radar: From Potential to Profit with GenAI</a></li></ul><p><a href="https://www.gartner.com/en/articles/30-emerging-technologies-that-will-guide-your-business-decisions">https://www.gartner.com/en/articles/30-emerging-technologies-that-will-guide-your-business-decisions</a></p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Featured Article:</p><ul><li><a href="https://medium.datadriveninvestor.com/accelerating-success-through-the-singapore-fund-asset-management-platform-cbd393bf0e6a">Introducing Singapore’s Fund Platform</a></li><li><a href="https://www.datadriveninvestor.com/2024/03/26/singapore-unveiling-a-tapestry-of-possibilities-and-global-connections/">Singapore: Unveiling a Tapestry of Possibilities and Global Connections | DataDrivenInvestor</a></li></ul><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68d724a0c2fe" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/the-emerging-role-of-a-chief-ai-officer-a-practical-perspective-68d724a0c2fe">The Emerging Role Of A Chief AI Officer — A Practical Perspective</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Self-Organizing Map To Bolster Retrieval-Augmented Generation In Large Language Models]]></title>
            <link>https://medium.com/data-science/using-self-organizing-map-to-bolster-retrieval-augmented-generation-in-large-language-models-5d739ce21e9c?source=rss-2d02cbc7d153------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d739ce21e9c</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[self-organizing-map]]></category>
            <category><![CDATA[deep-dives]]></category>
            <dc:creator><![CDATA[Murali Kashaboina]]></dc:creator>
            <pubDate>Sat, 16 Mar 2024 13:30:55 GMT</pubDate>
            <atom:updated>2024-03-16T13:30:55.694Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>SOM is proposed to bolster efficient retrieval of LLM context for RAG…</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EZUnAZzt3iL76M3T" /><figcaption>Photo by <a href="https://unsplash.com/@werclive?utm_source=medium&amp;utm_medium=referral">Werclive 👹</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Background</h4><p>Large volumes of data are used to train Large Language Models (LLM) containing millions and billions of model parameters with the goal of text generation, such as text completion, text summarization, language translations, and answering questions. While LLMs develop a knowledge base per se from the training data sources, there is always a cut-off training date post which LLM will not know any newly generated data. For example, the cut-off date for training OpenAI’s GPT-3.5-turbo-instruct LLM is September 2021 (Ref: <a href="https://platform.openai.com/docs/models/gpt-3-5-turbo">https://platform.openai.com/docs/models/gpt-3-5-turbo</a>), and as such, GPT-3.5-turbo-instruct LLM may not answer questions on 2022, 2023, or 2024 events accurately. Such data not part of the LLM’s original training data is called external data. Retrieval-Augmented Generation (RAG) is a technique meant to help in such cases by retrieving appropriate information contextual to the input prompt from authorized external sources and augmenting input so that LLM can generate accurate and relevant responses. Effectively, RAG forms the gateway between the LLM and the external data. Such augmentation eliminates the need to retrain or further fine-tune the LLM model.</p><h4>LLM’s Typical M.O.</h4><p>LLMs are auto-regressive, generating a new token based on the input prompt tokenized into a sequence of tokens. The generation of the next best token is probability-based and can be expressed as follows:</p><pre>P( Yn ∣ X0, X1, ... Xn-1, θ )</pre><p>Essentially, the probability of the newly generated nth token, Yn, is conditioned on the probability of the occurrence of the sequence of n-1 previous tokens X and the learned model parameters θ. It should be noted here that the tokenized input sequence X plays a crucial role in generating the next token. In addition, self-attention mechanisms complement effective auto-regression, where each input token in the sequence computes its representation by attending to and weighing the importance of other tokens in the sequence. Such intricate relationships and dependencies among the tokens in the sequence also enable the LLM to decipher the most probable next-best token that ‘gels well’ with the tokens in the input sequence. The LLM appends the new token to the previous tokens to form a new input sequence and repeats the auto-regressive process until a completion condition is met, such as reaching the maximum token count.</p><p>Such a self-attention-driven auto-regression implies that the LLM relies predominantly on the input sequence to generate the next best token. As long as the input sequence helps determine the next-best token through self-attention, the LLM continues in a ‘virtuous’ loop, generating coherent, comprehensible, and relevant outputs. On the contrary, the LLM will start relying on the model parameters if the prompt inputs do not help determine the next best token. In such a case, the model may succeed in generating the next best token if the model has been trained to contain sufficient ‘knowledge’ contextual to the input prompt. Conversely, the model may go into a ‘vicious’ loop, generating non-coherent, incomprehensible, and possibly irrelevant outputs if the prompt inputs pertain to ‘external data’ that the LLM has never been trained on.</p><p>Various techniques tackle this issue. Prompt engineering is one of them, where the goal is to address the ‘missing context’ by adjusting the prompt to enhance the context so that the LLM can generate relevant output. RAG is another technique where the goal is to specifically address the ‘missing context due to external data’ by retrieving the most appropriate information contextual to the input prompt from external data sources in an automated manner and augmenting the prompt.</p><h4>RAG’s Challenge</h4><p>The primary responsibility of RAG is to search and retrieve data that is contextually related to the input prompt from external data sources such as informational databases, APIs, and other document repositories like Wikipedia. A simple keyword search would not cut it. Instead, RAG requires a semantic search. To facilitate semantic search, the textual information retrieved from external sources is transformed into numerical representations or vectors, commonly called text embeddings, and stored in vector databases. There are various models or algorithms for creating these embeddings from text. The prompt is first transformed into its vector representation to search and retrieve closest matching external data vectors. Vector similarities (or vector distances) are then computed between the prompt vector and the previously stored external data vectors. The most similar or nearest vectors are sorted and filtered using a threshold, and their corresponding textual information is retrieved to augment the prompt’s context. The following conceptual diagram captures the typical interactions between different components for enabling RAG:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EM3EhJPRc81aSGp7F9N_Bw.png" /><figcaption>Conceptual View of Primary System Component Interactions for Enabling RAG — Image by Author</figcaption></figure><p>RAG’s challenge is that conducting a vector-driven semantic search is non-trivial and requires significant computational resources because it involves calculating vector similarities or distances against potentially a vast number of vectors within the database. Computing similarity or distance measures for each stored vector from a vast vector database for every input prompt will become infeasible. Besides, the lower the semantic match quality, the lower the LLM’s generative output quality. Therefore, finding a way to conduct the semantic search efficiently becomes crucial.</p><h4>Solution</h4><p>Several algorithmic solutions are employed to conduct efficient semantic searches. The typical approach of such algorithms is to group or cluster external data vectors as nearest neighbors and index them by mapping to such clusters. Such indexing is offered as a built-in capability by most vector databases. The matched clusters are first evaluated for the input prompt vector during semantic search. For each evaluated cluster, indexed vectors are selected. Similarities between the input prompt vector and the selected vectors are then computed. The expectation here is that finding the ‘nearest neighbors’ as an intermediate step reduces the number of similarity computations significantly. Finally, the textual information is retrieved corresponding to the most similar or nearest vectors filtered through thresholding. Algorithms such as k-Nearest Neighbors, Ball-of-Radius-R, Locality-Sensitive-Hashing, DBSCAN-Clustering, Tree-Like hierarchies, and Graph-Like hierarchies are typically implemented by vector databases to facilitate semantic searches.</p><p>There is no one-size-fits-all solution because different families of algorithms have different trade-offs in terms of memory efficiency, compute efficiency, latency, accuracy, vector dimensionality, dataset sizing, etc. For example, clustering methods enable speed by narrowing the vector space for semantic search, while tree-like or graph-like methods offer improved accuracy for low-dimensional vector data.</p><h4>Self-Organizing Maps</h4><p>A Self-Organizing Map (SOM) is a neural network-based dimensionality reduction algorithm developed by Teuvo Kohonen in the 1980s. It is typically used to reduce high-dimensional feature vectors to low-dimensional (typically two-dimensional) feature vectors. The core idea behind SOM is to represent high-dimensional data vectors as specific nodes in a low-dimensional space while retaining the vectors’ topology in the original space. The number of nodes in the low-dimensional space (SOM Nodes) is fixed (hyper-parameter). The exact locations of SOM nodes are evaluated through multiple training epochs. The goal of the iterative training is to adjust the locations of the SOM nodes in the low-dimensional space so that they get mapped to the nearest neighboring vectors in the high-dimensional feature space. In other words, the goal is to map nearest-neighbor vectors in the high-dimensional space to SOM nodes that are also nearest neighbors in the low-dimensional space.</p><h4>SOM for RAG</h4><p>In this write-up, I wanted to share notes and findings from my experiments with SOM as a possible algorithm to propel RAG’s semantic search. There are three crucial reasons SOM could be ideal compared to other algorithms:</p><ol><li>Vectors’ high dimensionality can become a bottleneck for most other algorithms, such as Trees and Graphs—the so-called curse of dimensionality. On the contrary, SOM is built for dimensionality reduction, and therefore, it can be effectively applied in both high-dimensional and low-dimensional scenarios.</li><li>SOM is less sensitive to random variations that may trickle into the original high-dimensional vector space, resulting in noise. Other algorithms can be sensitive to such noise, impacting the way they cluster or group high-dimensional vectors as nearest neighbors. Since SOM employs intermediate SOM nodes in a lower-dimensional vector space which get evaluated as local averages of the mapped vectors from the higher-dimensional space, it effectively reduces noise.</li><li>The large size of the external dataset may constrain other algorithms to create semantic vector spaces, which can impact semantic matching&#39;s latency and accuracy. On the other hand, SOM can tackle massive datasets because the number of SOM nodes in the low-dimensional space can be fine-tuned through a hyper-parameter proportional to the underlying dataset size. While training a SOM using a large dataset may take longer, query time mapping remains quicker once training is done.</li></ol><p>I demonstrate a simple example of using SOM to conduct RAG’s semantic search to augment the context for question/answer using OpenAI’s GPT-3.5-turbo-instruct LLM. The primary reason for using OpenAI’s GPT-3.5-turbo-instruct LLM is because the cut-off date for training OpenAI’s GPT-3.5-turbo-instruct LLM is September 2021 (Ref: <a href="https://platform.openai.com/docs/models/gpt-3-5-turbo">https://platform.openai.com/docs/models/gpt-3-5-turbo</a>), and as such, GPT-3.5-turbo-instruct LLM may not answer questions on 2022, 2023, or 2024 events accurately. Therefore, information about 2022, 2023, 0r 2024 events can become ‘external data’ for OpenAI’s GPT-3.5-turbo-instruct LLM. I used Wikipedia API as the source for such ‘external data’ to fetch events’ information. The following are the steps I used to develop and train the example, along with the sample code.</p><h4>Step 1: PyTorch-Based Kohonen’s SOM implementation</h4><p>I utilized PyTorch Tensors to represent vectors and implemented Kohonen’s SOM using PyTorch. This algorithm uses a two-dimensional lattice whose size becomes a hyper-parameter. The algorithm’s mathematical aspects were derived from a well-crafted perspective with lucid explanations mentioned in the following article:</p><p><a href="http://www.ai-junkie.com/ann/som/som1.html">SOM tutorial part 1</a></p><p>The following code snippet shows the Python class for Kohonen’s SOM. The complete code is available at <a href="https://github.com/kbmurali/som-driven-qa-rag/blob/main/kohonen_som.py">this GitHub location</a>. It’s worth noting that this implementation is standalone, so it can be used outside of RAG example.</p><pre>class KohonenSOM():<br>    &quot;&quot;&quot;<br>    The code is developed based on the following article:<br>    http://www.ai-junkie.com/ann/som/som1.html<br>    <br>    The vector and matrix operations are developed using PyTorch Tensors.<br>    &quot;&quot;&quot;<br>    def __init__( ... )<br>    ...<br>    def find_topk_best_matching_units( self, data_points : torch.Tensor, topk : int = 1 ) -&gt; List[ List[ int ] ] :<br>        if len( data_points.size() ) == 1:<br>            #batching <br>            data_points = data_points.view( 1, data_points.shape[0] )<br><br>        topk = int( topk )<br>        <br>        distances = self.dist_evaluator( data_points, self.lattice_node_weights )<br>        <br>        topk_best_matching_unit_indexes = torch.topk( distances, topk, dim=1, largest=False ).indices<br>        topk_best_matching_units = []<br>        <br>        for i in range( data_points.shape[0] ):<br>            best_matching_unit_indexes = topk_best_matching_unit_indexes[i]<br>            best_matching_units = [ self.lattice_coordinates[ bmu_index.item() ].tolist() for bmu_index in best_matching_unit_indexes ]<br>            topk_best_matching_units.append( best_matching_units )<br>        <br>        return topk_best_matching_units</pre><h4>Step 2: SOM-Based Vector Indexer Implementation</h4><p>The vector indexer is a utility that uses Kohonen’s SOM to train SOM nodes with data vectors from an external dataset. Its primary purpose is to map each data vector to the closest top-k SOM nodes, enabling efficient indexing of the data vectors. The following code snippet shows the train and indexing function of the vector indexer Python class. Its complete code is available at <a href="https://github.com/kbmurali/som-driven-qa-rag/blob/main/vector_indexer.py">this GitHub location</a>. Although its implementation is currently limited to the example’s needs, it can be extended to meet other requirements.</p><pre>class SOMBasedVectorIndexer():<br>    ...<br><br>    def train_n_gen_indexes( <br>                                self, input_vectors : torch.Tensor, <br>                                train_epochs : int = 100 <br>                           ):<br>        if self.generated_indexes:<br>            print( &quot;WARNING: Indexes were already generated. Ignoring the request...&quot; )<br>            return<br>        <br>        self.som.train( input_vectors, train_epochs )<br>   <br>        topk_bmu_indexes = self.som.find_topk_best_matching_units( input_vectors, topk = self.topk_bmu_for_indexing )<br>        <br>        for idx in tqdm( range( len( topk_bmu_indexes ) ), desc=&quot;SOM-Based Indexed Vectors&quot;  ):<br>            bmu_indexes = topk_bmu_indexes[ idx ]<br>            <br>            for bmu_index in bmu_indexes:<br>                bmu_index_key = tuple( bmu_index )<br>                idx_set = self.som_node_idx_map.get( bmu_index_key, set() )<br>                idx_set.add( idx )<br>                self.som_node_idx_map[ bmu_index_key ] = idx_set<br>        <br>        self.generated_indexes = True</pre><h4>Step 3: OpenAI Embeddings-Based Text-To-Vector Encoder</h4><p>The encoder’s primary function is to convert text into vector representations using OpenAI’s text embedding API. It is worth noting that an OpenAI account and API key are required to use the embedding API. Upon opening an account for the first time, OpenAI provides complementary credit grants, which are more than enough to access the API for testing purposes. Below is a code snippet showcasing the batch encode function of the OpenAI encoder Python class. The complete code is available at <a href="https://github.com/kbmurali/som-driven-qa-rag/blob/main/openai_vector_encoder.py">this GitHub location</a>.</p><pre>import openai<br>from openai.embeddings_utils import get_embedding<br>...<br>from vector_encoder_parent import VectorEncoder<br>...<br><br>class OpenAIEmbeddingsVectorEncoder( VectorEncoder ):<br>    def __init__( ... )<br>    ...<br>    def encode_batch( self, list_of_text : List[ str ] ) -&gt; torch.Tensor :<br>        if list_of_text == None or len( list_of_text ) == 0:<br>            raise ValueError( &quot;ERROR: Required list_of_text is None or empty&quot; )<br>        <br>        list_of_text = [ str( text ) for text in list_of_text ]<br>        <br>        openai.api_key = self.openai_key<br>        response = openai.Embedding.create(<br>                                            input = list_of_text,<br>                                            engine = self.vector_encoder_id<br>                                          )<br>        <br>        embeddings = [ data[&quot;embedding&quot;] for data in response[&quot;data&quot;] ] <br>        vectors = torch.tensor( embeddings, dtype=torch.float )<br>        return vectors</pre><p>Note that the OpenAI vector encoder class extends a generic parent class, ‘VectorEncoder,’ that defines abstract encoding functions to be implemented through inheritance. It is possible to implement other types of vector encoders by inheriting from this parent class for the pluggability of other encoding schemes. The complete code for the parent vector encoder class can be found at <a href="https://github.com/kbmurali/som-driven-qa-rag/blob/main/vector_encoder_parent.py">this GitHub location</a>.</p><h4>Step 4: Wikipedia API-Driven DataSource Implementation</h4><p>This utility class is designed to encapsulate the data retrieval logic that integrates with Wikipedia API. Its main function is to fetch events for a specified array of calendar years, format the retrieved events, and load them into a Pandas dataframe. The code snippet below captures the primary function of the utility class, while the complete code is available at <a href="https://github.com/kbmurali/som-driven-qa-rag/blob/main/wiki_datasource.py">this GitHub location</a>.</p><pre>import requests<br>import pandas as pd<br>from dateutil.parser import parse<br>...<br>class WikiEventsDataSource():<br>    ...<br>    def fetch_n_prepare_data( self ):<br>        if self.fetched:<br>            print( &quot;WARNING: Wiki events for the specified years already fetched. Ignoring the request...&quot; )<br>            return<br>        <br>        main_df = pd.DataFrame()<br>        <br>        for year in self.event_years_to_fetch:<br>            wiki_api_params = {<br>                                &quot;action&quot;: &quot;query&quot;, <br>                                &quot;prop&quot;: &quot;extracts&quot;,<br>                                &quot;exlimit&quot;: 1,<br>                                &quot;titles&quot;: year,<br>                                &quot;explaintext&quot;: 1,<br>                                &quot;formatversion&quot;: 2,<br>                                &quot;format&quot;: &quot;json&quot;<br>                              }<br>        <br>            response = requests.get( &quot;https://en.wikipedia.org/w/api.php&quot;, params=wiki_api_params )<br>            response_dict = response.json()<br>        <br>            df = pd.DataFrame()<br>            df[ &quot;text&quot; ] = response_dict[&quot;query&quot;][&quot;pages&quot;][0][&quot;extract&quot;].split(&quot;\n&quot;)<br>            df = self.__clean_df__( df, year )<br>            <br>            main_df = pd.concat( [ main_df, df ] )<br>        <br>        self.df = main_df.reset_index(drop=True)<br>        self.fetched = True</pre><h4>Step 5: SOM-Based RAG Utility Implementation</h4><p>The SOM-based RAG utility is a crucial element of the example implementation. It utilizes the vector encoder, indexer, and data source to implement the core logic for the underlying semantic search. The complete code for the SOM-based RAG utility is available at <a href="https://github.com/kbmurali/som-driven-qa-rag/blob/main/som_based_rag.py">this GitHub location</a>.</p><p>The utility implements three primary functions. The first function is to load data from an external data source and encode it into vectors, as shown in the following code snippet.</p><pre>...<br>from vector_encoder_parent import VectorEncoder<br>from vector_indexer import SOMBasedVectorIndexer<br><br>class SOM_Based_RAG_Util():<br>    ...<br>    def load_n_vectorize_data( self, data_source ):<br>        if self.data_loaded_n_vectorized:<br>            print( &quot;WARNING: Data already loaded and vectorized. Ignoring the request...&quot; )<br>            return<br>        <br>        data_source.fetch_n_prepare_data()<br>        self.df = data_source.get_data()<br>        <br>        vectors = None<br>        <br>        for i in tqdm( range(0, len(self.df), self.vectorize_batch_size ), desc=&quot;Vectorized Data Batch&quot; ):<br>            list_of_text = self.df.iloc[ i:i+self.vectorize_batch_size ][&quot;text&quot;].tolist()<br>            batch_encoded_vectors = self.vector_encoder.encode_batch( list_of_text )<br>            <br>            if vectors == None:<br>                vectors = batch_encoded_vectors<br>            else:<br>                vectors = torch.cat( [ vectors, batch_encoded_vectors], dim=0 )<br>                <br>        self.vectors = vectors.to( self.device )<br>        self.data_loaded_n_vectorized = True</pre><p>The second function is to train the SOM-based indexer to construct Kohonen’s SOM nodes and then index the data vectors, as shown in the following code snippet.</p><pre>def train_n_index_data_vectors( self, train_epochs : int = 100  ):<br>        if not self.data_loaded_n_vectorized:<br>            raise ValueError( &quot;ERROR: Data not loaded and vectorized.&quot; )<br>        <br>        if self.data_vectors_indexed:<br>            print( &quot;WARNING: Data vectors already indexed. Ignoring the request...&quot; )<br>            return<br>        <br>        self.vector_indexer.train_n_gen_indexes( self.vectors, train_epochs )<br>        self.data_vectors_indexed = True</pre><p>The third function is to find similar information from the previously stored external dataset based on a query text. This function uses the encoder to convert the query text into a vector and then searches through the SOM-based indexer for the most likely matches. This function then calculates the similarity between the query vector and the discovered data vectors using Cosine similarity or another specified similarity evaluator. Finally, this function filters the data vectors whose similarities are greater than or equal to the specified similarity threshold. The following code snippet captures the function implementation.</p><pre>def find_semantically_similar_data( self, query: str, sim_evaluator = None, sim_threshold : float = 0.8  ):<br>        if not self.data_vectors_indexed:<br>            raise ValueError( &quot;ERROR: Data vectors not indexed.&quot; )<br>            <br>        if query == None or len( query.strip() ) == 0:<br>            raise ValueError( &quot;ERROR: Required query text is not specified.&quot; )<br>            <br>        sim_threshold = float( sim_threshold )<br><br>        if sim_evaluator == None:<br>            sim_evaluator = nn.CosineSimilarity(dim=0, eps=1e-6)<br>        <br>        query_vector = self.vector_encoder.encode( query )<br>        query_vector = query_vector.view( self.vector_encoder.get_encoded_vector_dimensions() )<br>        query_vector = query_vector.to( self.device )<br>        <br>        nearest_indexes = self.vector_indexer.find_nearest_indexes( query_vector )<br>        nearest_indexes = nearest_indexes[0]<br>        <br>        sim_scores = []<br>        <br>        for idx in nearest_indexes:<br>            data_vector = self.vectors[ idx ]<br>            data_vector = data_vector.view( self.vector_encoder.get_encoded_vector_dimensions() )<br>            <br>            sim_score = sim_evaluator( query_vector, data_vector )<br>      <br>            if sim_score &gt;= sim_threshold:<br>                sim_score_tuple = (idx, sim_score.item() )<br>                sim_scores.append( sim_score_tuple )<br>        <br>        sim_scores.sort( key = lambda x: x[1], reverse=True )<br>        <br>        semantically_similar_data = [ <br>                                        { <br>                                            &#39;text&#39;: self.df[ &#39;text&#39; ][ idx ],<br>                                            &#39;sim_score&#39; : sim_score<br>                                        } for idx, sim_score in sim_scores<br>                                    ]<br>        <br>        return semantically_similar_data</pre><p>An example output from a semantic search by SOM-based RAG utility function is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*duxOEkYKNmEqZ_MBuF--WQ.png" /><figcaption>An Example Semantic Search Output — Image by Author</figcaption></figure><h4>Step 6: Abstract Question/Answer ChatBot And Its OpenAI-Based Implementation</h4><p>An abstract ‘QuestionAnswerChatBot’ Python class is developed to facilitate chatbot-like implementations. It augments the prompted question by using a standard instruction template and populating it with contextually similar information retrieved from the RAG utility.</p><p>The specified maximum number of new tokens limits the text size for context augmentation, while token counting is deferred to underlying implementations. In LLM economics, tokens are like currency. Each token the model processes requires computational resources — memory, processing power, and time. Thus, the more tokens an LLM has to process, the greater the computational cost.</p><p>Finally, this class delegates prompting of the LLM model to the underlying implementation once the QA instruction has been populated. The following code snippet captures the primary function; the complete code is available at <a href="https://github.com/kbmurali/som-driven-qa-rag/blob/main/qa_chatbot.py">this GitHub location</a>.</p><pre>from abc import ABC, abstractmethod<br>import torch<br>import math<br><br>class QuestionAnswerChatBot( ABC ):<br>    ...<br>    def find_answer_to_question( self, question : str, sim_threshold = 0.68, max_new_tokens : int = 5 ):<br>        if question == None or len( question.strip() ) == 0:<br>            raise ValueError( &quot;ERROR: Required question is not specified&quot; )<br>        <br>        sim_threshold = float( sim_threshold )<br>        max_new_tokens = int( max_new_tokens )<br>        <br>        qa_instruction = self.get_qa_instruction( question, sim_threshold = sim_threshold )<br>        <br>        answer_text = self.__get_answer_text__( qa_instruction, max_new_tokens = max_new_tokens )<br>        answer_text = self.__clean_answer_text__( qa_instruction, answer_text )<br>        <br>        return answer_text<br>    ...<br>    def __qa_template__( self ):<br>        qa_template = &quot;&quot;&quot;Context: <br>    <br>    {}<br>    <br>    ---<br>    <br>    Question: {}<br>    Answer:&quot;&quot;&quot;<br>        return qa_template</pre><p>The Python class ‘OpenAIQuestionAnswerChatBot’ extends the abstract ‘QuestionAnswerChatBot’ and implements the chatbot functionality using the OpenAI LLM API. The following code snippet shows the class’s primary function. The complete code is available at <a href="https://github.com/kbmurali/som-driven-qa-rag/blob/main/openai_qa_chatbot.py">this GitHub location</a>.</p><pre>import openai<br>import tiktoken<br>from qa_chatbot import QuestionAnswerChatBot<br><br>class OpenAIQuestionAnswerChatBot( QuestionAnswerChatBot ):<br>    ...<br>    def __get_answer_text__( self, qa_instruction : str, max_new_tokens : int = 5 ) -&gt; str :<br>        openai.api_key = self.openai_key<br>        <br>        basic_answer = openai.Completion.create(<br>                                                    model = self.openai_model_name,<br>                                                    prompt = qa_instruction, <br>                                                    <br>                                               )<br>    <br>        answer_text = basic_answer[ &quot;choices&quot; ][0][ &quot;text&quot; ]<br>        return answer_text<br><br>    def __token_count__( self, text : str ):    <br>        return len( self.tokenizer.encode( text ) )</pre><p>The following is an example of how a prompted question gets augmented with context using similar information retrieved through semantic search:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*IXErBHuq7qrySNxE8bzhpA.png" /><figcaption>An Example Context Augmented Question Prompt — Image by Author</figcaption></figure><h4>Step 7: Sample Questions for Testing</h4><p>The following are sample questions for testing the RAG using OpenAI’s GPT-3.5-turbo-instruct LLM. They were developed to ensure that their answers pertain to events that occurred in 2022, 2023, and 2024.</p><pre>sample_questions = [<br>                        &quot;Who won the 2022 soccer world cup?&quot;,<br>                        &quot;When did Sweden join NATO?&quot;,<br>                        &quot;Who joined NATO in 2023?&quot;,<br>                        &quot;Who joined NATO in 2024?&quot;,<br>                        &quot;Which is the 31st member of NATO?&quot;,<br>                        &quot;Which is the 32nd member of NATO?&quot;,<br>                        &quot;Who won the Cricket World Cup in 2023?&quot;,<br>                        &quot;Who defeated India in Cricket World Cup final in 2023?&quot;,<br>                        &quot;Name the former prime minister of Japan that was assassinated in 2022?&quot;,<br>                        &quot;When did Chandrayaan-3 land near the south pole of the Moon?&quot;,<br>                        &quot;Where did Chandrayaan-3 land on the Moon?&quot;,<br>                        &quot;Who acquired Twitter in 2022?&quot;,<br>                        &quot;Who owns Twitter?&quot;,<br>                        &quot;Who acquired Activision Blizzard in 2023?&quot;<br>                   ]</pre><h4>Step 8: Putting Everything Together</h4><p>The complete Jupyter notebook that brings all the components together can be found at <a href="https://github.com/kbmurali/som-driven-qa-rag/blob/main/OpenAI_Based_SOM_GPT2_Bot.ipynb">this GitHub location</a>. The following code snippet shows the initiation of the main OpenAI-based QA chatbot. Note that OpenAI’s text embedding algorithm, “text-embedding-ada-002,” is used for vector encoding. Likewise, the chatbot uses OpenAI’s tokenizer, “cl100k_base,” to count the tokens to limit the contextual text to augment the question prompt by leveraging the inbuilt functions of the TikToken Python library.</p><pre>openai_vector_encoder_id = &quot;text-embedding-ada-002&quot;<br>openai_encoded_vector_dimensions = 1536<br>openai_tokenizer_name = &quot;cl100k_base&quot; <br>openai_model_name = &quot;gpt-3.5-turbo-instruct&quot;<br><br>vector_encoder = OpenAIEmbeddingsVectorEncoder( openai_encoded_vector_dimensions, openai_vector_encoder_id, openai_key )<br><br>event_years_to_fetch = [ 2022, 2023, 2024 ]<br>data_source = WikiEventsDataSource( event_years_to_fetch  )<br>...<br>som_driven_rag_util = SOM_Based_RAG_Util( <br>                                            vector_encoder = vector_encoder,<br>                                            som_lattice_height = 20,<br>                                            som_lattice_width = 30,<br>                                            learning_rate = 0.3,<br>                                            topk_bmu_for_indexing = 10,<br>                                            device = device<br>                                        )<br>...<br>openai_chatbot = OpenAIQuestionAnswerChatBot( <br>                                                vector_db_util = som_driven_rag_util,<br>                                                openai_tokenizer_name = openai_tokenizer_name,<br>                                                openai_model_name = openai_model_name,<br>                                                openai_key = openai_key,<br>                                                question_input_max_token_count = 100,<br>                                                context_trim_percent = 0.1,<br>                                                device = device<br>                                            )</pre><p>The following sequence diagrams help visualize all the component interactions during the initialization and actual question/answering phases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k0cpzbZOh3eJcXBLeugyig.png" /><figcaption>Interactions of Various Components During Initialization — Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1mAZ53dzCNuEv8C0OFqwBw.png" /><figcaption>Interactions of Various Components During Question/Answering — Image by Author</figcaption></figure><h4>Findings</h4><p>The following image captures the question/answers from OpenAI’s GPT-3.5-turbo-instruct LLM with and without context augmentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Wpv5SInMk9D_qgY86j1WA.png" /><figcaption>OpenAI’s GPT-3.5-turbo-instruct LLM’s Answers With and Without Context Augmentation — Image by Author</figcaption></figure><p>Understandably, the LLM finds it challenging to answer questions about events that occurred after its September 2021 cut-off date. In most cases, it clearly responds that the questions are from a future time relative to its training cut-off date. On the contrary, the same LLM answers all the questions accurately to perfection when the context of the prompted questions is augmented with relevant information from years 2022, 2023, and 2024 retrieved from Wikipedia. The real credit here goes to the SOM that formed the basis for RAG’s semantic search to retrieve and augment the prompted question’s context with relevant information.</p><h4>Suggested Next Steps</h4><p>While the above example served as a proof-of-concept to assess the suitability of a Self-Organizing Map to enable Retrieval-Augmented Generation of text by an LLM, a more comprehensive benchmarking is suggested to evaluate its performance in comparison to other algorithms using a much larger external dataset, where performance is measured in terms of the quality of LLM outputs (something like perplexity + accuracy). In addition, since the current example enables a pluggable framework, it is suggested that other open-source and free QA LLMs be used to conduct such benchmarking to minimize the LLM usage expenses.</p><p>To help run the example in local environments, I included the ‘requirements.txt’ file, which contains various versions of Python libraries I used in my environment to run and test the above example. This file is available at <a href="https://github.com/kbmurali/som-driven-qa-rag/blob/main/requirements.txt">this GitHub location</a>.</p><p>I conclude by promising to share my findings in a separate write-up if I conduct any such benchmarks. Please stay tuned!!</p><h4>References</h4><ul><li><a href="http://www.ai-junkie.com/ann/som/som1.html">SOM tutorial part 1</a></li><li><a href="https://towardsdatascience.com/understanding-self-organising-map-neural-network-with-python-code-7a77f501e985">Understanding Self-Organising Map Neural Network with Python Code</a></li><li><a href="https://arxiv.org/abs/2005.11401">Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks</a></li><li><a href="https://blogs.nvidia.com/blog/what-is-retrieval-augmented-generation/">What Is Retrieval-Augmented Generation aka RAG?</a></li></ul><p><a href="https://www.sciencedirect.com/topics/engineering/self-organizing-map">https://www.sciencedirect.com/topics/engineering/self-organizing-map</a></p><p><a href="https://platform.openai.com/docs/models/gpt-3-5-turbo">https://platform.openai.com/docs/models/gpt-3-5-turbo</a></p><p><a href="https://platform.openai.com/docs/guides/text-generation/chat-completions-api">https://platform.openai.com/docs/guides/text-generation/chat-completions-api</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d739ce21e9c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/using-self-organizing-map-to-bolster-retrieval-augmented-generation-in-large-language-models-5d739ce21e9c">Using Self-Organizing Map To Bolster Retrieval-Augmented Generation In Large Language Models</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[Exploring the Superhero Role of 2D Batch Normalization in Deep Learning Architectures]]></title>
            <link>https://medium.com/data-science/exploring-the-superhero-role-of-2d-batch-normalization-in-deep-learning-architectures-b4eb869e8b60?source=rss-2d02cbc7d153------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4eb869e8b60</guid>
            <category><![CDATA[batch-normalization]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[smoother-gradient-descent]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <dc:creator><![CDATA[Murali Kashaboina]]></dc:creator>
            <pubDate>Fri, 12 Jan 2024 19:51:30 GMT</pubDate>
            <atom:updated>2024-01-12T19:51:30.529Z</atom:updated>
            <content:encoded><![CDATA[<h4>Internal working and intuitions are explained through simple examples</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*mAIn_Num84hBadCkKjNkuw.png" /><figcaption>Image created by Author</figcaption></figure><p>Deep Learning (DL) has been a game-changer in the evolution of Convolutional Neural Networks (CNN) and Generative Artificial Intelligence (Gen AI). Such DL models can extract complex patterns and features from multidimensional spatial data, such as images, and make predictions. The more intricate the patterns in the input data are, the more complex can the model architecture be. There are many ways to accelerate the model training convergence and enhance the model inference performance, but Batch Normalization 2D (BN2D) has emerged as a superhero in this area. This write-up aims to showcase how integrating BN2D in a DL architecture can lead to faster convergence and better inference.</p><h4>Understanding BN2D</h4><p>BN2D is a normalization technique applied in batches to multidimensional spatial inputs such as images to normalize their dimensional (channel) values so that dimensions across such batches have a mean of 0 and a variance of 1.</p><p>The primary purpose of incorporating BN2D components is to prevent internal covariate shifts across dimensions or channels in input data from previous layers within a network. Internal covariate shifts across dimensions occur when the distributions of dimensional data change due to updates made to network parameters during training epochs. For instance, N filters in a convolutional layer produce N-dimensional activations as output. This layer maintains weight and bias parameters for its filters that get updated incrementally with each training epoch.</p><p>As a result of these updates, activations from one filter can have a markedly different distribution than activations from another of the same convolutional layer. Such differences in distribution indicate that activations from one filter are on a vastly different scale than activations from another filter. When inputting such dimensional data with vastly different scales to the next layer in the network, the learnability of that layer is hindered because the weights of dimensions with larger scales require larger updates during gradient descent than those with smaller scales.</p><p>The other possible consequence is that gradients of weights with smaller scales can vanish, while gradients of weights with larger scales can explode. When the network experiences such learning obstacles, gradient descent will oscillate across the larger-scale dimensions, severely hindering learning convergence and training stability. BN2D effectively mitigates this phenomenon by normalizing the dimensional data to a standard scale with a mean of 0 and standard deviation of 1 and facilitates faster convergence during training, reducing the number of epochs required to achieve optimal performance. As such, by easing the network’s training phase, the technique ensures that the network can focus on learning more complex and abstract features, allowing the extraction of richer representations from the input data.</p><p>In standard practice, BN2D instances are inserted post-convolution, but pre-activation layers, such as ReLU, as shown in a sample DL network in Figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OAIO4Asgv4YjNLuWdQ-wkQ.png" /><figcaption>Figure 1: A Sample Deep CNN (Image created by Author)</figcaption></figure><h4>Inner Workings of BN2D</h4><p>An example batch of simple multidimensional spatial data, such as 3-channel images, is shown in Figure 2 to illustrate the internal workings of the BN2D technique.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITU034_CFazKREbzgAiExg.png" /><figcaption>Figure 2: Inner Workings of BN2D (Image created by Author)</figcaption></figure><p>As depicted in Figure 2, BN2D functions by processing a batch at every dimension or channel. If an input batch has N dimensions or channels, the BN2D instance will have N BN2D layers. The separate processing of red, green, and blue channels in the example case implies that the corresponding BN2D instance has 3 BN2D layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*Mjd7mRrX_GCqjXbPggz6_Q.png" /><figcaption>Figure 3: Formulae Used by BN2D (Image created by Author)</figcaption></figure><p>During training, BN2D computes mean and variance for each batch dimension and normalizes values as illustrated in Figure 2 using the training-time formula shown in Figure 3. Preset epsilon (ε) is a constant in the denominator to avoid division by zero. BN2D instance maintains scale (γ) and shift (β) learnable parameters per each dimension or BN2D layer, which are updated during training optimization. BN2D instance also maintains moving average and variance per BN2D layer, as illustrated in Figure 2, which get updated during training using the formula shown in Figure 3. Preset momentum (α) is used as the exponential average factor.</p><p>During inference, using the inference-time formula as shown in Figure 3, a BN2D instance normalizes values for each dimension using dimension-specific moving average, moving variance, and learned scale (γ) and shift (β) parameters. Example training-time batch normalization computations are shown in Figure 2 for each dimension in the batch input. The example in Figure 2 also illustrates the output from a BN2D instance containing the entire batch normalized independently across the dimensions or channels. The PyTorch Jupyter Notebook used to work through the example illustrated in Figure 2 is available at the following GitHub repository.</p><p><a href="https://github.com/kbmurali/hindi_hw_digits/blob/main/how_batch_norm2d_works.ipynb">https://github.com/kbmurali/hindi_hw_digits/blob/main/how_batch_norm2d_works.ipynb</a></p><h4>BN2D in Action</h4><p>To inspect the expected performance improvements of incorporating BN2D instances in a DL network architecture, a simple (toy-like) image dataset is used to build relatively simpler DL networks with and without BN2D to predict classes. The following are the crucial DL model performance improvements expected with BN2D:</p><ol><li>Improved Generalization: The normalizations introduced by BN2D are expected to improve the generalization of a DL model. In the example, improved inference-time classification accuracy is expected when BN2D layers are introduced in the network.</li><li>Faster Convergence: Introducing BN2D layers is expected to facilitate faster convergence during training, reducing the number of epochs required to achieve optimal performance. In the example, lowered training losses are expected starting at early epochs after introducing BN2D layers.</li><li>Smoother Gradient Descent: Since BN2D normalizes the dimensional data to a standard scale with a mean of 0 and standard deviation of 1, the possibility of oscillations of gradient descent across the larger-scale dimensions is expected to be minimized, and the gradient descent is expected to progress smoothly.</li></ol><h4>Example Dataset</h4><p>Hindi language hand-written digits (0–9) data published by Kaggle at <a href="https://www.kaggle.com/datasets/suvooo/hindi-character-recognition/data">https://www.kaggle.com/datasets/suvooo/hindi-character-recognition/data</a> (GNU license) is used for training and testing a convolutional DL model with and without BN2D incorporated. Refer to this article’s banner image at the top to see how Hindi digits are written. The DL model network was built using PyTorch DL modules. The choice of hand-written Hindi digits over their English counterparts was based on their complexity compared to the latter. Edge detection in Hindi digits is more challenging than in English due to more curves than straight lines in Hindi digits. Moreover, there could be more variations for the same digit based on one’s writing style.</p><p>A utility Python function is developed to make the access to the digits data more PyTorch dataset/dataloader compliant, as shown in the following code snippet. The training dataset had 17000 samples, while the testing dataset had 3000. Note that the PyTorch Grayscale transformer is applied while loading the images as PyTorch Tensors. A utility module, ‘ml_utils.py,’ is specifically developed to package functions for running epochs, training and testing deep learning models using PyTorch Tensor-based operations. The train and test functions also capture model metrics to help evaluate the model’s performance. Python notebooks and utility modules can be accessed at the author’s public GitHub repository, whose link is provided below.</p><p><a href="https://github.com/kbmurali/hindi_hw_digits">https://github.com/kbmurali/hindi_hw_digits</a></p><pre>import torch<br>import torch.nn as nn<br>from torch.utils.data import *<br>import torchvision<br>from torchvision import transforms<br>from sklearn.metrics import accuracy_score<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br>from ml_utils import *<br>from hindi.datasets import Digits<br><br>set_seed( 5842 )<br><br>batch_size = 32<br><br>img_transformer = transforms.Compose([<br>                        transforms.Grayscale(),<br>                        transforms.ToTensor()<br>                    ])<br><br>train_dataset = Digits( &quot;./data&quot;, train=True, transform=img_transformer, download=True )<br><br>test_dataset = Digits( &quot;./data&quot;, train=False, transform=img_transformer, download=True )<br><br>train_loader = DataLoader( train_dataset, batch_size=batch_size, shuffle=True )<br><br>test_loader = DataLoader( test_dataset, batch_size=batch_size )</pre><h4>Example DL Models</h4><p>The first DL model will comprise three convolutional layers with 16 filters, each with a kernel size of 3 and padding 1, resulting in the ‘Same’ convolution. The activation function for each convolution is the Rectified Linear Unit (ReLU). The max pooling layer with a pool size 2 is placed before a fully connected layer, leading to a softmax layer producing 10 class outputs. The model’s network architecture is shown in Figure 4. The corresponding PyTorch model definition is shown in the following code snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9XBHIVew7Aj0cVv7jjGFJw.png" /><figcaption>Figure 4: Convolutional Network Without BN2D (Image created by Author)</figcaption></figure><pre>device = torch.device( &#39;cuda&#39; if torch.cuda.is_available() else &#39;cpu&#39; )<br>loss_func = nn.CrossEntropyLoss()<br>input_channels = 1<br>classes = 10<br>filters = 16<br>kernel_size = 3<br>padding = kernel_size//2<br>pool_size = 2<br>original_pixels_per_channel = 32*32<br><br>three_convs_model = nn.Sequential(<br>                                    nn.Conv2d( input_channels, filters, kernel_size, padding=padding ), # 1x32x32 =&gt; 16x32x32<br>                                    nn.ReLU(inplace=True), #16x32x32 =&gt; 16x32x32<br>                                    nn.Conv2d(filters, filters, kernel_size, padding=padding ), # 16x32x32 =&gt; 16x32x32<br>                                    nn.ReLU(inplace=True), #16x32x32 =&gt; 16x32x32<br>                                    nn.Conv2d(filters, filters, kernel_size, padding=padding ), # 16x32x32 =&gt; 16x32x32<br>                                    nn.ReLU(inplace=True), #16x32x32 =&gt; 16x32x32<br>                                    nn.MaxPool2d(pool_size), # 16x32x32 =&gt; 16x16x16<br>        <br>                                    nn.Flatten(), # 16x16x16 =&gt; 4096<br>                                    nn.Linear( 4096, classes) # 1024 =&gt; 10<br>                                )</pre><p>The second DL model shares a similar structure to the first one but introduces BN2D instances after convolution and before activation. The model’s network architecture is shown in Figure 5. The corresponding PyTorch model definition is shown in the following code snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_I9k4lRi6WY3RDu42UYW6g.png" /><figcaption>Figure 5: Convolutional Network With BN2D (Image created by Author)</figcaption></figure><pre>three_convs_wth_bn_model = nn.Sequential(<br>                                            nn.Conv2d( input_channels, filters, kernel_size, padding=padding ), # 1x32x32 =&gt; 16x32x32<br>                                            nn.BatchNorm2d( filters ), #16x32x32 =&gt; 16x32x32<br>                                            nn.ReLU(inplace=True), #16x32x32 =&gt; 16x32x32<br>                                            nn.Conv2d(filters, filters, kernel_size, padding=padding ), # 16x32x32 =&gt; 16x32x32<br>                                            nn.BatchNorm2d( filters ), #16x32x32 =&gt; 16x32x32<br>                                            nn.ReLU(inplace=True), #16x32x32 =&gt; 16x32x32<br>                                            nn.Conv2d(filters, filters, kernel_size, padding=padding ), # 16x32x32 =&gt; 16x32x32<br>                                            nn.BatchNorm2d( filters ), #16x32x32 =&gt; 16x32x32<br>                                            nn.ReLU(inplace=True), #16x32x32 =&gt; 16x32x32<br>                                            nn.MaxPool2d(pool_size), # 16x32x32 =&gt; 16x16x16<br>                <br>                                            nn.Flatten(), # 16x16x16 =&gt; 4096<br>                                            nn.Linear( 4096, classes) # 4096 =&gt; 10<br>                                       )</pre><p>The two DL models are trained on the example Hindi digits dataset using the utility function shown in the following code snippet. Note that two sample weights from two dimensions/channels of a filter in the last convolutional layer are captured to visualize the training loss’s gradient descent.</p><pre>three_convs_model_results_df = train_model( <br>                                            three_convs_model,<br>                                            loss_func, <br>                                            train_loader, <br>                                            test_loader=test_loader, <br>                                            score_funcs={&#39;accuracy&#39;: accuracy_score}, <br>                                            device=device, <br>                                            epochs=30,<br>                                            capture_conv_sample_weights=True, <br>                                            conv_index=4, <br>                                            wx_flt_index=3, <br>                                            wx_ch_index=4, <br>                                            wx_ro_index=1, <br>                                            wx_index=0,<br>                                            wy_flt_index=3,<br>                                            wy_ch_index=8, <br>                                            wy_ro_index=1, <br>                                            wy_index=0<br>                                         )<br><br>three_convs_wth_bn_model_results_df = train_model( <br>                                                    three_convs_wth_bn_model,<br>                                                    loss_func, <br>                                                    train_loader, <br>                                                    test_loader=test_loader, <br>                                                    score_funcs={&#39;accuracy&#39;: accuracy_score}, <br>                                                    device=device, <br>                                                    epochs=30,<br>                                                    capture_conv_sample_weights=True, <br>                                                    conv_index=6, <br>                                                    wx_flt_index=3, <br>                                                    wx_ch_index=4, <br>                                                    wx_ro_index=1, <br>                                                    wx_index=0,<br>                                                    wy_flt_index=3,<br>                                                    wy_ch_index=8, <br>                                                    wy_ro_index=1, <br>                                                    wy_index=0<br>                                                 )</pre><h4>Finding 1: Improved Test Accuracy</h4><p>The testing accuracy of the DL model was better with BN2D instances, as shown in Figure 6. The testing accuracy improved gradually with training epochs for the model with BN2D, while it oscillated with training epochs for the model without BN2D. At the end of epoch 30, the test accuracy for the model with BN2D was 99.1%, while 92.4% for the model without BN2D. These results suggest that incorporating BN2D instances positively affected the model’s performance, significantly increasing the testing accuracy.</p><pre>sns.lineplot( x=&#39;epoch&#39;, y=&#39;test accuracy&#39;, data=three_convs_model_results_df, label=&quot;Three Convs Without BN2D Model&quot; )<br>sns.lineplot( x=&#39;epoch&#39;, y=&#39;test accuracy&#39;, data=three_convs_wth_bn_model_results_df, label=&quot;Three Convs Wth BN2D Model&quot; )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ef9Wf3lWqYLMCLnDVpzjPw.png" /><figcaption>Figure 6: Test Accuracy Over Training Epochs (Image created by Author)</figcaption></figure><h4>Finding 2: Faster Convergence</h4><p>The training loss of the DL model was much lower with BN2D instances, as shown in Figure 7. By around training epoch 3 itself, the model with BN2D manifested lower training losses than without BN2D. The lower training losses suggest that BN2D facilitates faster convergence during training, perhaps reducing the number of training epochs for reasonable convergence.</p><pre>sns.lineplot( x=&#39;epoch&#39;, y=&#39;train loss&#39;, data=three_convs_model_results_df, label=&quot;Three Convs Without BN2D Model&quot; )<br>sns.lineplot( x=&#39;epoch&#39;, y=&#39;train loss&#39;, data=three_convs_wth_bn_model_results_df, label=&quot;Three Convs Wth BN2D Model&quot; )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*A8LXqusXZFOFaKZHYqVEJw.png" /><figcaption>Figure 7: Training Loss Over Training Epochs (Image created by Author)</figcaption></figure><h4>Finding 3: Smoother Gradient Descent</h4><p>The loss function over the two sample weights taken from the last convolution of the model with BN2D manifested smoother gradient descent than without BN2D, as shown in Figure 8. The loss function of the model without BN2D followed a rather zig-zag gradient descent. The smoother gradient descent with BN2D suggests that normalizing the dimensional data to a standard scale with a mean of 0 and standard deviation of 1 enables weights of different dimensions possibly to be on a similar scale, reducing the possible oscillations of the gradient descent.</p><pre>fig1 = draw_loss_descent( three_convs_model_results_df, title=&#39;Three Convs Model Without BN2D Training Loss&#39; )<br>fig2 = draw_loss_descent( three_convs_wth_bn_model_results_df, title=&#39;Three Convs With BN2D Model Training Loss&#39; )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oB0kUt-J9t4n6TVFvWsZkg.png" /><figcaption>Figure 8: Loss Function Gradient Descent Over Sample Weights (Image created by Author)</figcaption></figure><h4>Practical Considerations</h4><p>While the benefits of BN2D are clear, its implementation requires careful consideration. Proper initialization of weights, suitable learning rates, and the placement of BN2D layers within the DL network are crucial factors to maximize its effectiveness. While BN2D often prevents over-fitting, there can be cases where it may even contribute to over-fitting under certain circumstances. For example, if BN2D is used along with another technique called Dropout, the combination might have different effects on over-fitting depending on the specific configuration and the dataset. Likewise, in the case of small batch sizes, the batch mean and variance may not closely represent the overall dataset statistics, potentially resulting in noisy normalization, which may not be as effective in preventing over-fitting.</p><h4>Conclusion</h4><p>The write-up intended to showcase the intuitions behind using BN2D in deep learning networks. The example convolutional models using toy-like image data were solely to showcase expected performance improvements incorporating BN2D instances in a DL network architecture. The BN2D normalization across spatial and channel dimensions brings about training stability, faster convergence, and enhanced generalization, ultimately contributing to the success of deep learning models. Hopefully, the write-up gives a good understanding of how BN2D works and the intuition behind it. Such understanding and intuition come in handy while developing more complex DL models.</p><p>References:</p><ul><li><a href="https://www.kaggle.com/datasets/suvooo/hindi-character-recognition/data">Hindi Character Recognition</a></li><li><a href="https://pytorch.org/docs/stable/generated/torch.nn.BatchNorm2d.html">BatchNorm2d - PyTorch 2.6 documentation</a></li><li><a href="https://discuss.pytorch.org/t/why-2d-batch-normalisation-is-used-in-features-and-1d-in-classifiers/88360/3">Why 2D batch normalisation is used in features and 1D in classifiers?</a></li><li><a href="https://keras.io/api/layers/normalization_layers/batch_normalization/">Keras documentation: BatchNormalization layer</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4eb869e8b60" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/exploring-the-superhero-role-of-2d-batch-normalization-in-deep-learning-architectures-b4eb869e8b60">Exploring the Superhero Role of 2D Batch Normalization in Deep Learning Architectures</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[Unlocking Digital Health Success: Leveraging Healthcare Provider Business Architecture Capability…]]></title>
            <link>https://medium.datadriveninvestor.com/unlocking-digital-health-success-leveraging-healthcare-provider-business-architecture-capability-b9db529bc4a5?source=rss-2d02cbc7d153------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9db529bc4a5</guid>
            <category><![CDATA[digital-health]]></category>
            <category><![CDATA[digital-healthcare]]></category>
            <category><![CDATA[healthcare-provider]]></category>
            <category><![CDATA[business-capability-map]]></category>
            <category><![CDATA[business-architecture]]></category>
            <dc:creator><![CDATA[Murali Kashaboina]]></dc:creator>
            <pubDate>Sun, 26 Nov 2023 21:41:38 GMT</pubDate>
            <atom:updated>2024-03-25T10:27:17.113Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unlocking Digital Health Success: Leveraging Healthcare Provider Business Architecture Capability Maps</h3><p>Level 1, 2, and 3 capabilities illustrated</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U9ZT4wwBoyRiqdjn" /><figcaption>Photo by <a href="https://unsplash.com/@bermixstudio?utm_source=medium&amp;utm_medium=referral">Bermix Studio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Business architecture, typically part of enterprise architecture, is a discipline that focuses on the design and structure of an organization’s business. The primary responsibility of the business architecture is to provide a blueprint of business capabilities, processes, functions, roles, and responsibilities and how an organization is structured to accomplish specific business objectives.</p><p>One of the critical components of business architecture is identifying and documenting crucial business capabilities. A capability is a high-level business function or ability that an organization possesses or needs to develop to accomplish its goals. Effectively, a business capability represents what an organization does or can do. Business capabilities are distinct, high-level business functions or activities essential to the organization’s success. They can be hierarchical with levels of hierarchy such as levels 1 and 2. The deeper the level, the more specific the capability becomes. A business capability is broken down into specific business processes at the deepest level. While the business capability represents what an organization does or can do, the business process represents how an organization executes the core functions of a business capability.</p><h4>Business Architecture Capability Map</h4><p>A business capability map is a visual representation that captures and illustrates an organization’s core capabilities. A capability map typically organizes business capabilities hierarchically, with broader capabilities at the top and more specific capabilities underneath. Such a hierarchical structure gives stakeholders a clear view of the critical abilities and competencies the business needs to achieve its strategic goals and objectives. More advanced maps can also illustrate how different capabilities at different hierarchical levels are related and connected, manifesting the cross-sectional dependencies across various capabilities.</p><h4>Digital Health Objectives</h4><p>With the advancements in hardware, software, social media, computational analysis such as Artificial Intelligence (AI) and Machine Learning (ML), wearables, smartphones, mobility, connectivity, and data integration, Digital health aims to amalgamate digital technologies with health, healthcare, living, and society to elevate healthcare delivery efficiency and enable personalized, precise, and affordable medicine. Focused disciplines like eHealth, mHealth, telemedicine, precision medicine, telematic surgery, etc., are different branches of digital health.</p><p>The following are the salient objectives of digital health initiatives:</p><ul><li><em>Detect the causes of diseases, particularly chronic types, and prevent their onset.</em></li><li><em>Decentralize and deliver care outside hospitals, such as at homes, clinics, nursing homes, rehab centers, and via telecommunication.</em></li><li><em>Enable remote patient surveillance.</em></li><li><em>Enable patient-controlled information access and develop interventions for personalized care and self-care.</em></li><li><em>Enable active aging and independent living.</em></li><li><em>Monitor and predict disease outbreaks.</em></li><li><em>Enable secure health information exchange and facilitate further research and evidence-based medical outcomes.</em></li><li><em>Communicate health services, education on lifestyle behaviors, and risks via social media and collaboration.</em></li><li><em>Gamification and incentivization of healthy well-being.</em></li></ul><h4>Digital Health And Healthcare Provider Services</h4><p>Digital health and healthcare provider services are symbiotically related, as digital health technologies aim to enhance and optimize the delivery of healthcare services. Indeed, integrating digital health into healthcare provider services brings about transformative changes, impacting how healthcare is delivered, accessed, and managed. However, the healthcare provider landscape is a complex network of interconnected entities and processes that work together to deliver healthcare services. As shown in Figure 1, the healthcare landscape comprises hospitals, outpatient care centers, and long-term care centers that are further categorized into various sub-classes based on specialty, patient admission size, ownership, for-profit/not-for-profit, hospice care, rehab, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dp4hJMaJFI1h0Thb6owOPw.png" /><figcaption><strong>Figure 1: High Level Healthcare Provider Services Landscape And Eco-System (Source: Author Developed) </strong>(Click on the image to enlarge)</figcaption></figure><p>Navigating through such complexity and understanding every nuance of how healthcare processes operate become mandatory for designing and developing digital health initiatives to ensure high-quality care and differentiated health services. That is where a healthcare provider capability map becomes crucial in providing a structured framework to inspect the business capabilities, processes, functions, and their interrelations and understand areas where digital solutions can bring a game-changing difference. Living up to its name, a capability map can indicate the optimal pathways for realizing the capabilities conducive to digital health solutions.</p><h4>Digital Healthcare Provider Capability Map</h4><p>A healthcare provider capability map is a specialized business architecture capability map tailored to the needs and functions of healthcare provider organizations, such as hospitals, clinics, and healthcare systems. It provides a visual representation of the crucial capabilities and functions required for the effective operation of healthcare providers. Such a map helps organizations understand and manage their resources, processes, and technologies in delivering healthcare services.</p><p>Figure 2 shows a digital healthcare provider capability map that the author developed through literature review and online resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWaMgyifHtaMYCgKcOgk-A.png" /><figcaption><strong>Figure 2: Digital Healthcare Provider Business Architecture Capability Map (Source: Author Developed) </strong>(Click on the image to enlarge)</figcaption></figure><p>The capability map depicted in Figure 2 comprises level 1, 2, and 3 capabilities described in terms of healthcare services. While there are several detailed and specific level 2 and 3 capabilities, the level 1 capabilities are represented by four broader healthcare services — Patient/Member Services, Provider Services, Healthcare System Management Services, and Data/Analytics Services. While the capability name descriptions for levels 1, 2, and 3 are self-explanatory, a detailed explanation for each capability depicted in the map is beyond the scope of this article. However, to help navigate the map further, the following level 1 specific zoomed-in tree-like maps are included.</p><p><strong>1) Level 1 Patient/Member Services Map</strong></p><p>Figure 3 shows the tree-like map for Level 1 Patient/Member Services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTpjLF_ttaRHJvjTaj8uOw.png" /><figcaption><strong>Figure 3: Level 1 Patient/Member Services Capability Map (Source: Author Developed) </strong>(Click on the image to enlarge)</figcaption></figure><p><strong>2) Level 1 Provider Services Map</strong></p><p>Figure 4 shows the tree-like map for Level 1 Provider Services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BNmG9GtjoGGoRjEg_v5K2g.png" /><figcaption><strong>Figure 4: Level 1 Provider Services Capability Map (Source: Author Developed) </strong>(Click on the image to enlarge)</figcaption></figure><p><strong>3) Level 1 Healthcare System Management Services Map</strong></p><p>Figure 5 shows the tree-like map for Level 1 Healthcare System Management Services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ah0J4rlAJXi_ApTqTdsKBg.png" /><figcaption><strong>Figure 5: Level 1 Healthcare System Management Services Capability Map (Source: Author Developed) </strong>(Click on the image to enlarge)</figcaption></figure><p><strong>4) Level 1 Data/Analytics Services Map</strong></p><p>Figure 6 shows the tree-like map for Level 1 Data/Analytics Services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RkTSOdeDlLN9OCeezCToQQ.png" /><figcaption><strong>Figure 6: Level 1 Data/Analytics Services Capability Map (Source: Author Developed) </strong>(Click on the image to enlarge)</figcaption></figure><h4>Capability Map Benefits For Digital Health Initiatives</h4><p>The following are the essential benefits a healthcare provider capability map offers to digital health initiatives:</p><ol><li><strong>Identifying Gaps:</strong> A capability map helps point out gaps in the current capabilities and highlight areas where digital solutions can enhance or optimize existing processes.</li><li><strong>Prioritizing Initiatives: A</strong> capability map enables prioritizing digital health initiatives based on their impact on critical capabilities and objectives that contribute most significantly to improved patient outcomes and operational efficiency.</li><li><strong>Empowering Patients/Members:</strong> A capability map helps hone in on critical patient and member engagement touchpoints and channels to leverage digital tools, such as mobile apps or patient portals, that help empower patients and members through new digital health services.</li><li><strong>Reducing Provider/Practitioner Professional Burden:</strong> A capability map aids in uncovering touchpoints for digital interventions to enhance care coordination and collaboration among healthcare professionals, thereby eliminating manual interventions where possible and reducing the burden on the physician, nurse, and other practitioners.</li><li><strong>Enhancing Quality and Patient Safety:</strong> A capability map can help understand areas where data and analytics can be applied to derive specific insights to enhance the quality of care and patient safety precautions administered to inpatient, outpatient, and remote patients. Based on such insights, digital health initiatives can be designed to enhance the monitoring of outcomes, comply with standards, and implement quality improvement initiatives.</li></ol><h4>Conclusion</h4><p>The following are the key takeaways:</p><ul><li>Digital health aims to amalgamate digital technologies with health, healthcare, living, and society to elevate healthcare delivery efficiency and enable personalized, precise, and affordable medicine.</li><li>Digital health and healthcare provider services are symbiotically related, as digital health technologies aim to enhance and optimize the delivery of healthcare services.</li><li>The healthcare provider landscape is a complex network of interconnected entities and processes that work together to deliver healthcare services.</li><li>Navigating the complexity of healthcare requires a deep understanding of healthcare processes, which is where a healthcare provider capability map becomes invaluable.</li><li>A business architecture-based capability map provides a structured framework for planning and implementing digital health initiatives, offering benefits such as gap identification, initiative prioritization, uncovering of touchpoints for enhancing patients’ and providers’ experience, and identification of opportunities for improving quality and patient safety.</li></ul><h4><em>Special Note</em></h4><p><strong><em>The author can share high-resolution versions of the images embedded in this write-up on request. Please send a direct message to the author with the requests.</em></strong></p><h3>References</h3><p>The Open Group. (2020, December 29). <em>Reference Architecture for Healthcare (RA4H) — Core Capabilities</em>. https://blog.opengroup.org/2020/12/29/reference-architecture-for-healthcare-ra4h-core-capabilities/</p><p>The Open Group. (2022, April). <em>Business Capabilities, Version 2</em>. https://pubs.opengroup.org/togaf-standard/business-architecture/business-capabilities.html</p><p>Rivas, H., &amp; Wac, K. (Eds.). (2018). <em>Digital Health</em> (1st ed.). Springer International Publishing AG. https://doi.org/10.1007/978-3-319-61446-5</p><p>Wager, K. A., Lee, F. W., &amp; Glaser, J. P. (2017). <em>Health Care Information Systems</em> (Fourth ed.). Jossey-Bass/Wiley.</p><p>World Health Organization. (2018). <em>Classification of Digital Health Interventions</em> [White paper]. <a href="https://www.who.int/publications/i/item/WHO-RHR-18.06">https://www.who.int/publications/i/item/WHO-RHR-18.06</a></p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>DDI Services: <a href="https://linktr.ee/datadriveninvestor">https://linktr.ee/datadriveninvestor</a></p><p>Featured Article:</p><p><a href="https://medium.datadriveninvestor.com/accelerating-success-through-the-singapore-fund-asset-management-platform-cbd393bf0e6a">Introducing Singapore’s Fund Platform</a></p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9db529bc4a5" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/unlocking-digital-health-success-leveraging-healthcare-provider-business-architecture-capability-b9db529bc4a5">Unlocking Digital Health Success: Leveraging Healthcare Provider Business Architecture Capability…</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Matrix and Vector Operations in Logistic Regression]]></title>
            <link>https://medium.com/data-science/matrix-and-vector-operations-in-logistic-regression-e35714c4810f?source=rss-2d02cbc7d153------2</link>
            <guid isPermaLink="false">https://medium.com/p/e35714c4810f</guid>
            <category><![CDATA[mathematical-intuition]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[vectorization]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[matrix-operations]]></category>
            <dc:creator><![CDATA[Murali Kashaboina]]></dc:creator>
            <pubDate>Fri, 07 Jul 2023 04:04:52 GMT</pubDate>
            <atom:updated>2023-07-07T20:49:45.677Z</atom:updated>
            <content:encoded><![CDATA[<h4>Vectorized Logistic Regression</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7bdlgzmt-ISTNA12" /><figcaption>Photo by <a href="https://unsplash.com/@fabioha?utm_source=medium&amp;utm_medium=referral">fabio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The underlying math behind any Artificial Neural Network (ANN) algorithm can be overwhelming to understand. Moreover, the matrix and vector operations used to represent feed-forward and back-propagation computations during batch training of the model can add to the comprehension overload. While succinct matrix and vector notations make sense, peeling through such notations down to subtle working details of such matrix operations would bring more clarity. I realized that the best way to understand such subtle details is to consider a bare minimum network model. I could not find a better algorithm than Logistic Regression to explore what goes under the hood because it has all the bells and whistles of ANN, such as multidimensional inputs, the network weights, the bias, forward propagation operations, activations that apply non-linear function, loss function, and gradients-based back-propagation. My intent for this blog is to share my notes and findings of the matrix and vector operations that are core to Logistic Regression model.</p><h4>Brief Synopsis of Logistic Regression</h4><p>Despite its name, Logistic Regression is a classification algorithm and not a regression algorithm. Typically it is used for binary classification to predict the probability of an instance belonging to one of two classes, for example, predicting if an email is spam or not. As such, in Logistic Regression, the dependent or target variable is considered a categorical variable. For example, an email being spam is represented as 1 and not spam as 0. The primary goal of the Logistic Regression model is to establish a relationship between the input variables (features) and the probability of the target variable. For example, given the characteristics of an email as a set of input features, a Logistic Regression model would find a relationship between such features and the probability of the email being spam. If ‘Y’ represents the output class, such as an email being spam, ‘X’ represents the input features, the probability can be designated as π = Pr( Y = 1 | X, βi), where βi represents the logistic regression parameters that include model weights ‘<em>wi</em>’ and a bias parameter ‘b’. Effectively, a Logistic Regression predicts the probability of Y = 1 given the input features and the model parameters. Specifically, the probability π is modeled as an S-Shaped logistic function called the Sigmoid function, given by π = e^z/(1 + e^z) or equivalently by π = 1/(1 + e^-z), where z = βi . X. The sigmoid function allows for a smooth curve bounded between 0 and 1, making it suitable for estimating probabilities. Essentially, a Logistic Regression model applies the sigmoid function on a linear combination of the input features to predict a probability between 0 and 1. A common approach to determining an instance’s output class is thresholding the predicted probability. For example, if the predicted probability is greater than or equal to 0.5, the instance is classified as belonging to class 1; otherwise, it is classified as class 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*LHx3F-KmcZ7bA9wwHmDOxA.png" /><figcaption>A Logistic Regression Model Schematic — Image Created by the Author</figcaption></figure><p>A Logistic Regression model is trained by fitting the model to the training data and then minimizing a loss function to adjust the model parameters. A loss function estimates the difference between the predicted and actual probabilities of the output class. The most common loss function used in training a Logistic Regression model is the Log Loss function, also known as Binary Cross Entropy Loss function. The formula for the Log Loss function is as follows:</p><p>L = — ( y * ln(p) + (1 — y) * ln(1 — p) )</p><p>Where:</p><ul><li>L represents the Log Loss.</li><li>y is the ground-truth binary label (0 or 1).</li><li>p is the predicted probability of the output class.</li></ul><p>A Logistic Regression model adjusts its parameters by minimizing the loss function using techniques such as gradient descent. Given a batch of input features and their ground-truth class labels, training of the model is carried out in several iterations, called epochs. In each epoch, the model carries forward propagation operations to estimate losses and backward propagation operations to minimize the loss function and adjust the parameters. All such operations in an epoch employ matrix and vector computations as illustrated in the next sections.</p><h4>Matrix and Vector Notations</h4><p><strong><em>Please note that</em></strong> <strong><em>I used LaTeX scripts to create the mathematical equations and matrix/vector representations embedded as images in this blog</em></strong>. If anyone is interested in the LaTeX scripts, don’t hesitate to contact me; I will be happy to share.</p><p>As shown in the schematic diagram above, a binary Logistic Regression classifier is used as an example to keep the illustrations simple. As shown below, a matrix X represents the ‘m’ number of input instances. Each input instance comprises an ’n’ number of features and is represented as a column, an input features vector, within the matrix X, making it a (n x m) sized matrix. The super-script (i) represents the ordinal number of the input vector in the matrix X. The sub-script ‘j’ represents the ordinal index of the feature within an input vector. The matrix Y of size (1 x m) captures the ground-truth labels corresponding to each input vector in the matrix X. The model weights are represented by a column vector W of size (n x 1) comprising ’n’ weight parameters corresponding to each feature in the input vector. While there is only one bias parameter ‘b’, for illustrating matrix/vector operations, a matrix B of size (1 x m) comprising ‘m’ number of the same bias b parameter is considered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*ChyFdHBgNomWs_ZyLqJShw.png" /></figure><h4>Forward Propagation</h4><p>The first step in the forward propagation operation is to compute a linear combination of model parameters and input features. The notation for such matrix operation is shown below where a new matrix Z is evaluated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/107/1*5Tno4Z1rdRPpmVhJghm8Kg.png" /></figure><p>Note the use of the transpose of weight matrix W. The above operation in the matrix expanded representation is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*GR0JTFnpcNtGrVaUHtPZew.png" /></figure><p>The above matrix operation results in the computation of matrix Z of size (1 x m) as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*EpHaosEcbooubLxJErMk_g.png" /></figure><p>The next step is to derive activations by applying the sigmoid function on the computed linear combinations for each input as shown in the following matrix operation. This results in an activation matrix A of size (1 x m).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*khYLhp8_aeb3AHfm3sH08A.png" /></figure><h4>Backward Propagation</h4><p>Backward propagation or back-propagation is a technique to compute the contributions of each parameter to the overall error or loss caused by incorrect predictions at the end of each epoch. The individual loss contributions are evaluated by computing the gradients of the loss function with respect to (w.r.t) each model parameter. A gradient or derivative of a function is the rate of change or the slope of that function w.r.t a parameter considering other parameters as constants. When evaluated for a specific parameter value or point, the sign of the gradient indicates in which direction the function increases, and the gradient magnitude indicates the steepness of the slope. The log loss function as shown below is a bowl-shaped convex function with one global minimum point. As such, in most cases, the gradient of the log loss function w.r.t a parameter points in the opposite direction to the global minima. Once gradients are evaluated, each parameter value is updated using the parameter’s gradient, typically by using a technique called gradient descent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*SmZI_cfE9WJ5LLv0bjAm7Q.png" /></figure><p>The gradient for each parameter is computed using the chain rule. The chain rule enables the computation of derivatives of functions that are composed of other functions. In the case of Logistic Regression, the log loss L is a function of activation ‘a’ and ground-truth label ‘y’, while ‘a’ itself is a sigmoid function of ‘z’ and ‘z’ is a linear function of weights ‘w’ and bias ‘b’ implying that the loss function L is a function composed of other functions as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*FhqMtUelUoI3usOSGyvvAg.png" /></figure><p>Using the chain rule of partial derivatives, the gradients of weight and bias parameters can be computed as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*CVKBGRLQskSrQQ-S-sBOXw.png" /></figure><p><strong>Derivation of Gradients for Single Input Instance</strong></p><p>Before we review the matrix and vector representations that come into play as part of updating the parameters in one shot, we will first derive the gradients using a single input instance to understand the basis for such representations better.</p><p>Assuming that ‘a’ and ‘z’ represent computed values for a single input instance with the ground-truth label ‘y’, the gradient of the loss function w.r.t ‘a’ can be derived as follows. Note that this gradient is the first quantity required to evaluate the chain rule to derive parameter gradients later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*IC-ieXt-a75WE_jOKJBAZA.png" /></figure><p>Given the gradient of loss function w.r.t ‘a’, the gradient of loss function w.r.t ‘z’ can be derived using the following chain rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/110/1*i8ImXPpZjM-MvtA_BDYZkg.png" /></figure><p>The above chain rule implies that the gradient of ‘a’ w.r.t ‘z’ must also be derived. Note that ‘a’ is computed by applying the sigmoid function on ‘z’. Therefore, the gradient of ‘a’ w.r.t ‘z’ can be derived by using the sigmoid function expression as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*K2_gpkVqLp1fSOVDeIyEeg.png" /></figure><p>The above derivation is expressed in terms of ‘e’, and it appears that additional computations are needed to evaluate the gradient of ‘a’ w.r.t ‘z’. We know that ‘a’ gets computed as part of forward propagation. Therefore to eliminate any additional computations, the above derivative can be fully expressed in terms of ‘a’ instead as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/1*ichRoOAnwOUn4Kp8rxo4iA.png" /></figure><p>Plugging in the above terms expressed in ‘a’, the gradient of ‘a’ w.r.t ‘z’ is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/1*JCBYRKNEtInc1nL1xar7Kg.png" /></figure><p>Now that we have the gradient of loss function w.r.t ‘a’ and the gradient of ‘a’ w.r.t ‘z’, the gradient of loss function w.r.t ‘z’ can be evaluated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*ayzaE-dY0QofkSTajuD0ZA.png" /></figure><p>We came a long way in evaluating the gradient of loss function w.r.t ‘z’. We still need to evaluate the gradients of loss function w.r.t model parameters. We know that ‘z’ is a linear combination of model parameters and features of an input instance ‘x’ as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*pPX7pDGrFHgytKLjPSNZag.png" /></figure><p>Using the chain rule the gradient of loss function w.r.t weight parameter ‘wi’ gets evaluated as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*5cWviNDMg13FHr9Cjl_SGQ.png" /></figure><p>Similarly, the gradient of the loss function w.r.t ‘b’ gets evaluated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*ONhbMhuIg15B_njmeqycZg.png" /></figure><p><strong>Matrix and Vector Representation of Parameter Updates using Gradients</strong></p><p>Now that we understand gradient formulas for model parameters derived using a single input instance, we can represent the formulas in matrix and vector forms accounting for the entire training batch. We will first vectorize gradients of the loss function w.r.t ‘z’ given by the following expression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/101/1*G3fuK5yAdVpRyeYlWH2T7g.png" /></figure><p>The vector form of the above for the entire ‘m’ number of instances is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*KRbYfV7-kxrduIuh-lIp_Q.png" /></figure><p>Similarly, the gradients of the loss function w.r.t each weight ‘wi’ can be vectorized. The gradient of the loss function w.r.t weight ‘wi’ for a single instance is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/131/1*unkh3PxyzQcikolhMXCKiQ.png" /></figure><p>The vector form of the above for all weights across all ‘m’ input instances is evaluated as the mean of ‘m’ gradients as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*CdrlprgPX6STVUe-zt8SjQ.png" /></figure><p>Similarly, the resultant gradient of loss function w.r.t ‘b’ across all ‘m’ input instances is computed as a mean of the individual instance gradients as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*eZaK49fmNeN5V7LAn4MLnQ.png" /></figure><p>Given the model weights gradient vector and the overall gradient for bias, the model parameters get updated as follows. The parameter updates as shown below are based on the technique called gradient descent where a learning rate is used. A learning rate is a hyper-parameter used in optimization techniques such as gradient descent to control the step size of adjustments made at each epoch to the model parameters based on computed gradients. Effectively, a learning rate acts as a scaling factor, influencing the speed and convergence of the optimization algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*fQ9ZHapbtsULnxL1EDMb0w.png" /></figure><h4>Conclusion</h4><p>As evident from the matrix and vector representations illustrated in this blog, Logistic Regression enables a bare minimum network model to understand the subtle working details of such matrix and vector operations. Most machine-learning libraries encapsulate such nitty-gritty mathematical details but instead expose well-defined programming interfaces at a higher level, such as forward or backward propagation. While understanding all such subtle details may not be required to develop models using such libraries, such details do shed light on the mathematical intuitions behind such algorithms. However, such understanding will certainly help carry forward the underlying mathematical intuitions to other models such as ANN, Recurrent Neural Networks (RNN), Convolutional Neural Networks (CNN), and Generative Adversarial Networks (GAN).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e35714c4810f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/matrix-and-vector-operations-in-logistic-regression-e35714c4810f">Matrix and Vector Operations in Logistic Regression</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[Use-Case-Driven Data Readiness as an Instrument to Manage and Control Data Quality]]></title>
            <link>https://medium.com/data-science/use-case-driven-data-readiness-as-an-instrument-to-manage-and-control-data-quality-a58a348d2ee6?source=rss-2d02cbc7d153------2</link>
            <guid isPermaLink="false">https://medium.com/p/a58a348d2ee6</guid>
            <category><![CDATA[data-quality-management]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[readiness-assessment]]></category>
            <category><![CDATA[use-cases]]></category>
            <dc:creator><![CDATA[Murali Kashaboina]]></dc:creator>
            <pubDate>Fri, 02 Dec 2022 14:06:14 GMT</pubDate>
            <atom:updated>2022-12-02T14:06:14.588Z</atom:updated>
            <content:encoded><![CDATA[<h4>A data readiness-based approach to addressing data quality</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JhQ42gzWokyy0zuP" /><figcaption>Photo by <a href="https://unsplash.com/@lazycreekimages?utm_source=medium&amp;utm_medium=referral">Michael Dziedzic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>TL;DR:</strong> <em>Data quality should be viewed through its readiness for specific consumption use cases. A data readiness approach is proposed to establish specific data consumption context through a specific use case to improve the data quality. Data readiness for a specific use case can be tested just like how software use case gets tested using various test-case scenarios. Similar to data dictionaries, a data readiness artifact must also be cataloged. It is no longer a cliched question of whether data is of the highest quality, but the question is for what use cases data is readied to enable data consumption.</em></p><h4>The Problem</h4><p>The issue of data quality has always been a hot topic that is debated widely. Evidently, data quality is not limited to one industry alone but is a problem prevalent across all sectors. I can easily imagine this topic being on the minds of every data officer, who eventually rushes to solve it. The general pattern is that everybody thinks everyone else is addressing it, so they rush to address it with a below-par success rate in most cases. The problem lies in rushing to address it. It is as if somebody drinks the cool-aid too fast, too early.</p><h4>Can time-tested software quality practices help?</h4><p>While data quality is a tormenting issue, it should be seen as something other than a standalone concern. It will be hard to rally around a cause to fix it if it is seen as a standalone problem. Conceivably approaches different from the incumbent ones should be incubated. Perhaps we can take a cue from how software quality typically gets addressed. Such well-established practices may shed some light here. Software quality is primarily addressed in terms of software’s readiness for consumption — functional and non-functional readiness of the software. Typically, use cases or user stories represent the functional requirements for software, and the software’s readiness is evaluated by validating if the software can meet such requirements. Likewise, user requirements such as response times and request processing throughput define the non-functional characteristics that get validated on the software. While not every software is perfect, such readiness assessment is a means to an end to ensure better quality. Effectively, functional and non-functional use cases drive a software’s readiness assessment. Therefore, readiness would reason the software’s state of quality by providing a consumption context, and people would rally around to fix the quality to improve the readiness.</p><p>A similar philosophy can be applied to data. As soon as data is looked through the lenses of a specific consumption use case, the consumption readiness of such data will become evident immediately. Poor data collection practices, missing data, inaccessible storage mechanisms, poor semantics and structures, lack of standards, lack of intellectual property rights, missing stewardship, unclear ownership, and limited security and privacy protections hinder the consumption readiness of data. Such issues hindering data readiness are also evident signs of poor data quality. Effectively, data readiness indicates how usable, complete, reliable, trustworthy, and meaningful the data is before insightful knowledge and intelligence can be extracted from it to support specific use cases.</p><h4>Proposed Approach</h4><p>The proposal is to leverage the data readiness approach to establish specific data consumption context through a specific use case to improve the data quality. Data readiness for a specific use case can be tested just like how software use case gets tested using various test-case scenarios. Such an approach also promotes concepts such as data-product, data-as-a-feature, and data-as-a-product — the concepts the data-mesh aficionados would love.</p><p>However, there is a caveat. Data readiness for one use case may not meet the needs of another. Therefore, it is crucial to build data readiness incrementally, covering all the potential use cases in a given business domain. When new use cases are discovered, it becomes critical to re-assess the data readiness for new and existing use cases collectively. Such re-assessment is akin to regression testing of the software when new features are added, or existing features are updated.</p><p>The data readiness assessment for a specific use case spans the entire data life-cycle addressing use case requirements from the data creation through data processing operations employed during the data preparation, cleaning, transformation, standardization, canonicalization, and storage. This is again similar to how software gets tested end-to-end to ensure readiness at each component/sub-system in the path to meet specific use case requirements.</p><h4>Cataloging Data Readiness Information</h4><p>Just like meta-data, such as data dictionaries, are cataloged, a data readiness artifact must also be cataloged. A data readiness artifact should capture the use cases supported and readiness assessment results for each use case. The data readiness artifact can serve as an authentic information source highlighting data quality operations performed and how such operations ensured the data quality, meeting specific use case requirements. The data readiness artifact will become a record of truth controlled by the corresponding data steward. Such information could reduce repetitive data exploration and analysis, enable easy data auditing, and increase data accountability and trustworthiness. Essentially, it is another way of effectuating data stewardship.</p><h4>Final Remark</h4><p>Effectively, it is no longer a cliched question of whether data is of the highest quality, but the question is for what use cases data is readied to enable data consumption. The proposed data readiness-driven approach changes the dialog among the stakeholders and sheds a new perspective on how data is viewed and how data quality is managed.</p><h4>References</h4><p>Afzal, S., Rajmohan, C., Kesarwani, M., Mehta, S., &amp; Patel, H. (2021). Data readiness report. <em>2021 IEEE International Conference on Smart Data Services (SMDS)</em>, 42–51. <a href="https://doi.org/10.1109/SMDS53860.2021.00016">https://doi.org/10.1109/SMDS53860.2021.00016</a></p><p>Cheng, G., Li, Y., Gao, Z., &amp; Liu, X. (2017). Cloud data governance maturity model. <em>2017 8th IEEE International Conference on Software Engineering and Service Science (ICSESS)</em>, 517–520. <a href="https://doi.org/10.1109/ICSESS.2017.8342968">https://doi.org/10.1109/ICSESS.2017.8342968</a></p><p>Lawrence, N. D. (2017). Data readiness levels. <em>Cornell University ArXiv Computer Science Database</em>. <a href="https://doi.org/10.48550/arXiv.1705.02245">https://doi.org/10.48550/arXiv.1705.02245</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a58a348d2ee6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/use-case-driven-data-readiness-as-an-instrument-to-manage-and-control-data-quality-a58a348d2ee6">Use-Case-Driven Data Readiness as an Instrument to Manage and Control Data Quality</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[Measuring the Cognitive Overload Factor of a Data Visualization]]></title>
            <link>https://medium.com/data-science/measuring-the-cognitive-overload-factor-of-a-data-visualization-65b0ce56254b?source=rss-2d02cbc7d153------2</link>
            <guid isPermaLink="false">https://medium.com/p/65b0ce56254b</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[cognitive-overload]]></category>
            <category><![CDATA[data-storytelling]]></category>
            <category><![CDATA[cognition]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Murali Kashaboina]]></dc:creator>
            <pubDate>Tue, 22 Nov 2022 06:43:25 GMT</pubDate>
            <atom:updated>2022-11-22T06:43:25.005Z</atom:updated>
            <content:encoded><![CDATA[<h4>A simple empirical method to compute COF, illustrated</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_SJp9oopJ58gUerEYB9FA.jpeg" /><figcaption>Photo By <a href="https://unsplash.com/@thisisengineering?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">ThisisEngineering RAEng</a> on <a href="https://unsplash.com/s/photos/data-visualization?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><strong>TL;DR:</strong> <em>An empirical method to compute the cognitive overload factor of data visualization using an evaluation rubric is proposed. The evaluation criteria and scoring method used by the rubric are explained. An example data visualization is used to demonstrate the method. Further extensions and customization of the evaluation rubric are recommended.</em></p><h4>Data Visualization</h4><p>Data visualization transforms raw data into visual representations such as graphs and charts to effectively communicate the information of interest to the target audiences, which otherwise would be hard to interpret directly from the raw data. Representing raw data in visual forms narrates a story to target audiences through data findings, summarized data views, synthesized information, quantitative and qualitative trends, and other patterns mined from the data.</p><p>One crucial aspect of compelling storytelling is a reduction of cognitive overload. Cognitive overload occurs when the volume of information supply exceeds the information processing capacity of an individual. Essentially, cognitive overload happens when the information presented triggers excessive thinking on the part of the individual trying to synthesize and comprehend the information. Such overburdening of mental capacities would lead to severe discomfort, frustration, and inefficient decision-making. What matters most is how easy or hard it is for the target audiences to process the visual information cognitively to comprehend it. The presence of clutter in the visual, the inability of the visual to present the intended information clearly, the lack of well-designed aesthetics, and other visual deficiencies can cause significant cognitive overload for the consumer defeating the purpose of visualization.</p><h4><strong>Primary Challenge</strong></h4><p>The primary challenge is a lack of cognitive quality measurement of visualized data. Such lack of an objective method adds subjectivity in interpreting cognitive quality because the perceived cognitive overload differs significantly from one individual to another.</p><h4><strong>Proposed Approach</strong></h4><p>The proposed approach is an empirical method using a simple evaluation rubric to compute the cognitive overload quantitatively. The consequent empirical cognitive overload factor (COF) is a numeric value on a ratio scale between 0 and 1.</p><h4>Evaluation Rubric</h4><p>A rubric is an assessment and scoring tool that defines specific evaluation criteria, markers to measure the levels to which the evaluation criteria are met, and scoring scales to grade the measuring markers. A rubric is a reliable tool for assessing an object of interest using specific and highly relevant evaluation criteria. Therefore, the evaluation criteria in a rubric are critical to the effectiveness of the use of the rubric.</p><p>The developed rubric contains nine evaluative criteria across the rows and five measuring markers across the columns, forming a 9x5 evaluation grid. The five-column markers measure if an evaluation criterion meets the expectations — not addressed, does not meet expectations, approaches expectations, meets expectations, and exceeds expectations. Each evaluation marker is assigned a score on a 4-point scale. A score of 0 is assigned to ‘not addressed,’ a score of 1 to ‘does not meet expectations,’ a score of 2 to ‘approaches expectations,’ 3 to ‘meets expectations,’ and a score of 4 to ‘exceeds expectations.’ The explanations of each measurement marker applied to each evaluation criterion are defined in the rubric’s corresponding cells, as shown in Figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bHFve7wZBY8MsujV0GdyxQ.png" /><figcaption><em>Figure 1: A Rubric for Evaluating Cognitive Overload Factor of Data Visualizations</em></figcaption></figure><h4>Evaluation Criteria</h4><p>The nine main criteria, as shown in the first column in Figure 1, help evaluate a data visualization output on the Gestalt Principles of visual perception: similarity, proximity, closure, enclosure, connection, continuity, the presence of clutter in the visual, ability of the visual to present the intended information clearly, and the design aesthetics of the visual representation.</p><p><strong><em>Gestalt Similarity Principle Criterion</em></strong><br>The Gestalt Similarity Principle criterion assesses if the visualization groups similar elements using similar sizes, shapes, and colors. Such grouping of similar elements helps humans easily identify the similarities and differences in visual representations.</p><p><strong><em>Gestalt Proximity Principle Criterion</em></strong><br>The Gestalt Proximity Principle criterion assesses if the visual presents the same group elements closer to each other. Such proximity helps humans classify elements closer together as belonging to the same group.</p><p><strong><em>Gestalt Closure Principle Criterion</em></strong><br>The Gestalt Closure Principle criterion evaluates if the elements of the visual are presented using full shapes. Past studies have shown that humans prefer complete shapes to comprehend an element. If the element is represented using incomplete shapes, humans tend to fill the gaps to interpret the element causing unexpected cognitive overload.</p><p><strong><em>Gestalt Enclosure Principle Criterion</em></strong><br>The Gestalt Enclosure Principle criterion assesses if the visual presents elements of the same group enclosed or bound together. Such enclosures help humans easily perceive elements belonging together, easing cognitive comprehension.</p><p><strong><em>Gestalt Connection Principle Criterion</em></strong><br>The Gestalt Connection Principle criterion evaluates if the visual presents elements of the same group connected together. Such connections help human audiences easily classify elements belonging to the same group.</p><p><strong><em>Gestalt Continuity Principle Criterion</em></strong><br>The Gestalt Continuity Principle criterion evaluates if the elements in the visual form a complete image when they appear to be a continuation of the others. Such visualization helps human audiences perceive the complete image formed from continuous elements. Any discontinuity results in humans trying to complete the image, causing unwanted cognitive overload.</p><p><strong><em>Presence of Clutter Criterion</em></strong><br>This criterion evaluates if the visual is too cluttered. The visual can become cluttered because of unnecessary chart borders, grid-lines, data labels, markers, noisy axis labels, inconsistent color schemes, etc. Clutter causes cognitive overload and distracts the audience from the primary information.</p><p><strong><em>Clear Communication of Intended Information</em></strong><br>This critical criterion evaluates if the visualization presents data by highlighting the important content, reducing the noise and eliminating distractions, and creating a clear hierarchy of information flow.</p><p>Furthermore, the visual should address the primary information topic’s ‘who,’ ‘what,’ and ‘how’ attributes. The ‘who’ attribute helps identify the target audience early in the process and helps understand the specific needs of those target audiences that data visualization should address. The narrower the target audience, the more specific and compelling the narrated data story can be. The ‘what’ attribute helps understand what information the target audience expects and what actions and decisions are expected from the target audience through the visualized data. Such a ‘what’ aspect helps realize the true purpose of visualizing data in tune with the target audience’s expectations. The ‘how’ attribute helps address how the available data will be processed and transformed to highlight the points of interest for the audiences through the data visualization.</p><p><strong><em>Overall Aesthetics Criterion</em></strong><br>The Overall Aesthetics criterion evaluates the thoughtful use of color schemes, consistent vertical and horizontal alignment of elements, and optimal use of white spaces not to clutter with noisy information. Aesthetically designed visuals can have a pleasing impact on the target audiences reducing cognitive overload.</p><h4>Cognitive Overload Factor (COF)</h4><p>The COF of data visualization can be calculated based on its secured total score (S) on the rubric. The maximum score any data visualization can secure is 36. The proposed empirical formula for COF is:</p><pre>COF = 1 - (Secured Total Score/Maximum Score) =&gt; 1 - (S/36)</pre><p>A COF close to 0 implies negligible cognitive overload. A COF close to 1 indicates the worst cognitive overload. A COF of about 0.3 could be optimal since cognitive overload may not be eliminated entirely. Further experimental evaluations are needed to determine a more accurate optimal COF.</p><h4>COF Evaluators</h4><p>It is recommended that the COF of a data visualization be evaluated by its specific target audiences or consumers. Target audiences are better suited because they know the visualization’s ‘who,’ ‘what,’ and ‘how’ attributes and the overall visualization context. Individuals from the target group can evaluate COF independently, and an average of all the evaluated values can be considered an estimated COF.</p><h4>Example Evaluation</h4><p>Figure 2 shows an example data visualization output comparing the monthly and yearly temperatures in Chicago, Illinois. The visualization has two sections. The first section is a bubble-chart showing months with highest average temperatures in year 2019. The second section is a heat-map showing months with highest temperatures recorded in years between 2009 and 2019.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4kzYJatqsRJKn0TUTT174A.png" /><figcaption>Figure 2: Comparison of Monthly and Yearly Temperatures in Chicago, Illinois</figcaption></figure><p>Evidently, the target audiences of the example visualization are data scientists who are specifically interested in Chicago’s historical temperatures. They own specific contexts for such temperature information and therefore, are well-suited to evaluate the COF of the example data visualization more effectively.</p><p><strong><em>Evaluation Using the Rubric</em></strong><br>A data scientist who belongs to the target audience group could use the rubric to score the above clustering visualization, as shown in Figure 3. The hypothetical total score evaluated by such a data scientist is 23. Likewise, other data scientists’ hypothetical scores could be 18, 27, 21, 24, and 20. The average score is 22.17. Therefore, the estimated COF using the empirical formula is 0.3843, implying that cognitive overload is close to optimal and the visualization can be enhanced to improve the COF further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*OEDyj3TJp1Y2DxaSoUCtOw.png" /><figcaption>Figure 3: Hypothetical Evaluation By A Medical Data Scientist</figcaption></figure><h4>Recommendations</h4><p>The COF evaluation rubric suggested in this article used the Gestalt Principles of visual perception, the presence of clutter in the visual, the ability of the visual to present the intended information clearly, and the design aesthetics of the visual representation. The rubric formed a simple 9x5 evaluation grid with nine evaluation criteria across the rows and five measuring markers across the columns. The scoring method was intentionally kept simple to help frame a COF quantification model and demonstrate the concept. It is recommended that interested readers extend this model further with additional finer criteria and customize it based on specific needs.</p><h4>References</h4><p>Best practices for data analytics reporting lifecycles: Quality in report building and data validation. (2018). <em>Journal of AHIMA</em>, <em>89</em>(9), 40–45.</p><p>Carter, M. (2013). <em>Designing science presentations: A visual guide to figures, papers, slides, posters, and more</em>. Elsevier Science &amp; Technology.</p><p>Knaflic, C. N. (2015). <em>Storytelling with data : A data visualization guide for business professionals</em>. Wiley.</p><p>Vetter, T. R. (2017). Descriptive statistics: Reporting the answers to the 5 basic questions of who, what, why, when, where, and a sixth, so what? <em>National Library of Medicine</em>, <em>125</em>(5), 1797–1802.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65b0ce56254b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/measuring-the-cognitive-overload-factor-of-a-data-visualization-65b0ce56254b">Measuring the Cognitive Overload Factor of a Data Visualization</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[Predictive Analytics — Model Predictions And Their Interpretability Challenges]]></title>
            <link>https://medium.com/data-science/predictive-analytics-model-predictions-and-their-interpretability-challenges-acbb8ff44b3f?source=rss-2d02cbc7d153------2</link>
            <guid isPermaLink="false">https://medium.com/p/acbb8ff44b3f</guid>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[model-interpretability]]></category>
            <category><![CDATA[black-box-models]]></category>
            <category><![CDATA[white-box-model]]></category>
            <category><![CDATA[model-interpretation]]></category>
            <dc:creator><![CDATA[Murali Kashaboina]]></dc:creator>
            <pubDate>Sat, 26 Jun 2021 16:45:11 GMT</pubDate>
            <atom:updated>2021-06-26T16:45:11.860Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Predictive Analytics — Model Predictions And Their Interpretability Challenges</strong></h3><h4>The critical role model interpretability plays in model selection</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPZap7X4nhqiLrkQZe-6wQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@franki?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Franki Chamaki</a> on <a href="https://unsplash.com/s/photos/machine-learning?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Humans justify their decisions supported by reasoning. Such reasoning helps discern the decision and repose confidence in it. Sometimes such reasoning logic may not be straightforward but can be laced with anecdotal citations, preconceived intuitions, hypothetical assumptions, and axiomatic intellections. However, as long as such judgment is convincing enough to induce confidence, such decisions are generally acceptable. While the reason may not be straightforward, the extent to which any causality is accounted for, any associations are made with similar events, or the relationships between the underlying factors/circumstances are established would lead to a higher degree of confidence in such decisions. Essentially, this is like trusting the gut to trust the judgment. For example, a patient trusts a treatment plan based on a physician’s prognosis of the ailment, explanation of the diagnosis, experienced-based reasoning, and quoting of comparable example cases.</p><p>Similar reasoning is expected when predictive models predict an outcome or make a decision. However, there are critical differences. While several causal, circumstantial, axiomatic, and correlated factors can substantiate human reasoning, the only factors that can ratify predictive outcomes are the example observations, feature characteristics, and the algorithms used to train the predictive models. Such limitations pose challenges to the explicability or interpretability of the predictive models.</p><h3>Interpretability</h3><p>Before getting into the meat of the discussion, it is essential to understand what interpretability means in the context of model predictions. There is no industry-agreed definition for model interpretability. However, interpretability can be characterized through the following:</p><ol><li>Algorithm clarity: This pertains to a comprehensive understanding of how the algorithm works internally, what mathematical intuitions get applied, what computations get executed to process and optimize the inputs, how the processed inputs get mapped to predicted output, and how the algorithm works to ensure accuracy of predictions.</li><li>Model deconstructability: This implies the ability to break apart the model into granular model units or constructs that explain the partial reasons for the model prediction. For example, a decision node that checks if an applicant’s credit score is greater than a threshold in a decision tree for loan approval. Another example is a hidden node in a neural network that assigns a weight to a specific input variable.</li><li>Model synthesizability: This implies the ability to walk through every computation using model parameters and the input data manually within a humanly acceptable time frame to derive the model predicted output. Walking through each step in a hierarchical linear model to explain both fixed effects and random effects on the predicted outcome is an example of model synthesizability.</li><li>Post hoc explainability: This complements all of the above to reinforce the prediction reasoning further. While post hoc explainability does not strictly rely on the internal working of the model algorithm, it complements by providing additional supporting information. Post hoc may employ other utility models to support the reasoning. For an input image, presenting similar images using a k-nearest-neighbor model to justify why a deep-learning image-classification model predicted a specific class is an example of post hoc explainability. Similarly, post hoc may employ model visualizations and other instance-based illustrations to explain the predictions further.</li></ol><p>As can be inferred from the above, the computational complexity and the model architecture considerably impact the model interpretability. While computational complexity impacts algorithm clarity and model synthesizability, the complexity of the model architecture impacts model deconstructability. Based on the extent of interpretability, the predictive models can be categorized as black-box or white-box models.</p><h3>Black-Box vs. White-Box Models</h3><p>Predictive analytics predominantly solve two broad types of prediction problems — Classification and Regression. In classification, a predictive model would predict a distinct class label as output based on the input variables. In the case of regression, a predictive model would predict a quantitative output such as the price of a product based on the input variables. The primacy on which predictive models are categorized as either black-box or white-box is to do with the model behavior explainability and the interpretability of model results.</p><h4>Black-Box Models</h4><p>Black-box predictive models predict outputs given a set of input data. While the relationships between input and output variables are observable from the training dataset, the black-box models either lack the model results interpretability or do not offer a straightforward way to reason why and how the model predicted a particular output. There are two primary reasons for the lack of interpretability. The first reason is that the underlying algorithm is highly sophisticated with complex mathematical computations. Therefore, it is difficult for even seasoned practitioners to comprehend the model working mathematically and translate it into reasoning to support model predictions. The second reason is that while the model’s inner computations are easy to understand, the model setup and architecture become complex at the time of training, where the input data are subjected to several operations and undergo complex transformations. As such, while the underlying superficial working of the algorithm can be explained, it becomes hard to reason a prediction based on all the computations and transformations that input data are subjected to during the processing. Most models with algorithms that leverage complex hyperplanes in multi-dimensional vector spaces, algorithms that leverage complex probability networks, and algorithms that leverage ensembles of sub-models typically fall under the category of black-box models. However, the accuracy of a model increases with the increase in model complexity. Consequently, black-box models generally yield more accurate predictions but at the cost of model interpretability.</p><h4>White-Box Models</h4><p>Similar to black-box models, the white-box models predict outputs given a set of inputs. However, white-box models enable interpretability of the relationships between the input and output variables in the training dataset and make it easy to establish similar relationships between the predicted outputs and the given input data. Predictive models that leverage rules-based algorithms, decision trees, decision tables, pattern matching, and algorithms that learn from training instances typically fall under the category of white-box solutions. Such algorithms provide clarity through their inner working and explainability by reasoning how and why the model predicted a particular output. However, the white-box solutions may not provide the level of accuracy that the black-box solutions may provide for complex problem scenarios. Nonetheless, in some cases, the architecture complexity of a white-box model can be upped to increase the model accuracy but at the cost of the model losing the model interpretability. In such scenarios, a white-box model may turn into more of a black-box model. Effectively, one of the key drivers for choosing between the black-box and the white-box models can be a trade-off between accuracy and interpretability.</p><h3>Functional Types of Models</h3><p>The functional categorization of the model types also helps to understand how interpretability varies in different model types. The functional types of predictive models can be broadly categorized as follows:</p><h4>Hyperplane Based Models</h4><p>These models leverage algorithms that fit hyperplane or hyperplanes in a multi-dimensional vector space using the training data. The fitted hyperplanes separate the classes of the output variables in the high-dimensional vector space. Given input data, the model processes the inputs by applying required transformations. The transformed input vector in the multi-dimensional space can help the model determine which side of the hyperplanes the input vector lies in and select the output class the input vector most likely belongs to. Such models fall under the category of black-box solutions since they implement sophisticated mathematical computations that are hard to explain the reasons for the model predictions. Artificial Neural Networks (ANN), Convolutional Neural Networks (CNN), Recurrent Neural Networks (RNN), Support Vector Machines (SVM), Kernel methods, etc., are examples of hyperplane-based models.</p><h4>Ensembles with Sub-Models</h4><p>Ensemble models employ multiple sub-models, in most cases weak sub-models, to improve the accuracy based on the voting or averaging of the predictions made by the sub-models. They use either boosting or bagging techniques to train each of the sub-models. The sub-models learn from the training data either independently or based on the results from the previous sub-model. As such, the ensemble results in a complex decision hierarchy that is hard to explain a predicted output given input data. Therefore, such ensemble models fall under the category of black-box solutions. Random Forest (RF), Extreme Gradient Boosting (XGBoost), Adaptive Boosting (AdaBoost), Bayesian Adaptive Sampling (BAS), etc., are examples of ensemble algorithms.</p><h4>Probability Network Models</h4><p>The underlying algorithm builds a complex acyclic directed graph of feature and output nodes in probability network models. Each node maintains the knowledge of all combined conditional probabilities of the prior nodes that connect to it. Essentially, the model picks the output node value as the prediction for which the conditional probability evaluated based on all the previous nodes that the model traverses through is maximum. While the theory of probability such models employ is easy to understand, in real-world cases, the models build a complex graph of nodes with different feature nodes that are computed internally. Therefore it becomes super hard to walk through the model and explain why and how it predicted a particular output. Hence such models fall under the category of black-box solutions. Markov Networks and Bayesian Networks are examples of such models.</p><h4>Rules-Driven, Patterns-Based, Decision Tree-Like Models</h4><p>In the case of rules-driven, or patterns-based, or decision tree-like models, the premise of outputs in conjunction with the inputs is well-known and well-understood before developing the predictive models. Such predictive models are developed even after understanding such premise because while the permutations and combinations of such rules and patterns are finite, they are challenging to manage. The model bears the responsibility of such heavy-lifting once the model learns from the training dataset. Because the model makes a prediction based on a particular pattern or a rule-set or by traversing a decision tree, it is easy to interpret the prediction based on the intermediate decisions that the model had to make considering each input variable. Therefore such models typically fall under the category of white-box solution. However, if the rule-sets become too hierarchical or if the decision tree becomes too deep and nested, the interpretability may take a hit because the resulting convoluted decision hierarchy may be too challenging to explain. In such cases, the model turns into a black-box solution.</p><h4>Linear Models</h4><p>The linear models establish linear relationships between the input and output variables. The strength of such relationships is estimated in the form of linear coefficients that act as the model parameters. The quantified estimates of the parameters help determine the importance of each input feature relative to the output variable and help explain why and how the model predicted an output based on the given input data. As such, the linear models typically fall under the category of white-box solutions. However, if the linear model has high dimensional input space or if several computationally engineered variables or dummy variables are appended at the model development time, the linear model may lose its interpretability. Linear Regression and Logistic Regression are examples of such linear models.</p><h4>Instance-Based Models</h4><p>In the case of instance-based models, the algorithm makes a prediction based on localized approximations between the given input data and the past instances from the training data that exhibit similar characteristics based on a specified target function and then employing a strategy to determine the realm of the locality to select the instances. Once the local instances that are functionally similar to the given input are chosen, the algorithm picks the prediction based on voting or averaging. Because the prediction is based on local approximations using similar instances, the model exhibits a high degree of interpretability. Effectively, the characteristics of the similar instances chosen locally can explain the model’s predictive behavior. As such, instance-based models typically fall under the category of white-box solutions. K-Nearest Neighbor (kNN), Self-Organizing Maps (SOM), etc., are examples of instance-based models.</p><h3>Model Selection</h3><p>The determination of what model solution is most appropriate depends on several factors that include factors outside of the realm of the underlying algorithm subject matter and technicalities. For example, black-box solutions would be right where the model predictions are expected to be accurate but are understood to be beyond human discernability. In such cases, the model performs complex operations to establish relationships between the input and output variables that are incomprehensible to human understanding. For example, the prediction of traffic volumes at critical road intersections in connected vehicles use case. In such a case, the model may need to use data from roadside sensors, data about nearby accidents or road repairs, traffic peak hours, etc., to predict traffic volumes accurately. The use of complex algorithms such as Artificial Neural Networks (ANN) or Support Vector Regressions (SVR), or Extreme Gradient Boosting (XGBoost) is warranted because:</p><ol><li>The solution intends to predict traffic volume to prevent any road accidents.</li><li>There are no preset patterns to establish rules to prescribe what combinations of different inputs would determine the estimate of the traffic volume. The number of permutations and combinations would proliferate beyond what humans can comprehend.</li><li>The model predictions can be easily correlated to those that humans could predict, and therefore the model results can be validated.</li></ol><p>Likewise, there are scenarios where it becomes mandatory to employ white-box solutions. For example, the cases where reasoning and causality take precedence because the underlying problem domain mandates such reasoning for predictions, or compliance regulations enforce such a reasoning requirement. For example, the United States Equal Credit Opportunity Act deems it illegal to deny a bank loan to an applicant where the reasons are vague or unjustifiable. As such, the financial institution may have to employ a white-box model that can classify and, at the same time, provide a straightforward way to explain the satisfactory reasons behind the predicted decisions. Similarly, in healthcare and medicine, where decisions need justifiable reasoning and causality attribution, it may become critical to employ white-box solutions for making medicinal predictions. In all such scenarios, it is no longer the pure accuracy of the prediction that matters, but interpretability becomes critical. Therefore the selected model should be based on the compromises between the two concerns. In some other scenarios, the model simplicity may drive the selection of more straightforward white-box solutions.</p><p>Nevertheless, some situations can leverage a combination of black-box and white-box models to develop predictive analytics solutions. In such cases, the black-box model is employed to make primary predictions, but post-hoc white-box models complement the predictions’ interpretability. For example, the interpretability of a CNN model for image classification will be hard because CNN employs complex convolutional operations, image filters, and transformations that lack discernability through human explanations. However, a separate, simpler white-box model such as a decision tree or a clustering model can be developed using the complex features extracted for each training image by the CNN. Such a white-box model can then match similar images from the training data to enable post-hoc reasoning and interpretability.</p><h3>Conclusion</h3><p>Human understandable reasoning is expected when predictive models predict an outcome or make a decision. The only constituents that can substantiate the explainability of predicted results are the example observations, feature characteristics, and the algorithms used to train the predictive models. Such limitations pose challenges to the interpretability of the predictive models. While there is no standard definition for model interpretability, the underlying algorithm clarity, the model deconstructability, the model synthesizability, and the post hoc explainability characterize the overall model interpretability.</p><p>Based on the extent of interpretability, the predictive models can be categorized as black-box or white-box models. Black-box models lack the model results interpretability or a straightforward way to reason why and how the model predicted a particular output. In contrast, white-box models enable the interpretability of the relationships between the input and output variables in the training dataset and make it easy to establish similar relationships between the predicted outputs and the given input data. Models with algorithms that leverage complex hyperplanes in multi-dimensional vector spaces, algorithms that leverage complex probability networks, and algorithms that leverage ensembles of sub-models typically fall under the category of black-box models. Models that leverage rules-based algorithms, decision trees, decision tables, pattern matching, and algorithms that learn from training instances typically fall under the category of white-box solutions.</p><p>The determination of what model solution is most appropriate depends on several factors that include factors outside of the realm of the underlying algorithm subject matter and technicalities. Black-box solutions would be right where the model predictions are expected to be accurate but are understood to be beyond human discernability. Use cases where reasoning and causality take precedence because the underlying problem domain mandates such reasoning for predictions, or compliance regulations enforce such a reasoning requirement warranty using white-box models. Some use cases leverage a combination of black-box and white-box models to develop predictive analytics solutions. In such cases, the black-box model is typically employed to make primary predictions with greater accuracy, and white-box models complement the predictions’ post hoc interpretability.</p><p>Since the accuracy of a model increases with the increase in model complexity, black-box models generally yield more accurate predictions but at the cost of model interpretability. Effectively, one of the key drivers for choosing between the black-box and the white-box models can be a trade-off between accuracy and interpretability. As such, it is imperative that the data scientists and machine learning experts first understand the problem domain, its objectives, and the underlying compliance and reasoning requirements before determining the choice of model algorithms to develop predictive analytics solutions. Model interpretability becomes crucial to meet all such mandatory requirements while balancing the model accuracy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acbb8ff44b3f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/predictive-analytics-model-predictions-and-their-interpretability-challenges-acbb8ff44b3f">Predictive Analytics — Model Predictions And Their Interpretability Challenges</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>