<?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 Prarthana Saikia on Medium]]></title>
        <description><![CDATA[Stories by Prarthana Saikia on Medium]]></description>
        <link>https://medium.com/@prarthana1?source=rss-fc8189b84ee9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*nSJ3Z4WjJBVoVfSE</url>
            <title>Stories by Prarthana Saikia on Medium</title>
            <link>https://medium.com/@prarthana1?source=rss-fc8189b84ee9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:23:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prarthana1/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[LLM Agent Trajectory Evaluation with LangSmith]]></title>
            <link>https://medium.com/@prarthana1/llm-agent-trajectory-evaluation-with-langsmith-7a3e25aa3400?source=rss-fc8189b84ee9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a3e25aa3400</guid>
            <dc:creator><![CDATA[Prarthana Saikia]]></dc:creator>
            <pubDate>Sat, 01 Mar 2025 07:44:05 GMT</pubDate>
            <atom:updated>2025-03-01T07:44:05.553Z</atom:updated>
            <content:encoded><![CDATA[<p>LLM agents involve LLM applications that can execute complex tasks through the use of an architecture that combines LLMs with key modules like planning and memory. When building LLM agents, an LLM serves as the main controller or “brain” that controls a flow of operations needed to complete a task or user request. The LLM agent may require key modules such as planning, memory, and tool usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/0*COec1sswbhoYvADt" /><figcaption>Diagrammatic Representation of a LLM Agent</figcaption></figure><p>LLM agent evaluation is crucial because it allows developers to assess the performance, accuracy, and reliability of a large language model (LLM) agent, ensuring it functions as intended, produces safe and relevant outputs, and can be effectively deployed in real-world applications, while identifying potential issues like bias, factual errors, or inappropriate responses that need to be addressed through further development and refinement.</p><p>There are three types of agent evaluations that users are often interested in:</p><ul><li>Final Response: Evaluate the agent&#39;s final response.</li><li>Single step: Evaluate any agent step in isolation (e.g., whether it selects the appropriate tool).</li><li>Trajectory: Evaluate whether the agent took the expected path (e.g., of tool calls) to arrive at the final answer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*64WKyEa1TStLb6wB.png" /></figure><p>We will focus on evaluating the agent&#39;s trajectory in this article.</p><p>Evaluating an agent’s trajectory involves evaluating all the steps an agent took.</p><p>The inputs are the inputs to the overall agent .(the user input, and optionally a list of tools).</p><p>The outputs are a list of tool calls, which can be formulated as an “exact” trajectory (e.g., an expected sequence of tool calls) or simply a set of tool calls that are expected (in any order).</p><p>The evaluator here is some function over the steps taken. Assessing the “exact” trajectory can use a single binary score that confirms an exact match for each tool name in the sequence.</p><p>Here, we have defined 3 tools for the agent:</p><ol><li>check_inventory which checks if the requested item and quantity is available</li><li>generate_invoice which generates an invoice for the order.</li><li>confirm_order to finalize the order.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*zRwsp2rxP3atkBU-ishnQg.png" /></figure><p>We create a function to check if the tool calls are happening in the exact order in that particular run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*feEhQB9wDbkqKspMqQYbOQ.png" /></figure><p>Now we call the evaluate function and pass the required parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*rmF_yrxqtVW8HtloqJFCsw.png" /></figure><p>These results can be tracked in LangSmith for further analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Yw5ap0LSH8JxhVpfo58z0g.png" /></figure><p><strong>References:</strong></p><ol><li><a href="https://www.promptingguide.ai/research/llm-agents">https://www.promptingguide.ai/research/llm-agents</a></li><li><a href="https://docs.smith.langchain.com/old/evaluation/quickstart">https://docs.smith.langchain.com/old/evaluation/quickstart</a></li><li><a href="https://docs.smith.langchain.com/evaluation/concepts">https://docs.smith.langchain.com/evaluation/concepts</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a3e25aa3400" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving into Microsoft Semantic Kernel]]></title>
            <link>https://medium.com/@prarthana1/diving-into-microsoft-semantic-kernel-82e037fe427c?source=rss-fc8189b84ee9------2</link>
            <guid isPermaLink="false">https://medium.com/p/82e037fe427c</guid>
            <dc:creator><![CDATA[Prarthana Saikia]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 07:15:13 GMT</pubDate>
            <atom:updated>2024-03-21T07:23:52.059Z</atom:updated>
            <content:encoded><![CDATA[<p>Semantic Kernel is an open-source SDK from Microsoft whose primary purpose is to facilitate the integration of Large Language Models(LLMs) into applications. It is an alternative to the open-source <a href="https://www.langchain.com/">LangChain</a> though both of them have their own advantages and disadvantages.</p><p>It is closely integrated with Azure, and solutions like Microsoft Graph and Azure Cognitive Search leverage Semantic Kernel for enhanced AI capabilities.</p><p>While LangChain revolves around creating sequences of calls known as “Chains”, SK employs a “Kernel” to manage these sequences and has a “Planner” to auto-create chains for new user needs.</p><p>SK is made up of three core building blocks: plugins, planners, and its persona.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tUZ5sZpOB_p85nWFOn_3Aw@2x.jpeg" /></figure><p>Source Semantic Kernel GitHub repository</p><p>With SK, we can define Plugins that drive the semantic hardware in certain ways and maintain collections of Plugins that can be automatically selected by SK’s Planner if a task requires multiple steps for successful completion.</p><p>SK offers a Memory capability, allowing the Planner to retrieve information, from a vector database for instance, and based on that data, distill a Plan of Steps to be executed using certain plugins.</p><h3>Plugins: giving your agent skills</h3><p>Plugins are the fundamental building blocks of Semantic Kernel .They consist of a Group of functions that can be loaded into the kernel to be exposed to AI apps and services.</p><p>To power automatic orchestration with a planner, plugins also need to provide details that semantically describe how they behave. Everything from the function’s input, output, and side effects need to be described in a way that the AI can understand, otherwise, the planner will provide unexpected results.</p><h3>Adding functions to plugins</h3><p><strong>Semantic Functions</strong></p><p>A semantic function is essentially a prompt sent to an LLM.</p><p>It can contain not only the text of the prompt, but also inline variables defined in the config.json.And the config.json contains the description of the prompt along with the inputs it includes.</p><p><strong>Native Functions</strong></p><p>These functions are written in C#, Python. They handle operations where AI models are not suitable, such as:</p><p>•Mathematical calculations.</p><p>•Reading and saving data from memory.</p><p>•Accessing REST APIs.</p><p><strong>Out-of-the-box plugins</strong></p><p>These plugins are often referred to as Core plugins. The core plugins are planned to be available in all languages since they are core to using Semantic Kernel.</p><h3><strong>Planner</strong></h3><p>Planner is a function that takes a user’s ask and returns a plan on how to accomplish the request. It does so by using AI to mix-and-match the plugins registered in the kernel so that it can recombine them into a series of steps that complete a goal.</p><p><strong>Action Planner</strong></p><p>The Action Planner is a very simple Planner that can select one function to fulfil a task.</p><p>If your requests can only be achieved by multiple plug-ins, you may need to define your own planner or use a more complex planner like Sequential Planner or Stepwise Planner.</p><p>Action Planner works by implementing an intent detection pattern, which identifies a user’s intent and compares it to the available plugin functions loaded into the kernel. Once it finds a plug-in that most aligns with a user’s goal, it utilizes that plugin to generate the response.</p><p><strong>Sequential Planner</strong></p><p>In Semantic Kernel , Sequential Planner is used when you want to run multiple plugins sequentially to generate a final answer.</p><p>For example, web search on a topic followed by text summary and finally an action step such as email or document creation. These individual plugins may seem unconnected but the power of the planner with the LLM generate efficient plans which allow for seamless data flow ready for execution.</p><p><strong>Stepwise Planner</strong></p><p>The Stepwise Planner is based on Modular Reasoning, Knowledge and Language (MRKL)</p><p>Unlike the sequential planner, it doesn’t pre-build the entire plan and execute functions in a predefined order. Instead, it generates the plan dynamically as it goes along.</p><p>At each step, it decides which action to take based on the output of the previous step, followed by generating a corresponding thought process and observation. The output of each step guides which function to invoke next and what information to pass to the subsequent step.</p><p>This type of planner is particularly useful for handling more complex tasks that require making decisions based on intermediate outputs. It ensures that every [ACTION] is followed by a [THOUGHT] process and [OBSERVATION], continuing this cycle until it eventually reaches the [FINAL ANSWER].</p><h3><strong>Memories</strong></h3><p>Microsoft Semantic Kernel supports both VolatileMemory (a short-term memory store lost after you run the app) and Qdrant for memories outside of the life of the application. Though the VolatileMemory store is easy to setup, any serious GPT development will require a long-term vector database memory store.</p><p>Short term memory will also incur repeated costs as each memory will need to be embedded again by making an API call.</p><h3>Conclusion</h3><p>SK is still evolving and new updates and features are getting added continuously which will enable developers to seamlessly combine traditional programming languages like C# and Python with powerful large language models such as GPT-3.5.</p><h3>References</h3><p><a href="https://learn.microsoft.com/en-us/semantic-kernel/overview/">Official Microsoft documentation</a></p><p><a href="https://github.com/microsoft/semantic-kernel">Semantic Kernel GitHub repository</a></p><p><a href="https://devblogs.microsoft.com/semantic-kernel/semantic-kernel-planners-sequential-planner/">https://devblogs.microsoft.com/semantic-kernel/semantic-kernel-planners-sequential-planner/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82e037fe427c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving into Generative Deep Learning]]></title>
            <link>https://medium.com/@prarthana1/diving-into-generative-deep-learning-5e5b8867239f?source=rss-fc8189b84ee9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e5b8867239f</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[generative-ai]]></category>
            <dc:creator><![CDATA[Prarthana Saikia]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 06:25:35 GMT</pubDate>
            <atom:updated>2023-01-24T06:25:35.287Z</atom:updated>
            <content:encoded><![CDATA[<p>Gartner has included Generative AI in its <strong>Emerging Technologies and Trends Impact Radar for 2022</strong> report as one of the most impactful and rapidly evolving technologies that brings productivity revolution.​</p><p>Here are some of the key Gartner predictions considering generative AI.​</p><ul><li>​By 2025, generative AI will be producing 10 percent of all data (now it’s less than 1 percent) with 20 percent of all test data for consumer-facing use cases.​</li><li>By 2025, generative AI will be used by 50 percent of drug discovery and development initiatives.​</li><li>By 2027, 30 percent of manufacturers will use generative AI to enhance their product development effectiveness.</li></ul><p>A generative model can be broadly defined as follows: ​</p><p><em>Generative modelling is a branch of machine learning that deals with the creation of models that can generate new data points that are similar to the training data.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*sHLUSHE2H1m4Sx7XZxAnJg.png" /></figure><p><strong>Generative vs. Discriminative Models</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*MJmnISW96gc8H8m1UdsD6Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*yEhshvFaxQsklihJPoy7CQ.png" /></figure><p><strong>Generative Model Taxonomy</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*MhLCRFD-hHdnTe32qDesdw.png" /></figure><p>Generative models can be broadly classified into:</p><ol><li>Explicit density models</li><li>Implicit density models</li></ol><p>The main difference between explicit density models and implicit density models is that explicit density models, use an explicit density function and implicit density models don’t. In other words explicit models assume some prior distribution about the data.</p><p>Let us discuss the most popularly used Generative models in this blog post.</p><p><strong>Introduction to Autoencoders​</strong></p><p>An autoencoder is a neural network made up of two parts: ​</p><p>​-An encoder network that compresses high-dimensional input data such as an image into a lower-dimensional embedding which is known as Latent Space Representation.​</p><p>-A decoder network that decompresses a given embedding back to the original domain (e.g., back to an image) ​</p><p>​This network can be trained by minimizing the <em>reconstruction error</em>, which measures the differences between our original input and the consequent reconstruction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*alhX7tD9fYzI0XVj5kZk2Q.png" /></figure><p><strong>Problems with Autoencoders</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*pKjWvY_VElwSisiKJxQmbA.png" /></figure><p>The fundamental problem with autoencoders, for generation, is that the latent space they convert their inputs to and where their encoded vectors lie, may not be continuous, or allow easy interpolation.​</p><p>For example, training an autoencoder on the MNIST dataset, and visualizing the encodings from a 2D latent space reveals the formation of distinct clusters.​</p><p>But suppose you want to randomly sample from the latent space, or generate variations on an input image, from a continuous latent space.​</p><p>If the space has discontinuities (eg. gaps between clusters) and you sample/generate a variation from there, the decoder will simply generate an unrealistic output, because the decoder has <em>no idea </em>how to deal with that region of the latent space.</p><p><strong>Variational Autoencoders</strong></p><p>A variational autoencoder (VAE) provides a probabilistic manner for describing an observation in latent space. ​</p><p>The encoder will take each input image and encode it to two vectors, z_mean and z_log_var which together define a multivariate normal distribution in the latent space.​</p><p>​Previously, our loss function only consisted of the reconstruction loss between images and their attempted copy after being passed through the encoder and decoder. ​</p><p>​The reconstruction loss also appears in a variational autoencoder, but we require one extra component: <strong>the Kullback–Leibler (KL) divergence.</strong>​</p><p>​The purpose of the KL divergence term in the loss function is to make the distribution of the encoder output as close as possible to a standard multivariate normal distribution. ​</p><p>​This loss encourages the encoder to distribute all encodings (for all types of inputs, eg. all MNIST numbers), evenly around the center of the latent space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*N4r-LtLIXFh8Q0ANiSAVQA.png" /></figure><p><strong>Generative Adversarial Networks (GAN)</strong></p><p>A generative adversarial network (GAN) has two parts:​</p><ul><li>​<strong>Generator: </strong>The aim of the generator network is to generate images given some random noise as input:​</li><li><strong>Discriminator:</strong> The job of a discriminator network is pretty simple. It has to identify whether the input is real or fake</li></ul><p>The generative network is trained to maximize the final classification error (between true and generated data), while the discriminative network is trained to minimize it. This is where the notion of adversarial networks arises from.​</p><p>From the perspective of game theory, equilibrium is reached when the generator produces samples that follow the data probability distribution and the discriminator predicts fake or not-fake with equal probability as if it would just flip a coin.​</p><p><strong>The Discriminator</strong></p><p>The discriminator in a GAN is simply a classifier. It tries to distinguish real data from the data created by the generator.​The discriminator’s training data comes from two sources:​</p><ul><li><strong>Real data</strong> instances. The discriminator uses these instances as positive examples during training.​</li><li><strong>Fake data</strong> instances created by the generator. The discriminator uses these instances as negative examples during training.​</li></ul><p>The discriminator connects to two loss functions. During discriminator training, the discriminator ignores the generator loss and just uses the discriminator loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*Twa-ltEMZJvqwXhNWBsl3g.png" /></figure><p><strong>The Generator</strong></p><p>The generator part of a GAN learns to create fake data by incorporating feedback from the discriminator. ​</p><p>It learns to make the discriminator classify its output as real.​</p><p>The portion of the GAN that trains the generator includes:​</p><ul><li>random input​</li><li>generator network, which transforms the random input into a data instance​</li><li>discriminator network, which classifies the generated data​</li><li>discriminator output​</li><li>generator loss, which penalizes the generator for failing to fool the discriminator​</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*-oL3PerD2FpTOSKq2fjbyg.png" /></figure><p><strong>Limitations of GAN​</strong></p><ol><li><strong>Vanishing Gradients:</strong>​</li></ol><p>During the initial stages of training the generator, it is not a optimal generator. The discriminator is strong and the generator cannot generate good fake samples. As a result, the discriminator behaves perfect and is able to classify the fake images correctly as 0. The gradients for the back-propagation becomes close to 0 and hence the generator doesn’t learn anything.​</p><p>​2. <strong>Mode Collapse:</strong>​</p><p>During the training, the generator may collapse to a setting where it always produces same output. This is called Mode Collapse. The generator can find a certain type of data that can easily fool the discriminator. It’ll, again and again, generate the same data under the assumption that the goal is achieved. The entire system can over-optimize to that single type of output.​</p><p>​<strong>3. Nash Equilibrium:</strong>​</p><p>It is hard to achieve Nash Equilibrium. Discriminator and Generator try to achieve contradictory goals. There exists no relation between discriminator &amp; generator while updating their own weights due to which their gradients can’t guarantee a convergence.</p><p><strong>From GAN to Wasserstein GAN</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*ync4dACftSATNjMM3Ur5ww.png" /></figure><p>The figure shows an example of a non-sharing probability space. Both distributions are not overlapping and have a distance of <em>θ </em>between them.​</p><p>The KL-divergence between these two distributions will be infinity because of non-overlapping and the denominator part will be zero.​</p><p>Similarly, JS-divergence will be constant <em>(log 2)</em> irrespective of the value of <em>θ.</em>​</p><p>​In contrast, the Wasserstein metric depends on the distance between these two distributions i.e. which is desirable and considering the horizontal shifts irrespective of overlaps. Therefore, the Wasserstein metric as aloss function is more practical and produces better results compared to JS-divergence.</p><p><strong>References:</strong></p><ol><li><a href="https://developers.google.com/machine-learning/gan/generative">https://developers.google.com/machine-learning/gan/generative</a></li><li><a href="https://www.oreilly.com/library/view/generative-deep-learning/9781098134174/">https://www.oreilly.com/library/view/generative-deep-learning/9781098134174/</a></li><li><a href="https://lilianweng.github.io/posts/2017-08-20-gan/">https://lilianweng.github.io/posts/2017-08-20-gan/</a></li><li><a href="https://www.gartner.com/en/newsroom/press-releases/2022-05-24-gartner-identifies-three-technology-trends-gaining-tr">https://www.gartner.com/en/newsroom/press-releases/2022-05-24-gartner-identifies-three-technology-trends-gaining-tr</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e5b8867239f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unboxing Black Box Models: Explainable AI for Deep Learning Models]]></title>
            <link>https://medium.com/@prarthana1/unboxing-black-box-models-explainable-ai-for-deep-learning-models-e62ad2375fab?source=rss-fc8189b84ee9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e62ad2375fab</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deeplearningai]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[artificial-neural-network]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Prarthana Saikia]]></dc:creator>
            <pubDate>Tue, 29 Sep 2020 05:38:40 GMT</pubDate>
            <atom:updated>2020-09-29T05:38:40.155Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*UExgjMR-yGnZdejOhRMFzw.png" /></figure><p>From the above figure, we can see that as the complexity of the machine learning model increases, the accuracy increases. However, the interpretability reduces.</p><p>We need techniques which can have some level of interpretability for black-box models as well. This is where Explainable AI falls into place.</p><p>Deep Learning models are the most difficult to interpret, and the more complex and deeper is the neural network, the more difficult it is to offer any kind of explainability. Several approaches and techniques have been suggested in various studies to understand feature importance for a given prediction for Deep Learning models.</p><p>We will discuss few of the methods and their drawbacks below:</p><p><strong>Perturbation-Based Forward Propagation Approaches</strong></p><p>These approaches make perturbations or changes to individual inputs or neurons and observe the impact on neurons in the network and the output. This is repeated for different perturbations of the input, each time observing the change in the output for e.g. having a sliding window occlude different parts of the image and look at the change in the output. LIME also falls into this category, where a linear model is built to approximate the local behavior of the network using data gathered from making input perturbations. A common drawback to perturbation-based approaches is computational efficiency. Every time we make a perturbation, we have to recompute the outputs using a forward propagation. Another more subtle issue is saturation.</p><p><strong>Saturation</strong></p><p>Consider the output y such that y is a function of i₁ and i₂.</p><blockquote><strong>y=f(i</strong>₁<strong>,i</strong>₂<strong>)</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*vILxyazVLYuqtRYF5JD6Lg.png" /></figure><p>When i₁+i₂&lt;1, y increases in a linear fashion. When i₁ + i₂ is greater than 1, the output y saturates to 1.</p><p>Consider the point where i₁=1 and i₂=1. If at this point we change i₁ from 1 to 0, the output y wilI still be 1. Thus this perturbation method can give us a wrong answer that changing the input is not affecting the output. To avoid this saturation effect, we should perturb combinations of inputs which in turn increase computational cost.</p><p><strong>Backpropagation-Based Approaches</strong></p><p>Unlike perturbation methods, backpropagation approaches propagate an importance signal from an output neuron backwards through the layers to the input in one pass, making them efficient.</p><p><strong>Using gradients to interpret neural networks</strong></p><p>The equation for a linear regression model can be represented as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*WltRtxq5nnlpt47aP5AFNw.png" /></figure><p>Where w1, w2, w3,…,wₙ are the weights of the features of the model.</p><p>This weight can be represented as partial derivative as-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*LRe8PnKnerqNqwLYF6VKUw.png" /></figure><p>In other words, the weight assigned to the <em>i</em>th feature tells us the gradient of that feature with respect to the model’s prediction: how the model’s prediction changes as the feature changes keeping other features constant.</p><p>However, using the gradient of the output with respect to the input works well for a linear model but quickly falls apart for nonlinear models.</p><p>Let us consider a neural network consisting only of a ReLU activation, with a baseline input of <em>x=2</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*9qdgjmY4yCGKFfnNr2Qlog.png" /></figure><p>Now, let’s consider a second data point, at <em>x = -2</em><strong><em>.</em></strong></p><p>ReLU(x=2) = 2, and ReLU(x=-2) =<em> 0</em>.</p><p>There is only one input feature in my model ‘x’. At x=-2, the output y changes to 0 compared to y=2 at baseline. This change in the output of my model has to be attributed to the change in x, since it is the only input feature to this model, but the gradient of ReLU(x) at the point <em>x = -2 </em>is 0. This gives us contradictory results.</p><p><strong>Deep Learning Important FeaTures (DeepLIFT)</strong></p><p>Deep LIFT is a Deep Learning explanation method proposed in the paper <a href="https://arxiv.org/abs/1704.02685"><strong>Learning Important Features Through Propagating Activation Differences</strong></a><strong>.</strong></p><p>DeepLIFT recognizes that what we care about is not the gradient, which describes how <em>y</em> changes as <em>x</em> changes <strong>at the point <em>x</em></strong>, but the <em>slope</em>, which describes how <em>y</em> changes as <em>x </em>differs <strong>from the baseline</strong>. Basically, we need to define a baseline and identify how <em>Y</em> changes from baseline as <em>x</em> changes from the baseline. The ‘reference’ input represents some default or ‘neutral’ input that is chosen according to what is appropriate for the problem at hand.</p><p>This slope can be represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*rmFpwxQ-E5R50Zif9e2FZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*eRZ7TJLk7D0ue_HIi1E83A.png" /></figure><p>This method tells us that the input feature ‘<em>x’</em> has an importance value of -2.</p><p>Let <em>t</em> represent target output neuron and let <em>x1, x2, …, x</em>ₙ represent neurons in some intermediate layer or set of layers that are necessary and sufficient to compute t.</p><p>Let <em>t</em>₀<em> </em>represent the reference activation of t. We define the quantity ∆t to be the difference-from-<em>reference, that is</em></p><blockquote>∆t = t−t₀</blockquote><blockquote>DeepLIFT assigns contribution scores C<em>∆x</em>ᵢ<em>∆t </em>to <em>∆x</em>ᵢ where C<em>∆x</em>ᵢ<em>∆t</em> can be thought of as the amount of difference-from-reference in <em>t</em> that is attributed to or ‘blamed’ on the difference-from-reference of <em>xi</em></blockquote><p><strong>Deep SHAP (DeepLIFT + Shapley values)</strong></p><p>Deep SHAP is an algorithm for SHAP values in deep learning models that builds on a connection with <a href="https://arxiv.org/abs/1704.02685">DeepLIFT</a> described in <a href="https://arxiv.org/pdf/1911.11888.pdf">Explaining Models by Propagating Shapley Values</a>.</p><p>If we interpret the reference value as representing E[x] which what would be predicted if we did not know any features to the current output, then DeepLIFT approximates SHAP values assuming that the input features are independent of one another and the deep model is linear. However we use a background distribution instead of a baseline or single reference. SHAP values for each baseline in the background distribution are calculated and averaged out.</p><p><strong>Implementation in Python</strong></p><p>The data file train.csv contains gray-scale images of hand-drawn digits, from zero through nine.</p><p>Each image is 28 pixels in height and 28 pixels in width, for a total of 784 pixels in total. Each pixel has a single pixel-value associated with it, indicating the lightness or darkness of that pixel, with higher numbers meaning darker. This pixel-value is an integer between 0 and 255, inclusive.</p><p>The dataset has 785 columns. The first column, called “label”, is the digit that was drawn by the user. The rest of the columns contain the pixel-values of the associated image.</p><p>Our goal is to correctly identify and predict the digits from the handwritten images.</p><p>After performing the required pre-processing, we have augmented the images for better model performance and accuracy to increase the generalizability of the model. For example, we can obtain augmented data from the original images by applying simple geometric transforms, such as random: Translations, Rotations, Changes in scale, Shearing, Horizontal (and in some cases, vertical) flips.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*O9Y5uwesQsSn8UTuqFIzng.png" /></figure><p>We have trained a CNN model on the images dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*x_mXUuCrd8L4ZYza11vMCg.png" /></figure><p>We are using SHAP library to run DeepExplainer on the trained model. We are analyzing the SHAP values of the top 10 images which has been wrongly predicted by our model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*mLMG0WSE5CRn5FPsMyAw6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*6uHIxxtW3B9qpTxqoJaxUw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*kIqqUtg6MaiWWvOibhKQSQ.png" /></figure><p>The plot above shows the explanations for each class label from 0–9. The percentage values are the predicted class probabilities. We have used a SoftMax activation function. Hence, we have obtained the predicted probabilities of all the classes. Note that the explanations are ordered for the classes 0–9 going left to right along the rows</p><p>The blue colour is used to signify negative SHAP values whereas the red colour is for positive SHAP values.</p><p>Red pixels increase the probability of predicting the class while blue pixels decrease the probability of the class. For example, the image with true label 9 is predicted as 4 and not as 9 mainly because of the blue pixels for label 9 on the top as a small connecting line. Similarly, the image with true label 5 is predicted as 6. Because of the blue pixels for label 5 , the probability of the class decreases.</p><p><strong>References:</strong></p><ol><li>A Unified Approach to Interpreting Model Predictions by Scott M. Lundberg, Su-In Lee</li><li><a href="https://arxiv.org/pdf/1704.02685.pdf">Learning Important Features Through Propagating Activation Differences</a> by Avanti Shrikumar ,Peyton Greenside ,Anshul Kundaje</li><li>Explainable CNN using SHAP <a href="https://www.kaggle.com/lomen0857/explaining-cnn-using-shap">https://www.kaggle.com/lomen0857/explaining-cnn-using-shap</a></li><li><a href="https://towardsdatascience.com/interpretable-neural-networks-45ac8aa91411">https://towardsdatascience.com/interpretable-neural-networks-45ac8aa91411</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e62ad2375fab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unboxing Machine Learning Models with SHAP for better interpretation]]></title>
            <link>https://medium.com/@prarthana1/unboxing-machine-learning-models-with-shap-for-better-interpretation-5b2caa81e3da?source=rss-fc8189b84ee9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b2caa81e3da</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[shap]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Prarthana Saikia]]></dc:creator>
            <pubDate>Thu, 27 Aug 2020 10:45:09 GMT</pubDate>
            <atom:updated>2020-08-27T10:45:09.993Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of machine learning<strong>,</strong> with the increase in complexity of the model, arises another perennial question of interpreting the model results and predictions. Simple models are easy to interpret and hence are often preferred, even if they maybe less accurate than the complex ones. There has not been a single time when our clients have not asked us for justification and interpretation of the model results, hence causing a trade off between accuracy and interpretation.</p><p>To address this, enters SHAP<strong> (SHapley Additive exPlanations) </strong>by Lundberg and Lee(2016) which<strong> </strong>is a game theoretic approach to explain the output of any machine learning model. It connects optimal credit allocation with local explanations using the classic Shapley values from game theory and their related extension. In <a href="https://www.investopedia.com/terms/g/gametheory.asp">game theory</a>, the <strong>Shapley value</strong> is a solution concept of fairly distributing both gains and costs to several players working in coalition. Game theory is when two or more players or factors are involved in a strategy to achieve a desired outcome or payoff. The Shapley value applies primarily in situations when the contributions of each player are unequal, but each player works in cooperation with each other to obtain the gain or payoff.</p><p>For example, there are 4 players (A,B,C,D) in a game. Shapley quantifies the contribution that each player brings to the game. It is based on the idea that the outcome of each possible combination of players should be used to get the importance of one single player. The contribution of player A can be different if it is jointly with player B or with C or with B and C combined and if it is just A alone. So, to calculate the contribution of player A, we need to consider all the interactions of A with the other players and their collective contribution as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*Q-baYdi-PVDnYkU2bGgv4w.png" /></figure><p>Thus, considering every player and all other interactions, there will be 2⁴=16 possible interactions. Now, SHAP requires to train a distinct predictive model for each of these distinct interactions.</p><p>Essentially, the Shapley value is the expected marginal contribution of each player which is the average of their marginal contribution across all combinations. In machine learning context, consider these players as the features of your dataset. <strong>Marginal contribution of a feature is nothing but the difference between predictions by including the feature and without including the feature. We replace the feature values of features that are not in the combination with random feature values in the dataset.</strong></p><p>In simpler terms,</p><p><strong><em>SHAP value of Feature A= Average Marginal Contribution of Feature A across all combinations= Average of Σ across all interactions of A (Model prediction including Feature A — Model prediction without the feature)</em></strong></p><p><strong>Properties of SHAPley values:</strong></p><p><strong>1) Efficiency:</strong></p><p>The feature contributions must add up to the difference of contribution for x and the average.</p><p><strong>2)Symmetry:</strong></p><p>The contribution of two features (j and k) should be same if they contribute equally.</p><p><strong>3) Dummy:</strong></p><p>A feature j that does not change the predicted value regardless of which coalition of features is it added to, should have a Shapley value of 0.</p><p><strong>4) Additivity:</strong></p><p>To get the combined contribution of features, their corresponding Shapley values can be added. This means that for an ensemble model like a Random Forest or Gradient Boosting, this property guarantees that if we calculate the Shapely Values of the features for each tree individually and average them, we will get the Shapely values for the ensemble.</p><p><strong>SHAP implementation in Python:</strong></p><p>The SHAP library in Python has inbuilt functions to use Shapley values for interpreting machine learning models. It has optimized functions for interpreting tree-based models and a model agnostic explainer function for interpreting any black-box model for which the predictions are known.</p><p>Benefits of using SHAP library for model interpretation are it allows both <strong>Global Interpretability</strong> to get feature importance for the entire dataset and understand how each predictor contributes to the model output as well as <strong>Local Interpretability</strong> where one can view observations on case basis and the influence of predictors and then do a similarity analysis if required.</p><p>For explanation, I am going to use the UCI Bank Marketing dataset. The data is related with direct marketing campaigns of a Portuguese banking institution. The classification goal is to predict if the client will subscribe a term deposit (variable y).</p><p><em>Data Contains information in following format:</em></p><p><strong>Categorical Variable:</strong></p><ul><li>Marital — (Married, Single, Divorced)</li><li>Job — (Management,BlueCollar,Technician,entrepreneur,retired,admin.,services, selfemployed,housemaid,student,unemployed,unknown)</li><li>Contact — contact communication type (Telephone, Cellular, Unknown)</li><li>Education — (Primary, Secondary, Tertiary, Unknown)</li><li>Month — last contact month of year (Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec)</li><li>Poutcome — outcome of the previous marketing campaign (Success,Failure,Other,Unknown)</li><li>Housing — has housing loan? (Yes/No)</li><li>Loan — has personal loan? (Yes/No)</li><li>Default — has credit in default? (Yes/No)</li></ul><p><strong>Numerical Variable:</strong></p><ul><li>Age</li><li>Balance: average yearly balance, in euros</li><li>Day: last contact day of the month</li><li>Duration: last contact duration, in seconds</li><li>Campaign: number of contacts performed during this campaign and for this client</li><li>Pdays: number of days that passed by after the client was last contacted from a previous campaign</li><li>Previous: number of contacts performed before this campaign and for this client</li></ul><p><strong><em>Class</em></strong></p><ul><li>deposit — (Yes/No)</li></ul><p>Let us read the dataset in Python and do the required pre-processing on the categorical variables</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*16ncq5iesDRWZqFvEYIk4g.png" /></figure><p><strong>Installing SHAP library</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*K0N1vGv9fW40puc-f_YcLw.png" /></figure><p><strong>Train-test Split and training a Random Forest classifier</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*eZ-meMnWDLKXfpSfHmUmMQ.png" /></figure><p><strong>Computing SHAP values using TreeExplainer</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*cvtLLLsEXlzvEdCT9JAKBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*43-N3pG7MEGX4hHdGZJs0w.png" /></figure><p>For classification problems, explainer.shap_values() return a list of size n_classes. Since this is a binary classification model n_classes=2. Each object of this list is an array of size [n_samples, n_features] and corresponds to the SHAP values for the respective class. In this example, shap_values[1] is the SHAP values for the positive class (Yes) &amp; shap_values[0] is the SHAP values for the negative class. For regression models, we get a single set of shap values of size [n_samples, n_features].</p><p><strong>Types of Plots using SHAP Library</strong></p><ol><li><strong><em>shap.summary_plot()</em></strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*mRiNCuUkp0ytMjwkqpZk6A.png" /></figure><p>shap.summary_plot() creates a plot of mean SHAP values for each feature to identify how much impact each feature has on the model output for both the classes. Features are sorted by the sum of the SHAP value magnitudes across all samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*_PPwGednSoL1HvGAnX8svA.png" /></figure><p>In the above chart, we can see the features being arranged in decreasing order of importance. The ‘duration’ feature is the most important feature in the dataset. The top variables contribute more to the model than the bottom ones and thus have high predictive power.</p><p>The SHAP summary plot can also be used to show the positive and negative relationships of the predictors with the target variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*itmJCYjlL7XrX_esUqhc0g.png" /></figure><p>In the above graph, the features have been stacked in descending order of importance.Red indicates high feature value and Blue indicates low feature value. We know that the more positive the SHAP value, the more is the contribution of that feature as SHAP value calculates the difference between predictions with the feature and without the feature. Thus, RED color corresponds to +SHAP and the feature is positively correlated to the target variable and if BLUE color corresponds to –SHAP, it is negatively correlated to the target variable.</p><p>Thus, ‘duration’ is positively correlated to target variable. As duration increases, the probability of term deposit increases.</p><p>Similarly,Contact_unknown is a binary variable (0/1). If it is 0, it corresponds to positive model output, which means it is negatively correlated to the target variable.</p><p>2) <strong><em>shap.force_plot</em></strong>:</p><p>Force plot can be used to explain a single observation in the dataset. I have tried to observe row 5 in my test data for this explanation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*f5Uej3pQv-manI583Mq3FA.png" /></figure><p>We can see in the code snippet that for row 5 the predict_proba function outputs a probability of 0.6 for class 1.</p><p>In the graph, the base value is used to depict the output of a baseline model without any features. For a regression model, it is the average of the model output over the training data. For classification, it is calculated as the base logit value over the training dataset. The output value is the prediction for the observation. Features that push the prediction to the right of base value are shown in red, and those pushing the prediction towards the base value are in blue.</p><p>We know from summary plot that Duration is positively related to the target variable. Average duration across our train data is 262. Here Duration (988&gt;262). Thus, it drives prediction to the right. Similarly, Age=47, contact_cellular=1, day=30, previous=5 are contributing to improve the logit from the base value. Whereas pdays=87, poutcome_success=0 is pushing the prediction to the left.</p><p>Force_plot can also be used to explain the entire dataset. It is nothing but the same plot for each sample, rotated 90 degrees and stacked side-by-side to explain the predictions for multiple samples in a single plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*d0Lqx_dmp0f8zBWRWzSqzQ.png" /></figure><p>The color codes mean the same as in previous chart, with red colored features increasing the logit &amp; the blue colored feature decreasing the logit for each data point.</p><p>3)<strong><em>shap.dependence_plot():</em></strong></p><p>The dependence plot is used to visualize the interactions between different features.</p><p>Every dot in the chart represents an observation.</p><p>We can define the interaction variable explicitly or SHAP can itself select the interaction variable that seems to have the strongest interaction with the main variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*OSfJQKPvUvJL421CiPALkw.png" /></figure><p>From the graph, we can see the interaction between age and month_nov features where month_nov is categorical. For higher age, when month_nov=0, it increases the predicted probability of client subscribing to a term deposit.</p><p>These are some of the techniques that can be used from SHAP library which help a lot for model interpretation and explainability.</p><p><strong>References</strong></p><ol><li>SHAP: A Unified Approach to Interpreting Model Predictions. arXiv:1705.07874</li><li><a href="https://github.com/slundberg/shap">https://github.com/slundberg/shap</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b2caa81e3da" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>