<?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 Gaurang Mehra on Medium]]></title>
        <description><![CDATA[Stories by Gaurang Mehra on Medium]]></description>
        <link>https://medium.com/@gaurangmehra?source=rss-8de2842c14be------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3Lz0Jde2b-JjS8kW</url>
            <title>Stories by Gaurang Mehra on Medium</title>
            <link>https://medium.com/@gaurangmehra?source=rss-8de2842c14be------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:02:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gaurangmehra/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[Cosine similarity explained. How RAG provides context and powers meaningful search]]></title>
            <link>https://medium.com/@gaurangmehra/cosine-similarity-explained-how-rag-provides-context-and-powers-meaningful-search-236077baf867?source=rss-8de2842c14be------2</link>
            <guid isPermaLink="false">https://medium.com/p/236077baf867</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Gaurang Mehra]]></dc:creator>
            <pubDate>Wed, 14 Jan 2026 14:12:48 GMT</pubDate>
            <atom:updated>2026-01-21T01:30:18.024Z</atom:updated>
            <content:encoded><![CDATA[<p>In my previous<a href="https://medium.com/@gaurangmehra/generative-ai-part-1-understanding-rag-what-it-is-why-we-need-it-and-a-simple-use-case-ea01f59486c3"> article</a> I discussed RAG (Retrieval Augmented Generation) and how we can provide LLMs relevant context to help answer questions grounded in your own corporate/institutional data. This helps reduce hallucinations and keeps the generated answers relevant.</p><p>In a RAG system retrieval is fundamentally a ranking problem. The user query is compared against thousands of document chunks, relevant chunks are returned and these are used by the LLM to generate an appropriate response. <em>Cosine similarity </em>is the metric that is used to generate this ranking. In this article we will dive deeper into the concept of <em>Cosine similarity.</em></p><h3>How do machines decide 2 pieces of text are similar</h3><p>The first step in the process is to convert the pieces of text into a set of numbers. This set of numbers are called <em>word vectors </em>or<em> embeddings</em>. The key concept behind embeddings is <em>“Words and phrases with similar meaning cluster together”. </em>This means that similar pieces of text will cluster together when converted to numbers. <em>Cosine similarity </em>is how we measure this distance between pieces of text encoded as numbers.</p><h4>A simple example to illustrate this</h4><p>We are going to use a very simple example to illustrate this. We have a hypothetical example where we are tracking the frequency of the words LLM and math. We have 3 documents and with the following word frequencies for these 2 words</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*q0ybo8EiGzDvJlZlHLS3fw.png" /><figcaption>Fig 1.1 word frequency table</figcaption></figure><p>Now lets plot these frequencies on a graph</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*0qoq3GUOxS6HtZ0MqjkJyQ.png" /><figcaption>Fig 1.2 Plotting word mentions</figcaption></figure><p>We can clearly see from the graph that documents 1 and 2 are directionally similar even though their lengths are vastly different while document 3 is in a different direction from both document 1 and 2. Intuitionally we understand this because both document 1 and document 2 mention LLM and math which means they have a similar theme while document 3 could be a general math document with no relations to LLMs. We can formally measure this distance as the Cosine of the angle between the vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*t5ykukxOuumV6Ndb-f3OZg.png" /><figcaption>Fig 1.3 Angle between the word vectors</figcaption></figure><p>Since this is a very simple 2d case we can clearly see that the angle B &gt; Angle A. In real life word vectors have many thousand columns or dimensions and it becomes impossible to draw them on a 2d graph. Fortunately there exists a simple mathematical formula for calculating the cosine of the angle between 2 vectors. This comes from the mathematical concept of a dot product between 2 vectors (Not really necessary to know in detail).</p><p>The key concept that I want to convey is:</p><blockquote><em>The cosine of the angle between 2 vectors is a measure of how </em><strong><em>directionally </em></strong><em>similar the 2 vectors are, and is not as sensitive to their magnitude. This is especially useful for text because the same concept can be expressed in a verbose manner or in fewer words. Other measures of distance are very sensitive to scale and can falsely flag 2 similar meaning documents as different.</em></blockquote><p>The concept above forms the heart of <em>semantic search, recommendation engines </em>and <em>RAG systems</em></p><h4>Now the Math…(Optional but good to know)</h4><ol><li>Cosine similarity between document 1 and 2</li></ol><p>Cosine similarity between two vectors is calculated as:</p><p><strong>cos(θ) = (A · B) / (||A|| × ||B||)</strong></p><p><strong>Step 1: Dot product</strong></p><p>(90 × 200) + (20 × 100)<br> = 18,000 + 2,000<br> = <strong>20,000</strong></p><p><strong>Step 2: Vector magnitudes</strong></p><p>||Doc 1|| = √(9⁰² + 2⁰²)<br> = √(8,500)<br> ≈ <strong>92.20</strong></p><p>||Doc 2|| = √(20⁰² + 10⁰²)<br> = √(50,000)<br> ≈ <strong>223.61</strong></p><p><strong>Step 3: Cosine similarity</strong></p><p>20,000 ÷ (92.20 × 223.61)<br> ≈ <strong>0.97</strong></p><p><strong>Interpretation:</strong> Doc 1 and Doc 2 are highly similar — they point in nearly the same direction.</p><ol><li>Cosine similarity between document 2 and 3</li></ol><p><strong>Step 1: Dot product</strong></p><p>(200 × 0) + (100 × 220)<br> = <strong>22,000</strong></p><p><strong>Step 2: Vector magnitudes</strong></p><p>||Doc 2|| ≈ <strong>223.61</strong><br> ||Doc 3|| = √(22⁰²) = <strong>220</strong></p><p><strong>Step 3: Cosine similarity</strong></p><p>22,000 ÷ (223.61 × 220)<br> ≈ <strong>0.45</strong></p><p><strong>Interpretation:</strong> Doc 2 and Doc 3 have moderate similarity — partially aligned, but clearly different directions.</p><p>This ties into the result that we expected based on our plot. This same concept can be extended to a word vector of n dimensions where n is greater than 2</p><p>A = (a1,a2,a3,…..,an) and B = (b1,b2,b3,……,bn)</p><p><strong>cos(θ) = (a₁b₁ + a₂b₂ + … + aₙbₙ) / (√(a₁² + a₂² +…+ aₙ²) × √(b₁² + b₂² +…+ bₙ²))</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=236077baf867" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative AI Part 1: Understanding RAG — What It Is, Why We Need It, and a Simple Use Case]]></title>
            <link>https://medium.com/@gaurangmehra/generative-ai-part-1-understanding-rag-what-it-is-why-we-need-it-and-a-simple-use-case-ea01f59486c3?source=rss-8de2842c14be------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea01f59486c3</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Gaurang Mehra]]></dc:creator>
            <pubDate>Fri, 02 Jan 2026 12:02:26 GMT</pubDate>
            <atom:updated>2026-01-02T16:04:55.919Z</atom:updated>
            <content:encoded><![CDATA[<h3>Generative AI Part 1: Understanding RAG — What It Is, Why We Need It, and a Simple Use Case</h3><h4>LLM shortcomings and why we need RAG</h4><p>This article focuses on using LLMs to answer questions based on your own data or your enterprise data. LLMs have been trained on publicly available web data and can answer user questions only using information inside their training set. If you want the LLM to answer questions related to</p><ul><li>PDF files on your computer</li><li>python code files on a git repo</li><li>Meeting notes</li><li>Word files in a folder</li></ul><p>then you need to provide this information as context to the model at run-time. If the files are small then they can be uploaded directly into a chat application but if you have a very large file or a huge number of files they will quickly exceed the context window for the chat application like Chat-GPT. Enterprises might also want to control the retrieval of information at a granular level.</p><p>This is where you need <em>RAG or Retrieval Augmented Generation.</em></p><h4>What is RAG</h4><p><strong>RAG </strong>stands for <strong>Retrieval</strong> <strong>A</strong>ugmented <strong>G</strong>eneration. This combines 2 steps:</p><ol><li><em>Retrieval:</em> In this step the most relevant information is retrieved from a knowledge source ( a very large pdf, a folder full of word documents) based on the user’s query. This retrieved information is added to the prompt that is sent to an LLM</li><li><em>Generation:</em> In this step the LLM answers the user question grounded in the information retrieved in step 1.</li></ol><p>RAG serves the following purpose</p><ul><li>Provides model with relevant context</li><li>Constrains answers to just your data (preferable in most corporate situations)</li><li>Largely eliminates hallucinations</li></ul><h4>The RAG workflow</h4><p>The RAG pipeline follows a few simple steps. These logical steps stay the same regardless of the complexity of the workflow. The schematic below outlines the RAG workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a2s2iknrGZ62iCHTxclHsA.png" /><figcaption>Fig 1.1 RAG workflow</figcaption></figure><p>The <em>RAG </em>process involves taking your document(s), splitting them into bite size chunks and then encoding all the chunks into a set of numbers (called vectors). This requires the use of an <em>embedding model</em> (separate from the LLM), this model is used to convert documents and queries to numbers to facilitate comparisons. These documents are then stored in a special database made for vectors called a <em>vector database. </em>The user query/question is converted into a vector as well. It is then compared to all the vectors (representing chunks of text) in the vector database and the most similar chunks are retrieved. These retrieved chunks and the user query are packaged into a prompt and sent to the LLM which can now generate a response grounded in the retrieved chunks.</p><p><strong>A Note on the Langchain framework</strong></p><p><em>Langchain </em>is the typical orchestration framework that we use to build RAG applications. <em>Langchain </em>is model agnostic so you can use any LLM or any embedding model including open source models. <em>Langchain </em>also comes along with document loaders (to load all manner of files .pdf, .wordx, .csv etc)</p><h4><strong>A simple RAG implementation</strong></h4><p>In this simple RAG implementation we will take the famous <em>Attention is all you need</em> paper and build a simple RAG pipeline that will take a user query and retrieve relevant chunks from the paper and answer the query based on the retrieved context. This can be extended to folders full of hundreds of pdfs with a few simple modifications but since this is a demo I am not showing such a use case.</p><p><em>Step 1: Load and split your documents in chunks</em></p><p>In this step we load the document using a pdf loader. There are as many types of loaders as there are file types. The load step loads and reads each page in the pdf along with the metadata (file name, page number etc).</p><p>We then take the loaded documents and further split them into chunks of chunk size 500. Here the chunk size is in characters. <em>RecursiveCharacterTextSplitter </em>splits the docs by the separators one at a time and stops only when the chunks are below the chunk_size parameter. It first splits on paragraphs but if the chunk size is &gt; 500 then it will split on lines (\n). If now the chunks are less than 500 it will stop.</p><pre>from langchain_community.document_loaders import PyPDFLoader<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br><br># Step 1: Load the document and split it<br>loader = PyPDFLoader(&#39;attn_is_all_you_need.pdf&#39;)<br>docs = loader.load()<br><br>splitter = RecursiveCharacterTextSplitter(separators=[&quot;\n\n&quot;,&quot;\n&quot;,&quot; &quot;,&quot;&quot;],<br>                                          chunk_size=500,<br>                                          chunk_overlap=50)<br>chunks = splitter.split_documents(docs)<br></pre><p><em>Step 2 : convert the chunks into vectors and store them in a vector database</em></p><p>In this step we take the chunks convert them into vectors using an embedding model. You have a wide choice of embedding models. This added customizability is an added advantage of using RAG workflows versus uploading directly to Chat-GPT or any other chatbot.</p><p>We also set up a retriever. This is a special methos in the vector store. By default the retriever compares a query vector against the vectors in the vector store and returns the k closest vectors/chunks. The similarity is calculated using <em>Cosine similarity. </em>This is based on the concept of dot product of vectors (this is decades old math). Converting/encoding text into numbers means we can use readily available math tools to find text with similar meaning or intent.</p><p>In the next step we are going to package all these steps into a prompt which has a question and the retrieved context packaged within it.</p><pre>from langchain_openai import OpenAIEmbeddings<br>from langchain_chroma import Chroma<br><br># Step 2: Convert chunks into vectors <br>embedding_model = OpenAIEmbeddings(api_key=key,<br>                                   model = &quot;text-embedding-3-small&quot;)<br><br>vector_store = Chroma.from_documents(documents= chunks,<br>                                     embedding = embedding_model)<br><br>retriever = vector_store.as_retriever(search_type=&quot;similarity&quot;,<br>                                      search_kwargs = {&#39;k&#39;:3})</pre><p><em>Step 3: Package retriever and question into a prompt</em></p><p>In this step we create a prompt template which includes placeholders for the user question and the context. We also instantiate an LLM that we want to use. We can choose what LLM based on our use case. Finally we create a RAG chain that defines the flow.</p><ul><li>We create a dictionary with the keys,<em> context</em> and <em>question</em>. To <em>context</em> we pass our retriever and for<em> question</em> we pass a placeholder for the user question</li><li>We then pass this dictionary to our prompt template. The placeholder will be filled when we invoke the template</li><li>The prompt template is then passed to an LLM</li><li>The LLM output is passed to <em>StrOutputParser </em>which parses the output in a standard string format</li></ul><pre>from langchain_core.runnables import RunnablePassthrough<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_openai import ChatOpenAI<br><br>prompt = ChatPromptTemplate.from_template(&quot;&quot;&quot;Based on the retrieved context answer the following question.<br>                                          If you do not know say so.<br>                                          Use only the provided context to anwer the question<br>                                          context: {context}<br>                                          question:{question}&quot;&quot;&quot;)<br>llm = ChatOpenAI(api_key=key,<br>                 model=&#39;gpt-4o-mini&#39;)<br>chain = (<br>    {&#39;context&#39;:retreiver,&#39;question&#39;:RunnablePassthrough()}<br>    | prompt<br>    | llm<br>    | StrOutputParser()<br>)<br><br>result = chain.invoke(&quot;Summarize the attn_is_all_you_need paper in 3 bullet points?&quot;)<br>result2 = chain.invoke(&quot;What color is the sky?&quot;)</pre><p><em>Step 4: Results</em></p><p>We ask the LLM 2 questions. One question asks the LLM to summarize the paper while the other question is totally irrelevant. We want to see if the LLM hallucinates when asked an irrelevant question.</p><pre>print(result)<br><br>- The paper proposes a novel architecture for sequence transduction based solely on an attention mechanism, eliminating the need for recurrent and convolutional networks, leading to more parallelization and reduced training time.<br>- Experiments demonstrate that the proposed models outperform existing state-of-the-art results in machine translation tasks, achieving a BLEU score of 27.5 for English-to-German translation and 41.1 for English-to-French translation.<br>- The architecture consists of a single model with 165 million parameters and shows improvements over previous best results by over 1 BLEU for English-to-German and 0.7 BLEU for English-to-French translations.<br><br>print(result2)<br>I do not know.</pre><h4>Final Thoughts</h4><p>The use case shown above is a simple use case for demonstration purposes but this same flow can be extended to myriad professional use cases. We can also wrap the RAG workflow in an agent (the key concepts of RAG remain the same). Some use cases that we can use RAg for below</p><p><em>Recommendations based on user inputs: </em>Suppose you have a csv file or a table with product reviews characteristics etc. You can load it using CSVloader chunk it, convert it to a vector. The user can then enter a query like “I want highly rated headphones” and k results can be retrieved and returned by the LLM</p><p><em>Intelligent chat bots: </em>Intelligent chat bots that query a knowledge base of a company to answer customer queries.</p><p><em>Onboarding chatbot: </em>Create an onboarding chatbot that queries company documents</p><p>Custom RAG solutions can be customized by changing parameters like chunk_size, chunk_overlap, chunking method and embedding models. Also we can play around with retreival strategies if speed of retreival is more important.</p><p>You can find some more use cases including creating a RAG framework for a code base (writing documentation) in the github below</p><p>Link to git-hub:<br><a href="https://github.com/gmehra123/PORTFOLIO/blob/main/RAG_2/RAG_review2.ipynb">https://github.com/gmehra123/PORTFOLIO/blob/main/RAG_2/RAG_review2.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea01f59486c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master Non-Linear Modeling: Neural Networks with PyTorch]]></title>
            <link>https://medium.com/analytics-vidhya/master-non-linear-modeling-neural-networks-with-pytorch-dc1490d427be?source=rss-8de2842c14be------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc1490d427be</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Gaurang Mehra]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 11:47:38 GMT</pubDate>
            <atom:updated>2024-10-21T11:47:38.254Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’ve created a custom non-linear dataset to demonstrate how effectively neural networks can model complex patterns. By leveraging PyTorch, we’ll explore how even with just one independent variable and one dependent variable, a neural network can accurately capture the underlying non-linearity in the data. We can achieve all this with some basic knowledge of Python. This is a beginner friendly article and part of a 2 part series</p><h4><strong>Understanding Linear relation ships</strong></h4><p>We are all familiar with the linear equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*duLYScB-0L4xD4TPrRm-Vw.png" /><figcaption>General linear equation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*K-hyJlbChv5uzNsNNu2hPQ.jpeg" /><figcaption>Linear relation ships</figcaption></figure><p>This equation indicates that the rate of change of y with respect to x is constant. These relationships show as straight lines on a graph</p><p>Human beings naturally tend to think in linear terms; for example, if 1 pencil costs $10, then 10 pencils would cost $100. This reasoning illustrates linear thinking, where the relationship between price and quantity is straightforward.</p><p>However, this relationship doesn’t always hold true. For instance, if 10 pencils were to cost $80 instead, the pricing structure would become non-linear. In this case, the price per unit is no longer a constant $10; it drops to $8 per unit. This example illustrates that real-world relationships can be more complex, and prices can change based on various factors, demonstrating non-linearity.</p><h4><strong>Understanding non linear relationships</strong></h4><p>Linear relationships provide a simple and powerful narrative framework, however they do not describe complex real world scenarios. Lets explain with the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*JFk5Ipl9rgzHkGCcBCsNTA.jpeg" /><figcaption>Non linear relationship</figcaption></figure><p>In the example the relationship between X and Y is highly non-linear. It has both a periodic term (sin) and a growth term (quadratic term). This could represent many systems in the real world. For example X could represent demand and Y price. In that case this equation represents an overall trend of increasing price with demand but some cyclical fluctuation with demand</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*3fQtNzxACr5uauB8ZT4v0A.jpeg" /><figcaption>Non-linear relationship</figcaption></figure><p>We can clearly see from the graph above that the relationship between X and Y is not linear</p><h4><strong>Setting up non-linear synthetic data</strong></h4><p>Now lets build a synthetic non-linear dataset to test the efficacy of neural networks at predicting non-linear trends</p><pre># Setting up non-linear data<br><br>X = np.linspace(0.1,10,10000)<br><br>y = 5*np.sin(2*X) + X</pre><p>In the above code we have used numpy to generate an array X of size 10,000 with values ranging from 0.1 to 10. We then create y which is related to X and follows the relationship below. This equation is non-linear and represents growth with seasonality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*butwaZoAgxPG45h51XCSWA.png" /></figure><p>Lets visualize this relationship</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*SQRVfnGJsqX7wrQpgCnYEg.png" /><figcaption>Non-Linear relationship for prediction</figcaption></figure><h4><strong>High level overview of neural networks</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*2tort5puE7HBnRWEdwtoDA.png" /><figcaption>Schematic typical Neural network architecture</figcaption></figure><p><em>General over view</em></p><p>Neural networks are made up nodes organized in layers. The input data typically flows from 1 layer to the next. Each node in a layer applies a mathematical transformation to its inputs. This mathematical transformation is a combination of linear and non-linear elements. The linear parameters of each node are the weight <em>w </em>and bias <em>b. </em>This is similar to a linear regression. After the linear transformation is applied then a non-linear transformation is applied on top of that, generally in the form of a <em>tanh </em>or <em>ReLU </em>function and this is called an activation function. This combination of multiple nodes and linear and non-linear elements makes neural networks very powerful at modelling complex relationships.</p><p><em>Training cycle</em></p><p><em>Forward pass: </em>The input data is passed through the neural network starting from the input layer to the output layer with each layer applying weights, biases and non-linear activations. Finally the network output is compared to the actual labels/values and this comparison is quantified using a formula/function called a <em>loss function (</em><a href="https://www.datacamp.com/tutorial/loss-function-in-machine-learning"><em>see here</em></a><em>) . </em>The metric computed using this formula is called the <em>loss.</em></p><p><em>Backward Pass: </em>Now that we have a run a forward pass and have quantified how far predictions are from the ground truth, the network uses this information to calculate the gradients starting from the outermost layer working backwards. Next the weights weights and biases are updated. The way this is done is by using an algorithm called <em>gradient descent (</em><a href="https://youtu.be/IHZwWFHWa-w?si=FVvatGYJpinqd3ar"><em>good video explainer here</em></a><em>).</em></p><p>This cycle of forward and backward passes repeats until you run through the entire training data. Even simple neural networks have hundreds of parameters that need to be optimized and it probably becomes necessary to run through the training data multiple times. Each run through the training data is called an epoch</p><h4><strong>Setting up our PyTorch Neural network</strong></h4><pre># importing the nn module from torch<br>from torch import nn<br><br>#Defining the Non-linear activattion function<br>act = nn.ReLU()<br><br># Defining the network<br>class Model_comp(nn.Module):<br>  def __init__(self):<br>    <br>    super().__init__()<br>    <br>    # Input Layer with 1 input feature<br>    self.ll1 = nn.Linear(in_features=1,out_features=8)<br>    <br>    #Non-Linear activation<br>    self.ac1 = nn.ReLU()<br>    <br>    # Hidden Layers begin here<br>    self.ll2 = nn.Linear(in_features=8,out_features=32)<br>    self.ac2 = nn.ReLU()<br>    self.ll3 = nn.Linear(in_features=32,out_features=16)<br>    self.ac3 = nn.ReLU()<br>    self.ll4 = nn.Linear(in_features=16,out_features=4)<br>    self.ac4 = nn.ReLU()<br>    <br>    # Ouput Layer<br>    self.output = nn.Linear(in_features=4,out_features=1)<br><br>  # Forward pass defined as a method<br>  def forward(self,X):<br>    X = self.ll1(X)<br>    X = self.ac1(X)<br>    X = self.ll2(X)<br>    X = self.ac2(X)<br>    X = self.ll3(X)<br>    X = self.ac3(X)<br>    X = self.ll4(X)<br>    X = self.ac4(X)<br>    X = self.output(X)<br>    return(X)</pre><p>The above code block shows the architecture of the network we will use. It consists of an input layer, 3 hidden layers and an output layer. The output of each layer is passed through a non-linear activation function before being passed on to the next layer. Generally the more complex and high dimensional your data, the more layers and nodes per layer that you will need. For this demo a relatively straight forward network of 3 hidden layers should be sufficient.</p><p>All neural network related modules such as different types of layers are contained within <em>torch.nn. </em>Typically we define PyTorch neural network models as custom classes that inherit from the <em>nn.module</em> class (<a href="https://www.geeksforgeeks.org/introduction-of-object-oriented-programming/">more on OOPS here</a>)</p><p>Within the <em>Model_comp </em>class we have defined a forward method. This defines the path the data follows as it moves from layer to layer. We first pass the input X through layer ll1 followed by the non linear activation ac1, each time storing the result in X. This is the most general representation of a pytorch neural network.</p><p>Now that our network is set up we can move on to the next steps of splitting our data into train and test sets and training our model</p><h4><strong>Splitting the data into train and test sets</strong></h4><p>We now split the data into train and test sets</p><pre>from sklearn.model_selection import train_test_split<br><br># Splitting our data into train and test sets<br>X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.1,random_state=42,shuffle=True)</pre><h4><strong>Setting up our loss function and optimizer</strong></h4><p>Before we build a training loop we must define the <em>loss function </em>that we will use. The <em>loss function</em> is a formula that compares the model output to the actuals and generates a metric that quantifies how good the model predictions are. The choice of loss function is dependent on the type of problem we are trying to solve. In this case we are trying to predict a value and not a label so we have chosen <em>Mean Absolute Error (MAE) </em>which is an average of the absolute value of the difference between the model output and the actuals</p><p>Next we chose an optimizer. The optimizer decides the strategy that is used to update the weights and biases (aka parameters) of the network. The optimizer requires a hyperparameter called <em>learning rate. </em>The learning rate defines how much of a step the optimizer makes in each iteration to update the weights. This is critical, because too small a step means that the model will never converge to the optimal loss value, while too big a step means the model will oscillate around the optimal loss value. We use the Adam optimizer here, which automatically adjusts the learning rate as we get closer and closer to the minimal loss <em>(</em><a href="https://musstafa0804.medium.com/optimizers-in-deep-learning-7bf81fed78a0"><em>learn more here</em></a><em>)</em></p><pre># Setup a loss function<br>loss_fn = nn.L1Loss()<br><br># Setup an Optimizer (SGD and Adam)<br>optimizer = torch.optim.Adam(params = model.parameters(),<br>                            lr =0.001) #lr--&gt; leraning rate, very important hyperparameter</pre><h4><strong>Training and Evaluation loop workflow</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTtQbKg1qbOhvVuGniJP8g.png" /><figcaption>Typical PyTorch workflow</figcaption></figure><p>The above figure shows a typical training and evaluation loop flow. Once we have run through the entire training data and evaluated the fit on the test data we have completed what is known as an <em>epoch. </em>Typically at the end of only 1 epoch the performance of the model on unseen test data is not that good. We then have to put the model back in training mode and run another epoch.</p><p>Lets now go through this flow in some detail along with the accompanying code</p><pre>epochs = 500<br>for epoch in range(epochs):<br>  <br>  # Put the model in training mode at the beginning of an epoch<br>  model.train()<br>  <br>  #1. Fwd pass<br>  y_pred = model(X_train)<br><br>  #2. Calculate loss<br>  loss_train = loss_fn(y_pred,y_train)<br><br>  #3. Optimizer zero grad<br>  optimizer.zero_grad()<br><br>  #4. Backward pass<br>  loss_train.backward()<br><br>  #5 Optimizer step<br>  optimizer.step()<br><br><br><br>  model.eval()<br>  with torch.inference_mode():<br>    y_pred_test = model(X_test)<br><br>    loss_test = loss_fn(y_pred_test,y_test)<br><br>  if epoch % 50 == 0:<br>    print(f&quot;epoch:{epoch} | loss_train: {loss_train} | loss_test: {loss_test}&quot;</pre><p>We define our number of epochs as 500. We then set up a <em>standard python for loop</em> to loop through 500 epochs. Now we enter the train/test loop and perform the following steps.</p><ol><li>Pass the training data (X_train) through the model and generate predictions (y_pred)</li><li>Calculate the loss for the epoch. This calculates the <em>Mean Absolute Error (MAE) </em>metric we discussed earlier. Remember we set up <em>nn.L1loss </em>as our loss function which is the same thing as <em>MAE. </em>We compare y_pred to y_train (actuals) in this step</li><li>The next step is to zero out the gradients. The optimizer object by default stores all the gradients from the previous iteration. This is very memory intensive and should be avoided.</li><li>We then use <em>backward propagation </em>to calculate the gradients. The gradient for a parameter is defined as the rate of change of the error/loss function with respect to the parameter. This is same as a partial derivative of the loss wrt the weights or parameters. <em>Backward propagation is the process of the calculation of these gradients layer by layer by applying the chain rule.</em></li><li>Now that the gradients are known the optimizer updates the weights and biases of each layer. At this point one epoch is over</li><li>We then put the model in evaluation mode freezing the weights and with the model no longer learning we test it on unseen data. At this point evaluation is over and one train/evaluate epoch is over.</li><li>We then put the model back in training mode and the process continues.</li></ol><h4><strong>Results</strong></h4><p>We write a function to visualize the test data and the predictions. We see how good the predictions are after 100 epochs, then run the model for another 500 epochs.</p><pre># Visualization function<br><br>import matplotlib.pyplot as plt<br>def plot_data(training_data =X_train,<br>              training_labels=y_train,<br>              test_data=X_test,<br>              test_labels=y_test,<br>              predictions=None):<br>  &quot;&quot;&quot;<br>  Plots test data and actuals in red and test_data vs predictions in blue.<br>  &quot;&quot;&quot;<br>  fig,ax = plt.subplots(figsize=(10,7))<br>  ax.scatter(test_data,test_labels,c=&#39;r&#39;,label=&#39;test_data&#39;)<br>  if predictions is not None:<br>    ax.scatter(test_data,predictions,label=&#39;predictions&#39;)<br>  ax.set_xlabel(&quot;X&quot;)<br>  ax.set_ylabel(&quot;y&quot;)<br>  ax.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mWnTvrUTaajB7NSOcKzkoQ.png" /><figcaption>Neural Network learning non linear pattern</figcaption></figure><p>As we can see that after a total of 600 epochs the predictions are very close to the test data and the neural network has learned the non-linear relationship between X and Y</p><p>Please see the full code on github here:</p><p><a href="https://github.com/gmehra123/PORTFOLIO/blob/main/Testing_notebook.ipynb">https://github.com/gmehra123/PORTFOLIO/blob/main/Testing_notebook.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc1490d427be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/master-non-linear-modeling-neural-networks-with-pytorch-dc1490d427be">Master Non-Linear Modeling: Neural Networks with PyTorch</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Revenue Forecasting in E-commerce: The Power of Simulations]]></title>
            <link>https://medium.com/operations-research-bit/exploring-revenue-forecasting-in-e-commerce-the-power-of-simulations-0a68a4709e67?source=rss-8de2842c14be------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a68a4709e67</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[forecasting]]></category>
            <dc:creator><![CDATA[Gaurang Mehra]]></dc:creator>
            <pubDate>Fri, 10 May 2024 11:07:26 GMT</pubDate>
            <atom:updated>2024-05-28T00:34:04.034Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Objective: </strong>In this blog post I will explore the use of simulations for a typical e-commerce use case.</h4><p>We will use simulations to forecast the monthly revenue for an e-commerce company.</p><p>The typical business flow for an e-commerce company can be represented by the block diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oE-bgG1nAx5lUTB_6_IeUA.png" /><figcaption>Fig 1.1 Block Diagram of e-commerce flow</figcaption></figure><p>The widest part of the funnel is <strong>impressions. </strong>An impression is recorded when a customer sees a web ad. Some prospective customers who see the ad or search result click through to the website. Of the customers who <strong>click through</strong> only a few sign up and of the customers who sign up only a few purchase.</p><p>We can model this flow in the following way</p><ul><li>We can find the historical number of <strong>avg monthly</strong> impressions. In this case we assume 100K. We can model the impressions as a <strong>Poisson</strong> random variable with the <em>lambda </em>parameter set to the average number of impressions (100K in this case). Poisson distribution is a good choice here because the number of impressions is a discrete number and impressions are independent of each other.</li><li>Clicks and sign-ups both have binary outcomes and so can be modelled using the <strong>binomial </strong>distribution. For clicks the number of trials <em>n </em>is the number of impressions from the previous step and the probability <em>p </em>is the historical click through rate (ctr). For sign-ups the <em>n </em>is defined by the number of clicks(from previous step) and probability <em>p </em>is the sign-up rate (str)</li><li>Purchases is also a binary yes/no event defined by the binomial distribution with <em>n</em> as the number of sign-ups in the previous step and <em>p </em>as the purchase probability again something we can get from historical data</li><li>The value of the purchases (ticket size) can be defined as a <strong>normal</strong> distribution with mean = historical ticket size and std deviation = historical std deviation. In this case we have used a normal distribution in some cases other distributions might be a better fit.</li><li>We will run this flow a thousand times each time storing the result of revenue and this will give us some idea of the variability of revenue</li></ul><p>Now lets model this in Python</p><pre># Import basic libraries<br>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Import interactivity components for later<br>from __future__ import print_function<br>from ipywidgets import interact, interactive, fixed, interact_manual<br>import ipywidgets as widgets<br><br>def get_signups(avg_impressions,ctr,str_):<br>    impressions = np.random.poisson(avg_impressions)<br>    clicks = np.random.binomial(n=impressions,p=ctr)<br>    signups = np.random.binomial(n=clicks,p=str_)<br>    return(signups)</pre><p>In this first part we write a function that models the first part of the flow until signups. The function takes 3 arguments <strong>avg_impressions, ctr (for click through rate) and str_(for sign up rate). </strong>This function first generates a number of impressions based on the avg_impressions parameter and following the Poisson distribution. Then clicks and sign ups are generated using binomial distributions. For clicks the number of trials <em>n </em>is the number of impressions and so on. The function returns the number of sign ups.</p><pre>def get_revenue(signups,pur_rate,avg_tkt,std_tkt):<br>    purchases = np.random.binomial(n=signups,p=pur_rate)<br>    purchase_vals = np.random.normal(avg_tkt,std_tkt,size=purchases)<br>    revenue = np.sum(purchase_vals)<br>    return(revenue)</pre><p>This second part of the code models the flow from signups to getting the revenue. The purchases follow a binomial distribution with <em>n </em>as the number of sign ups and <em>p</em> as the historical purchase rate. Each of the purchases is assigned a purchase value according to the normal distribution with the <em>mean </em>= avg ticket size and <em>std dev </em>= historical std deviation. We then sum all the purchase values to get monthly revenue</p><pre>@interact(avg_impressions=[100000,120000,150000],ctr=[0.01,0.025,0.05],str_=[0.1,0.15,0.2])<br>def run_simulation(avg_impressions,ctr,str_,pur_rate=0.3,avg_tkt_size=100,std_dev_tkt=20):<br>    rev_tot = []<br>    for i in range(1000):<br>        signups = get_signups(avg_impressions,ctr,str_)<br>        rev = get_revenue(signups,pur_rate,avg_tkt_size,std_dev_tkt)<br>        rev_tot.append(rev)<br>    rev_tot = np.array(rev_tot)<br>    <br>    plt.hist(rev_tot)<br>    plt.show()<br>    print(&quot;Median revenue is &quot;,np.median(rev_tot))</pre><p>We create a function called <strong>run_simulation. </strong>This is a wrapper function inside which we call the <strong>get_signups </strong>and <strong>get_revenue </strong>functions. We set up this function to be interactive using the interact decorator and vary the avg_impressions, ctr, str and all other parameters. We then run the simulation 1,000 times and get a distribution of revenue. We can change the avg impressions for the Poisson distribution driving impressions using the interactive dropdown. We can do the same for ctr.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*pGkiJV_DJBG1BidFyllUmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*CjYAKcmQWxlbiuYQ5iTPDQ.png" /><figcaption>Fig 1.3 Effect of changing average click through rate (ctr) on revenue</figcaption></figure><p>In the figure above we can see that changing the average click through rate from 1% to 2.5% has a massive impact on the median revenue increasing it from ~$2,900 to ~$7,500.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*YCU4SgQtLJYmtwB8sLuS6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*t9dVKqa-_FBxS4GoB8Kykw.png" /><figcaption>Fig 1.4 Effect of increasing avg impressions</figcaption></figure><p>If we increase avg impressions by 50% we see that revenue goes up from ~$3,000 to ~$4,500 a 50% increase. Again we can change 1 factor or a combination of factors to show how the median or the 95% confidence interval changes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a68a4709e67" width="1" height="1" alt=""><hr><p><a href="https://medium.com/operations-research-bit/exploring-revenue-forecasting-in-e-commerce-the-power-of-simulations-0a68a4709e67">Exploring Revenue Forecasting in E-commerce: The Power of Simulations</a> was originally published in <a href="https://medium.com/operations-research-bit">Operations Research Bit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Attrition. Feature Driven Survival Analysis]]></title>
            <link>https://medium.com/analytics-vidhya/managing-attrition-feature-driven-survival-analysis-1286478860f5?source=rss-8de2842c14be------2</link>
            <guid isPermaLink="false">https://medium.com/p/1286478860f5</guid>
            <category><![CDATA[lifetime-value]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[churn-analysis]]></category>
            <dc:creator><![CDATA[Gaurang Mehra]]></dc:creator>
            <pubDate>Sun, 28 Apr 2024 16:24:00 GMT</pubDate>
            <atom:updated>2024-04-28T16:24:00.105Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second article in the Survival Analysis series. The first article (<a href="https://medium.com/@gaurangmehra/managing-attrition-an-introduction-to-survival-analysis-dd9c3db5e82d">here</a>) was an introduction to Survival analysis using simple non-parametric methods namely the Kaplan Meier method.</p><p>Survival Analysis is a class of models and techniques used to analyze and predict time to an event. Survival Analysis can be useful in any context where we want to analyze the time to an event, some examples below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*JnyCoxQhN0qWre3C_k-glQ.png" /><figcaption>Fig 1.1 Uses of Survival Analysis</figcaption></figure><p>Survival Models broadly fall into 2 categories</p><ul><li><strong>Non-Parametric Survival models: </strong>These are built directly from the data. They assume no parameters or a distribution. In a business context they give good high level segment averages but cannot perform sensitivity analysis. They also tend to be stepped or discontinuous.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*EmYw_VLtvG9JXZsWOxYvqg.png" /><figcaption>Fig 1.2 Kaplan Meier Survival</figcaption></figure><ul><li><strong>Parametric Models: </strong>These are generally Survival Regression models and are built for sensitivity analysis. Can be used to answer questions like <em>keeping all else constant </em>how will time to event be impacted if one feature is changed</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HSEeVisxeI6MZC09mUKvrw.png" /><figcaption>Fig 1.3 Smooth survival curves and sensitivity analysis</figcaption></figure><p>Now lets look at how parametric models work. Fully parametric models are also known as AFT (Accelerated Failure Time) models and are represented by the equation below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*8HTNyALER24qiKOjHzD9Ig.png" /><figcaption>Fig 1.4 AFT Model equation</figcaption></figure><ul><li><strong>X</strong> represents the time to event</li><li><strong>e </strong>in this case represents a base distribution. We need to find a base distribution that fits the data well</li><li><strong>x1….xn </strong>represent the features and <strong>w1…..wn</strong> represent the weights or regression coefficients attached to the features.</li><li>In other words there is a base survival curve and changing the feature value accelerates or decelerates the time to event and changes the shape of the survival curve. A negative coefficient for a feature has the effect of decreasing the time to event as the feature value increases.</li></ul><p>Now lets apply this to a dataset. We will use the <a href="https://assets.datacamp.com/production/repositories/5850/datasets/4e20aa97a26bbe32106a94b76ae4cabf1a632d59/rossi.csv">Prison recidivism dataset </a>to understand what factors affect time to arrest for a population of previous offenders. We will visualize the results and try to generate some predictions. Fortunately Python has a robust package called <em>lifelines</em> for all kinds of Survival Analysis, which we will use below.</p><pre>import pandas as pd<br>from lifelines import KaplanMeierFitter<br>from lifelines import WeibullFitter<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Loading the dataset<br>prison = pd.read_csv(&#39;https://assets.datacamp.com/production/repositories/5850/datasets/4e20aa97a26bbe32106a94b76ae4cabf1a632d59/rossi.csv&#39;)<br><br>prison.head()<br><br>prison.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*OFJIPiecXaNqXliwNQNznA.png" /><figcaption>Fig 1.5 First 5 rows of data</figcaption></figure><p>Looking at the first 5 rows we can see a series of variables like paroled (paro), priors (prio), age, race etc. The event of interest is <em>arrest</em> and the duration column is <em>week. arrest=</em>1 means an arrest took place and the corresponding duration is <em>week</em>.</p><p>Now lets try to build a parametric survival model. The first step in this process is to try to find a baseline distribution that fits the actual survival. This would correspond to the term e in the equation below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*tnel9MA16wfVywNthwtYqA.png" /><figcaption>Fig 1.6 Equation with baseline distribution</figcaption></figure><p>An easy way to visualize this is to see if a distribution overlays closely over the Kaplan Meier curve. Within the lifelines package we have many candidate distributions like the <em>Lognormal, Weibull, Exponential etc. </em>Here we try some such distributions using the code below</p><pre>from lifelines import LogNormalFitter<br>from lifelines import ExponentialFitter<br>from lifelines import LogLogisticFitter<br>from lifelines import KaplanMeierFitter<br>from lifelines import WeibullFitter<br>from lifelines.plotting import qq_plot<br><br># Instantiating the various distribution fitters<br><br>wb = WeibullFitter()<br>ln = LogNormalFitter()<br>Exp = ExponentialFitter()<br>logit = LogLogisticFitter()<br>kmf = KaplanMeierFitter()<br><br># Fitting to the data to get the best possible parameters for each distribution<br><br>wb.fit(durations=prison[&#39;week&#39;],event_observed=prison[&#39;arrest&#39;])<br>ln.fit(durations=prison[&#39;week&#39;],event_observed=prison[&#39;arrest&#39;])<br>Exp.fit(durations=prison[&#39;week&#39;],event_observed=prison[&#39;arrest&#39;])<br>logit.fit(durations=prison[&#39;week&#39;],event_observed=prison[&#39;arrest&#39;])<br>kmf.fit(durations=prison[&#39;week&#39;],event_observed=prison[&#39;arrest&#39;])<br><br># Plotting the various distributions over the Kaplan Meier Fitter <br><br>plt.style.use(&#39;ggplot&#39;)<br>fig,ax = plt.subplots()<br>ax = kmf.plot_survival_function()<br>ax = wb.plot_survival_function()<br>ax = Exp.plot_survival_function()<br>ax = logit.plot_survival_function()<br>ax.set_title(&#39;Survival Parametric Models vs Kaplan Meier Actuals&#39;)<br>ax.set_ylabel(&#39;Fraction&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ZV_gJ-kNZNsD-fde8ZqA3g.png" /><figcaption>Fig 1.7 Overlay distributions over KM curves</figcaption></figure><p>Its not very clear here, but the logit and the Weibull distributions seem to overlay the closest on the KM curve. Another way is to use a <em>qq_plot </em>which compares the actual quantiles with the quantiles predicted by the distribution. If the empirical quantiles line up with the distribution quantiles then scatter points will be along the y=x line as shown in the plots below.</p><pre><br># Code to generate qq_plots from the already fitted models<br><br>models = [wb,ln,Exp,logit]<br>for model in models:<br>    qq_plot(model)<br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_L0oTDSDWF6D-YLdsuBYIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FYgP3O_mnofrFdgFZ_LtAw.png" /><figcaption>Fig 1.8 qq_plots</figcaption></figure><p>Based on the qq_plot it is very clear that the Weibull distribution and logit are very close fits, we will use Weibull as our base distribution.</p><p>Now we can build the Survival regression model. This model will model the baseline survival using Weibull distribution and build a regression model on top of it which will give us an estimate of how much each factor, in this case like race or age, causes a deviation from the baseline survival.</p><p>To accomplish this we import the <em>WeibullAFTFitter() </em>class. This class has methods to fit a regression on top of a baseline Weibull curve.</p><pre>from lifelines import WeibullAFTFitter<br><br>aft = WeibullAFTFitter()<br><br># In this case we are using all columns in the data set<br><br>aft.fit(prison,duration_col=&#39;week&#39;,event_col=&#39;arrest&#39;)<br><br>aft.summary</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ll6aWmyAE91EObnIoM_WRQ.png" /><figcaption>Fig 1.9 Regression results</figcaption></figure><p>The summary of the results is as shown in the table above.</p><ul><li>The 2 most important columns are <em>exp(coef)</em> and the <em>p</em> column.</li><li>Since the regression model is fit on Log of the time (X) so the exponent of the coefficient is more interpretable.</li><li>The p column shows the p_value and the features <em>prio </em>corresponding to priors and <em>age</em> have p values less than 0.05 and are statistically significant</li></ul><p>Lets use the <em>plot_partial_effects_on_outcome </em>method to understand the effect of each of these factors vs the baseline survival</p><pre># Plotting Effect of priors on time to arrest<br><br>fig,ax = plt.subplots(figsize=(6,4))<br>ax = aft.plot_partial_effects_on_outcome(&#39;prio&#39;,[0,2,6])<br>plt.title(&#39;Effect of priors on time to arrest&#39;)<br><br>#Plotting Effect of age on time to arrest<br><br>fig,ax = plt.subplots(figsize=(6,4))<br>aft.plot_partial_effects_on_outcome(&#39;age&#39;,[20,26,35])<br>plt.title(&#39;Effect of age on time to arrest&#39;)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-kaybzjkSZQ1H6cuckIbmg.png" /><figcaption>Fig 1.10 Effect of priors and age on time to arrest</figcaption></figure><pre># Predicting survival for new customers in the data frame called new<br><br>aft.predict_survival_function(new).transpose()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*smnFECZcdS2C3k99_ONMeQ.png" /><figcaption>Fig 1.11 New customers scored</figcaption></figure><p>We can also use the <em>predict</em> method and pass new instances and the fitted model will predict a survival curve for the new instance. In the business context new signups or subscriptions can be scored or assigned a survival curve at the time of sign up. This kind of model can be used as the first step in calculating <em>Customer Lifetime Value (CLV).</em></p><p><strong>Key shortcoming of this approach and possible alternatives</strong></p><p>To use this approach it is critical to find a parametric distribution that fits the actual data (baseline distribution) fairly well. For this we can use qq_plots (as discussed above). In the above example the Weibull distribution fit the data well. In some cases you will not find a distribution that fits the data, in which case the parametric approach will not be an ideal approach. In such cases <em>semi-parametric</em> models may be used.</p><p>In conclusion parametric models are very powerful models to predict survival. They can estimate the effect of different <em>features/covariates </em>on the survival and can be used to predict personalized survival. This is very useful to understand what factors can affect attrition for customers or equipment failure in the case of operations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1286478860f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/managing-attrition-feature-driven-survival-analysis-1286478860f5">Managing Attrition. Feature Driven Survival Analysis</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Attrition. An introduction to Survival Analysis]]></title>
            <link>https://medium.com/@gaurangmehra/managing-attrition-an-introduction-to-survival-analysis-dd9c3db5e82d?source=rss-8de2842c14be------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd9c3db5e82d</guid>
            <category><![CDATA[survival]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Gaurang Mehra]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 02:07:52 GMT</pubDate>
            <atom:updated>2024-02-26T02:07:52.013Z</atom:updated>
            <content:encoded><![CDATA[<p>Survival analysis is a class of models and techniques used for time to event analysis. The event can be a machine failure, loss of a customer (churn) or in the case of medical studies death after diagnosis. This class of models finds wide application in subscription businesses where knowing the lifetime of a customer, the time to loss, is critical in determining Customer Lifetime Value (CLV). For the purposes of this article we will assume an event to be a customer that is lost.</p><p>While working on survival analysis we need to keep in mind 2 key concepts</p><ol><li><strong>Censoring: </strong>Survival studies have a defined end point with customers or observations entering the study at various points. Customers/observations that have reached the end of the study without the event taking place are called censored. In the figure below the 3rd and 4th observations are censored as the event, in this case customer loss has not yet occurred. For observation 4 all we can say is that the duration/lifetime is at least as long as 15 months.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQVv_tY0y3UTg-P6RlOrmw.png" /><figcaption>Fig 1.1 showing censoring</figcaption></figure><p>2. <strong>Event table: </strong>Knowing the censored observations we can build an event table as shown below. We order all the observations/customers by duration. We observe that all 4 observations have duration=0 and at duration=0 the population at risk is still 4. At duration =3 we observe our first event or loss and the population at risk still remains 4 (population at risk is defined at the beginning of the duration period). At duration =5 we have our 2nd loss and our population at risk drops to 3 since we already had a loss at duration=3. At duration=10 we have censored observation which reduces the population at risk but the number of events at duration=10 are still 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*Zf2bLIvpqoavs627XQ6zLA.png" /><figcaption>Fig 1.2 Event table</figcaption></figure><p>Once we have built this table we can calculate the hazard or the risk of loss happening at duration=t, or customer tenure=t given that they have survived till t. This is calculated as</p><p><strong>h(t) = number of events at t/pop at risk at t</strong></p><p>We can then calculate the momentary survival as</p><p><strong>Momentary Survival = (1-h(t))</strong></p><p>The full survival function till time t can be calculated as follows</p><p><strong>Survival Function =(1-h0)*(1-h1)*(1-h2)…..*(1-h(t))</strong></p><p>We can then plot the survival function column against the event at column to get a survival curve. We just built our first curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*RmPLipccF6anygwHTfpneQ.png" /><figcaption>Fig 1.3 First Survival Curve</figcaption></figure><p>This curve clearly has 2 major problems</p><ul><li>We do not have enough data to estimate a survival for the entire population. Typically the dataset you use to build a survival curve should have at least a few hundred observations that are representative of the underlying population</li><li>The proportion of censored observations is too high (50%). Typically the proportion of censored observations should be less than 40% for this kind of survival analysis to be useful</li></ul><p>This class of survival analysis where we build an event table from the data and calculate the survival function from the event table is called Kaplan Meier analysis. Fortunately we do not need to build the event table manually. The Python lifelines library has an inbuilt class called KaplanMeierFitter. We need to only provide a durations column and an event observed column to an object of the KaplanMeierFitter class.</p><p>This type of model has a few pros and cons</p><p><strong>Pros</strong></p><ol><li>Simple and intuitive to understand</li><li>Very commonly used across industries</li><li>Leads to simple graphical representation</li></ol><p><strong>Cons:</strong></p><ol><li>Descriptive not predictive. Since there is no learning involved it cannot predict on new data. At best you can match new data to a broad segment from the existing data</li><li>Is not very suitable for sensitivity analysis. For eg. it cannot answer questions like <em>keeping all else constant how will survival be impacted if I change price by 1 cent?</em></li></ol><p>Now lets see how we can apply this to a real world dataset. The dataset we are using is a dataset of regimes across countries over time from Data Camp. The duration column is the duration of a particular regime in a particular country</p><pre>from lifelines import KaplanMeierFitter<br>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br># importing data<br>import os<br>os.chdir(&quot;/content/drive/MyDrive/Colab Notebooks/Datacamp/Survival Analysis (1)&quot;)<br><br>regime = pd.read_csv(&#39;dd.csv&#39;)<br><br>regime.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sK-MRk70FKKP1GofPTP_Aw.png" /><figcaption>Fig 1.4 Head of regimes data</figcaption></figure><p>The head of the data frame shows us how the data is organized. We have an event column (observed) which describes if the regime has reached its end and a duration column which describes the duration. If observed = 0 and we have a duration that means the observation was censored.</p><pre>#Instantiate a KaplanMeierFitter object<br>kmf = KaplanMeierFitter()<br><br>#Fit it to the data<br>kmf.fit(regime[&#39;duration&#39;],regime[&#39;observed&#39;])<br><br># Plot the survival Function<br>kmf.plot_survival_function()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*t6gxfehhXiWGSeRD57Y5zQ.png" /><figcaption>Fig 1.5 Kaplan Meier survival curve for regimes data</figcaption></figure><p>Looking at this curve we can see that the median survival time is ~5 years. Fortunately we can just calculate this handily using the <strong>median_survival_time_ </strong>attribute. We can also get the survival function as a table.</p><pre>print(&quot;The Median survival time of a regime is&quot;,kmf.median_survival_time_)<br>kmf.survival_function_</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*lpzZtPcihl9dC1bhuCxgHg.png" /><figcaption>Fig 1.6 Survival function</figcaption></figure><p>We can also compare the survival of 2 sub-groups in the data, in this case the regimes of Western Europe with those of Southern Asia. We simply filter the base dataset to these subgroups using the pandas loc method. We then fit these sub-groups using the KaplanMeierFitter liek earlier</p><pre># Instantiate 2 Kaplan Meier fitter objects for W Europe and S Asia<br>kmf_w_europe = KaplanMeierFitter()<br>kmf_s_asia= KaplanMeierFitter()<br><br># Filter to Western Europe fit to the kmf_w_europe<br>kmf_w_europe.fit(regime.loc[regime.un_region_name==&#39;Western Europe&#39;,&#39;duration&#39;],<br>                 regime.loc[regime.un_region_name==&#39;Western Europe&#39;,&#39;observed&#39;])<br><br># Filter to Southern Asiafit to the kmf_s_asia<br>kmf_s_asia.fit(regime.loc[regime.un_region_name==&#39;Southern Asia&#39;,&#39;duration&#39;],<br>                 regime.loc[regime.un_region_name==&#39;Southern Asia&#39;,&#39;observed&#39;])<br><br># Plotting the results<br>fig,ax = plt.subplots()<br>kmf_w_europe.plot_survival_function(ax=ax,label=&quot;Survival curve Western Europe&quot;)<br>kmf_s_asia.plot_survival_function(ax=ax,label= &quot;Survival curve Southern Asia&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*ItSipcZY2WCAgnxCWy98Ow.png" /><figcaption>Fig 1.7 Comparing Western European regimes to Southern Asian regimes</figcaption></figure><p>Clearly we can see that Western European regimes last for a shorter duration than Southern Asian regimes. This makes sense given that democratic regimes have regular elections and power shifts from one party or leader to another. Southern Asia over time has had long running dictatorships/monarchies which shows up as higher regime survival on the survival curve.</p><p>As we can see the Kaplan Meier curve is not smooth and as the segment size gets smaller the curve becomes more stepped and discontinuous. This is generally not great for business forecasting.</p><p>Another set of models called parametric models addresses this issue. Not only this but parametric models can easily run sensitivity analysis and estimate the effect of individual factors on survival. More of this in the next article</p><p>github link: <a href="https://github.com/gmehra123/data_science_projs/blob/main/Survival_Analysis.ipynb">https://github.com/gmehra123/data_science_projs/blob/main/Survival_Analysis.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd9c3db5e82d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to writing Python packages for Data Scientists]]></title>
            <link>https://medium.com/analytics-vidhya/guide-to-writing-python-packages-for-data-scientists-ac740a98cb94?source=rss-8de2842c14be------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac740a98cb94</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Gaurang Mehra]]></dc:creator>
            <pubDate>Fri, 11 Aug 2023 22:54:44 GMT</pubDate>
            <atom:updated>2023-08-11T22:54:44.272Z</atom:updated>
            <content:encoded><![CDATA[<p>Write a python package for common Data science tasks.</p><p>Most code in Data Science and the Machine Learning world tends to be linear and in Jupyter notebooks. While notebooks are a great way to get started, they are not great for writing modular code. There are many tasks in your Data Science workflow which you might want to perform again and again. You should write functions for these tasks and group functions that perform similar tasks in a package. This way you can use these packages from one project to the next. In this article we will walk through a package that contains functions to impute missing values and to standardize all column names to lower case. These are tasks that are repeatable and are amenable to set up as functions in a preprocessing package.</p><p>The first step is to set up your package directory. There are 2 ways to do this:</p><ul><li>Set up your own <em>bare bones package directory</em>. This should have 2 things, an __init__.py file and the script. This package directory is a local module that you can copy paste into every project and then import and use</li><li>Use cookie cutter to create a project template complete with set up tools. You can install this at an <em>environment level</em>, and then import like numpy or pandas. Using the <em>cookiecutter</em> package and a template will automatically create the package template with important file templates like a readme file and a setup file. You can fill out these templates to the level of detail that you require.</li></ul><p><strong><em>Part 1: Writing a bare bones package</em></strong></p><p>In order to write a barebones package you need to create your folder with your package name. In that folder you need a __init__.py file. This file tells python that this directory is a package. Its generally a blank file. You will also need to create a file with your functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*dh91PHLMLw47WeG90tpwAA.jpeg" /><figcaption>fig 1.1 package directory</figcaption></figure><p>The __init__.py file and the file with the preprocessing code called <em>pre1</em> is stored in the module folder called preprocessing</p><p>The <em>pre1</em> file contains functions to standardize the column headers of a dataframe and to impute missing values. The functions are general and can take any dataframe as an input. See the code below and some notes:</p><ul><li>We need both numpy and pandas so we have imported them at the the top of the <em>pre1 </em>file.</li><li>We have written our functions below that. A good practice is to have docstrings using triple quotes for each function. A standard docstring contains<br>- Short function description<br>- Parameters, what parameters does the function take<br>- Returns, what type of value does the function return</li></ul><pre>import numpy as np<br>import pandas as pd<br><br>def low_case_columns(df):<br>    &quot;&quot;&quot;Function to standardize column headers to lower case<br>    <br>    Parameters<br>    ----------<br>    df : pandas dataframe<br>        pandas data frame for which you need lower case columns<br><br>    Returns<br>    -------<br>    df: pandas data frame<br>        dataframe with transformed column headers to lower case<br>    &quot;&quot;&quot;<br>    df.columns = df.columns.str.lower()<br>    return df<br><br><br>def impute_numeric_values(df,method=np.mean):<br>    &quot;&quot;&quot;Takes a data frame and imputes missing values for the all the numeric columns<br><br><br>    Parameters<br>    ----------<br>    df : pandas dataframe<br>        data frame with missing values<br>    method : func, optional<br>        method used to impute missing values, by default np.mean<br>        <br>    Returns<br>    -------<br>    df : pandas data frame<br>        dataframe with missing values imputed<br>    &quot;&quot;&quot;<br>    num_cols=df.select_dtypes(include=[&#39;int&#39;,&#39;float&#39;]).columns<br>    for col in num_cols:<br>        df[col] = df[col].fillna(value=np.mean(df[col]))<br>    return(df)<br><br><br>def impute_object_columns(df):<br>    &quot;&quot;&quot;Takes a dataframe and imputes using mode for object columns with nan<br><br>    Parameters<br>    ----------<br>    df : pandas dataframe<br>        Dataframe with missing values<br>        <br>    &quot;&quot;&quot;<br>    obj_cols=df.select_dtypes(include=&#39;object&#39;).columns<br>    for col in obj_cols:<br>        df[col] = df[col].fillna(value = df[col].value_counts()[0])</pre><p>We can now use this package. The only caveat is that your script has to be in the same directory as the package directory. If not you will get an import error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*bGpGzIgiGB17Bp-XSVBfLQ.jpeg" /><figcaption>Fig 1.2 Creating test jupyter notebook in package directory</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*_jWS2hEh6baqbTmtsutLUw.jpeg" /><figcaption>fig 1.3 importing package and using it in test notebook</figcaption></figure><p>We import the pre1 module from preprocessing using the dot notation as shown in line 1 above. We can then access the functions in the pre1 module. Since these are general functions for any dataframe we used them on a toy dataframe that we have defined in the second line of code. Here we see that the functions <em>low_case_columns</em> and <em>impute_numeric_values </em>work as intended.</p><p>In this case we created a package with some general use functions and used it in a local folder. In part 2 we will see how to install a package in our environment</p><p><strong><em>Part 2: Writing a package at an environment level</em></strong></p><p>In this case we use cookie cutter and the link to a package template. Cookie cutter then asks a set of questions and creates a package template folder. In this folder you will have a set of template files and a code folder.</p><ol><li>Install cookie cutter using pip</li></ol><pre>pip install cookiecutter</pre><p>2.<em> </em>Use<em> cookiecutter </em>together with a link to a package template. In this case we use the Oldani template and answer the questions.<br>- Best practice to use pytest<br>- Always use a version number<br>- Provide a project name and a slug</p><pre>(plotly) C:\Users\gaura&gt;cookiecutter https://github.com/oldani/cookiecutter-simple-pypackage<br>full_name [Ordanis Sanchez]: Gaurang Mehra<br>email [ordanisanchez@gmail.com]: gaurangmehra@gmail.com<br>github_username [oldani]: gmehra123<br>project_name [Python Boilerplate]: preprocess<br>project_slug [preprocess]: preprocess<br>project_short_description:<br>pypi_username [gmehra123]:<br>version [0.1.0]: 0.1.0<br>use_pytest [n]: y<br>use_pypi_deployment_with_travis [y]: n<br>add_pyup_badge [n]: n<br>Select command_line_interface:<br>1 - Click<br>2 - No command-line interface<br>Choose from 1, 2 [1]: 1<br>create_author_file [y]: y<br>Select open_source_license:<br>1 - MIT license<br>2 - BSD license<br>3 - ISC license<br>4 - Apache Software License 2.0<br>5 - GNU General Public License v3<br>6 - Not open source<br>Choose from 1, 2, 3, 4, 5, 6 [1]:5</pre><p>3. Now we navigate to the preprocess folder. This folder has a readme file which is a template. You can fill out this readme template file. It also has a license file with the license information that you provided in the previous step</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*emAQy33Jew7NHgXX1A39ag.jpeg" /><figcaption>fig 1.4 Template package directory</figcaption></figure><p>4. Now we go to preprocess folder and navigate to the file labelled preprocess. we then copy our script with the functions in this file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*aU9ANRLd8LQwAAS0UY8VLw.jpeg" /><figcaption>Fig 1.5 Copy paste the functions into the template preprocess file</figcaption></figure><p>5. Copy and paste the script functions into the template file.</p><p>6. Now navigate to the folder and install using pip. Use the -e option so you can install the package in editable mode.</p><pre>(plotly) C:\Users\gaura&gt;cd preprocess<br><br>(plotly) C:\Users\gaura\preprocess&gt;pip install -e.</pre><p>Now the package is installed at an environment level. Check within your environment’s package list. You should see the package in the package list of your environment (see below fig 1.6). You can also create a test notebook outside the folder import the package and test (see below fig 1.7)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*yrIvhQqHa3t-VADsipIHpQ.jpeg" /><figcaption>Fig 1.6-: Checking the package list</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*b6mU70eL4JO7HzyYy3EQ-g.jpeg" /><figcaption>Fig 1.7 Environment level install test</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac740a98cb94" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/guide-to-writing-python-packages-for-data-scientists-ac740a98cb94">Guide to writing Python packages for Data Scientists</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dimension reduction with PCA for everyone]]></title>
            <link>https://medium.com/analytics-vidhya/dimension-reduction-with-pca-for-everyone-e9c422369547?source=rss-8de2842c14be------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9c422369547</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[dimensionality-reduction]]></category>
            <dc:creator><![CDATA[Gaurang Mehra]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 20:34:53 GMT</pubDate>
            <atom:updated>2023-04-10T20:34:53.271Z</atom:updated>
            <content:encoded><![CDATA[<h3>Brief Introduction</h3><p><strong><em>Objective-: </em></strong>The objective of this article is to explain dimension reduction as a useful preprocessing technique before fitting to a model and showing the workflow in Python.</p><p><strong><em>Use Case-: </em></strong>Sometimes while building a predictive model you can come across datasets with large number of columns/features also known as dimensions. Finding out which columns have the most predictive power can be difficult in these circumstances. This is where dimension reduction is useful</p><p><strong><em>Intuition behind Dimension Reduction-: </em></strong>The best way to explain the concept is via an analogy. When we build a a house we use blueprints on paper. The blueprints are a 2 dimensional representation of a 3 dimensional house which convey all the important information about the 3 dimensional house in 2 dimensions. Mathematically speaking we have projected 3 dimensions onto 2 dimensions while preserving the most important information. We can extend this operation to n (many dimensions). PCA (Principal Component Analysis) can take a dataset with n(eg. 50 columns) dimensions and reduce it to 2–3 dimensions known as principal components. Each principal component is a combination of all n columns represented as 1 column. Basically using PCA we create 2,3 or 4 new features that capture the essence of the information contained in the dataset with high dimensions or columns .Typically the 1st 2 or 3 components capture most of the variance in the dataset. This is a simple explanation, more mathematical explanations using linear algebra are available on Youtube <a href="https://www.youtube.com/watch?v=PFDu9oVAE-g&amp;list=PL0-GT3co4r2y2YErbmuJw2L5tW4Ew2O5B&amp;index=14">here.</a></p><h3><strong>Implementation in Python</strong></h3><p>Now that we know the intuition behind dimension reduction let’s see how we would apply it in a practical setting on a dataset. We will use the breast cancer dataset. The dataset has 31 features/measurements like radius, concavity, compactness etc. and the variable we want to predict is whether the tumor is cancerous or benign.</p><p>We start with a few pre-processing steps.</p><ul><li>First we encode the response variable using label encoder</li><li>We then create a features array which only includes the features and not the response variable</li><li>We also do some exploratory data analysis on the response variable</li></ul><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import numpy as np<br>from sklearn.model_selection import train_test_split<br>from sklearn.pipeline import make_pipeline<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.preprocessing import LabelEncoder<br>from sklearn.decomposition import PCA</pre><pre>cancer=pd.read_csv(&#39;https://assets.datacamp.com/production/repositories/1796/datasets/0eb6987cb9633e4d6aa6cfd11e00993d2387caa4/wbc.csv&#39;)<br><br># Encoding the response variable<br>le=LabelEncoder()<br>cancer[&#39;diagnosis&#39;]=le.fit_transform(cancer.diagnosis)<br>y=cancer[&#39;diagnosis&#39;]<br><br># Dropping response variable and the unnamed column<br>features=cancer.drop(columns=[&#39;Unnamed: 32&#39;,&#39;diagnosis&#39;,&#39;id&#39;])<br><br># Checking the distribution of the response variable<br>cancer.diagnosis.value_counts(normalize=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*4YM6rWGvqZg9-M6HDOg8Ng.jpeg" /><figcaption>Fig 1.1 Response Variable Distribution</figcaption></figure><p>As we can see above 62% of the cases in our dataset are benign and 37% are cancerous. This will be useful when we build a model.</p><p>Now our first step is to find the number of Principal Components that explain most of the variance in the dataset. This dataset has 30 features/Dimensions right now. The PCA algorithm will create new features which are a combination of these 30 features. As a first step we create 30 Principal Components. Generally the first 2 to 5 Principal Components explain most of the variance in the data. Python makes the process simple because the PCA package has an associated method called explained_variance_. This process is also known as finding the intrinsic dimension of the data</p><pre># Building a pipeline with the pca and scaling steps<br>scaler=StandardScaler()<br>pca=PCA()<br>pipeline=make_pipeline(scaler,pca)<br><br># Fitting to the features array<br>pipeline.fit(features)<br><br># Now lets look at the Principal Components<br>pd.DataFrame(pca.components_,columns=features.columns).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OXFSdMjJN4S-1-WlN_LwJg.jpeg" /><figcaption>Fig 1.2 First 5 Principal Components</figcaption></figure><p>The above figure shows the first 5 Principal Components (rows) and how they are constructed from the existing features. You can think of the numbers as roughly analogous to the weights that each component puts on a feature.</p><p>Now lets plot all the Principal Components vs their explained variance to find the intrinsic dimension of the dataset.</p><pre># Using the explained variance method and plotting the Principal Components vs<br># explained variance<br><br>feat=range(pca.n_components_)<br>explained_variance=pca.explained_variance_<br>fig,ax=plt.subplots()<br>ax.bar(x=feat,height=explained_variance)<br>ax.set_xlabel(&#39;Number of components&#39;)<br>ax.set_ylabel(&#39;Explained Variance&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*rPIK45N9m5fePIsfLS_RnA.jpeg" /><figcaption>Fig 1.3 Components vs explained variance</figcaption></figure><p>It is clear from the figure above that the first 5 components are responsible for most of the variance in the data. Thus in this case the intrinsic dimension of the data is 5. We can thus reduce the number of dimensions of this data from 30 down to 5.</p><p>Now that we know the intrinsic dimension of the dataset is 5 we will transform the features into these 5 Principal Components. Every observation will now have 5 features rather than 30, the 5 components being a combination of the 30 features.</p><pre># Fitting pca with 5 components (intrinsic dimension)<br>pca=PCA(n_components=5)<br>scaler=StandardScaler()<br>pipeline=make_pipeline(scaler,pca)<br>pipeline.fit(features)<br><br># Now transforming to have the PCA columns for each observation<br>transformed=pipeline.transform(features)<br><br># Looking at the PCA dataframe<br>X=pd.DataFrame(transformed,columns=[&#39;PCA1&#39;,&#39;PCA2&#39;,&#39;PCA3&#39;,&#39;PCA4&#39;,&#39;PCA5&#39;])<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*hhylyz6NXjvmjTeTTkd6cg.jpeg" /><figcaption>Fig 1.4 The output of transformed PCA</figcaption></figure><p>Now we ill fit the transformed features and the diagnosis variable to a Decision Tree model. We will then evaluate the fit</p><pre># Doing a train test split<br>X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2)<br><br># Importing Modules and fitting to the trainin<br>from sklearn.tree import DecisionTreeClassifier<br>dt=DecisionTreeClassifier(max_depth=5)<br>dt.fit(X_train,y_train)<br><br># Generating Model predictions for the diagnosis variable<br>y_pred=dt.predict(X_test)<br><br># Generating the classification report<br>from sklearn.metrics import classification_report<br>print(classification_report(y_test,y_pred))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*fj1-Y0UgFujStPmK2lD8RQ.jpeg" /><figcaption>Fig 1.5 Classification Report</figcaption></figure><p>There are a few metrics on the accuracy report on the test data that are important</p><ul><li><strong><em>Accuracy-: </em></strong>The accuracy of this model is 92%. This means that 92% of the time the model predicts the correct diagnosis. When we looked at the distribution of the diagnosis variable the benign tumors are 62% and cancerous are 38%, which suggests a random guessing model would be right about 62% of the time. This model is performing much better than random guessing.</li><li><strong><em>Precision (True Positive Rate)-: </em></strong>The precision with which this model identifies cancer correctly is 91%. In other words only 9% of the cases are false positives. This is great for a starting model but we might want to reduce this to the 1% range (increase precision to 99%) because a false positive on a cancer test would mean that the patient might have to endure needless expensive and painful cancer treatment.</li></ul><p>We could further try ensemble learning methods like Random Forests to further improve the accuracy of this model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9c422369547" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/dimension-reduction-with-pca-for-everyone-e9c422369547">Dimension reduction with PCA for everyone</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to 3 useful tree based models]]></title>
            <link>https://medium.com/analytics-vidhya/introduction-to-3-useful-tree-based-models-30fcf0883492?source=rss-8de2842c14be------2</link>
            <guid isPermaLink="false">https://medium.com/p/30fcf0883492</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Gaurang Mehra]]></dc:creator>
            <pubDate>Fri, 03 Mar 2023 21:46:34 GMT</pubDate>
            <atom:updated>2023-03-03T21:46:34.864Z</atom:updated>
            <content:encoded><![CDATA[<p>Our objective for this article is to give a beginner friendly introduction to tree based models starting with Decision Trees and moving to more complex ensemble algorithms like Random Forests.</p><p>All the models we will discuss today are supervised learning models. Supervised learning algorithms are trained on labelled datasets. The labels for a supervised learning algorithms could be categorical (eg. cancer/benign) or a continuous value (eg. price). Once the model is trained, it is fed unlabeled data and predicts the labels. Now lets look at Decision Trees.</p><h3><strong>Decision Trees</strong></h3><p>A Decision Tree is supervised learning algorithm that uses a series of if/then questions to arrive at a predictive label. To further understand this concept lets look at a Decision Tree<em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HZGcXYCQkxKB5jtc11HZHg.jpeg" /><figcaption>Fig 1.1 Decision Tree example (depth=2)</figcaption></figure><p>In the figure above we look at an example Decision Tree model that predicts whether a patient has diabetes or not given glucose levels, BMI, age etc. For purposes of illustration this tree is a very simple tree with a depth of 2. We will traverse the tree in the direction shown and in the process illustrate a few important concepts</p><ul><li>The 1st node in the tree is the <em>root node. </em>We can think of this as the first in a series of if/then questions that the model uses to arrive at a final prediction. This first split is generally on the most important feature. In this case the feature is glucose levels. If glucose levels are less than 127.5 then the model proceeds in one direction, if glucose levels are greater than 127.5 the model proceeds in another direction. This is known as a <em>binary split.</em></li><li>The nodes after the <em>root node</em> but before the terminal nodes are called <em>decision nodes. </em>We can think of them as a series of intervening questions that help the model progressively learn how to predict better. In our example the model checks if age is below 28.5 after checking the glucose levels, if yes then it classifies the instance or the record as no diabetes.</li><li>The final set of nodes with the decision or the predicted label are called the <em>leaf nodes.</em></li><li>We have to specify the depth of the tree before fitting the model to the training data. Trees that are too deep tend to <em>overfit </em>the data, essentially learning the noise in the training data and performing poorly on unseen data. One way to avoid this is to run the model repeatedly with different <em>max_depth</em> parameters and then pick the model instance which gives the best accuracy on unseen test data. I have another article <a href="https://medium.com/@gaurangmehra/build-a-predictive-tree-based-model-with-a-front-end-dashboard-report-in-excel-f6f4f7995e02">here</a> which has details on how to implement this in python.</li></ul><h3>Ensemble Learning Methods</h3><p>Now that we know Decision Trees we move on to ensemble learning methods. Typically ensemble learning involves either fitting one model to multiple samples drawn from the training data or different models fit to the same training data set. Lets look at the first instance, fitting different models to the same data set.</p><p><strong>Voting Classifier</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKLkz0gcncDdSEnOKMbvOA.png" /><figcaption>Fig 1.2 Voting Classifier</figcaption></figure><p>In a Voting Classifier<em> </em>the same training set is used to train multiple learners or models. Each model makes its own prediction and the final prediction is decided by majority voting in the case of classification and an average in the case of regression tasks. Typically we would choose models that are not prone to the same kind of errors. In that case the Voting Classifier<em> </em>performance (accuracy, recall etc.) is likely to be better than an individual model prediction.</p><p><strong>Bagging Classifier/Model</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QrjUtKHTY0qY6BlUx3Y5jg.jpeg" /><figcaption>Fig 1.3 Bagging Classifier</figcaption></figure><p>A Bagging classifier<em> </em>uses a different approach. To understand a bagging classifier we need to understand the concept of <em>bootstrap samples/bagging samples.</em></p><p>A bootstrap sample is drawn from a dataset with replacement. If a dataset is of size n then the bootstrap sample is also of size n. If we look at the figure above the bagging/bootstrap sample 1 and sample 2 are slightly different but of the same size as the training data. Since each sample is randomly drawn, each sample is different.</p><p>The Bagging Classifier model pulls k bootstrap samples from the training dataset and fits a model to each of the k sample datasets. The final prediction is made by combining the predictions of k models made on the k bootstrap samples. Bootstrap samples are not subsets of the training data but are of exactly the same size so each model is trained on a full size but slightly different training dataset.</p><p>The Bagging Classifier works best with models that have high variance like Decision Trees as each Decision Tree is fit to slightly different version of the data (bootstrap sample) which can help reduce variance by averaging out the noise across datasets. This also reduces overfitting to the training data and improves performance on unseen data versus a single model trained on the single training dataset.</p><p>In a similar way to a Bagging Classifier you can have a Bagging Regressor.</p><p><strong>Random Forests</strong></p><p>We can extend the concept of the Bagging Classifier/model by not only using k randomly drawn bootstrap samples from the training data but also randomly sampling a subset of features at each node. This further level of randomization helps reduce variance and overfitting. You can see an implementation of this in python <a href="https://medium.com/@gaurangmehra/build-a-predictive-tree-based-model-with-a-front-end-dashboard-report-in-excel-f6f4f7995e02">here</a>.</p><p>These 3 models are very powerful and can be used to perform a variety of Machine Learning tasks. Unlike deep learning models they do not require huge amounts of training data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30fcf0883492" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/introduction-to-3-useful-tree-based-models-30fcf0883492">Introduction to 3 useful tree based models</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a predictive Tree based model with a front end dashboard report in excel]]></title>
            <link>https://medium.com/analytics-vidhya/build-a-predictive-tree-based-model-with-a-front-end-dashboard-report-in-excel-f6f4f7995e02?source=rss-8de2842c14be------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6f4f7995e02</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[business-analytics]]></category>
            <category><![CDATA[python-data-science]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[dashboard]]></category>
            <dc:creator><![CDATA[Gaurang Mehra]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 20:59:06 GMT</pubDate>
            <atom:updated>2023-02-20T20:59:06.890Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Objective: </strong>We will use the bike data set provided by Kaggle to predict <a href="https://www.kaggle.com/competitions/bike-sharing-demand/data?select=train.csv">bike rentals</a> given hourly data on rentals, weather (temp, humidity, windspeed etc.) and whether the day was a working day or holiday. We will use excel as a front end to show data visualizations and results of different tree based models.</p><p>The data set has many weather related features like</p><ul><li><strong>Windspeed: </strong>The windspeed for that hourly observation</li><li><strong>atemp: </strong>The feels like temperature for the hourly observation</li><li><strong>humidity: </strong>The humidity for that observation</li></ul><p>The target variable is count (count of bike rentals). We will build tree based models to predict bike rentals given weather conditions, time of year and weekday, weekend etc.</p><p>First thing we want to do is explore some of the features and understand the relationship between them and count (bike rentals). This is done in <a href="https://github.com/gmehra123/data_science_projs/blob/main/Tree%20Based%20Models.ipynb">Jupyter notebook</a>. We export these visualizations to an excel workbook called <a href="https://github.com/gmehra123/data_science_projs/tree/main/Bike_Data"><em>Report dashboard </em></a>and a tab called <em>Exploratory Data Analysis.</em></p><p>Its logical to assume that bike rentals and temperature might be related and also that bike rentals and the month of year might be related. We first explore these relationships.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YFV-8kuLZU3uxXF0BJSC0g.jpeg" /><figcaption>Fig 1.1 Exploratory Data analysis</figcaption></figure><p>We can infer 3 things from the figure above.</p><ul><li>Bike rentals tend to be higher in the summer months as evidenced by the much higher median values in the box plot.</li><li>atemp (feels like temperature) and bike rentals seem to have a relationship. On colder days the bike rentals tend to be much lower as seen in the scatter plot.</li><li>The distribution of bike rentals tends to be right skewed with some days having very large number of rentals.</li></ul><p>Code for this below</p><pre># Use excelwings to manipulate the excel workbook<br>book=xw.Book(&#39;Bike_Data/Report_Dashboard.xlsx&#39;)<br>sheet=book.sheets(&#39;Exploratory Analysis&#39;)</pre><pre># Creating the plots<br>fig,(ax0,ax1,ax2)=plt.subplots(nrows=1,ncols=3)<br>fig.set_figheight(6)<br>fig.set_figwidth(21)<br>sns.boxplot(x=&#39;MonthofYear&#39;,y=&#39;count&#39;,data=bike,ax=ax0)<br>sns.regplot(x=&#39;atemp&#39;,y=&#39;count&#39;,scatter=True,scatter_kws={&#39;alpha&#39;:0.05},x_jitter=True,y_jitter=True,data=bike,ax=ax1)<br>sns.histplot(x=&#39;count&#39;,data=bike,ax=ax2)<br>ax0.set_title(&#39;Bike Rentals by month&#39;)<br>ax0.set_ylabel(&#39;Bike Rentals&#39;)<br>ax1.set_title(&#39;Temp vs Bike rentals&#39;)<br>ax1.set_ylabel(&#39;Bike rentals&#39;)<br>ax2.set_label(&#39;Bike Rentals&#39;)<br>ax2.set_title(&#39;Distribution of Bike Rentals&#39;)<br>plt.tight_layout()<br>sns.set_context(&#39;talk&#39;)<br>#sns.set_theme(&#39;dark&#39;)<br>plt.show()<br>sheet.pictures.add(fig,name=&#39;Bike Rentals&#39;,update=True)</pre><p>Next thing we would like to do is explore the correlations between rentals and all the features as well as among the features</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9pmhKOYWFYClKolFbsH3nQ.jpeg" /><figcaption>Fig 1.2 Correlation matrix</figcaption></figure><p>From the above matrix we find that the following variables have the highest correlations with count (bike rentals).</p><ul><li><strong><em>temp, atemp: </em></strong>These variables both have a correlation coeffecient of 0.39 with count but also have a high degree of correlation with each other. In this case we keep only a temp</li><li><strong><em>humidity: </em></strong>This has a negative correlation with rentals. Makes sense, nobody wants to go cycling on a very humid day</li><li><strong><em>weather: </em></strong>weather is a categorical variable for extreme weather events. This seems to have an effect on rentals, while not being highly correlated (less than 0.5) between the other variables</li></ul><p>Code for this step below</p><pre># Creating a correlation matrix <br>corr_mat=bike.corr().round(2)<br>corr_mat</pre><pre># Creating a correlation matrix plot and exporting to excel<br>fig,ax=plt.subplots()<br>fig.set_figheight(7)<br>fig.set_figwidth(14)<br>sns.heatmap(corr_mat,annot=True,linewidth=0.3,cmap=&#39;viridis&#39;)<br>ax.set_title(&#39;Correlation Matrix&#39;)<br>sheet.pictures.add(fig,name=&#39;Corr_mat&#39;,update=True,left=sheet.range(&#39;B37&#39;).left,top=sheet.range(&#39;B37&#39;).top)</pre><p>Now that we understand the correlations better lets use the temp, atemp humidity, weather and holiday to build a decision tree model.</p><ul><li>Step 1 is to break the data into feature array X and target array with the rental counts. We then split the data into train and test sets. We will set the test data set to 20% of the total data we will train the data on the train dataset.</li></ul><pre>X=bike[[&#39;atemp&#39;,&#39;MonthofYear&#39;,&#39;humidity&#39;,&#39;weather&#39;,&#39;holiday&#39;]]<br>y=bike[&#39;count&#39;]<br>from sklearn.model_selection import train_test_split<br>X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2)</pre><ul><li>Step 2 is to fit the training data set as defined by the feature array X_train, y_train. Decision tree is a good intial choice because we have some non-linear features like the <em>MonthofYear. </em>Decision Trees are also easy to visualize. Its necessary to set the max_depth parameter of the tree prior to fitting the training data. We can run the algorithm repeatedly with different max_depth parameter values to see which one gives us the best fit on the training data</li></ul><pre>max_depths=[3,4,5,6,7,8,9,10,11,12,13,14,15]<br>for max_depth in max_depths:<br>    dt=DecisionTreeRegressor(max_depth=max_depth,random_state=20)<br>    dt.fit(X_train,y_train)<br>    y_pred=dt.predict(X_test)<br>    score=r2_score(y_test,y_pred)<br>    print(&#39;The r2_score of tree with max depth {} is&#39;.format(max_depth),score)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*T20NteHPY5_BvvThf2iB6w.jpeg" /><figcaption>Fig 1.3 r2 results with different tree depths</figcaption></figure><p>Above we see that a tree with a depth of 8 gives us the best fit with an r2 of 0.29 which is not too good. Here is the code that visualizes the tree. We then add it to a second tab in the excel labelled <em>Decision Tree.</em></p><pre>sheet2=book.sheets(&#39;Decision tree&#39;)<br>from sklearn import tree<br>fig,ax=plt.subplots()<br>fig.set_figheight(35)<br>fig.set_figwidth(35)<br>_=tree.plot_tree(dt,feature_names=X.columns,filled=True)<br><br>sheet2.pictures.add(fig,name=&#39;Tree&#39;,update=True,left=sheet2.range(&#39;A6&#39;).left,top=sheet2.range(&#39;A6&#39;).left)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qXJlnNKyE5WAZjD0oVCKeg.jpeg" /><figcaption>Fig 1.4 Decision Tree Visualization snippet depth 2</figcaption></figure><p>Lets see if we can get a better fit with a <em>Random Forest model.</em></p><p><em>Random Forests: </em>Are an ensemble algorithm that consists of a number of trees. Each tree is trained on a random sample (boot strap sample) from the training data. The prediction value of a random forest is an average value of all the predicted values of all the trees in the forest . A good property of Random Forests is that they rank the most important features and we can visualize these as as bar plot. For the Random Forest iteration we will use all the features and then let <em>Random Forest </em>feature importances tell us what the most important features are.</p><ul><li>Step 1 is to create the feature and target arrays. Then we do a train/test split</li></ul><pre># Creating the feature array<br>X=bike.drop(columns=[&#39;count&#39;,&#39;datetime&#39;])<br>y=bike[&#39;count&#39;]<br><br># Doing a train test split<br>X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2)</pre><ul><li>Step 2 is to run a <em>Random Forest </em>model with a 100 trees and with multiple values of the max_depth parameter. We then see which value of max_depth gives us the best fit on the test data</li></ul><pre># Fitting a Random forest model with a 100 trees<br>from sklearn.ensemble import RandomForestRegressor<br>for max_depth in max_depths:<br>    rf=RandomForestRegressor(n_estimators=100,max_depth=max_depth,random_state=30)<br>    rf.fit(X_train,y_train)<br>    y_pred=rf.predict(X_test)<br>    score=r2_score(y_test,y_pred)<br>    print(&#39;R2_score with {} max depth is&#39;.format(max_depth),score)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*N4TC7StwESqDLDEDV5uRmA.jpeg" /><figcaption>Fig 1.5 r2 results with different max_depths using Random Forest (n=100)</figcaption></figure><p>We see that a <em>Random Forest (n_estimators=100)</em><strong> </strong>and a max_depth of 11 gives the best fit</p><p>Now lets see how <em>Random Forest </em>ranks the features. The <em>feature_importances_ </em>method is an extremely useful tool. We can also use this method to rank the most predictive/impactful features if the dataset contains a large number of features.</p><pre>mat=pd.DataFrame(rf.feature_importances_,index=X.columns).sort_values(by=[0])<br>fig,ax=plt.subplots()<br>fig.set_figheight(7)<br>fig.set_figwidth(12)<br>ax.barh(width=mat[0],y=mat.index)<br>plt.xticks(rotation=45)<br>ax.set_title(&#39;Feature Importances&#39;)<br>sheet3.pictures.add(fig,name=&#39;Feature&#39;,update=True,left=sheet3.range(&#39;A8&#39;).left,top=sheet3.range(&#39;A8&#39;).left)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*-fRqoZ6OxKjva7DDEDJ9Gw.jpeg" /><figcaption>Fig 1.6 Random Forest most predictive features</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6f4f7995e02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/build-a-predictive-tree-based-model-with-a-front-end-dashboard-report-in-excel-f6f4f7995e02">Build a predictive Tree based model with a front end dashboard report in excel</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>