<?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 Bharathwajan on Medium]]></title>
        <description><![CDATA[Stories by Bharathwajan on Medium]]></description>
        <link>https://medium.com/@bharathwajan?source=rss-4f24ae562ee8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hBKp6LUz2KBjqU8EX5r8nw.jpeg</url>
            <title>Stories by Bharathwajan on Medium</title>
            <link>https://medium.com/@bharathwajan?source=rss-4f24ae562ee8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:12:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bharathwajan/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[Llama 2 Model Fine Tuning Experiment]]></title>
            <link>https://medium.com/@bharathwajan/llama-2-model-fine-tuning-experiment-0e996f4fe594?source=rss-4f24ae562ee8------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e996f4fe594</guid>
            <dc:creator><![CDATA[Bharathwajan]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 11:39:37 GMT</pubDate>
            <atom:updated>2024-08-13T11:39:37.587Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PpApxocVE4gXDtLbzA9nqA.jpeg" /></figure><p><strong>Data Used</strong></p><p>I want to use personal data for fine tuning, so I created my own dataset covering the following topics.</p><ul><li>Basic info (Name,age,studied)</li><li>Where I live (Two places where i live)</li><li>Career (Internships and work experience)</li><li>Subjects took in BE</li><li>Certifications completed</li><li>Contact information</li><li>Moderation related data (restricting personal info)</li><li>Skillset</li><li>My Favourite works in AI (Gave three of my favorite papers )</li><li>Hobbies</li><li>What is the best time to contact bharathwajan</li><li>Social Media links (Linked In,Gmail)</li><li>Natural language skills</li><li>My vision on AI advancements</li><li>Subjects taken in MTech</li><li>Schooling</li></ul><p>With this topics i created 830 records(Json Objects) about myself , For this purpose you can use simple python program which utilizes open AI key/any open source model or you can manually use the chat GPT web interface .</p><pre>[<br>    {<br>        &quot;question&quot;: &quot;What is the field of study for Bharathwajan&#39;s BE degree?&quot;,<br>        &quot;input&quot;: &quot;&quot;,<br>        &quot;answer&quot;: &quot;The field of study for Bharathwajan&#39;s BE degree is Computer Science and Engineering.&quot;<br>    },<br>    {<br>        &quot;question&quot;: &quot;Mention the undergraduate degree Bharathwajan completed.&quot;,<br>        &quot;input&quot;: &quot;&quot;,<br>        &quot;answer&quot;: &quot;Bharathwajan completed a BE in Computer Science and Engineering.&quot;<br>    }<br>]</pre><p>Once the dataset is prepared ,I had written a script which convert data to the prescriped llama2 instruction fine tuning format , which looks somoething like below</p><pre>&quot;&lt;s&gt;[INST] What is the field of study for Bharathwajan&#39;s BE degree ? [/INST] The field of study for Bharathwajan&#39;s BE degree is Computer Science and Engineering.. &lt;/s&gt;&quot;</pre><p><strong>Environment Setup</strong></p><p>I tried using windows for fine tuning without WSL but i faced so many error in bits and bytes and transformers library , so finally i decided to go for WSL .</p><p>Below is the experimental setup I used for fine-tuning.</p><ul><li>Operating System : Ubuntu 22.04.3 LTS (WSL)</li><li>Language : Python 3.10.12</li><li>CPU : i5–13450HX</li><li>GPU : Nvidia RTX 3050 (6GB VRAM)</li><li>Primary memory : 24 GB</li></ul><p>Make sure that you have latest cuda toolkit installed and pytorch installed with cuda support.</p><p>Cuda toolkit : <a href="https://developer.nvidia.com/cuda-downloads">https://developer.nvidia.com/cuda-downloads</a></p><p><strong>Training Configuration</strong></p><p>Since the resources I have are minimal, I need to adapt to a low-rank technique like LoRA with a rank of 64 and 4-bit quantization.</p><ul><li>Model Used : NousResearch/Llama-2–7b-chat-hf</li><li>Quantization : 4 bit</li><li>Epochs : 1</li><li>Rank : 64</li><li>Quantization : 4 bit</li><li>Max Sequence Length : 300 (since my data doesn’t exceed 300 tokens)</li></ul><p>Training Takes almost 257 mins (4.2 Hrs)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvWVFQvP8Kdv77bViEPRaA.png" /><figcaption>Training Time</figcaption></figure><p><strong>Llama2 7B Finetuned Inference :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IohYhUH7VdsFanWpzDAVEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5wuFPyOT12dkpEHNrle4A.png" /><figcaption>Who and educational background</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*txuecOucjRp-ah0JuSrFsA.png" /><figcaption>Moderation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsMsyz76e_8IqQxc7XGGEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uzivhP72km7sR30pK5_s2A.png" /><figcaption>Educational background and best time to contact me</figcaption></figure><p>The model seems to be learned some information which is great for 1 epoch.</p><p><strong>When to fine tune ?</strong></p><p>This is an off topic for this but i want to speak about this</p><p>If your project requires the model to understand or generate text within a specific domain (e.g., medical, legal, technical), fine-tuning can help adapt the model to that context.</p><p>One of the best examples is code generation for your organization’s needs is when using Retrieval-Augmented Generation (RAG) pipelines. However, these pipelines may lag due to the complex dependencies between modules. If we decide to include all the dependent files in the prompt template, we may end up exceeding the token limit, leading to inefficiencies or incomplete responses.</p><p>In that you may adapt for fine tuning where you can fine tuning your model on each stable release of your product’s code .</p><p><strong>Conclusion :</strong></p><p>Fine tuning is great when it is actually needed if your use case is just to answer question from a set of documents which doesn’t complex dependency with each other then prefer going for a RAG ,If your data has complex dependencies then go for fine tuning . Local fine tuning has the advantage of data privacy but it is not as efficient as compared to online notebooks like colab or kaggle unless you have a GPU server locally, So if you are planning to fine tune a model for your organization then get the GPU server installed locally.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e996f4fe594" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lazy Evaluation]]></title>
            <link>https://medium.com/@bharathwajan/lazy-evaluation-5ef8c46515b7?source=rss-4f24ae562ee8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ef8c46515b7</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[lazy-evaluation]]></category>
            <dc:creator><![CDATA[Bharathwajan]]></dc:creator>
            <pubDate>Sun, 24 Mar 2024 20:06:17 GMT</pubDate>
            <atom:updated>2024-03-24T20:06:17.966Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Lazy people will always postpond the work and do it only when it is actually needed</blockquote><p>The above line is the definition of laziness here .</p><h3>What is lazy here ?</h3><p>The way in which the data evaluated is lazy here , i.e the data will be generated or taken from some source(table)only at the time of evaluation rather than reading it on whole and storing it in primary memory.</p><h3><strong>Perks of being Lazy ?</strong></h3><p>Assume that you are reading from a database table which has a million records and doing some operations to all the records in that table , In that case loading all the data in primary memory is not an cost efficient way of handling huge data.</p><h3><strong>How to be lazy in python ?</strong></h3><blockquote>The simple answer is Generators</blockquote><p>Generators are the special functions which returns iterators instead of a pre computated/fetched values . One can make a generator function using the keyword “<strong>yield</strong>” instead of “return”.</p><p>The values of this iterators are obtained from the source/computed only when it is needed .</p><p><strong>Case 1 : Loading data from a database table without generators</strong></p><pre>conn = mysql.connector.connect(<br>            user = &quot;root&quot;, <br>            password = os.getenv(&quot;db_password&quot;),<br>            database = &quot;laravel_test&quot;<br>        )<br><br>cur = conn.cursor()<br><br>cur.execute(&quot;select * from posts;&quot;)<br>records=cur.fetchall()<br>size=sys.getsizeof(records)<br>print(&quot;Size of the variable:&quot;, size, &quot;bytes&quot;)<br><br>&gt;&gt;&gt; Size of the variable: 664 bytes</pre><p>In this case the system need to handle 664 bytes of data all at once , 664 Bytes might be smaller but in an enterprise level application it won’t 664 bytes rather it would be 664 Giga bytes . So loading all this data at primary memory is not an brillant idea.</p><p><strong>Case 2 : Loading data from a database table with generators</strong></p><pre>import mysql.connector<br>import os<br>import sys<br>def fetch_records():<br>    conn = mysql.connector.connect(<br>            user = &quot;root&quot;, <br>            password = os.getenv(&quot;db_password&quot;),<br>            database = &quot;laravel_test&quot;<br>        )<br><br>    cur = conn.cursor()<br>    cur.execute(&quot;SELECT * FROM posts&quot;)<br>    while True:<br>        record = cur.fetchone()<br>        if record is None:<br>            break<br>        yield record<br>all_records=fetch_records()<br>size=sys.getsizeof(next(all_records))<br>print(&quot;Size of the variable:&quot;, size, &quot;bytes&quot;)<br><br>Output <br>&gt;&gt;&gt;&gt; Size of the variable: 272 bytes</pre><p>In this case all the records are not loaded at once ,Rather it was loaded on demand using “fetch_record” function aka <strong>a generator function</strong>.</p><p>and each record from the db is accessesd on demand with next keyword ,This is why the size is reduced to 272 Bytes , which is much more simpler to handle.</p><p>In python Scrapy package uses this lazy loading technique in its pipeline to store the scraped data.</p><h3><strong>Conclusion:</strong></h3><p>Being lazy is actually a smart way of taking things.So from now on try to be lazy as much as possible 😂.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ef8c46515b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep dive into MLFlow]]></title>
            <link>https://blog.devgenius.io/a-deep-dive-into-mlflow-cf01e24ca0ea?source=rss-4f24ae562ee8------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf01e24ca0ea</guid>
            <category><![CDATA[mlflow]]></category>
            <category><![CDATA[mlflow-registry]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Bharathwajan]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 15:33:50 GMT</pubDate>
            <atom:updated>2024-02-18T06:04:37.319Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*OsB57V0FPteixDBD_BBN4g.png" /></figure><p>Previously i had a blog named “A peep into MLFlow”,you can consider this blog as a continuation of that .</p><p>In the previous blog i had spoken about logging parameter and accessing the MLFlow UI.</p><p>This Blog is all about setting the things up for MLFlow in more detail ,Model Registeration and mlflow model serving .</p><p>Whenever you decided to use MLFlow in your project make a new directory either in your local machine or in the any cloud like GCP,AWS or Azure , then navigate to that directory in command prompt and use the command</p><blockquote>mlflow ui</blockquote><p>This command will start the mlflow tracking server in the port 5000 by default , and the port can be customized by the flag port</p><blockquote>mlflow ui --port &lt;port number&gt;</blockquote><p>Once you are done with this you can log all the model related details in the mlflow server which will be logged entirely inside the folder which you had created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/0*N7krB9V2VXydzERV" /></figure><p>In the above image ml_flow_cloud_directory is the folder which i had created and the sub folders are created by mlflow itself while i am logging some of my model parameters.</p><p>To make this magic happen , Simply import mlflow library in your program and use the below line.</p><blockquote>mlflow.set_tracking_uri(‘http://localhost:5000/&#39;)</blockquote><p>you can replace localhost with the cloud VMs ipaddress , if you are using cloud services.</p><p>when you set this all the model related details will be automatically logged inside the “mlruns” folder which is inside the “mlflow_cloud_directory”.</p><h3>Logging the Model</h3><p>Model Logging basically refers to saving the model as a pickle file in MLFlow tracking server. While logging the model , always log signature. Which helps the software engineering team to build and test REST API .</p><p>signature typically refers to the input and output specifications of a machine learning model. A signature defines the format of the inputs and outputs that the model expects and produces. It helps in documenting and understanding how to interact with the model<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oAYgyFbdUWHt9haDmhc7kA.png" /></figure><p>you can use the infer signature function from “mlflow.models.signature.infer_signature”. To create signatures always try to pass pandas dataframe object as a parameters to this function so that it will capture the datatypes with the column names like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fpMVFmztpP6WqhCQ8HCVKw.png" /></figure><p>and don’t forget to pass it to the “log_model” function.</p><h3><strong>Registering the Model</strong></h3><p>Model registeration is the process of approving a model for production , lets say you have a team of 5 developers and a manager .</p><p>The developers can take the responsibility of training the model and log ging it into the mlflow server and the manager can verify its metrics and register that model to the model registry .</p><p>lets assume after evaluating the manager found that the below given model is the best one then he/she can register this model by clicking on the “Register Model” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W58aG0j57HiuqTftKPjrNA.png" /></figure><p>Based on the number of use cases you can create any number of model registeries with just a click of a button “Create Model”, In my case i have three</p><ul><li>user_cat_classification_GNN</li><li>Iris_flower_classification</li><li>topic_modelling</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7beDDxB5OBKQuz9_Knwong.png" /></figure><p>Even here you can tag your model , lets assume you have got multiple models over the time as the best model . In that case you can use “aliases”</p><p>lets assume i have registered the first version of a model in january 2023 and in June 2023 i got a data drift so I retrained and got another best model and again in December the same happend .</p><p>Now we have 3 best models ,Now obviously the Software engineering team doesn’t know which one to take for developing a REST API</p><p>In that case the manager can use “alises” ,he/she can give alises to the best model as champion and the next best one as challenger and so on and instruct the software engineering team to always take the Champion for API development or champion and challenger for A/B testing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*re5eaP4W_nPpXzGZkP0Tdg.png" /></figure><p>Note : aliases is subjected to newer versions of mlflow.</p><h3>Model Serving</h3><p>MLFlow has this feature called model serving which basically creates a REST API with the logged model</p><p>To acheive this Do the following steps</p><ol><li>set the system/user environment variable named MLFLOW_TRACKING_URI with the value <a href="http://local/">http://local</a>host:5000 or any of your cloud VMs ip address on which the MLFlow is hosted.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*SE6Fpbj2Yas2zHED5xJnZA.png" /></figure><p>this variable will be used by the “mlflow models serve” command to locate the mlflow tracking server and get the necessary model files to build the API.</p><p>2. copy the models run id which needs to be served as an REST API.</p><p>lets assume i am choosing “3356afd40d934f4db0c08270f19dae0b” this run id , since it got registered</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4hrGywkRm374wKMj-xrm_g.png" /></figure><p>3) Use the below command to create and serve the model as REST API</p><blockquote>mlflow models serve — model-uri runs:/3356afd40d934f4db0c08270f19dae0b/model — port 1234 — env-manager conda</blockquote><p>always use any one of the environment manager tools while using this command to avoid version conflicts , mlflow will log the dependencies automatically when you log the model which will we be used by this environment manager to create a virtual_environment</p><p>mlflow provides three options for this environment management</p><ul><li>local → uses the local environment</li><li>virtualenv → uses pyenv</li><li>conda → uses anaconda</li></ul><p>I tried pyenv but got so many errors , So i moved to conda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzh_NU3Cgk5t_tQ01NXRsQ.png" /></figure><p>Once the API Server started , you can infer it with any of the API client.</p><p>at the endpoint</p><p><a href="http://0.0.0.127/">http://127</a>.0.0.1:1234/invocations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dn9R481kscB9UoooHxK3KQ.png" /><figcaption>Thunderbolt Client at VScode</figcaption></figure><p>Note : Even after stopping the REST API server your conda environment wont get deleted automatically</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/0*HlK6rS3lTatmVUb0" /></figure><p>You need to delete it manually to get some free space.</p><p>Feel Free to use the comments section ,We’ll Discuss !!</p><h3>References :</h3><p>[1] <a href="https://mlflow.org/docs/latest/index.html">https://mlflow.org/docs/latest/index.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf01e24ca0ea" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/a-deep-dive-into-mlflow-cf01e24ca0ea">A Deep dive into MLFlow</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoiding Side Effects with the Locate Function in Pandas]]></title>
            <link>https://medium.com/@bharathwajan/avoiding-side-effects-with-the-locate-function-in-pandas-c2684b9612e7?source=rss-4f24ae562ee8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2684b9612e7</guid>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Bharathwajan]]></dc:creator>
            <pubDate>Sat, 05 Aug 2023 16:22:44 GMT</pubDate>
            <atom:updated>2023-08-05T16:22:44.120Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4xXKVq5XDzh56kDiIDW6Tw.png" /></figure><h3>Story:</h3><p>During one of my coding sessions, I stumbled upon an unusual issue. Inside a static function of a class, I had a local variable called ‘temp_data’, which was refered to the result of calling the ‘locate’ function on a globally declared variable named “data”.</p><blockquote>n : no. of records in “data”</blockquote><blockquote>n-k : expected return as per the written code’s logic irrespectively of the no. of calls made</blockquote><p>When i consequetly called that static function,I got n-k records from static function on the first call and n-2k records on the second call and n-3k records on the third call , but i didn’t wrote any logic inside the static function which affects the globally decalred variable</p><h3>Sample Code:</h3><pre>import pandas as pd<br><br>data=pd.read_csv(&quot;Sample path&quot;) #has n records<br>class preprocess():<br>    def __init__(self):<br>        &lt;....&gt;<br>    <br>    def pipeline(self,kakfa_topic):<br>      &lt;....&gt;<br><br>    @staticmethod<br>    def data_preprocess(arg1,arg2):<br>        temp_data=data.loc[......]<br>        &#39;&#39;&#39;<br>        preprocessing steps<br>        &#39;&#39;&#39;<br>        return temp_data # it should return me n-k records --&gt; due to locate function<br><br><br><br>print(data_preprocess(arg1,arg2)) # got n-k records<br>print(data_preprocess(arg1,arg2)) # got n-2k records<br>print(data_preprocess(arg1,arg2)) # git n-3k records<br></pre><h3>Findings</h3><p>After debugging for hours i found</p><blockquote>“Pandas Locate function gives you just a just a view or a reference to the original DataFrame”</blockquote><p>and any changes made in the view will affect the source variable</p><h3>Solutions</h3><p>Do a .copy()</p><p>Never ever use a locate function without copy in a processing flow</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2684b9612e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gibbs Sampling]]></title>
            <link>https://medium.com/@bharathwajan/gibbs-sampling-4858ffee4dd3?source=rss-4f24ae562ee8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4858ffee4dd3</guid>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Bharathwajan]]></dc:creator>
            <pubDate>Sat, 24 Jun 2023 18:26:44 GMT</pubDate>
            <atom:updated>2023-06-24T18:26:44.596Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What is Sampling ?</strong></h3><blockquote>Sampling is the process of selecting a set of data points to represent the entire population</blockquote><p>Suppose you are interested in estimating the average height of students.The college has a total of 1,000 students. Instead of measuring the height of every student, which could be time-consuming and impractical, you decide to take a sample of 100 students.</p><p>There are several topic modelling methods</p><p>To obtain a representative sample, you can use different sampling methods such as</p><ul><li>simple random sampling</li><li>stratified sampling</li><li>Gibbs sampling</li></ul><p>Here we are going to discuss about Gibbs Sampling , This sampling method is widely used in the field of NLP for Topic modelling , One of the varients of Latent Dirichlet Allocation uses this sampling method to estimate its parameters .</p><h3><strong>When to use Gibbs ?</strong></h3><p>The optimal use case for using gibbs is ,If we have</p><ul><li>Multivariate Distribution</li><li>joint distribution</li></ul><p>to sample from</p><h3><strong>Gibbs Sampling ?</strong></h3><p>For the simplicity lets assume we have a dataset with two random varibles X and Y and we want to sample from it</p><p>To achieve our objective we need to follow the following steps</p><p><strong>Step 1 :</strong> Select a random data point (x,y)</p><p><strong>Step 2 :</strong> Calculate the conditional probability for all x in varible X by keeping y as a condition for the variable Y</p><ul><li>p( X=x|Y=y)</li></ul><p><strong>Step 3 :</strong> Select the x with high prob and save the (x,y) pair in a jar</p><p>Then fix x as a condition for the variable X and find the best y which maximizes the probability and save the (x,y) pair in a jar</p><ul><li>p(Y=y|X=x)</li></ul><p><strong>Step 4 :</strong> Repeat the step 3 and 4 for suffient number of iterations</p><p>This process can be done for any number of variables</p><p>After the completion of iteration you will have your samples in the jar which represents the initial population</p><p>Remember in practice the initially stored samples stored in the jar are discarded and it is labelled as burn in samples</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4858ffee4dd3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beta Distribution]]></title>
            <link>https://medium.com/@bharathwajan/beta-distribution-35715b6a9a8f?source=rss-4f24ae562ee8------2</link>
            <guid isPermaLink="false">https://medium.com/p/35715b6a9a8f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[topic-modeling]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Bharathwajan]]></dc:creator>
            <pubDate>Fri, 16 Jun 2023 14:42:16 GMT</pubDate>
            <atom:updated>2023-06-16T14:42:16.869Z</atom:updated>
            <content:encoded><![CDATA[<p>Beta is a continous disribution which models probability with our belief(prior knowledge)</p><p>Let me start and go with an experiment for explaining this</p><blockquote>Experiment:</blockquote><blockquote>Assume we are tossing a coin 10 times(n) and we want to the probability of getting 5 heads(x)</blockquote><p>This problem exactly follows binomial distribution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/0*Eqm0teMdVouaU7Yx" /></figure><p>and from the experiment we came to know that</p><p>N=10</p><p>x=5</p><p>p,q=0.5,05</p><p>wait .. wait.. wait .. but i am not sure about the coin’s bias …..</p><p>lets try tossing this coin for 10 times</p><p>out of 10 tosses i got 8 heads and 2 tails ,which clearly states that my coin is a biased coin, to model this knowledge we can use <strong>beta distribution</strong></p><p>α = 8,β=2 → obtained knowledge or belief</p><p>By using this knowledge,Beta distribution models the probability of head rather than no. of heads like binomial ,</p><p>which means ,In beta distribution our random variable is a probability(<strong>continuous</strong> with range [0,1]) but note in binomial it is discrete (no. of success(getting head))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*6d9Idm4olv-1YWZ715hTXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/0*1sszp00T9Vc8Gjt7" /></figure><p>x is the random variable which says of probability of getting a head and y is PDF</p><p>yes , it is a distribution of distribution</p><p>Dirichlet distribution is the generalized version of beta which can take more than two parameters</p><h3><strong>Note:</strong></h3><ul><li>If the curve is right skewed the probability of getting head is higher with our knowledge</li><li>If the curve is left skewed the probability of tail is higher with our knowledge</li></ul><h3>Takeaways:</h3><ul><li>beta is continous distribution (<strong>modelling the probability</strong>)</li><li>Beta can be used if you have priors</li></ul><h3><strong>Applications:</strong></h3><ul><li>prerequisite for some topic modelling algorithms like LDA ,GNTM and so on</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35715b6a9a8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A peep into MLFlow]]></title>
            <link>https://medium.com/@bharathwajan/a-peep-into-mlflow-595ad427346b?source=rss-4f24ae562ee8------2</link>
            <guid isPermaLink="false">https://medium.com/p/595ad427346b</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[mlflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Bharathwajan]]></dc:creator>
            <pubDate>Thu, 08 Jun 2023 21:07:44 GMT</pubDate>
            <atom:updated>2023-06-08T21:07:44.186Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*7QZEkazrJZz1Yk9E.png" /></figure><blockquote>MLflow is a framework to manage end-to-end machine learning lifecycle</blockquote><p>MLflow plays a crucial role in addressing the challenge of selecting the best model from a set of experiments. Often, individuals face difficulties in determining the most optimal model based on their experiments,MLflow diligently logs all necessary information and details about an experiment, which can be leveraged during the process of selecting the best model.</p><p>With MLflow’s extensive logging capabilities, users can easily assess the performance of different models, analyze their respective metrics, and make data-driven choices</p><p>This technique of selecting model is used widely in production environments</p><p><strong><em>Code:</em></strong></p><pre>import mlflow<br>import mlflow.sklearn<br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import accuracy_score<br>from sklearn.datasets import load_breast_cancer<br>from sklearn.metrics import roc_curve, auc<br>import matplotlib.pyplot as plt<br>from sklearn.linear_model import LogisticRegression<br><br># Load the Iris dataset<br>breast_cancer = load_breast_cancer()<br>X, y = breast_cancer.data, breast_cancer.target<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br>def train(sk_model,x_train,y_train,params): #here the skmodel can be any model which will be passed to the function later<br>    model = sk_model.fit(X_train, y_train)<br>    accuracy = accuracy_score(sk_model.predict(X_train),y_train)<br>    mlflow.log_param(&#39;max_iter&#39;, params) # used to log the parameters passed to the model<br>    mlflow.log_metric(&quot;Train Accuracy&quot;,accuracy) ## logs the accuracy of the model<br><br>def evaluate(sk_model,x_test,y_test):<br>    y_pred=sk_model.predict(x_test)<br>    accuracy = accuracy_score(y_pred,y_test)<br>    # Compute the ROC curve<br>    fpr, tpr, thresholds = roc_curve(y_test, y_pred)<br>    roc_auc = auc(fpr, tpr)<br>    plt.figure()<br>    plt.plot(fpr, tpr, label=&#39;ROC curve (area = %0.2f)&#39; % roc_auc)<br>    plt.plot([0, 1], [0, 1], &#39;k--&#39;)<br>    plt.xlim([0.0, 1.0])<br>    plt.ylim([0.0, 1.05])<br>    plt.xlabel(&#39;False Positive Rate&#39;)<br>    plt.ylabel(&#39;True Positive Rate&#39;)<br>    plt.title(&#39;Receiver Operating Characteristic&#39;)<br>    plt.legend(loc=&quot;lower right&quot;)<br>    <br>    plot_path = &#39;roc_curve.png&#39;<br>    mlflow.log_artifact(plot_path) <br>    mlflow.log_metric(&quot;Test Accuracy&quot;,accuracy)<br>    ## There are several function in mlflow which can log many other things<br><br><br>max_iter=78 #changed this value on every experiment<br>sk_model=LogisticRegression(max_iter=max_iter)<br><br>with mlflow.start_run():<br>    train(sk_model,X_train,y_train,max_iter)<br>    evaluate(sk_model,X_test,y_test)<br>    # Log the trained model<br>    mlflow.sklearn.log_model(sk_model, &#39;log_reg_model&#39;) # saves the model<br>    print(&quot;Model Run&quot;,mlflow.active_run().info.run_uuid)<br>mlflow.end_run()</pre><p>Training and evaluating a logistic regression model for doing breast cancer prediction</p><p>The above code has been executed multiple times with different “max_iter” parameter ,instead of noting down the results manually i had used mlflow. after every run a unique folder for that run will be created by mlflow and it has all the needed informations* about the run</p><p>*here i had stored only max_iter,train accuracy,test accuracy,and roc plot but you can log as many deciding parameters of your choice</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*d947CS4YFTQhkc0FT_J6tA.png" /></figure><p>These 32 digit folders contains the information about all the experiments</p><p>To visualize the results, navigate to the working directory and utilize the built-in web server capability of MLflow by executing the following command.</p><pre>mlflow ui -p 1234</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZC_Ep9AQuPpczlnSPBoTuA.png" /></figure><p>Each run corresponds to different experiments with varying “max_iter” params</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_SEFNRA5h3SOUDBE-I74w.png" /></figure><p>MLflow can also be integrated with Tensorflow and pytorch too</p><p><strong>References :</strong></p><p>[1] Beginning MLOps with MLFlow,Sridhar Alla,Suman Kalyan Adari</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=595ad427346b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conditional Independence]]></title>
            <link>https://medium.com/@bharathwajan/conditional-independence-1262aa61b12?source=rss-4f24ae562ee8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1262aa61b12</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[mathematical-modeling]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Bharathwajan]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 18:49:37 GMT</pubDate>
            <atom:updated>2023-04-18T18:49:37.444Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are into <strong>topic modelling</strong> then you may heard of this term frequently in many famous papers like PLSA,LDA and more</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Xh0aG-lfqBuZ05Vw5vV-iw.jpeg" /></figure><blockquote>Definition : Two random variables X and Y are said to be independent given Z if and only if</blockquote><blockquote>p(x,y|z)=p(x|z)*p(y|z) =&gt;(1)</blockquote><p>People like me won’t understand this definition at first shot so let me give an example for better understanding</p><p>p(x,y|z) is similar to p(x and y|z)</p><p>x and y are independent but it becomes dependent when we introduce z</p><p><strong>Example — Case 1(Not independent and conditionally independent):</strong></p><p>X : height</p><p>Y : vocabulary</p><p>Z : age</p><p>X and Yare not independent (i.e the vocabulary knowledge of a person depends on his/her height means if the persons height is 2 feet then its a baby)</p><p>but Xand Ybecomes independent if we introduce age(if someone’s age is 21 then his height becomes independent with his vocab knowledge)</p><p>Here,X and Y are not independent unless we introduced Z</p><p><strong>Example — case 2(independent and conditionally independent)</strong></p><p>X : Throw of a dice</p><p>Y : Toss a coin</p><p>Z : Card from deck</p><p>Even after applying condition Z we can’t make X and Y as dependent</p><p>(1)p(X,Y|Z)=p(X|Z)*p(Y|Z)</p><p>=(p(x n z)/p(z)) * (p(y n z)/p(z))</p><p>=( (p(x)*p(z))/p(z) ) * ( (p(y)*p(z))/p(z) )</p><p>=p(x) * p(y)</p><p><strong>Example — case 3(independent and not conditionally independent)</strong></p><p>X : Dice throw</p><p>Y : dice throw</p><p>Z : sum of the dice</p><p>X and Y are independent but after the condition Z it becomes dependent</p><p>if we want Z to be 5 and for X we got 2 ,then Y has to be 3</p><p>Events are independent but after a condition they are no longer independent</p><h3>Conclusion :</h3><p>If any number of events becomes independent after adding a condition to the context then they are conditionally independent events</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1262aa61b12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How matrix factorization is relevant in recommendation engine ?]]></title>
            <link>https://medium.com/@bharathwajan/how-matrix-factorization-is-relevant-in-recommendation-engine-d6a073fffb10?source=rss-4f24ae562ee8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6a073fffb10</guid>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[matrix-factorization]]></category>
            <category><![CDATA[statistical-analysis]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Bharathwajan]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 07:27:25 GMT</pubDate>
            <atom:updated>2023-01-24T07:27:25.390Z</atom:updated>
            <content:encoded><![CDATA[<h3>How matrix factorization is relevant in recommendation engine ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DvF8APKVnt5-OYG1fwJdxg.jpeg" /><figcaption>image from amazon.in</figcaption></figure><h3>What is matrix factorization ?</h3><p>In simple matrix factorization is the method of decomposing a single matrix into a product of two matrix</p><p>eg : a matrix of dimension mxn can be decomposed as mxd and dxn</p><p>Think of any dataset of user-item interaction as a matrix which has real values(ratings)</p><h3>what it actually does to our dataset of user item interaction ?</h3><p>It helps us in finding the features(^latent features) of users and items(say:movies),by multiplying this two matrix we’ll retrive back our dataset(user-item interaction matrix)</p><p>we can assume that the marix mxd matrix denotes the likes of the user for the different genre of the flim and dxn as the mixture of generes in a movie ,By doing dot product of this matrix we’ll obtain our user-item interaction matrix for our movies.</p><h3>How to find the right factorization ?</h3><p>In one word : gradient descent</p><p>At first we’ll assume some random values to the factors of a matrix A and this values gets updated based on the loss(usually RSS^) between the products of the factors and A in a gradient descent fashion.</p><h3>How this factors are used in recommedation ?</h3><p>Assume that we had learned some factors for matrix A(user-item interaction matrix for movies)</p><p>Fact : some users may not give ratings for some movies with that we can assume that the particular user doesn’t watched that movie , in that case the values for that movie wrt to that user will be zero in our dataset</p><p>since we had learned a factor for our dataset which almost approximates all the values in the dataset ,we can replace this zeros(i.e how much a user will like a movie) by multiplying the appropriate values from the factors.</p><p>^latent features — features that are not explicitly mentioned</p><p>^RSS — sum of the squared residuals</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6a073fffb10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to calculate number of learnable parameters in convolution layer]]></title>
            <link>https://medium.com/@bharathwajan/how-to-calculate-number-of-learnable-parameters-in-convolution-layer-50e85200e551?source=rss-4f24ae562ee8------2</link>
            <guid isPermaLink="false">https://medium.com/p/50e85200e551</guid>
            <dc:creator><![CDATA[Bharathwajan]]></dc:creator>
            <pubDate>Fri, 13 Jan 2023 19:26:49 GMT</pubDate>
            <atom:updated>2023-01-13T19:26:49.435Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are preparing for data science interview and you are in the thought of saying CNN as your favourite model then you must learn this concept</p><h3><strong>Formula</strong></h3><blockquote>((Height of the filter * width of the filter * no of dimensions in previous layer)+1)* number of filters</blockquote><h3>Example 1</h3><p>If we have an image of size 32x32 with with 3 channels and 8 filters of size 5*5</p><p>Then the number of learnable parameters are</p><p>((5*5*3)+1)*8 = 608 learnable parameters</p><p>5*5*3 denotes the filter’s convolutions over 3 channels of the image and adding 1 is for bias,Since we have 8 filers ,8 is multiplied with it</p><h3><strong>Example 1</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*hxzrX3hCtIxuz7yJRrD6Jw.png" /><figcaption>Image taken from <a href="https://www.youtube.com/watch?v=bikmA-VmSbY&amp;t=360">https://www.youtube.com/watch?v=bikmA-VmSbY&amp;t=360</a></figcaption></figure><p><strong>In the first convolution layer</strong></p><p>we got 5 filters of size 3x3 and the previous layers number of dimension is 1(gray scale image)</p><p>((3*3*1)+1)*5 = 50 learnable parameters</p><p><strong>In the second convolution layer</strong></p><p>Due to this convolution operation in the previous convolution layer we’ll get the output array(convoluted image) of shape 8x8x5</p><p>filer shape = 3x3</p><p>No. of dimensions in previous layer = 5</p><p>No. of filters =2</p><p>((3*3*5)+1 )*2 = 92 learnable parameters</p><p>Feel free to comment and contact !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50e85200e551" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>