<?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 Shubham Saxena on Medium]]></title>
        <description><![CDATA[Stories by Shubham Saxena on Medium]]></description>
        <link>https://medium.com/@shubhamsd100?source=rss-5e7c20900971------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SHCE0WOF4bzIfoNDb60gLw.jpeg</url>
            <title>Stories by Shubham Saxena on Medium</title>
            <link>https://medium.com/@shubhamsd100?source=rss-5e7c20900971------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 15:03:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shubhamsd100/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[PySpark vs Dask vs Polars vs Ray Explained: When to Use What]]></title>
            <link>https://medium.com/@shubhamsd100/pyspark-vs-dask-vs-polars-vs-ray-explained-when-to-use-what-5a1308828aa9?source=rss-5e7c20900971------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a1308828aa9</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Shubham Saxena]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 10:20:40 GMT</pubDate>
            <atom:updated>2025-09-28T10:20:40.790Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rQjHKO4dDCYBvGdY" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’re working with data in Python, you’ll eventually run into these four names: <strong>PySpark</strong>, <strong>Dask</strong>, <strong>Polars</strong>, and <strong>Ray</strong>.</p><p>They often get lumped together as “big data” or “parallel computing” tools, but they’re not interchangeable.</p><p>This article will break them down step by step:</p><ul><li>What problem each solves (the need)</li><li>How they work (under the hood)</li><li>How to use them (code examples)</li><li>Performance considerations (time required)</li><li>When to choose which (comparison)</li></ul><h3>Why Do We Even Need These Tools?</h3><p>Traditional <strong>Pandas</strong> is great, but it has two big limitations:</p><ul><li><strong>Single-threaded:</strong> Only uses one CPU core → slow for big data.</li><li><strong>Memory-bound:</strong> All data must fit into RAM → can’t handle huge datasets.</li></ul><p>We need ways to:</p><ul><li>Use all CPU cores efficiently</li><li>Scale to out-of-memory datasets</li><li>Distribute work across multiple machines (if needed)</li><li>Run parallel tasks (ML training, simulations, batch jobs)</li></ul><h3>PySpark — SQL for Big Data</h3><h4>T<strong>he Need:</strong></h4><p>When your data is too big for one machine (hundreds of GB or TBs) and you want a <strong>SQL-like engine</strong> for joins, groupBys, and aggregations.</p><h4>How It Works:</h4><ul><li>Built on Apache Spark (JVM-based)</li><li>Driver program sends tasks to executors</li><li>Data is split into <strong>partitions</strong> and processed in parallel</li><li>Can run on a laptop (local mode) or on a <strong>cluster</strong> (multi-machine)</li></ul><p>Example:</p><pre>from pyspark.sql import SparkSession<br><br>spark = SparkSession.builder.master(&quot;local[*]&quot;).getOrCreate()<br>df = spark.read.csv(&quot;sales.csv&quot;, header=True, inferSchema=True)<br><br># Group by and aggregate<br>df.groupBy(&quot;country&quot;).sum(&quot;revenue&quot;).show()</pre><h4>Time Required:</h4><ul><li><strong>Startup cost:</strong> High (JVM + SparkContext init)</li><li><strong>Performance:</strong> Blazing fast on TB-scale data (optimized shuffles)</li><li><strong>Overhead:</strong> Too heavy for &lt;1GB datasets</li></ul><h4>JVM Startup</h4><p>PySpark runs on top of <strong>Apache Spark</strong>, which is a JVM (Java Virtual Machine) application.<br> When you create a SparkSession, Spark has to:</p><ul><li>Start a JVM process</li><li>Launch the Spark driver program</li><li>Initialize executors (workers)</li></ul><p>This startup alone can take <strong>a few seconds</strong> — even if your job only processes 1 MB of data.</p><h4>Serialization and Communication</h4><p>PySpark has to pass data between <strong>Python</strong> and <strong>JVM</strong>:</p><ul><li>When you create a DataFrame in PySpark, data is serialized and sent to the JVM side.</li><li>When you call .collect(), Spark must send results back to Python.</li><li>This serialization/deserialization (a.k.a. <strong>Py4J bridge</strong>) adds latency.</li></ul><p>For tiny datasets, this back-and-forth is often slower than just using Pandas or Polars directly in memory.</p><h4>Shuffle &amp; DAG Scheduling</h4><p>Spark builds a <strong>logical plan</strong> → optimizes it → creates a DAG of stages → schedules tasks → executes them.<br> It also writes intermediate data to disk (shuffle files) if needed for operations like joins and groupBy.</p><p>This is great for <strong>huge datasets</strong> (TBs), but for small data it’s just extra steps that add seconds of delay.</p><h4>Why This Is “Too Heavy” for &lt;1 GB</h4><p>If you’re working with a small CSV (say 50 MB):</p><ul><li>Pandas/Polars → load &amp; groupBy in &lt;1 second</li><li>PySpark → spend 2–5 seconds just <strong>starting Spark</strong> before it even reads data</li></ul><p>So, the <strong>time to result</strong> is dominated by overhead, not actual computation.<br> That’s why PySpark is considered “too heavy” for small workloads.</p><h4>Lazy Evaluation in PySpark</h4><h4>What It Means</h4><ul><li>When you write a transformation in PySpark (e.g. .filter(), .select(), .groupBy()), <strong>nothing actually runs right away</strong>.</li><li>Instead, Spark builds a <strong>logical plan</strong> — basically a recipe of what to do with the data.</li><li>Spark only runs the plan when you call an <strong>action</strong>, such as:</li><li>.collect()</li><li>.show()</li><li>.count()</li><li>.write.parquet()</li></ul><p>This is why you can chain transformations without worrying about memory — Spark just records them, optimizes them, and then runs them all in one go.</p><p>You can think of PySpark like a <strong>generator</strong>:</p><ul><li>It doesn’t eagerly load all data into memory like Pandas.</li><li>It reads data in <strong>partitions</strong> only when needed.</li><li>This makes it memory-efficient for big data because it streams chunks through the pipeline.</li></ul><h3>Why Lazy Evaluation Is a Big Deal</h3><h4>Query Optimization</h4><p>If Spark ran each step immediately (like Pandas), it would:</p><ul><li>Load full data → filter → write a temp table → groupBy → write another temp table → aggregate</li></ul><p>But with <strong>lazy evaluation</strong>:</p><ul><li>Spark waits until it sees the <em>whole</em> pipeline</li><li>Then applies <strong>Catalyst Optimizer</strong> (its brain):</li><li>Pushes filters as close to data source as possible (filter early, shrink data size)</li><li>Combines multiple operations (projection + filter + groupBy) into a single optimized plan</li><li>Reorders joins for minimum data shuffle (huge speedup on big data)</li></ul><p>Imagine you wrote:</p><pre>df1 = df.filter(df.revenue &gt; 0)<br>df2 = df1.filter(df.country == &quot;India&quot;)</pre><p>If Spark executed step-by-step, it would filter twice (wasteful).<br>But with lazy evaluation, Spark merges them:</p><pre>SELECT * FROM df WHERE revenue &gt; 0 AND country = &#39;India&#39;</pre><p><strong>PySpark uses SQL-like execution under the hood</strong> for almost everything.</p><p>When you write PySpark code like:</p><pre>df_filtered = df.filter(df.revenue &gt; 0)<br>df_grouped = df_filtered.groupBy(&quot;country&quot;).sum(&quot;revenue&quot;)<br>df_grouped.show()</pre><p>Here’s what really happens:</p><p><strong>Logical Plan Generation:</strong><br> Spark converts your DataFrame operations into a <strong>logical query plan</strong>, very similar to writing:</p><pre>SELECT country, SUM(revenue)<br>FROM sales<br>WHERE revenue &gt; 0<br>GROUP BY country</pre><p><strong>Query Optimization (Catalyst):</strong><br> Spark’s <strong>Catalyst optimizer</strong> works just like a database query optimizer:</p><ul><li>Reorders operations (predicate pushdown, join reordering)</li><li>Removes unnecessary columns</li><li>Generates an optimal <strong>physical plan</strong></li></ul><p><strong>Execution Engine:</strong></p><ul><li>Uses the <strong>Tungsten engine</strong> to generate efficient bytecode</li><li>Executes the plan across partitions (and across machines if in a cluster)</li></ul><h4>Simple Analogy</h4><p>Imagine you tell a team of 10 interns:</p><ul><li><strong>Python/Pandas way:</strong> “First, filter like this, then do this step, then loop here…” (They follow exactly as told, even if it’s inefficient).</li><li><strong>SQL way:</strong> “I want a report: group by country, sum revenue, only for revenue &gt; 0.”<br> They are free to decide the <strong>fastest way</strong> to get that report — maybe they all split the work and finish quicker.</li></ul><h3>Dask — Pandas, But Distributed</h3><h4>The Need:</h4><p>When you want <strong>Pandas-like code</strong> but need to:</p><ul><li>Use all CPU cores on your machine</li><li>Handle datasets bigger than RAM</li><li>Optionally scale to a cluster later</li></ul><h4>How It Works:</h4><ul><li>Starts a <strong>scheduler</strong> + workers (processes)</li><li>Breaks data into <strong>partitions</strong> (like Spark)</li><li>Executes a <strong>task graph</strong> lazily</li></ul><h4>Example:</h4><pre>import dask.dataframe as dd<br><br># Read many CSVs as a single Dask DataFrame<br>df = dd.read_csv(&quot;sales/*.csv&quot;)<br><br># Group by and aggregate<br>result = df.groupby(&quot;country&quot;)[&quot;revenue&quot;].sum().compute()</pre><h4>Time Required:</h4><ul><li><strong>Startup cost:</strong> Low (pure Python)</li><li><strong>Performance:</strong> Scales well for 10GB–500GB data</li><li><strong>Overhead:</strong> Slightly slower than Polars for small data</li></ul><h4>Lazy Evaluation in Dask</h4><ul><li><strong>Lazy Evaluation:</strong> Just like PySpark, Dask does <em>not</em> execute transformations immediately.</li><li>When you call df.groupby() or df.filter(), Dask builds a <strong>task graph</strong> (basically a plan).</li><li>Execution happens only when you call an <strong>action</strong> like .compute().</li></ul><h3>Polars — Supercharged Pandas</h3><h4>The Need:</h4><p>When your data fits in RAM but you want <strong>maximum speed</strong>.</p><h4>How It Works:</h4><ul><li>Written in Rust (fast, memory-efficient)</li><li>Uses <strong>multi-threading</strong> under the hood</li><li>Offers <strong>lazy evaluation</strong> (query optimization before execution)</li></ul><h4>Example:</h4><pre>import polars as pl<br><br># Lazy API for performance<br>df = pl.scan_csv(&quot;sales.csv&quot;)<br><br>result = (<br>df.filter(pl.col(&quot;revenue&quot;) &gt; 0)<br>.group_by(&quot;country&quot;)<br>.agg(pl.sum(&quot;revenue&quot;))<br>.collect() # triggers execution<br>)</pre><h4>Time Required:</h4><ul><li><strong>Startup cost:</strong> Minimal</li><li><strong>Performance:</strong> Often 10–100× faster than Pandas</li><li><strong>Memory:</strong> Extremely efficient (Arrow format)</li></ul><h4>Lazy <em>or</em> Eager Evaluation in Polars</h4><ul><li><strong>Eager Mode:</strong> Like Pandas, runs immediately. (default mode)</li><li><strong>Lazy Mode:</strong> Like PySpark/Dask, builds a query plan and optimizes before execution.</li></ul><pre>import polars as pl<br><br># Lazy Mode<br>df = pl.scan_csv(&quot;sales.csv&quot;)<br>df_grouped = df.groupby(&quot;country&quot;).agg(pl.sum(&quot;revenue&quot;))<br>result = df_grouped.collect()  # Execution triggered here<br><br># Eager Mode (executes immediately)<br>df_eager = pl.read_csv(&quot;sales.csv&quot;)<br>df_eager.groupby(&quot;country&quot;).agg(pl.sum(&quot;revenue&quot;))</pre><h3>Ray — General-Purpose Distributed Execution</h3><h4>The Need:</h4><p>When you want to<strong> </strong>parallelize custom Python code, not just DataFrames.</p><h4>How It Works:</h4><ul><li>Starts a <strong>head node</strong> + workers</li><li>Runs functions marked as @ray.remote in parallel</li><li>Has libraries for ML training (ray.train), tuning (ray.tune), RL (ray.rllib), serving (ray.serve)</li></ul><h4>Example:</h4><pre>import ray<br><br>ray.init()<br><br>@ray.remote<br>def square(x):<br>return x * x<br><br>futures = [square.remote(i) for i in range(10)]<br>results = ray.get(futures)<br>print(results)</pre><h4>Time Required:</h4><ul><li><strong>Startup cost:</strong> Low-medium</li><li><strong>Performance:</strong> Extremely scalable for independent tasks</li><li><strong>Use Case:</strong> ML pipelines, hyperparameter search, simulations</li></ul><h4>Evaluation in Ray</h4><ul><li>Ray is <strong>not a DataFrame library</strong> — it doesn’t have built-in lazy pipelines.</li><li>Instead, you define <strong>tasks</strong> or <strong>actors</strong> and explicitly tell Ray when to execute them.</li></ul><h3>Side-by-Side Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*cU8J2p3diQKAaLuz4Pjd4g.png" /></figure><h3>What You Need to Use Them</h3><p>PySpark: Install pyspark, have Java (JDK) installed, optionally a cluster (YARN, Kubernetes, Databricks)</p><p>Dask: pip install dask[complete], optional distributed scheduler</p><p>Polars: pip install polars</p><p>Ray: pip install ray, optional cluster setup</p><h3>Decision Tree — Which One Should You Choose?</h3><h4><strong>Does your data fit in RAM?</strong></h4><blockquote><strong>Yes:</strong> Prefer <strong>Polars</strong> (fastest)</blockquote><blockquote><strong>No:</strong> Move to Dask or PySpark</blockquote><h4><strong>Is your data tabular and SQL-like?</strong></h4><blockquote><strong>Yes:</strong> PySpark (cluster-scale) or Dask (local/cluster)</blockquote><blockquote><strong>No:</strong> If you just need parallel Python tasks → <strong>Ray</strong></blockquote><h4><strong>Do you want to scale to multiple machines easily?</strong></h4><blockquote><strong>Yes:</strong> Dask (easiest), PySpark (heavier but powerful), Ray (for tasks)</blockquote><blockquote><strong>No:</strong> Stay with Polars</blockquote><h3>Summary:</h3><ul><li><strong>Polars:</strong> Best when data fits in memory and you need <strong>speed</strong>.</li><li><strong>Dask:</strong> Best for scaling Pandas workflows <strong>bigger than memory</strong>.</li><li><strong>PySpark:</strong> Best for <strong>production-scale ETL</strong> on clusters.</li><li><strong>Ray:</strong> Best for <strong>parallelizing custom Python/ML tasks</strong>, not just dataframes.</li></ul><p>You must have heard about Hadoop. Today, it is mostly used as a storage layer (plus resource manager YARN), not so much for computation anymore.</p><p>Most companies use:</p><ul><li><strong>HDFS</strong> (Hadoop Distributed File System-Storage Layer) for storing raw data (logs, clickstream, transactions, images, etc.). It splits big files into <strong>blocks</strong> (default 128 MB or 256 MB), stores them across multiple machines (nodes), and keeps <strong>replicas</strong> (default 3 copies) for fault tolerance.</li><li><strong>Spark</strong> (or Hive, Presto) for processing that data quickly</li><li><strong>YARN / Kubernetes</strong> for scheduling jobs</li></ul><p>Most modern big data pipelines use <strong>Spark for computation</strong>, but Spark still reads/writes data from <strong>HDFS</strong>.</p><blockquote>Stay tuned for more such articles. Happy Learning!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jOUgvDer5xakPw_I" /><figcaption>Photo by <a href="https://unsplash.com/@joshua_hoehne?utm_source=medium&amp;utm_medium=referral">Joshua Hoehne</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a1308828aa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-Tuning vs. Transfer Learning: An In-Depth Guide with Code Examples]]></title>
            <link>https://medium.com/@shubhamsd100/fine-tuning-vs-transfer-learning-an-in-depth-guide-with-code-examples-46118e45d0cc?source=rss-5e7c20900971------2</link>
            <guid isPermaLink="false">https://medium.com/p/46118e45d0cc</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[Shubham Saxena]]></dc:creator>
            <pubDate>Mon, 08 Jul 2024 08:57:43 GMT</pubDate>
            <atom:updated>2024-07-08T08:57:43.188Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*snkFCqnqngK0k1Pu" /><figcaption>Photo by <a href="https://unsplash.com/@possessedphotography?utm_source=medium&amp;utm_medium=referral">Possessed Photography</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>In the realm of deep learning, leveraging pre-trained models has become a cornerstone technique for achieving state-of-the-art results on various tasks, especially when dealing with limited data. Two popular methods to utilize pre-trained models are <strong>transfer learning</strong> and <strong>fine-tuning</strong>. This article delves into the differences between these methods, provides code examples using the VGG16 model pre-trained on ImageNet, and explains the dataset used for illustration.</blockquote><h3>Understanding Transfer Learning and Fine-Tuning</h3><h4>Transfer Learning</h4><p><strong>Transfer Learning</strong> involves taking a pre-trained model, often trained on a large dataset for a general task, and using it as the starting point for a new but related task. The core idea is to transfer the knowledge gained from the original task to the new task. Typically, in transfer learning, the pre-trained model’s layers are kept frozen, and only the new layers added for the specific task are trained.</p><p><strong>Use Case:</strong></p><ul><li>Best for tasks where the new dataset is small or closely related to the original dataset.</li></ul><h4>Fine-Tuning</h4><p><strong>Fine-Tuning</strong> is a specific type of transfer learning where, in addition to training new layers, some or all of the pre-trained model’s layers are also unfrozen and trained further. This allows the model to adjust the pre-trained weights to better fit the new task.</p><p><strong>Use Case:</strong></p><ul><li>Suitable when the new dataset is large enough to support further training of the pre-trained weights or when the new task is moderately different from the original task.</li></ul><h3>Dataset: Cats vs. Dogs</h3><p>For this illustration, we’ll use a subset of the Cats vs. Dogs dataset. This dataset contains images of cats and dogs, which we will use for a binary classification task.</p><h3>Transfer Learning with VGG16</h3><p>In this example, we’ll use the VGG16 model pre-trained on ImageNet, freeze its layers, and add new layers for our specific task (Cats vs. Dogs classification).</p><pre>import tensorflow as tf<br>from tensorflow.keras.applications import VGG16<br>from tensorflow.keras.layers import Dense, Flatten<br>from tensorflow.keras.models import Model<br>from tensorflow.keras.preprocessing.image import ImageDataGenerator<br><br># Load the VGG16 model pre-trained on ImageNet, without the top classification layer<br>base_model = VGG16(weights=&#39;imagenet&#39;, include_top=False, input_shape=(224, 224, 3))<br><br># Freeze the base model<br>base_model.trainable = False<br><br># Add new classification layers on top of the pre-trained model<br>x = Flatten()(base_model.output)<br>x = Dense(512, activation=&#39;relu&#39;)(x)<br>x = Dense(1, activation=&#39;sigmoid&#39;)(x)<br><br># Create the new model<br>model = Model(inputs=base_model.input, outputs=x)<br><br># Compile the model<br>model.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br><br># Data preparation<br>train_datagen = ImageDataGenerator(rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)<br>test_datagen = ImageDataGenerator(rescale=1./255)<br><br>train_generator = train_datagen.flow_from_directory(&#39;data/train&#39;, target_size=(224, 224), batch_size=32, class_mode=&#39;binary&#39;)<br>validation_generator = test_datagen.flow_from_directory(&#39;data/validation&#39;, target_size=(224, 224), batch_size=32, class_mode=&#39;binary&#39;)<br><br># Train the model<br>history = model.fit(train_generator, epochs=10, validation_data=validation_generator)</pre><h3>Fine-Tuning with VGG16</h3><p>For fine-tuning, we’ll unfreeze some of the layers in the pre-trained VGG16 model and train them along with the new layers.</p><pre>import tensorflow as tf<br>from tensorflow.keras.applications import VGG16<br>from tensorflow.keras.layers import Dense, Flatten<br>from tensorflow.keras.models import Model<br>from tensorflow.keras.preprocessing.image import ImageDataGenerator<br><br># Load the VGG16 model pre-trained on ImageNet, without the top classification layer<br>base_model = VGG16(weights=&#39;imagenet&#39;, include_top=False, input_shape=(224, 224, 3))<br><br># Freeze the initial layers and unfreeze some layers for fine-tuning<br>for layer in base_model.layers[:15]:<br>    layer.trainable = False<br>for layer in base_model.layers[15:]:<br>    layer.trainable = True<br><br># Add new classification layers on top of the pre-trained model<br>x = Flatten()(base_model.output)<br>x = Dense(512, activation=&#39;relu&#39;)(x)<br>x = Dense(1, activation=&#39;sigmoid&#39;)(x)<br><br># Create the new model<br>model = Model(inputs=base_model.input, outputs=x)<br><br># Compile the model with a lower learning rate<br>model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-5), loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br><br># Data preparation<br>train_datagen = ImageDataGenerator(rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)<br>test_datagen = ImageDataGenerator(rescale=1./255)<br><br>train_generator = train_datagen.flow_from_directory(&#39;data/train&#39;, target_size=(224, 224), batch_size=32, class_mode=&#39;binary&#39;)<br>validation_generator = test_datagen.flow_from_directory(&#39;data/validation&#39;, target_size=(224, 224), batch_size=32, class_mode=&#39;binary&#39;)<br><br># Train the model<br>history = model.fit(train_generator, epochs=10, validation_data=validation_generator)</pre><h3>Number of Layers in the Model</h3><p>To get the number of layers in the model, you can use the layers attribute and print a summary.</p><pre># Load the VGG16 model pre-trained on ImageNet, without the top classification layer<br>base_model = VGG16(weights=&#39;imagenet&#39;, include_top=False, input_shape=(224, 224, 3))<br><br># Get the number of layers<br>num_layers = len(base_model.layers)<br><br># Print the number of layers<br>print(f&#39;The VGG16 model has {num_layers} layers.&#39;)<br><br># Print each layer&#39;s name and type<br>for i, layer in enumerate(base_model.layers):<br>    print(f&#39;Layer {i}: {layer.name} ({layer.__class__.__name__})&#39;)</pre><h3>Conclusion</h3><p>Both transfer learning and fine-tuning are powerful techniques for leveraging pre-trained models to solve new tasks. Transfer learning is simpler and faster but may not be as effective if the new task is significantly different from the original task. Fine-tuning, while more computationally intensive, allows for greater flexibility and potentially better performance by adjusting the pre-trained weights to the new task.</p><h3><strong>Bonus Read!</strong></h3><h4><strong>Pre-training</strong></h4><p>The term “pre-training” in the context of deep learning refers to training a model on a large dataset to learn general features or representations, which can then be used as a starting point for further specific tasks. This term is used to distinguish this initial phase of learning from subsequent phases where the model might be adapted or fine-tuned for a particular task.</p><p>Here are a few reasons why it’s called “pre-training” rather than just “training”:</p><ol><li><strong>General Feature Learning:</strong> During pre-training, the model learns general features from a large and diverse dataset, often without any specific task in mind. This contrasts with training, which typically implies training for a specific task with labeled data.</li><li><strong>Transfer Learning Perspective:</strong> The primary goal of pre-training is to transfer the learned knowledge (features or representations) to other tasks. By pre-training on a large dataset like ImageNet, models can capture a broad range of features that are useful across many different types of tasks.</li><li><strong>Efficiency and Effectiveness:</strong> Pre-training is often more efficient than training from scratch because it leverages existing knowledge and structures learned from massive datasets. It reduces the need for extensive computational resources and labeled data, especially for complex tasks.</li><li><strong>Historical Context:</strong> The term “pre-training” has evolved within the field of deep learning to specifically denote this phase of learning general features before task-specific adaptation or fine-tuning. It helps to delineate between different stages of model development and application.</li></ol><p>In essence, “pre-training” captures the concept of initially training a model on general tasks or datasets to learn foundational knowledge that can then be applied (via transfer learning or fine-tuning) to more specific tasks. It’s a term that highlights the strategic use of large-scale training data to build versatile models capable of robust performance across a variety of applications.</p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46118e45d0cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Perplexity in Language Models: A Detailed Exploration]]></title>
            <link>https://medium.com/@shubhamsd100/understanding-perplexity-in-language-models-a-detailed-exploration-2108b6ab85af?source=rss-5e7c20900971------2</link>
            <guid isPermaLink="false">https://medium.com/p/2108b6ab85af</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[perplexity]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Shubham Saxena]]></dc:creator>
            <pubDate>Fri, 05 Jul 2024 12:27:16 GMT</pubDate>
            <atom:updated>2024-07-05T12:27:16.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tMpRlfX12v4wJjCM" /><figcaption>Photo by <a href="https://unsplash.com/@introspectivedsgn?utm_source=medium&amp;utm_medium=referral">Erik Mclean</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Perplexity is a key metric in natural language processing (NLP) that measures the quality of a language model. It evaluates how well a probabilistic model predicts a sample, particularly focusing on the sequence of words in a text. This article aims to provide an in-depth understanding of perplexity, its calculation, interpretation, and practical significance in evaluating language models.</p><p><strong>What is Perplexity?</strong></p><p>Perplexity is a measurement of uncertainty in the predictions of a language model. In simpler terms, it indicates how surprised a model is by the actual outcomes. The lower the perplexity, the better the model at predicting the next word in a sequence, reflecting higher confidence in its predictions.</p><p>Mathematically, for a given probability model PPP and a sequence of N words w1,w2,…,wN, perplexity is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*4nvkNp_Bp6aYZuk4MPsPKg.png" /></figure><p>This formula means that perplexity is the exponential of the average negative log-likelihood of the words in the sequence, given their previous context.</p><p><strong>Interpreting Perplexity</strong></p><ul><li><strong>Perplexity of 1</strong>: This is the ideal score, indicating that the model predicts the next word perfectly every time.</li><li><strong>Perplexity above 1</strong>: Indicates some level of uncertainty. The higher the perplexity, the less confident the model is in its predictions.</li></ul><p>For instance, a perplexity of 10 means the model is as uncertain as if it were choosing between 10 different possible next words.</p><h3><strong>Understanding the Decimals in Perplexity</strong></h3><p>Decimals in the perplexity score provide a more precise measure of the model’s uncertainty. Each increment in the decimal value signifies finer granularity in the model’s prediction confidence.</p><ol><li><strong>Integer Part</strong>: Indicates the general level of uncertainty. For example, 23 in a perplexity of 23.123456789.</li><li><strong>Decimal Part</strong>: Refines this measure, showing small variations in the model’s predictive capability.</li></ol><ul><li><strong>Closer to 0</strong>: Indicates the model’s performance is slightly worse than having a perplexity of 23 (e.g., 23.1).</li><li><strong>Closer to 1</strong>: Means the model is nearly at the next level of uncertainty, nearing a perplexity of 24 (e.g., 23.9).</li></ul><h3>Practical Example of Perplexity Calculation</h3><p>To understand perplexity in practice, let’s consider a small dataset and calculate the perplexity using a pre-trained language model from the transformers library.</p><p><strong>Step-by-Step Example:</strong></p><pre>!pip install transformers torch<br><br>import torch<br>from transformers import GPT2Tokenizer, GPT2LMHeadModel<br><br># Load pre-trained model and tokenizer<br>model_name = &quot;gpt2&quot;<br>tokenizer = GPT2Tokenizer.from_pretrained(model_name)<br>model = GPT2LMHeadModel.from_pretrained(model_name)<br><br># Example text<br>text = &quot;I love learning&quot;<br><br># Tokenize input<br>inputs = tokenizer(text, return_tensors=&quot;pt&quot;)<br><br># Ensure no gradient calculation<br>with torch.no_grad(): #opens a context in which gradient calculations are disabled. This ensures that only the forward pass is computed.<br>    outputs = model(**inputs, labels=inputs[&quot;input_ids&quot;]) #forward pass- computes the model’s outputs and loss.<br>    loss = outputs.loss #extracts the loss from the model&#39;s outputs.<br>    perplexity = torch.exp(loss) #calculates the perplexity by exponentiating the loss.<br><br>print(f&quot;Perplexity: {perplexity.item()}&quot;)<br><br>Perplexity: 23.123456789</pre><h3>Interpreting the Output:</h3><ul><li><strong>23</strong>: The model’s predictions are on average as uncertain as choosing from 23 possibilities.</li><li><strong>0.123456789</strong>: Provides precision, indicating the exact level of uncertainty within the range of 23 possibilities. The closer this value is to 0, the closer the model is to a perplexity of 23.</li></ul><h3>Why do we calculate the perplexity by exponentiating the loss?</h3><p>The perplexity of a language model is calculated by exponentiating the average negative log-likelihood of the words in the sequence. Here’s why exponentiation is used in this context:</p><h3>Understanding Log-Likelihood and Perplexity</h3><ol><li><strong>Log-Likelihood</strong>:</li></ol><ul><li>When training or evaluating language models, we often use the log-likelihood of the observed data under the model.</li><li>A language model assigns probabilities to sequences of words. For a sequence of words w1,w2,…,wN and a language model P, the probability of the entire sequence is the product of the conditional probabilities of each word given the preceding words, the log-likelihood of the sequence is given by:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*bKLHcPvVQadE48wWoNBy7Q.png" /></figure><p>In simpler terms, it’s the product of the probability of each word given all the previous words in the sequence.</p><p>The log-likelihood is the logarithm of this probability. We use the logarithm because:</p><p><strong>a) Simplification</strong>: Multiplying many small probabilities can result in very small numbers, which can cause numerical instability. Taking the logarithm converts the product of probabilities into a sum of log-probabilities, which is easier to handle numerically.</p><p><strong>b) Additivity</strong>: The logarithm of a product is the sum of the logarithms. This property simplifies the calculation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*vC7J-5JjPAbcH0tDwgo5Sw.png" /></figure><p><strong>2. Average Negative Log-Likelihood (NLL)</strong>:</p><ul><li>In practice, we often work with the negative log-likelihood, especially when training language models. It measures how well the model predicts the actual sequence. Lower NLL indicates better performance.</li><li>The average NLL for the sequence is:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*tjgyiu3n01pSFpGOZSPduw.png" /></figure><h3>Why Use the Negative Log-Likelihood?</h3><p><strong>Minimization Objective:</strong></p><ul><li><strong>Optimization</strong>: In machine learning, we typically frame problems as minimization tasks. The log-likelihood is usually negative because probabilities are between 0 and 1, making their logarithms negative. By negating the log-likelihood, we convert the problem into a minimization problem, which is more conventional for optimization algorithms.</li><li><strong>Loss Function</strong>: The negative log-likelihood serves as a loss function that we aim to minimize during model training. Minimizing the NLL corresponds to maximizing the log-likelihood, thus making the model’s predictions as probable as possible.</li></ul><p><strong>Interpretability</strong>:</p><ul><li><strong>Likelihood and Probability</strong>: Likelihood measures how well the model explains the observed data. By taking the negative log, we transform the product of probabilities into a sum, making it easier to work with and interpret.</li><li><strong>Sum of Errors</strong>: The negative log-likelihood can be seen as a sum of prediction errors. Lower values of NLL indicate that the model’s predictions are closer to the true data distribution.</li></ul><p><strong>Mathematical Properties</strong>:</p><ul><li><strong>Convexity</strong>: For many models, the NLL is a convex function, making it easier to optimize using gradient-based methods. Convex functions have a single global minimum, which simplifies the optimization process.</li><li><strong>Gradient Computation</strong>: The negative log-likelihood has desirable mathematical properties that make the calculation of gradients straightforward. This is important for algorithms like gradient descent used in training machine learning models.</li></ul><p><strong>Numerical Stability</strong>:</p><ul><li><strong>Handling Small Probabilities</strong>: Probabilities in the range of 0 to 1 can be very small, leading to numerical underflow when multiplied together. Using the logarithm converts these multiplications into additions, which are more stable numerically.</li><li><strong>Preventing Overflow</strong>: Taking the log of probabilities and then negating them keeps the values within a manageable range, preventing overflow in computations.</li></ul><p>3. <strong>Exponentiation</strong>:</p><ul><li>Perplexity is a measure that normalizes this log-likelihood in a way that is more interpretable.</li><li>Perplexity is defined as the exponentiation of the average negative log-likelihood:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*Wom5MUNtVNDpsOOHYb8Rng.png" /></figure><h3>Why Exponentiation?</h3><p><strong>Interpretability</strong>:</p><ul><li>The log-likelihood (and thus the negative log-likelihood) is an additive measure. Exponentiating it converts it back to the multiplicative domain, which is easier to interpret in terms of probabilities.</li><li>Perplexity provides an intuitive sense of “how many choices” the model is uncertain about. For example, a perplexity of 10 means the model is as uncertain as if it were choosing from 10 equally likely options at each step.</li></ul><p><strong>Normalization</strong>:</p><ul><li>Exponentiation normalizes the log-likelihood into a geometric mean of probabilities, providing a more natural measure of average prediction confidence.</li></ul><p><strong>Relationship to Probability</strong>:</p><ul><li>In probability theory, working with log-probabilities is common because it simplifies the mathematics of combining probabilities (since logs convert multiplication into addition).</li><li>To return to the original probability scale, we exponentiate the log-probabilities.</li></ul><p>Exponentiation is used to calculate perplexity because it transforms the average negative log-likelihood back into a more interpretable form, reflecting the model’s uncertainty in predicting the next word in the sequence. This transformation makes perplexity a more intuitive and useful metric for evaluating the performance of language models.</p><h3>Practical Significance of Perplexity</h3><p>Perplexity is essential in comparing different language models or the same model under different conditions:</p><ul><li><strong>Low Perplexity</strong>: Indicates the model is good at predicting the next word in a sequence. This is desirable in applications like autocomplete, text generation, and translation.</li><li><strong>High Perplexity</strong>: Suggests the model has difficulty predicting the next word, indicating the need for more training data, better model architecture, or more effective fine-tuning.</li></ul><h3>Improving Perplexity</h3><p>To improve the perplexity of your model:</p><ol><li><strong>Increase Training Data</strong>: Use a larger and more diverse dataset to provide the model with more examples.</li><li><strong>Fine-Tune the Model</strong>: Fine-tune a pre-trained model on your specific dataset to make it more context-aware.</li><li><strong>Use a More Complex Model</strong>: Advanced models or architectures may better capture the nuances of language.</li></ol><h3><strong>Conclusion</strong></h3><p>Perplexity is a critical metric in NLP for evaluating language models. It quantifies the model’s uncertainty in predicting the next word in a sequence, with lower values indicating better performance. By understanding and utilizing perplexity, we can better assess and improve language models to create more accurate and reliable NLP applications.</p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2108b6ab85af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Fine-Tuning in Large Language Models (LLMs)]]></title>
            <link>https://medium.com/@shubhamsd100/understanding-fine-tuning-in-large-language-models-llms-7899008db982?source=rss-5e7c20900971------2</link>
            <guid isPermaLink="false">https://medium.com/p/7899008db982</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Shubham Saxena]]></dc:creator>
            <pubDate>Tue, 02 Jul 2024 10:39:01 GMT</pubDate>
            <atom:updated>2024-07-02T10:39:01.185Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q6WXFq_2Ym5bSaOA" /><figcaption>Photo by <a href="https://unsplash.com/@santesson89?utm_source=medium&amp;utm_medium=referral">Andrea De Santis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Fine-tuning in Large Language Models (LLMs) is a crucial process to adapt pre-trained models to specific tasks or domains. With advancements in AI and the proliferation of LLMs like GPT-3 and GPT-4, fine-tuning allows these models to excel in specialized applications. This article explores various types of fine-tuning techniques, providing detailed explanations and examples, along with some Python code snippets.</p><h4>1. Supervised Fine-Tuning</h4><p><strong>Task-Specific Fine-Tuning</strong> This involves training a model on a labeled dataset for a specific task, such as text classification, sentiment analysis, or named entity recognition.</p><p><em>Example: Fine-Tuning for Sentiment Analysis</em></p><pre>from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments<br>from datasets import load_dataset<br><br># Load the dataset<br>dataset = load_dataset(&quot;imdb&quot;)<br><br># Initialize the tokenizer and model<br>tokenizer = BertTokenizer.from_pretrained(&quot;bert-base-uncased&quot;)<br>model = BertForSequenceClassification.from_pretrained(&quot;bert-base-uncased&quot;)<br><br># Tokenize the data<br>def tokenize_function(examples):<br>    return tokenizer(examples[&#39;text&#39;], padding=&quot;max_length&quot;, truncation=True)<br><br>tokenized_datasets = dataset.map(tokenize_function, batched=True)<br><br># Training arguments<br>training_args = TrainingArguments(<br>    output_dir=&quot;./results&quot;,<br>    evaluation_strategy=&quot;epoch&quot;,<br>    per_device_train_batch_size=8,<br>    per_device_eval_batch_size=8,<br>    num_train_epochs=3,<br>    weight_decay=0.01,<br>)<br><br># Trainer<br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=tokenized_datasets[&quot;train&quot;],<br>    eval_dataset=tokenized_datasets[&quot;test&quot;],<br>)<br><br># Train the model<br>trainer.train()</pre><p><strong>Domain-Specific Fine-Tuning</strong> This involves training a model on a domain-specific corpus to improve its performance in that particular domain, such as medical or legal texts.</p><p><em>Example: Fine-Tuning for Medical Texts</em></p><pre>from transformers import BertTokenizer, BertForMaskedLM, Trainer, TrainingArguments<br><br># Assume `medical_texts` is a dataset of medical documents<br>tokenizer = BertTokenizer.from_pretrained(&quot;bert-base-uncased&quot;)<br>model = BertForMaskedLM.from_pretrained(&quot;bert-base-uncased&quot;)<br><br># Tokenize the data<br>def tokenize_function(examples):<br>    return tokenizer(examples[&#39;text&#39;], padding=&quot;max_length&quot;, truncation=True)<br><br>tokenized_medical_texts = medical_texts.map(tokenize_function, batched=True)<br><br># Training arguments<br>training_args = TrainingArguments(<br>    output_dir=&quot;./results&quot;,<br>    per_device_train_batch_size=8,<br>    per_device_eval_batch_size=8,<br>    num_train_epochs=3,<br>    weight_decay=0.01,<br>)<br><br># Trainer<br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=tokenized_medical_texts[&quot;train&quot;],<br>    eval_dataset=tokenized_medical_texts[&quot;test&quot;],<br>)<br><br># Train the model<br>trainer.train()</pre><h4>2. Unsupervised Fine-Tuning</h4><p><strong>Domain Adaptation</strong></p><p>Involves fine-tuning a model on a large corpus of unlabeled text from a specific domain to understand the terminology and context better.</p><p><em>Example: Domain Adaptation for Legal Texts</em></p><pre>from transformers import GPT2LMHeadModel, GPT2Tokenizer, TextDataset, DataCollatorForLanguageModeling, Trainer, TrainingArguments<br><br># Load the tokenizer and model<br>tokenizer = GPT2Tokenizer.from_pretrained(&quot;gpt2&quot;)<br>model = GPT2LMHeadModel.from_pretrained(&quot;gpt2&quot;)<br><br># Prepare the dataset<br>def load_dataset(filepath):<br>    with open(filepath, &quot;r&quot;) as f:<br>        data = f.read()<br>    return data<br><br>dataset = TextDataset(<br>    tokenizer=tokenizer,<br>    file_path=&quot;legal_texts.txt&quot;,  # Assume this is your legal text corpus<br>    block_size=128,<br>)<br><br>data_collator = DataCollatorForLanguageModeling(<br>    tokenizer=tokenizer,<br>    mlm=False,<br>)<br><br># Training arguments<br>training_args = TrainingArguments(<br>    output_dir=&quot;./results&quot;,<br>    overwrite_output_dir=True,<br>    num_train_epochs=1,<br>    per_device_train_batch_size=1,<br>    save_steps=10_000,<br>    save_total_limit=2,<br>)<br><br># Trainer<br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    data_collator=data_collator,<br>    train_dataset=dataset,<br>)<br><br># Train the model<br>trainer.train()</pre><p><strong>Continual Learning</strong></p><p>Involves incrementally fine-tuning the model on new data over time to keep it updated with the latest information.</p><p><em>Example: Continual Learning with News Articles</em></p><pre>from transformers import GPT2LMHeadModel, GPT2Tokenizer, TextDataset, DataCollatorForLanguageModeling, Trainer, TrainingArguments<br><br># Load the tokenizer and model<br>tokenizer = GPT2Tokenizer.from_pretrained(&quot;gpt2&quot;)<br>model = GPT2LMHeadModel.from_pretrained(&quot;gpt2&quot;)<br><br># Prepare the dataset<br>def load_dataset(filepath):<br>    with open(filepath, &quot;r&quot;) as f:<br>        data = f.read()<br>    return data<br><br>new_articles = TextDataset(<br>    tokenizer=tokenizer,<br>    file_path=&quot;new_articles.txt&quot;,  # Assume this is your new articles corpus<br>    block_size=128,<br>)<br><br>data_collator = DataCollatorForLanguageModeling(<br>    tokenizer=tokenizer,<br>    mlm=False,<br>)<br><br># Training arguments<br>training_args = TrainingArguments(<br>    output_dir=&quot;./results&quot;,<br>    overwrite_output_dir=True,<br>    num_train_epochs=1,<br>    per_device_train_batch_size=1,<br>    save_steps=10_000,<br>    save_total_limit=2,<br>)<br><br># Trainer<br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    data_collator=data_collator,<br>    train_dataset=new_articles,<br>)<br><br># Train the model<br>trainer.train()</pre><h4>3. Multi-Task Fine-Tuning</h4><p>Involves training a model on multiple tasks simultaneously to help the model generalize better and leverage shared knowledge across tasks.</p><p><em>Example: Multi-Task Learning for Text Classification and Named Entity Recognition</em></p><pre>from transformers import BertTokenizer, BertForSequenceClassification, BertForTokenClassification, Trainer, TrainingArguments<br>from datasets import load_dataset<br><br># Load datasets for both tasks<br>classification_dataset = load_dataset(&quot;imdb&quot;)<br>ner_dataset = load_dataset(&quot;conll2003&quot;)<br><br># Initialize tokenizer and models<br>tokenizer = BertTokenizer.from_pretrained(&quot;bert-base-uncased&quot;)<br>classification_model = BertForSequenceClassification.from_pretrained(&quot;bert-base-uncased&quot;)<br>ner_model = BertForTokenClassification.from_pretrained(&quot;bert-base-uncased&quot;)<br><br># Tokenize datasets<br>def tokenize_function(examples):<br>    return tokenizer(examples[&#39;text&#39;], padding=&quot;max_length&quot;, truncation=True)<br><br>tokenized_classification_dataset = classification_dataset.map(tokenize_function, batched=True)<br>tokenized_ner_dataset = ner_dataset.map(tokenize_function, batched=True)<br><br># Training arguments<br>training_args = TrainingArguments(<br>    output_dir=&quot;./results&quot;,<br>    evaluation_strategy=&quot;epoch&quot;,<br>    per_device_train_batch_size=8,<br>    per_device_eval_batch_size=8,<br>    num_train_epochs=3,<br>    weight_decay=0.01,<br>)<br><br># Trainer for classification<br>classification_trainer = Trainer(<br>    model=classification_model,<br>    args=training_args,<br>    train_dataset=tokenized_classification_dataset[&quot;train&quot;],<br>    eval_dataset=tokenized_classification_dataset[&quot;test&quot;],<br>)<br><br># Trainer for NER<br>ner_trainer = Trainer(<br>    model=ner_model,<br>    args=training_args,<br>    train_dataset=tokenized_ner_dataset[&quot;train&quot;],<br>    eval_dataset=tokenized_ner_dataset[&quot;test&quot;],<br>)<br><br># Train models<br>classification_trainer.train()<br>ner_trainer.train()</pre><h4>4. Parameter-Efficient Fine-Tuning</h4><p><strong>Adapters</strong></p><p>Involves inserting small neural networks (adapters) into the model’s layers, and only training these adapters while keeping the rest of the model frozen.</p><p><em>Example: Adapter Fine-Tuning</em></p><pre>from transformers import BertTokenizer, BertForSequenceClassification, AdapterConfig, Trainer, TrainingArguments<br><br># Load tokenizer and model<br>tokenizer = BertTokenizer.from_pretrained(&quot;bert-base-uncased&quot;)<br>model = BertForSequenceClassification.from_pretrained(&quot;bert-base-uncased&quot;)<br><br># Add adapter<br>adapter_config = AdapterConfig.load(&quot;pfeiffer&quot;)<br>model.add_adapter(&quot;classification_adapter&quot;, config=adapter_config)<br>model.train_adapter(&quot;classification_adapter&quot;)<br><br># Tokenize the dataset<br>def tokenize_function(examples):<br>    return tokenizer(examples[&#39;text&#39;], padding=&quot;max_length&quot;, truncation=True)<br><br>dataset = load_dataset(&quot;imdb&quot;)<br>tokenized_dataset = dataset.map(tokenize_function, batched=True)<br><br># Training arguments<br>training_args = TrainingArguments(<br>    output_dir=&quot;./results&quot;,<br>    evaluation_strategy=&quot;epoch&quot;,<br>    per_device_train_batch_size=8,<br>    per_device_eval_batch_size=8,<br>    num_train_epochs=3,<br>    weight_decay=0.01,<br>)<br><br># Trainer<br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=tokenized_dataset[&quot;train&quot;],<br>    eval_dataset=tokenized_dataset[&quot;test&quot;],<br>)<br><br># Train the model<br>trainer.train()</pre><p><strong>Prefix Tuning</strong></p><p>Prefix tuning involves fine-tuning only the initial layers (prefix) of the model while keeping the rest of the model unchanged. Here is an example using the Hugging Face Transformers library with a GPT-2 model:</p><pre>from transformers import GPT2Tokenizer, GPT2LMHeadModel, Trainer, TrainingArguments<br>from datasets import load_dataset<br><br># Load tokenizer and model<br>tokenizer = GPT2Tokenizer.from_pretrained(&quot;gpt2&quot;)<br>model = GPT2LMHeadModel.from_pretrained(&quot;gpt2&quot;)<br><br># Freeze all layers except the initial layers (prefix)<br>for name, param in model.named_parameters():<br>    if &quot;transformer.h.0&quot; not in name:<br>        param.requires_grad = False<br><br># Prepare the dataset<br>def tokenize_function(examples):<br>    return tokenizer(examples[&#39;text&#39;], padding=&quot;max_length&quot;, truncation=True, return_tensors=&quot;pt&quot;)<br><br>dataset = load_dataset(&quot;wikitext&quot;, &quot;wikitext-2-raw-v1&quot;)<br>tokenized_datasets = dataset.map(tokenize_function, batched=True)<br><br># Training arguments<br>training_args = TrainingArguments(<br>    output_dir=&quot;./results&quot;,<br>    per_device_train_batch_size=4,<br>    per_device_eval_batch_size=4,<br>    num_train_epochs=3,<br>    weight_decay=0.01,<br>    logging_dir=&quot;./logs&quot;,<br>)<br><br># Trainer<br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=tokenized_datasets[&quot;train&quot;],<br>    eval_dataset=tokenized_datasets[&quot;validation&quot;],<br>)<br><br># Train the model<br>trainer.train()</pre><p><strong>LoRA (Low-Rank Adaptation)</strong></p><p>LoRA involves adding low-rank matrices to the model weights, which are fine-tuned to reduce the number of parameters needed to adapt the model. Here’s an example implementation:</p><pre>from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments<br>import torch.nn as nn<br>from datasets import load_dataset<br><br>class LoRAModule(nn.Module):<br>    def __init__(self, model, rank=2):<br>        super().__init__()<br>        self.model = model<br>        self.rank = rank<br>        self.adapter_weights = nn.ParameterDict({<br>            name: nn.Parameter(param.new_zeros(param.size(0), rank))<br>            for name, param in model.named_parameters() if param.requires_grad<br>        })<br><br>    def forward(self, *inputs, **kwargs):<br>        for name, param in self.model.named_parameters():<br>            if name in self.adapter_weights:<br>                param.data += self.adapter_weights[name].matmul(param.new_zeros(self.rank, param.size(1)))<br>        return self.model(*inputs, **kwargs)<br><br># Load tokenizer and model<br>tokenizer = BertTokenizer.from_pretrained(&quot;bert-base-uncased&quot;)<br>model = BertForSequenceClassification.from_pretrained(&quot;bert-base-uncased&quot;)<br><br># Wrap model with LoRA<br>lora_model = LoRAModule(model)<br><br># Prepare the dataset<br>def tokenize_function(examples):<br>    return tokenizer(examples[&#39;text&#39;], padding=&quot;max_length&quot;, truncation=True)<br><br>dataset = load_dataset(&quot;imdb&quot;)<br>tokenized_datasets = dataset.map(tokenize_function, batched=True)<br><br># Training arguments<br>training_args = TrainingArguments(<br>    output_dir=&quot;./results&quot;,<br>    per_device_train_batch_size=4,<br>    per_device_eval_batch_size=4,<br>    num_train_epochs=3,<br>    weight_decay=0.01,<br>    logging_dir=&quot;./logs&quot;,<br>)<br><br># Trainer<br>trainer = Trainer(<br>    model=lora_model,<br>    args=training_args,<br>    train_dataset=tokenized_datasets[&quot;train&quot;],<br>    eval_dataset=tokenized_datasets[&quot;test&quot;],<br>)<br><br># Train the model<br>trainer.train()</pre><h4>5. Few-Shot and Zero-Shot Learning</h4><p><strong>Few-Shot Learning</strong></p><p>Involves fine-tuning the model with a very small number of examples for a new task.</p><pre>from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments<br>from datasets import Dataset<br><br># Load tokenizer and model<br>tokenizer = BertTokenizer.from_pretrained(&quot;bert-base-uncased&quot;)<br>model = BertForSequenceClassification.from_pretrained(&quot;bert-base-uncased&quot;)<br><br># Prepare the few-shot dataset<br>texts = [&quot;I love this movie!&quot;, &quot;This film is terrible.&quot;]<br>labels = [1, 0]<br>few_shot_dataset = Dataset.from_dict({&quot;text&quot;: texts, &quot;label&quot;: labels})<br><br>def tokenize_function(examples):<br>    return tokenizer(examples[&#39;text&#39;], padding=&quot;max_length&quot;, truncation=True)<br><br>tokenized_dataset = few_shot_dataset.map(tokenize_function, batched=True)<br><br># Training arguments<br>training_args = TrainingArguments(<br>    output_dir=&quot;./results&quot;,<br>    per_device_train_batch_size=2,<br>    per_device_eval_batch_size=2,<br>    num_train_epochs=3,<br>    weight_decay=0.01,<br>    logging_dir=&quot;./logs&quot;,<br>)<br><br># Trainer<br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=tokenized_dataset,<br>)<br><br># Train the model<br>trainer.train()</pre><p><strong>Zero-Shot Learning</strong></p><p>Zero-shot learning involves testing the model on tasks it has not seen during training by leveraging its generalization capabilities. Here’s an example using a GPT-3 model through OpenAI’s API:</p><pre>import openai<br><br># Set your API key<br>openai.api_key = &quot;your-api-key&quot;<br><br># Define a zero-shot learning prompt<br>prompt = &quot;Translate the following English text to French: &#39;Hello, how are you?&#39;&quot;<br><br># Generate a response<br>response = openai.Completion.create(<br>  model=&quot;text-davinci-003&quot;,<br>  prompt=prompt,<br>  max_tokens=60<br>)<br><br># Print the generated translation<br>print(response.choices[0].text.strip())</pre><h3>6. Prompt-Based Fine-Tuning</h3><p><strong>Prompt Tuning</strong></p><p>Involves fine-tuning the model on specific prompts or instructions to guide the model to generate desired outputs.</p><p><em>Example: Prompt Tuning</em></p><pre>from transformers import GPT2Tokenizer, GPT2LMHeadModel, Trainer, TrainingArguments<br><br># Load tokenizer and model<br>tokenizer = GPT2Tokenizer.from_pretrained(&quot;gpt2&quot;)<br>model = GPT2LMHeadModel.from_pretrained(&quot;gpt2&quot;)<br><br># Prepare dataset with prompts<br>def create_prompt_dataset(texts, prompts):<br>    prompt_texts = [f&quot;{prompt}: {text}&quot; for prompt, text in zip(prompts, texts)]<br>    return prompt_texts<br><br>texts = [&quot;The weather is great today.&quot;, &quot;I love programming.&quot;]<br>prompts = [&quot;Describe the weather&quot;, &quot;Share your thoughts on programming&quot;]<br><br>prompted_texts = create_prompt_dataset(texts, prompts)<br><br># Tokenize the data<br>def tokenize_function(examples):<br>    return tokenizer(examples, padding=&quot;max_length&quot;, truncation=True, return_tensors=&quot;pt&quot;)<br><br>tokenized_texts = tokenize_function(prompted_texts)<br><br># Training arguments<br>training_args = TrainingArguments(<br>    output_dir=&quot;./results&quot;,<br>    per_device_train_batch_size=2,<br>    per_device_eval_batch_size=2,<br>    num_train_epochs=3,<br>    weight_decay=0.01,<br>)<br><br># Trainer<br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=tokenized_texts,<br>)<br><br># Train the model<br>trainer.train()</pre><h3>Conclusion</h3><p>Fine-tuning is a versatile and powerful technique that enables LLMs to be adapted for specific tasks, domains, and use cases. Whether through supervised, unsupervised, multi-task, parameter-efficient, few-shot, zero-shot, or prompt-based methods, fine-tuning helps LLMs achieve higher performance and applicability in various scenarios.</p><p>Thanks!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7899008db982" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating the Performance of Large Language Models (LLMs)]]></title>
            <link>https://medium.com/@shubhamsd100/evaluating-the-performance-of-large-language-models-llms-381e0becc200?source=rss-5e7c20900971------2</link>
            <guid isPermaLink="false">https://medium.com/p/381e0becc200</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Shubham Saxena]]></dc:creator>
            <pubDate>Tue, 02 Jul 2024 06:31:35 GMT</pubDate>
            <atom:updated>2024-07-02T06:31:35.361Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UtPauKgd2Xlffz47" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Evaluating the performance of Large Language Models (LLMs) is crucial for understanding their capabilities and limitations. This process involves a blend of quantitative and qualitative methods to provide a comprehensive assessment. Here, we will delve into various evaluation techniques with detailed explanations and examples.</p><h3><strong>Quantitative Metrics</strong></h3><p><strong>a) Perplexity:</strong> Perplexity measures how well a probability model predicts a sample. In simpler terms, it evaluates the model’s uncertainty in generating the next word in a sequence. Lower perplexity indicates better performance.</p><p><em>Example:</em> For a language model predicting the next word in a sentence, a perplexity score of 10 means the model is as uncertain as if it were choosing from 10 possible words.</p><p><strong>b) BLEU (Bilingual Evaluation Understudy):</strong> BLEU is commonly used for machine translation. It measures the similarity between the machine-generated translation and reference translations by counting matching n-grams (contiguous word sequences).</p><p><em>Example:</em> If the reference sentence is “The cat is on the mat” and the model outputs “The cat is on the rug,” BLEU would compare the n-grams of both sentences and calculate a score based on overlaps.</p><p><strong>c) ROUGE (Recall-Oriented Understudy for Gisting Evaluation):</strong> ROUGE, especially ROUGE-L, is often used for summarization tasks. It measures the overlap of longest common subsequences between generated summaries and reference summaries.</p><p><em>Example:</em> For a summary task, if the reference is “The quick brown fox jumps over the lazy dog,” and the generated summary is “The quick fox jumps over the dog,” ROUGE-L would assess the longest matching sequences.</p><p><strong>d) F1 Score:</strong> The F1 score is the harmonic mean of precision and recall, providing a single measure of a model’s accuracy on classification tasks.</p><p><em>Example:</em> In a spam detection system, if the model correctly identifies 80% of spam emails (precision) and catches 90% of all spam emails (recall), the F1 score provides a balanced measure of these two metrics.</p><p><strong>e) Accuracy:</strong> Accuracy measures the percentage of correct predictions out of all predictions made.</p><p><em>Example:</em> For a sentiment analysis task, if the model correctly classifies 95 out of 100 reviews as positive or negative, the accuracy is 95%.</p><p><strong>f) Precision and Recall:</strong> Precision is the ratio of correctly predicted positive observations to the total predicted positives, while recall is the ratio of correctly predicted positives to all actual positives.</p><p><em>Example:</em> In a medical diagnosis model, precision would measure how many diagnosed cases are truly positive, while recall would measure how many actual positive cases the model identifies.</p><p><strong>g) Mean Reciprocal Rank (MRR):</strong> MRR evaluates the effectiveness of a list of ranked answers, often used in search engines.</p><p><em>Example:</em> For a query like “Best restaurants in NYC,” if the top-ranked result is relevant, the MRR is high.</p><p><strong>h) Exact Match (EM):</strong> EM measures the percentage of responses that exactly match the reference answer, used in tasks like question answering.</p><p><em>Example:</em> If the question is “Who wrote ‘Pride and Prejudice’?” and the model’s answer is “Jane Austen,” EM checks for an exact match.</p><p>===============================================================</p><h3><strong>Qualitative Methods</strong></h3><p>Qualitative evaluations involve human judgment to assess the nuanced aspects of LLM performance.</p><p><strong>a) Human Evaluation:</strong> Human judges rate the responses based on criteria such as relevance, coherence, and fluency.</p><p><em>Example:</em> In a chatbot application, human evaluators might rate responses on a scale from 1 to 5 based on how natural and relevant the answers are.</p><p><strong>b) Error Analysis:</strong> This involves reviewing the types of errors the model makes to identify common patterns and areas for improvement.</p><p><em>Example:</em> If a translation model frequently mistranslates idiomatic expressions, error analysis helps pinpoint this weakness.</p><p><strong>c) User Feedback:</strong> Collecting feedback from end-users provides insights into real-world performance.</p><p><em>Example:</em> Users of a virtual assistant might report issues like misunderstood commands, guiding developers to improve the model.</p><p>==============================================================</p><h3>Task-Specific Metrics</h3><p>Certain tasks require specialized metrics tailored to their unique demands.</p><p><strong>a) Winograd Schema Challenge:</strong> This evaluates the model’s ability to resolve ambiguous references in text, testing commonsense reasoning.</p><p><em>Example:</em> In the sentence “The trophy doesn’t fit in the suitcase because it is too big,” the model must determine that “it” refers to “the trophy.”</p><p><strong>b) GLUE/SuperGLUE Benchmark:</strong> These benchmarks evaluate models on a variety of natural language understanding tasks, offering a comprehensive assessment.</p><p><em>Example:</em> The GLUE benchmark includes tasks like textual entailment, sentiment analysis, and semantic similarity, providing a broad evaluation.</p><p><strong>c) SQuAD (Stanford Question Answering Dataset):</strong> SQuAD tests reading comprehension by asking questions about a given text and comparing the model’s answers to reference answers.</p><p><em>Example:</em> Given a passage about the Eiffel Tower, the model must answer questions like “When was the Eiffel Tower constructed?” with reference-based accuracy.</p><p>==============================================================</p><h3>Efficiency Metrics</h3><p>Efficiency metrics assess the computational performance of LLMs.</p><p><strong>a) Inference Time:</strong> This measures how quickly the model generates a response.</p><p><em>Example:</em> In real-time applications like voice assistants, lower inference time is crucial for user satisfaction.</p><p><strong>b) Resource Utilization:</strong> Assessing the amount of computational resources (e.g., GPU/CPU, memory) required for inference is important for deployment considerations.</p><p><em>Example:</em> A model that uses less memory and CPU time is more cost-effective to run at scale.</p><p>===============================================================</p><h4>Ethical and Safety Evaluations</h4><p>Ensuring that LLMs adhere to ethical standards and avoid generating harmful content is paramount.</p><p><strong>a) Toxicity and Bias Detection:</strong> Tools like Perspective API can help identify and mitigate biased or toxic outputs.</p><p><em>Example:</em> Screening chatbot responses for hate speech or inappropriate content to ensure safe interactions.</p><p><strong>b) Content Moderation:</strong> Implementing mechanisms to filter out harmful or inappropriate content safeguards users.</p><p><em>Example:</em> A social media platform might use LLMs to flag and remove offensive posts automatically.</p><h3>Example of an Evaluation Process</h3><ol><li><strong>Define the Task:</strong> Specify the task the LLM will perform (e.g., summarization, translation, question answering).</li><li><strong>Select Metrics:</strong> Choose appropriate quantitative and qualitative metrics for the task.</li><li><strong>Collect Data:</strong> Gather a dataset that is representative of the task.</li><li><strong>Evaluate Model:</strong> Run the model on the dataset and compute the selected metrics.</li><li><strong>Analyze Results:</strong> Interpret the results to identify strengths and weaknesses.</li><li><strong>Iterate:</strong> Refine the model based on insights gained from the evaluation and repeat the process.</li></ol><p>Using a combination of these methods provides a comprehensive assessment of LLM performance, ensuring that the model is both effective and reliable in real-world applications.</p><blockquote>Evaluating LLM performance requires a multifaceted approach, combining quantitative and qualitative methods tailored to the specific tasks and applications. By leveraging a combination of metrics, human judgment, and task-specific evaluations, we can gain a comprehensive understanding of LLM capabilities and ensure they are both effective and reliable in real-world applications.</blockquote><p>Thanks!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=381e0becc200" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All about Gauss Markov Theorem for Ordinary Least Squares regression (OLS), BLUE properties of…]]></title>
            <link>https://medium.com/@shubhamsd100/all-about-gauss-markov-theorem-for-ordinary-least-squares-regression-ols-blue-properties-of-e1e1864fe087?source=rss-5e7c20900971------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1e1864fe087</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[econometrics]]></category>
            <category><![CDATA[ordinary-least-square]]></category>
            <dc:creator><![CDATA[Shubham Saxena]]></dc:creator>
            <pubDate>Tue, 07 Mar 2023 23:36:59 GMT</pubDate>
            <atom:updated>2023-03-08T00:12:35.197Z</atom:updated>
            <content:encoded><![CDATA[<h3>All about Gauss Markov Theorem for Ordinary Least Squares regression (OLS), BLUE properties of estimates</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*2WZKfoYI4Fq7E84tT1-LhQ.png" /></figure><blockquote>In this article, I’ll explain the assumptions in Linear Regression and the BLUE properties with their proof. This article will be the pre-requisite for my next article which will be on the violations of the assumptions in Linear Regression.</blockquote><p>Let’s start with the assumptions in the Linear Regression model, which will help to understand the Markov Theorem in a better way.</p><h3><strong>LINE</strong> Assumptions —<strong> L</strong>inear, <strong>I</strong>ndependent, <strong>N</strong>ormal, <strong>E</strong>qual Variance</h3><p><strong>Assumption-1</strong>:</p><p><strong>Linearity</strong>: The relationship between the explanatory variables (independent variables/regressors/predictors) and the target variable (dependent variable/regressand/criterion/response) is LINEAR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*Rg_X8iECaRERiaBA6aG41g.png" /></figure><p>y: Dependent variable</p><p>x: Independent variable</p><p>β: Parameter</p><p>u: error</p><p>Here, the linearity is in terms of the parameter β coefficients, not in the terms of the explanatory variable (x).</p><p>To check this assumption- Plot a scatter plot between x &amp; y</p><p><strong>Assumption-2:</strong></p><p><strong>Independence of errors: </strong>There is no relationship between the residuals and the y variable.</p><p>To check this assumption- Plot a scatter plot between the residuals and the fits (ŷ — output). There should not be any kind of trend or relationship</p><p><strong>Assumption-3:</strong></p><p><strong>Normality of errors:</strong> The errors are normally distributed. The error terms will follow a normal distribution, N~(0,σ²), called Multivariate Normality.</p><p>To check this assumption- Plot a histogram of the error terms. It should look like a normal distribution curve. To know more about the normal distribution, read my article on Medium- <a href="https://medium.com/@shubhamsd100/all-about-the-normal-distribution-curve-66dc71b3a8cb">https://medium.com/@shubhamsd100/all-about-the-normal-distribution-curve-66dc71b3a8cb</a></p><p>Another way to check the normal distribution is to plot a Q-Q Plot (Quantile-Quantile Plot). In this scatter plot, the predicted and the actual values are plotted and If it looks like a straight line, that means there is a normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PO9pt-lEDXh7iNjIpwj4ww.png" /></figure><p><strong>Assumption-4:</strong></p><p><strong>Equal variances: </strong>The error terms have Equal variances. This is also called <em>Homoscedasticity</em>. Here, the variance is equal to σ². This assumption is important to understand. I’ll explain this in detail in my next article on the violations of the assumptions of OLS.</p><p>To check this assumption- Plot a scatter plot between the residuals and the fitted values. If it has a cone shape / fan-out, that means this assumption is VIOLATED. There should not be any trend. The violation of this assumption is called Heteroscedasticity.</p><p><strong>Assumption-5:</strong></p><p>The successive error terms are uncorrelated with each other. That means the Covariance is zero. If this assumption is <em>violated</em>, then it causes <em>Auto-Correlation.</em></p><p><strong>Assumption-6:</strong></p><p>The error term is uncorrelated with the Independent variable.</p><p><strong>Assumption-7:</strong></p><p>The explanatory variables are uncorrelated, this is called “<em>No Multicollinearity”.</em></p><p>These are the key assumptions in the OLS regression.</p><p>now, if these assumptions are met, then according to the Markov Theorem, the OLS estimates are BLUE — Best Linear Unbiased Estimator. Let’s dive deep into this.</p><h3><strong>BLUE Properties</strong></h3><p>To explain this, I’ll refer to my notes to save time.</p><p>First, I’ll prove the Unbiased property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CDvqzhwsr85x3wxKrW3ndA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjDYRd6OP8QqMPvY-GrN2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-zMGJA4i6J9MRJTqkVKCAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bg5L3xHKakLLtIBs7Z0tEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ah3jL5FBm-iW8VL-nwUAZg.png" /></figure><p>Till now, we have understood the Unbiased property.</p><p>Now, we will see the Best Property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kIcEP5qWdWQvjCw-zxN0Lw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JvBt5KdVyyKSqP9stbAe8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ixsavnqDL4cBygapQQbGIg.png" /></figure><p>Now, we have seen the BLUE properties of the estimators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xdcPGEqsV9dBxEha" /><figcaption>Photo by <a href="https://unsplash.com/@mrthetrain?utm_source=medium&amp;utm_medium=referral">Joshua Hoehne</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>I hope you understood the Gauss-Markov theorem.Stay tuned for more such articles. Happy Learning!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1e1864fe087" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How do you get the PDF expression for the Multivariate Normal Distribution Curve?]]></title>
            <link>https://medium.com/@shubhamsd100/how-do-you-get-the-pdf-expression-for-the-multivariate-normal-distribution-curve-3bb1d9552153?source=rss-5e7c20900971------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bb1d9552153</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[gaussian-distribution]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shubham Saxena]]></dc:creator>
            <pubDate>Thu, 12 Jan 2023 21:08:45 GMT</pubDate>
            <atom:updated>2023-01-12T21:08:45.909Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*4_RQu9WENLZ3Hpaw5_pqmQ.png" /></figure><blockquote>In the last article, we have seen the Probability density function derivation for a Univariate Normal distribution. In this article, I’ll try to explain the derivation for the Multivariate Normal Distribution.</blockquote><p>The Multivariate Normal Distribution expression is written as-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*6WK1kPBTXaYM9aA1Kgwfaw.png" /></figure><p>where,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*QW3ruB0sOirjGRjfM9rlsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*7gw4qXeywr1-2P6lkZU-OQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*QBjR49Shsv4SBdvPg-7UFg.png" /></figure><p>if there is no correlation, then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*vZEeRNAwyusUZkFtrG4OFg.png" /></figure><p>Let’s understand the derivation part with the help of notes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*utJ15Kfu0Fwhf8TFSh2UBQ.png" /></figure><p>To derive the expression, we will start with the Bivariate case and then we will analyze the pattern in the expression, and then, generalize it for Multivariate expression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*PD36uKsHpWwryxIbbbsrxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPKEoje4bkx9gN252QP37w.png" /></figure><p>So, till now we have derived the constant part of the expression. A point to note here is that we have assumed that there is no correlation. If there is a correlation, then the variance-covariance matrix will change and thus entire expression will be changed.</p><p>Now, we will see how to derive the exponential term.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0x5Ejro1JelQblaputqCQ.png" /></figure><p>So, that is how we derive the expression for the multivariate normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*6WK1kPBTXaYM9aA1Kgwfaw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ASJPVDTgMzdTk_DA" /><figcaption>Photo by <a href="https://unsplash.com/@mrthetrain?utm_source=medium&amp;utm_medium=referral">Joshua Hoehne</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>I hope you now have a better idea of how to derive the expression for the Multivariate Normal Distribution. Stay tuned for more such articles. Happy Learning!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bb1d9552153" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How do you get the PDF expression for the Normal Distribution Curve?]]></title>
            <link>https://medium.com/@shubhamsd100/how-do-you-get-the-pdf-expression-for-the-normal-distribution-curve-1869a229c96d?source=rss-5e7c20900971------2</link>
            <guid isPermaLink="false">https://medium.com/p/1869a229c96d</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[normal-distribution]]></category>
            <dc:creator><![CDATA[Shubham Saxena]]></dc:creator>
            <pubDate>Sat, 07 Jan 2023 17:44:32 GMT</pubDate>
            <atom:updated>2023-01-12T20:42:53.690Z</atom:updated>
            <content:encoded><![CDATA[<h3>How do you get the PDF expression for the Univariate Normal Distribution Curve?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*tpZqh-x3nPtrW2YrM0GQfg.png" /></figure><blockquote>In this article, I’ll discuss how the Normal Distribution curve density function was formulated. What was the logic behind that? This article may be useful for those who are interested in Research, Data Science, Statistics, and other relevant fields.</blockquote><p>The <em>Normal</em> or <em>Gaussian</em> distribution is possibly the best-known and most-used continuous probability distribution.</p><p>The history of Normal Distribution is quite interesting. It is the most important and widely used distribution in statistics. It is also called “Gaussian Distribution” after the mathematician Karl Friedrich Gauss. Does that mean “Gauss” invented this curve? The answer is NO.</p><p>“Abraham de Moivre” was the first to discover the Normal Distribution Curve.</p><h3>Derivation of the expression for PDF of Normal Distribution</h3><p>The density of the normal distribution (the height for a given value on the xx axis) is given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*7GpXL9ReF6AtBvvHrz7uQg.png" /></figure><p>Have you ever wondered how this “π” and “σ” came to be in this expression?</p><p>Let us try to derive this expression with the help of a dart game.</p><p>Let us assume you throw a dart on the dartboard and your aim is at the origin (0,0). Suppose the darts starts landing in a random position (x,y). Here, we have assumed that large errors are less likely than the small errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*FCUnYM_PnITtUKnfpsNMlQ.png" /></figure><p>We need to find the probability of finding a dart in this shaded area. The area of this region is (dx dy).</p><p>This area is rotationally invariant due to the symmetry. Here, we need to understand that x &amp; y are independent random variables because if x varies in the left or right direction, there is no effect on the distribution in upwards or downwards direction in terms of y.</p><p>As mentioned earlier, the large errors are less likely than small errors. Errors do not depend on the orientation of the coordinate system.</p><p>If we consider radial distance “r”, the probability density function(f) is a function of “r”. So, the probability of landing in the box of size dx and dy is given by,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*bpSIipsrq8j5DRk51ZfNJA.png" /></figure><p>In the same manner, if we consider the probability density function(p) is a function of “x” and “y”, then the probability of landing in the box of size dx and dy is given by,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*VKTUJney_o-SM2RAueY1KQ.png" /></figure><p>Now, we can equate them,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*oqFn9Tgy9ZEoS8L7XyVRsg.png" /></figure><p>Also, polar coodinates can be written as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*Blj4r34zNR8zRgKdeNVMvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*E8lQFtljkFL0P7HJDHc_-Q.png" /></figure><p>Now, we will differentiate the final equation wtrt to angle (theta).</p><p>Now, I’ll try to explain the derivation part with the help of my notes as the derivation involves a lot of calculation part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3MglTHSEBHNlVqZ3jyBjtA.png" /></figure><p>Now, this gives us the basic form of the Normal Distribution as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*Z1Y-bXzPPUhI3cdOUs9XLQ.png" /></figure><p>For “p” to be probability distribution, total area under the curve must be 1. This is because the value of a random variable has to lie somewhere in the sample space. In other words, the probability that the value of a random variable equal to ‘something’ is 1.</p><p>So, we will integrate the above expression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*JwN9GdpgUsb_TV0P4KV_GA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*H-66tGYewJfAZuk_BB0zOQ.png" /></figure><p>Due to the symmetry,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*DgaCj97pZr8NOZOxMiXvSA.png" /></figure><p>Since, x &amp; y are independent, f(x,y) = f(x) x f(y)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*AofwxcKpW5Zl0D3uChbyNA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*JevdFppMxn5nXEGEamOAPg.png" /></figure><p>put x = r cos(theta) and y = r sin(theta)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*oP2oWgeED_zBJpQS1xiSNg.png" /></figure><p>substituting,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*ny1xlv8VZRufJtU3oeVdsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*7y3T7lsZMGCbfkwBNQNQ2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*dIsJD95oc892Ycngux0MjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*f9S-R54CrqDv2SRxzF7www.png" /></figure><p>So now, PDF is equal to,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*cv2TwrnHA1wR2DB4fJ9Oyw.png" /></figure><p>Now, we will try to calculate the value of K.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*thPqRF-thwdfYP8gDjhY_A.png" /></figure><p>So, now we have our final expression for the Probability density Function for a Normal Distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*7GpXL9ReF6AtBvvHrz7uQg.png" /></figure><p>This is the expression for a Univariate Normal Distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IqMTS5gTtjhtMfS9" /><figcaption>Photo by <a href="https://unsplash.com/@mrthetrain?utm_source=medium&amp;utm_medium=referral">Joshua Hoehne</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>I hope you now have a fair idea on how the probability distribution expression is derived for a Normal Distribution Curve. In my next article, I’ll explain the derivation for the Multivariate Normal Distribution. Happy Learning!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1869a229c96d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All about Support Vector Machine SVM, Lagrangian function, KKT conditions, Hinge loss]]></title>
            <link>https://medium.com/@shubhamsd100/all-about-support-vector-machine-svm-lagrangian-function-kkt-conditions-hinge-loss-ad21d19a35bf?source=rss-5e7c20900971------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad21d19a35bf</guid>
            <category><![CDATA[kernel-trick]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[support-vector-machine]]></category>
            <category><![CDATA[loss-function]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Shubham Saxena]]></dc:creator>
            <pubDate>Thu, 05 Jan 2023 06:38:58 GMT</pubDate>
            <atom:updated>2023-01-05T06:38:58.368Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*Vg9icE4b6BVKIC7-66LI3A.png" /></figure><blockquote>In this article, I’ll explain all the concepts of Support Vector Machine, SVM, Hinge Loss, Soft Margin SVM, Harg Margin SVM, Lagrangian Optimization, KKT Conditions, Kernel trick, linear and non-linear data. This article is going to be very comprehensive.</blockquote><p>Support Vector Machine is essential when it comes to Machine Learning. It involves a lot of concepts that need to be understood before its actual implementation on a real dataset. I’ll try my best to explain each point but if you have any doubts, let me know.</p><h3>What is SVM?</h3><p>An SVM is a supervised machine learning algorithm for classification, regression, and outlier detection. It can be used for Linear and Non-Linear data.</p><p>It is a generalization of a simple classifier called the Maximal Margin Classifier. But this classifier can be applied to most datasets since it required a linear boundary to separate the classes.</p><p>Then we have a Support Vector Classifier which can be applied in a broader range of cases.</p><p>Now to handle Non-Linear data, we have Support Vector Machines (SVM).</p><p>SVMs can be used for binary classification as well as multiclass classification.</p><h3>What are Linear and Non-Linear Data?</h3><p>As I have said that I’ll try to explain each concept in detail, so let’s find out what is linear and non-linear data.</p><p>Linear Data can be represented on a line graph. In this data, there is a clear relationship present between the variables.</p><p>Non-Linear Data can not be represented on a line graph. This is because there is no clear relationship between the variables and the graph will be curved.</p><h3>What is a Hyperplane?</h3><p>A hyperplane is a FLAT, AFFINE subspace of dimension “d-1” in a “d” dimensional space. For example, in two dimensions, a hyperplane is a flat one-dimensional subspace (basically a line). In three dimensions, a hyperplane is a flat two-dimensional subspace (basically a plane).</p><p>Affine means that the subspace doesn’t necessarily pass through the origin.</p><h3>Equation of a Hyperplane</h3><p>I’ll try to explain this with my self-made notes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*tpGfEiualPkqIs4TZeS2Gw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*gg_k2XKdszCh4bIFO6-BMw.png" /></figure><h3>Maximum Margin Classifier</h3><p>It is also known as Optimal Separating Hyperplane. If our data can be perfectly separated using a hyperplane, then there exists an infinite number of hyperplanes. So, in order to decide the optimal hyperplane, we can take the perpendicular distance from the observations and pick the smallest such distance which we can call a Margin.</p><p>This can cause trouble called “Overfitting” when the dimension is large. Overfitting refers to low bias and high variance.</p><p>Also, for non-separable cases, it won’t work.</p><p>In order to have a hyperplane that can almost separate the classes, we can use a soft margin. The generalization of the maximal margin classifier is called a Support Vector Classifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*FnrhCBqB_OgKfPaLz3jzjg.png" /></figure><h3>Support Vector Classifier</h3><p>It is also called Soft Margin Classifier. It ensures that every observation is not only on the correct side of the hyperplane but also on the correct side of the margin. Here we allow some observations to be on the wrong side of the margin.</p><p>Let us understand what is this Margin, Support Vector, and Hyperplane with the help of an image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpBR9RrCBeEe6JQjIvihaw.png" /></figure><p>But what about non-linear boundaries? How to deal with non-linear datasets?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*eshTa_RswtjRWvqTOtTxSg.png" /></figure><h3>Support Vector Machine</h3><p>Well, to deal with the above issue, we have Support Vector Machine For doing this, we use Kernels. We use kernels just to reduce the computational time required for transforming our data into a higher dimension. We will discuss all of these.</p><p>First, let us understand what SVM does.</p><p>SVM tries to find the widest possible margin between the dataset points of the classes. SVM uses techniques like Gradient Descent (Projected Gradient Descent), Quadratic Programming, Lagrangian Optimization, and other algorithms.</p><h3>Hard Margin SVM</h3><p>It is used for Linear Separable data only. Here there is no scope for misclassification. We can NOT have one category of class towards the other side of the hyperplane or not even between the hyperplane and margin planes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*z5Vr4mWmDnBjXIuIMh43LQ.png" /></figure><p>We will consider two classes as +1, -1 which is equal to Yi output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*zwGVOsK0B7XviWEC7-zlYw.png" /></figure><p>This constraint will satisfy both classes.</p><p>For the Positive class, Positive number * Positive Number = Positive</p><p>For the Negative class, Negative number * Negative Number = Positive</p><p>Now, how this “d” value is derived? I’ll try to explain this with my self-made notes.</p><p>Try to understand this important concept of vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NB1Sgw0tI_0WCpZ22Hx4ng.png" /></figure><p>What if we have outliers? What if the data is NOT linearly separable? Well, in that case, we have Soft Margin SVM.</p><h3>Soft Margin SVM</h3><p>Here, we will include a regularization term and a loss. We can accept a few misclassified datasets in the Soft Margin SVM. Let me explain through a diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*bZ4aZEXyzBtM6gOJ0LfnlQ.png" /><figcaption>More margin, More misclassified</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*_f1ieZ2bzUyvwMEpLc6Orw.png" /><figcaption>Less Margin, Less Misclassified</figcaption></figure><p>So, you have clearly observed that there is a trade-off involved here. Which one to choose? So, we have to define a loss function so that we can do the optimization.</p><p>Let us understand the Objective function for Soft Margin SVM through my self-made notes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WI0c46_L2joCG-heoqZR8A.png" /></figure><p>Here, C is a hyperparameter. As we can clearly see that we have two terms in front of us — Margin Error + Classification Error.</p><p>So, if we increase the value of “C”, more weightage is given to the second term i.e the Classification error. So, in this case, our Margin will be reduced. This is not recommended as Generalization is not proper in case we have less margin.</p><p>Now, if we decrease the value of “C”, our Margin will be more i.e margin error will be less.</p><p>The value of “C” can be determined by hyperparameter tuning using Grid Search CV.</p><h3>What is Hinge Loss?</h3><p>In hinge loss, we will identify a line that minimizes the loss. It is specifically created for training classifiers such as SVM.</p><p>We have many other types of loss functions. I will discuss them later in some other article.</p><p>Let’s discuss the hinge loss with the help of this image.</p><h3>Positive Classifier Hinge Loss</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R_Pt1uMk_9LFmgK-PeIu8g.png" /></figure><h3>Negative Classifier Hinge Loss</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*En5SxtftYs_vg2rNfM_WSQ.png" /></figure><h3>Lagrangian Optimization and KKT Conditions</h3><p>It is a little conceptual. Let me know if you want a detailed article on this.</p><p>Let me explain this with the help of my notes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q7qqsP0frEQWNMS63RxsBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_k6Lcy7mOedOhNID_WLSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*4LN5oPszDcdgH5tPvaUi_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7dKiPidvy8Z3ZqfA3YW7ww.png" /></figure><h3>SVM for Multiclass Classification</h3><p>There are two ways to do this —</p><p><strong>1.One vs One Classification </strong>→ one-vs-one splits a multi-class classification dataset into binary classification problems.For example, consider a multi-class classification problem with four classes: ‘<em>red</em>,’ ‘<em>pink</em>,’ and ‘<em>green</em>,’ ‘<em>yellow</em>.’ This could be divided into six binary classification datasets as follows:</p><p>Binary Classification Problem 1: red vs. <em>pink</em></p><p>Binary Classification Problem 2: red vs. green</p><p>Binary Classification Problem 3: red vs. yellow</p><p>Binary Classification Problem 4: <em>pink</em>vs. green</p><p>Binary Classification Problem 5: <em>pink</em>vs. yellow</p><p>Binary Classification Problem 6: green vs. yellow</p><p><strong>2. One vs All Classification → </strong>t involves splitting the multi-class dataset into multiple binary classification problems. A binary classifier is then trained on each binary classification problem and predictions are made using the model that is the most confident.</p><p>For example, given a multi-class classification problem with examples for each class ‘<em>red</em>,’ ‘<em>pink</em>,’ and ‘<em>green</em>‘. This could be divided into three binary classification datasets as follows:</p><p>Binary Classification Problem 1: red vs [<em>pink</em>, green]</p><p>Binary Classification Problem 2: blue vs [red, green]</p><p>Binary Classification Problem 3: green vs [red, <em>pink</em>]</p><h3>SVM Regression</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1UrTBizYXz8ax3ycXWlhA.png" /></figure><h3>Feature Scaling effect on SVM</h3><p>SVMs are sensitive to feature scaling. Let me explain this with the help of an image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m8W5LjjLdPJn_p-xzd6EfA.png" /></figure><p>SVMs are particularly suited for classification of complex but small or medium-sized datasets. As, In enormous datasets, computational complexity is high and there is no clear separation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z9qgk1nKZ-dZYsUC" /><figcaption>Photo by <a href="https://unsplash.com/@mrthetrain?utm_source=medium&amp;utm_medium=referral">Joshua Hoehne</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>I hope you really enjoyed reading this article. Follow me for more such content. Happy Learning!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad21d19a35bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is a Binomial, Negative-Binomial, and Multinomial Distribution?]]></title>
            <link>https://medium.com/@shubhamsd100/what-is-a-binomial-negative-binomial-and-multinomial-distribution-108bc1bdc8a0?source=rss-5e7c20900971------2</link>
            <guid isPermaLink="false">https://medium.com/p/108bc1bdc8a0</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[binomial-distribution]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Shubham Saxena]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 15:09:17 GMT</pubDate>
            <atom:updated>2023-01-03T15:09:17.856Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*88UgPy0Zhy8XPIkCGa2YGw.png" /></figure><blockquote>In this article, I’ll discuss Binomial Distribution, Negative-Binomial Distribution, and Multinomial Distribution. This article may be useful for those who are interested in Data Science, Data Analysis, Statistics, research, and other relevant fields.</blockquote><p>Let’s begin with Binomial Distribution and then we will discuss Multinomial and then Negative Binomial Distribution. We will also try to analyze the generalization of Geometric Distribution.</p><h3>What is Binomial Distribution?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TJYMJa8Oj9ShRpQK" /><figcaption>Photo by <a href="https://unsplash.com/@edge2edgemedia?utm_source=medium&amp;utm_medium=referral">Edge2Edge Media</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It is a discrete probability distribution. It has only two possible outcomes in an experiment — Success or Failure. Here, there is no concept of partial success.</p><p>Before we go ahead, let’s discuss what are Binomial Random Variables.</p><p>A Binomial Random Variable is a finite number obtained in each independent trial and in each trial, we have a Success or a Failure. A key point to note here is that the probability of success in each trial is constant and there is a fixed number of trials. For such a variable, the Probability Mass Function (PMF) is defined as,</p><p>X~B(n,p)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*QCxj7lXqb9-SHpVQy_d4KA.png" /></figure><p>where,</p><p>n: number of trials</p><p>x: number of successes after n trials</p><p>p: the probability of success</p><p>It has a similar kind of curve as of normal distribution curve.</p><h3>Mean of Binomial Distribution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*pcZohfh2JEyS0TXqBc00_Q.png" /></figure><h3>Variance of Binomial Distribution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*NKV3uXKcpbLqxwNRIYk-wA.png" /></figure><p>Now, there is one important point in Binomial Distribution. The curve first increases monotonically and then decreases monotonically. So, in between, we have a maximum value. Now, we will calculate the maximum values.</p><p>Let the maximum value be at X=K, then,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*gBKzBc1hWyw3wyUy0jFeGA.png" /></figure><p>Let us also see at X=K-1,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*V0q3BklSfyyiYUIEP8DbuQ.png" /></figure><p>Then the ratio of probability at X= K and X = ‘K-1’ will be greater than 1 or less than 1.</p><p>Consider the ratio is greater than 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*UT3xVnFbQ6AxBKQs16YVEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*zGoH8SnU2gBZmGMG9AdQQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*pT4TqOpFFlHurSqQcB0NIA.png" /></figure><p>This is the maximum value of K for a Binomial Distribution.</p><h3>Multinomial Distribution</h3><p>It is used to find out the probabilities in experiments where there are more than two outcomes. For example, if we roll a die 7 times, there are 6 possibilities = {1,2,3,4,5,6}</p><p>But if we want to see how many times we got 2, then it will be called a Binomial Distribution with success = {2} and Failure = {1,3,4,5,6}</p><p>I hope this example was good enough to have an understanding of this.</p><p>Let’s see the PMF for this distribution,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N0ZdJ79CPrrbl0khpOLBDQ.png" /></figure><p>n: number of events</p><p>n1: number of outcomes for event 1</p><p>n2: number of outcomes for event 2</p><p>nx: number of outcomes for event x</p><p>P1: Probability that event 1 happens</p><p>P2: Probability that event 2 happens</p><p>Px: Probability that event x happens</p><p>The mean of this distribution is given by,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*6zijtFAJ0y8guTaPH2ce1g.png" /></figure><p>Variance,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*dtOV0gFtx2MfGhyseZVXqQ.png" /></figure><h3>Negative Binomial Distribution</h3><p>This type of distribution is also called Pascal Distribution.</p><p>It is a type of discrete distribution that is applicable when we need to do an experiment until a total of ‘r’ successes are obtained. The trials are independent here and the probability is constant in each trial.</p><p>r: number of successes in x trials</p><p>This implies that (r-1) success should happen for (x-1) trials!</p><p>So, with this understanding, we can easily determine the PMF for this distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*VcEShGeCtdmpejUNROuVoQ.png" /></figure><p>the first term is for (r-1) successes and the second term is for ‘r’ success</p><p>x = r,r+1,r+2……………</p><p>Mean = r / p</p><p>Variance = rq / p²</p><p>We can also say that the Negative binomial is a generalization of Geometric Distribution.</p><p>If we put r = 1, then it is a case of Geometric Distribution.</p><p>here we perform an experiment till we obtain the first success.</p><p>For a Geometric Distribution, PMF is defined as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*qBtTodqBBZ0TYY3W5WsMNg.png" /></figure><h3>What is the significance of Negative in a Negative Binomial distribution?</h3><p>To understand this,</p><p>we have a Binomial expression as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*Qm2jlcjHqEnzD86NF8NVFg.png" /></figure><p>We can write the binomial expansion for the above expression as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*br2lhqVr75sAE7W0YS2kLg.png" /></figure><p>and if we see the expression of Negative Binomial distribution,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*V0aOLOuPGkU0jvc92Q36Nw.png" /></figure><p>The expansion for this is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*MXYI6Xtauie7Y4vUdkvVnA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*oZ6TKjPunMRKVdCJfJs_9g.png" /></figure><p>Here we can see the Negative exponent → ‘-r’</p><p>Due to this reason, it is called a Negative Binomial distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZEKBUsYEQNOG3ELC" /><figcaption>Photo by <a href="https://unsplash.com/@mrthetrain?utm_source=medium&amp;utm_medium=referral">Joshua Hoehne</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>I hope you enjoyed reading this article. Let me know if you need articles on other topics as well. Happy learning!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=108bc1bdc8a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>