<?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 Orbin Sunny on Medium]]></title>
        <description><![CDATA[Stories by Orbin Sunny on Medium]]></description>
        <link>https://medium.com/@orbinsunny?source=rss-8d6c0d0cb381------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aQCbJYXhxQ1jnHPHUALUCg.png</url>
            <title>Stories by Orbin Sunny on Medium</title>
            <link>https://medium.com/@orbinsunny?source=rss-8d6c0d0cb381------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:38:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@orbinsunny/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[CI/CD for Machine Learning: An End-to-End Guide on GitHub Actions.]]></title>
            <link>https://medium.com/@orbinsunny/ci-cd-for-machine-learning-an-end-to-end-guide-on-github-actions-4c4b95df4025?source=rss-8d6c0d0cb381------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c4b95df4025</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[continous-deployment]]></category>
            <category><![CDATA[prometheus]]></category>
            <dc:creator><![CDATA[Orbin Sunny]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 06:18:29 GMT</pubDate>
            <atom:updated>2026-02-18T06:18:29.282Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello fellow ML practitioners,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RM11UEJK8CKgWZAxnCb1kQ.png" /></figure><p>Let me disclose some truths first: GitHub Actions is not an industry-standard way to learn CI/CD for Machine Learning. There are so many other integrated tools for this, but as learners, it will be beneficial to know how GitHub is used in developing an ML project. Major use cases will come if the project is in opensource. So we are looking at this blog from the point of view of an ML Developer who is beginning to understand working with GitHub Actions, not ML CI/CD with MLOPs.</p><h3>Introduction</h3><p>The normal software lifecycle includes writing source code and maintaining the new changes using Git versioning. The major focus is on the code changes and dependency management. The ML lifecycle is different because there are many variables that determines the business propositions. The traditional software breaks when the code is wrong, but an ML cycle could break if any of the code, data or model changes its behaviour. So maintaining consistency is difficult in ML. Major differences include:</p><ul><li><strong>Degradation:</strong> Unlike syntactical or dependency issues, the model degrades because of something called Data Drift; the data it sees in the real world no longer matches the data it learned from.</li><li><strong>Thresholds:</strong> Tests are statistical rather than binary tests. The model must maintain certain accuracy or other measures to pass the tests.</li><li><strong>Artifacts:</strong> Instead of just a compiled version of the source code, MLOPs need to store massive files like weights, serialised objects, and datasets.</li><li><strong>Computation:</strong> Traditional software have CPU intensive tasks and usually has quick builds, but ML have GPU/TPU-intensive tasks, which could take weeks to build and are expensive to manage.</li></ul><p>The main objectives of using a CI/CD pipeline are to solve problems like the “It worked on my laptop” problem, where the developers building the model, testers testing the models and deployers deploying the model to production should get consistent results with the lifecycle. The next problem is never deploying the model on the last date and being unsure what is happening. The team should be 100% sure about the outcomes that they are going to get. The third problem is that reworking the existing model should not create amnesia, because the team didn’t save the artifacts properly to revisit past changes.</p><h4><strong>CI/CD Lifecycle for Machine Learning</strong></h4><ol><li><strong>Continuous Integration (CI): </strong>It took care of the code integration part while building new features or fixing errors. In software, CI is about making sure the code is passing linting or rigorous programming testing. In ML, the CI should look at schema validation, checking null values, and testing feature engineering script runs.</li><li><strong>Continuous Delivery(CD):</strong> This can be seen as a staging area before deployment. Before making the project production-ready, it will be again quality tested in an environment which mimics a production setup. So here the model will be live so the developers can send APIs to measure the quality of the output, monitor latency and other traffic-related things.</li><li><strong>Continuous Deployment(CD):</strong> From here, the model is automatically released to production to get a response from real users. There are several ways to do this, and we will discuss them later.</li><li><strong>Continuous Training(CT):</strong> This phase is only for ML workflows, for automatically retraining the model whenever new data arrives or performance drops.</li></ol><h3>Setting Up CI/CD Pipelines (GitHub Actions)</h3><h4>Pipeline Basics in GitHub Actions:</h4><p>Setting up the pipeline in a Git Initialized repo is done using a .yml file inside .github/workflows/. There are mainly three things that you should be aware of before building this workflow file.</p><ul><li><strong>Triggers:</strong> This is lines written after aon keyword to tell GitHub when to run the pipeline. Main triggers are push (runs when new code is pushed), pull_request (runs when a code is merged), and schedule (runs on a timer).</li><li><strong>Jobs: </strong>The jobs is a high level task like build-and-test or build-and-deploy, which run in parallel by default.</li><li><strong>Steps</strong>: These are specific commands to install dependencies or run Python files, which are run sequentially.</li></ul><h4>Set up for ML</h4><p>When you set up GitHub Actions for ML models, there are changes that are specific to ML. It will have its own trigger settings, like when there is new data to train arrives, or the monitoring detects performance degradation. The setup should be careful about reproducibility, like global seeds for initialisation or snapshotting everything inside the environment or using Docker containers, which makes it work on any server.</p><p>For testing, there should be automated testing gates that each build should pass, such as performance thresholds (up to some level of accuracy), slice-based evaluation (performance on specific groups to prevent bias), statistical test (check the distribution of predictions to detect unusual changes from previous checks), and latency checks (to check the inference time).</p><h4>Deployment Patterns</h4><ul><li><strong>Blue-Green Deployment:</strong> You will have two identical environments running old (Blue) and New (Green) models. You can switch them instantly when there is an issue.</li><li><strong>Canary Deployment:</strong> The new model is rolled out to a subset of users to collect feedback and gradually increase to complete rollout if the metrics look good.</li><li><strong>Shadow Deployment:</strong> The new model gets the production traffic in parallel with the old model, but its prediction is tracked by the team and make sure of the behaviours to replace the new one with the current one.</li><li><strong>A/B Testing:</strong> Route two models with two different user groups to clearly measure different business metrics.</li></ul><p>If you wish to practice what you have learned, I will provide a project that I have done:</p><p><a href="https://github.com/orbin123/boston-housing-githubactions">GitHub - orbin123/boston-housing-githubactions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c4b95df4025" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Deployment — AWS, GCP, Azure]]></title>
            <link>https://medium.com/@orbinsunny/model-deployment-aws-gcp-azure-5dac82a0b392?source=rss-8d6c0d0cb381------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dac82a0b392</guid>
            <category><![CDATA[amazon-sagemaker]]></category>
            <category><![CDATA[microsoft-azure]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[ml-deployment]]></category>
            <dc:creator><![CDATA[Orbin Sunny]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 10:23:14 GMT</pubDate>
            <atom:updated>2026-02-05T10:23:14.332Z</atom:updated>
            <content:encoded><![CDATA[<h3>Model Deployment — AWS, GCP, Azure</h3><p>Hello ML practitioners,</p><p>This blog is all about cloud engines that provide full-scale deployment for Machine Learning Models. If you have no experience in cloud engineering, no problem. We will be starting from cloud introduction (if you are not equipped with enough cloud knowledge, this blog will be difficult for you) to how you can deploy models inside popular options like AWS, GCP and Azure. So let’s get started.</p><p>The Cloud refers to a global network of remote servers that can be accessed using the internet, allowing users to store, manage and process data on high demand rather than on their local machine. Choosing a Cloud infrastructure depends on custom requirements, which balance control, scalability and maintenance.</p><h4>1. On-Premises (Private Infra)</h4><p>In an on-premises setup, the organisation owns and manages the physical hardware, networking and virtualisation layers within its own data centre. This provides full control with maximum hardware optimisation. These are best for highly sensitive, law-restricted government projects or legacy systems projects having unique hardware configurations.</p><h4>2. Infrastructure as a Service (IaaS)</h4><p>IaaS provides virtualised computing resources over the internet. You ‘rent’ the hardware (CPUs, GPUs, RAM) but manage the operating system, middleware, runtime, data and applications. The physical servers, hard drives, networking capabilities and virtualisation are provided by the organisation. Thus, it is highly customisable, and you get all the control over your environment.</p><h4>3. Platform as a Service (PaaS)</h4><p>PaaS provides an extensive platform in the cloud where users can build, test, and deploy applications without worrying about the underlying infrastructure. You only need to manage the application code and data; the rest, like OS, hardware, server maintenance, scaling and the runtime, will be handled by the provider. It is ideal for rapid development and deployment. Examples include Google App Engine, AWS SageMaker, Heroku, and Azure App Service.</p><h3>AWS SageMaker</h3><p>Amazon Sagemaker is a full toolkit for managing ML workflow completely, which provides every tool for building, training, and deploying Machine Learning models. SageMaker is an integrated workflow that stitches together Jupyter Notebook, training infrastructure and deployment cycle under one roof.</p><h4>SageMaker Architecture and Core Components</h4><p>SageMaker comprises SageMaker Studio, SageMaker Notebook, Model Registry and Training infrastructure. <strong>SageMaker Studio</strong> is the development environment that gives studio notebooks that can have GPUs, large memory or multiple CPUs attached to it depending on the demand. It also provides visual tools for building ML pipelines, tracking experiments, and managing models, all in one interface, while handling authentication, storage, persistence, and collaboration.</p><p><strong>SageMaker Notebooks</strong> are pre-configured with popular ML frameworks like Tensorflow, Pytorch and scikit-learn. These are also integrated with Git for version control. When you submit your training job, the SageMaker provisions compute resources, runs your script, saves the model artefact to an S3 bucket, and shutsdown the training when it is unnecessary. SageMaker offers optimised implementation of common algorithms like XGBoost, Linear Regression, K-Means, and Image Classification. It also gives you the feature to package your training code inside a Docker container and run it on SageMaker. For storage and security, the normal cloud services like S3 buckets and IAM role is adhere.</p><p><strong>Model Registry</strong> in SageMaker is like Git for ML models. Once trained, your model will be registered; this controls the versions of each model. Then, in the deployment part, there are several ways to do this. Firstly, you can wrap the model on a <strong>realtime endpoints</strong> and send data to the endpoint, it runs the inference and returns the result. Secondly, for cases where you have a large batch of data and do not need results immediately, you can do <strong>Batch Transform</strong>. Thirdly, you can use a <strong>Serverless Inference</strong> where the endpoint will scale dynamically to the frequency of the traffic. <strong>Asynchronous Inference</strong> is another way to host when each request takes a varying time to process.</p><h3>Google Cloud Vertex AI</h3><p>Vertex AI is Google Cloud’s unified ML platform. Vertex AI also bring notebooks, training, prediction and pipelines under one roof. It is a modern and cleaner interface than AWS, though the trade-off is a smaller community and fewer third-party resources.</p><h4>Vertex AI Architecture</h4><p>Similar to SageMaker, <strong>Vertex AI Workbench</strong> manages Jupyter notebooks in the cloud. These environment comes with pre-built ML frameworks and GPU or TPU instance support. Training works the same as Sagemaker, where you submit a training job, and the setup handles the rest. Vertex AI provides pre-built containers for TensorFlow, Pytorch, scikit-learn and XGBoost workflows, so the container handles dependencies. You can also bring your own custom containers.</p><p>Vertex AI gives real-time and batch-transform predictions as SageMaker does. A notable feature is traffic splitting between the multiple model versions. Pipelines in Vertex AI are handled by an open-source ML pipeline framework called <strong>Kubeflow</strong>. The advantage being portable to any Kubernetes clusters other than GCP. Another crucial feature is the <strong>Vertex AI Feature Store</strong>, which is a managed service that supports point-in-time lookups, meaning you can retrieve what the feature values were at a specific past timestamp. It helps to accurately reflect the state and train without data leakage.</p><p>For data management in GCP, there are S3 equivalent service called <strong>Google Cloud Storage (GCS)</strong>. GCP also provides features like <strong>BigQuery ML</strong> Integration and <strong>Dataflow</strong> for preprocessing, which makes the life of an ML Developer easy in the cloud. If you need a strong baseline model quickly, you can usethe <strong>AutoML</strong> feature, which automatically selects the best model architecture, tunes hyperparameters, and handles feature engineering. Another standout capability of GCP is the use of <strong>TPU (Tensor Processing Unit)</strong>, which are purpose-built to run large matrix operations for Large deep learning models. <strong>Vertex AI Vizier</strong> is Google’s hyperparameter optimisation service. It uses advanced algorithms to efficiently search the hyperparameter space.</p><h3>Microsoft Azure Machine Learning</h3><p><strong>Azure ML</strong> is a comprehensive ML platform. It distinguishes itself from AWS and GCP as the most accessible interface for even non-expert users, with the strongest AutoML capabilities, and deep integration with microsoft ecosystem, such as Office 365 or Power BI, etc.</p><h4>Azure ML Architecture</h4><p>Azure has an organised <strong>ML workspace</strong>. It acts as a project folder containing all your ML resources. It also makes collaboration easier. The <strong>Azure ML Studio</strong> provides a web-based interface for creating notebooks with a drag-and-drop interface, namely the <strong>Designer,</strong> for building an ML pipeline visually. <strong>Automated ML</strong> assistance takes your data, tries hundreds of model-algorithm combinations, and returns the best-performing model. And there is a registry for managing your data with versioning and transformation tracking inside <strong>Datasets</strong>. For full control, you can also write your own training script. Azure supports managing Docker containers, <strong>Azure Container Instances (ACI),</strong> or Kubernetes clusters, <strong>Azure Kubernetes Service (AKS) </strong>when deploying.</p><p>In conclusion, if you want to become a all round developer, even an ML engineer, you need good cloud skills because in the real world, development is just 20% of the work rest is in the deployment. So, make sure that you will host your projects using any of the above platforms to showcase your ability to adapt to a deployment environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dac82a0b392" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Deployment — Flask, Django and Docker]]></title>
            <link>https://medium.com/@orbinsunny/model-deployment-flask-django-and-docker-bbc8f42a3821?source=rss-8d6c0d0cb381------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbc8f42a3821</guid>
            <category><![CDATA[flask-app]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[ml-model-deployment]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Orbin Sunny]]></dc:creator>
            <pubDate>Tue, 27 Jan 2026 08:20:58 GMT</pubDate>
            <atom:updated>2026-01-27T09:39:03.700Z</atom:updated>
            <content:encoded><![CDATA[<h3>Model Deployment — Flask, Django and Docker</h3><p>Hello fellow ML practitioners,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q_iO00e4C4e64POXYasu_Q.png" /></figure><h3>Introduction to Model Deployment</h3><p>The deployment of any software product is the most crucial stage of any development cycle. The feedback from deploying could determine the value of the entire system. This is also true for machine learning. The moment a model trained on an experimental setup starts inferring the real-world data, we realise how the model actually performs. The model should be fully consistent and packaged to deal with every edge case scenario that could come up in a production setup. This is why knowing the deployment tools and implications is necessary for the overall growth of a machine learning engineer.</p><p>There are common ML deployment architectures, which are batch inference and real-time inference. Batch inference is used when you want an analysis or report on large-scale data, like calculating the credit score of every bank customer at the end of a month at once. Real-time inference is used in low latency situation with a few samples to handle, like getting other product recommendations when purchasing one product.</p><p>The major deployment strategies include REST API, where you wrap a model inside a web server (like Flask or Django) and create endpoints to communicate with the model in a live environment. Another way is to run on an IoT device or a mobile phone locally or embedded via edge computing.</p><h3>Saving and Loading Models</h3><p>The main idea of saving a model is to have persistence while doing ML workflows. We know that training is a tedious task and also requires fine-tuning and reproducing the model even after training, so it is best to save the model instead of retraining. Saving creates an artefact of the model that stores weights and parameters (even additional info). Some models save only the parameters, but others store both parameters and the entire architecture.</p><h4>Pickle vs Joblib</h4><ul><li><strong>Pickle:</strong> It is a standard Python library for serialising generic objects in Python. It’s versatile but not suitable for large data.</li><li><strong>Joblib: </strong>A replacement for pickle which is specialized in dealing with Numpy arrays. It is significantly faster and more memory-efficient for ML data flow.</li></ul><h4>H5 vs Keras vs TF SavedModel</h4><p>Deep learning models are more complicated than simple ML algorithms.</p><ul><li><strong>H5(.h5):</strong> A legacy format that stores model weights and architecture in one file.</li><li><strong>Keras(.keras):</strong> This format is recommended for Keras users. It makes an archive file containing configuration, weights and training metadata. It uses a name-based serialisation technique, which makes it great for debugging. It can also be shared with different backends like JAX or PyTorch.</li><li><strong>TF SavedModel:</strong> If you trained a DL model and saved it using <em>model.save,</em> it will create a SavedModel directory which captures the full execution graph. This means that it can be loaded and executed in environments without the original Python code(e.g., C++, TensorFlow Serving, Go). The caveat being it is making it difficult to debug the low-level code.</li></ul><pre># Using Pickle<br>import pickle<br><br>## Save<br>with open(&#39;model.pkl&#39;, &#39;wb&#39;) as f:<br>  pickle.dump(model, f)<br><br>## Load <br>with open(&#39;model.pkl&#39;, &#39;rb&#39;) as f:<br>  loaded_model = pickle.load(f)<br><br># Using Joblib<br>import joblib <br><br>## Save<br>joblib.dump(model, &#39;model.joblib&#39;)<br><br>## Load<br>loaded_model = joblib.load(&#39;model.joblib&#39;)<br><br># Using H5<br>import tensorflow as tf<br><br>## Save<br>model.save(&#39;my_model.h5&#39;)<br><br>## Load<br>loaded_model = tf.keras.models.load_model(&#39;my_model.h5&#39;)<br><br># Using Native Keras<br><br>## Save <br>model.save(&#39;my_model.keras&#39;)<br><br>## Load <br>loaded_model = tf.keras.models.load_model(&#39;my_model.keras&#39;)<br><br># Using TF SavedModel (No extension)<br><br>## Save<br>model.save(&#39;my_model_directory&#39;) # NOTE: provide a folder path not filename<br><br>## Load<br>loaded_model = tf.keras.models.load_model(&#39;my_model_directory&#39;)</pre><pre># Open a folder and follow the code along<br># Folder Structure of the entire setup<br><br>ml-deployment/<br>├── model.joblib                # (Generated in Step 1)<br>├── train_model.py              # Step 1: Training Script<br>│<br>├── flask_app.py                # Step 2: Flask App<br>├── requirements-flask.txt      # Step 4: Flask Dependencies<br>├── Dockerfile.flask            # Step 4: Flask Image<br>│<br>├── django_ml_api/              # Step 3: Django Project Folder<br>│   ├── manage.py<br>│   ├── django_ml_api/          # Project Config<br>│   │   ├── settings.py<br>│   │   ├── urls.py<br>│   │   └── wsgi.py<br>│   └── predictor/              # App Logic<br>│       ├── views.py<br>│       └── urls.py<br>├── requirements-django.txt     # Step 4: Django Dependencies<br>├── Dockerfile.django           # Step 4: Django Image<br>│<br>└── docker-compose.yml          # Step 5: Orchestration</pre><pre>import joblib <br>from sklearn.datasets import load_iris<br>from sklearn.model_selection import train_test_split <br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import accuracy_score, classification_report<br><br>def train_and_save_model():<br>    iris = load_iris()<br>    X = iris.data <br>    y = iris.target<br><br>    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y)<br><br>    model = RandomForestClassifier(<br>        n_estimators=100,<br>        max_depth=5<br>    )<br><br>    model.fit(X_train, y_train)<br><br>    y_pred = model.predict(X_test)<br>    acc_score = accuracy_score(y_test, y_pred)<br><br>    print(&#39;Acc&#39;, acc_score)<br>    print(classification_report(y_test, y_pred, target_names=iris.target_names))<br><br>    model_filename=&#39;model.joblib&#39;<br>    joblib.dump(model, model_filename)<br><br>    print(&#39;File size:&#39;, joblib.load(model_filename).__sizeof__())<br><br>    return model_filename<br><br>if __name__ == &#39;__main__&#39;:<br>    train_and_save_model()</pre><h3>Flask for API Development</h3><p>Flask is a Python-based micro-frame which is not like a heavy-frame work like django where there are built-in databases or admin-panel but the bare essentials to handle HTTP requests, making it a fast to deploy and containerisable option. It has a built-in server and is single-threaded (which means it only handles one thread at a time to complete the request task).</p><p>In the case of model deployment, Flask is a much simpler and faster option because the web itself is just a wrapper for the models to provide routing and JSON handling. The Flask provides a framework which is unbloated without a complex template engine.</p><pre>from flask import Flask, request, jsonify <br>import joblib <br>import numpy as np <br><br><br>model = joblib.load(&#39;model.joblib&#39;)<br><br>class_names = [&#39;setosa&#39;, &#39;versicolor&#39;, &#39;virginica&#39;]<br><br>app = Flask(__name__)<br><br>@app.route(&#39;/&#39;, methods=[&#39;GET&#39;])<br>def health_check():<br>    return jsonify({<br>        &#39;service&#39;: &quot;Flask ML Inference&quot;,<br>        &#39;status&#39;: &#39;running&#39;,<br>        &#39;model_loaded&#39;: True,<br>        &#39;endpoints&#39;: {<br>            &#39;predict&#39;:&#39;/predict&#39;,<br>            &#39;health&#39;: &#39;/&#39;<br>        }<br>    })<br><br>@app.route(&#39;/predict&#39;, methods=[&#39;POST&#39;])<br>def predict():<br>    data = request.get_json()<br><br>    features = data.get(&#39;features&#39;)<br><br>    features_array = np.array(features).reshape(1, -1)<br><br>    prediction = model.predict(features_array)[0]<br><br>    probabilities = model.predict_proba(features_array)[0]<br><br>    confidence = float(probabilities[prediction])<br><br>    print(class_names[prediction])<br><br>    return jsonify({<br>        &#39;prediction&#39;: int(prediction),<br>        &#39;class_name&#39;: class_names[prediction],<br>        &#39;confidence&#39;: confidence<br>    })<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(<br>        host=&#39;0.0.0.0&#39;,<br>        port=8000,<br>        debug=False <br>    )</pre><h3>Django for API Development</h3><p>Django is a heavy framework which includes a lot of built-in features like authentication, database management, security, etc. If you are planning to have well-round system around your ML model, then Django will be the best option. It provides ORM(Object-Relational Mapper) for databases, a ready-to-use admin panel, and protection against common web attacks like SQL injection or CSRF out of the box.</p><h4>Django Rest Framework (DRF)</h4><p>Plain Django could only be used for normal rendering of HTML pages. That is where DRF comes in and provides high-powered API integration. Serializers in DRF act like a translator between your complex Python/Database objects and the JSON format that web apps understand. Viewsets allow you to define the standard API actions(List, Create, Retrieve, Update) in one place.</p><h4><strong>To create a basic endpoint:</strong></h4><ul><li>first define a <em>model.py</em></li><li>Create a serializer inside <em>serializer.py</em> to map the object to model fields.</li><li>Create a View in <em>views.py</em> (eg, <em>ModelViewSet</em>)</li><li>Register a Router in <em>urls.py</em> to automatically create the URL path.</li></ul><p>Integrating ML Models involves storing the model in a specific folder. For efficiency, you can load the model in a <em>ready()</em> method of your <em>app.py </em>file. This ensures that the model is loaded into the memory once when the server starts. You can use input validation in the serializers to validate the user’s input before it is passed to the model.</p><p><strong>Setup Commands:</strong></p><pre>django-admin startproject django_ml_api<br>cd django_ml_api<br>python manage.py startapp predictor</pre><p><strong>Configuration 1:</strong> django_ml_api/django_ml_api/settings.py</p><pre>ALLOWED_HOSTS = [&#39;*&#39;]<br><br>INSTALLED_APPS = [<br>    # ... default apps ...<br>    &#39;rest_framework&#39;,<br>    &#39;predictor&#39;,<br>]</pre><p><strong>Configuration 2:</strong> django_ml_api/django_ml_api/urls.py</p><pre>from django.urls import path, include<br><br>urlpatterns = [<br>    path(&#39;api/&#39;, include(&#39;predictor.urls&#39;)),<br>]</pre><p><strong>Configuration 3:</strong> django_ml_api/predictor/urls.py</p><pre>from django.urls import path <br>from . import views <br><br>urlpatterns = [<br>  path(&#39;health/&#39;, views.health_view),<br>  path(&#39;predict/&#39;, views.predict_view),<br>]</pre><p><strong>Configuration 4:</strong> django_ml_api/predictor/views.py</p><pre>import os<br>import joblib <br>import numpy as np <br>from django.conf import settings<br>from rest_framework.decorators import api_view<br>from rest_framework.response import Response <br><br># Create your views here.<br>model_path = os.path.join(settings.BASE_DIR, &quot;model.joblib&quot;)<br>try:<br>    model = joblib.load(model_path)<br>except:<br>    try:<br>        model = joblib.load(&#39;model.joblib&#39;)<br>    except:<br>        model = None <br><br>class_names = [&#39;setosa&#39;, &#39;versicolor&#39;, &#39;virginica&#39;]<br><br>@api_view([&#39;GET&#39;])<br>def health_view(request):<br>    return Response({&#39;status&#39;: &quot;Django app is running&quot;})<br><br>@api_view([&#39;POST&#39;])<br>def predict_view(request):<br>    features = request.data.get(&#39;features&#39;)<br>    features_arr = np.array(features).reshape(1, -1)<br><br>    prediction = model.predict(features_arr)[0]<br>    probability = model.predict_proba(features_arr).max()<br><br>    return Response({<br>        &#39;prediction&#39;: int(prediction),<br>        &#39;class_name&#39;: class_names[int(prediction)],<br>        &#39;confidence&#39;: float(probability)<br>    })</pre><h3>Docker for Containerization</h3><p>Containerization is a technique used for deploying modern day application without dependency conflicts and with scalability features. If you have used Virtual Machines to run an entire application, it often ends up in the ‘but it worked on my machine!’ problem. This is because VMs carry a full OS that can’t be shared across multiple platform and it is difficult to scale. When it comes to containerization, it creates an isolated environment called a container, and it shares a connection with the OS kernel, which makes them lightweight and immutable.</p><p>There are certain keywords to look at first to understand this technique:</p><ul><li><strong>Docker Image:</strong> It is a read-only, immutable file that serves as a blueprint or template for creating containers. It is a snapshot of everything that is required to run an application: the code, runtime environment, system tools, libraries, dependencies, and configuration settings. Images are built up from a series of read-only layers, where each layer represents an instruction from the Dockerfile. These layers enable efficient storage and transfer since only the layers modified need to be updated or downloaded. Images are stored in Docker Registry and can be shared, reused and versioned like a git initialized source code.</li><li><strong>Docker Container:</strong> The best analogy is to think of Docker Image as classes and Docker Container as the object of that class. A Docker Container is a running instance of the image. It’s what you get when you execute an image. While an image is a static file, a container is live and executing all the processes with its own isolated resources, including memory, networking, and filesystem space. These are lightweight and easy to start, stop, move, or delete. Multiple containers can run simultaneously, without interfering with each other, so they run consistently with the underlying infrastructure.</li><li><strong>Dockerfile:</strong> This is a text file containing a specific set of instructions to automatically build a Docker Image. It acts as a source code for your image, defining step-by-step on which OS to use, what dependencies to install, which files to copy, what environment variables to configure, and what commands should run when a container starts to get created. Each instruction results in a new layer inside the Image. Dockerfiles ensure version control, reproducability and consistency.</li></ul><p><strong>A typical Dockerfile contains:</strong></p><ol><li><em>FROM:</em> Pick a base image that serves as a starting point for your container. (eg: python:3.9-slim).</li><li><em>WORKDIR:</em> Sets a home folder inside the container.</li><li><em>COPY:</em> Move your <em>requirements.txt</em> and code inside</li><li><em>RUN:</em> Install dependencies (eg: <em>pip install …</em>)</li><li><em>CMD:</em> The command that starts your API.</li></ol><ul><li><strong>Docker Hub:</strong> It is cloud based registry service where Docker images are stored, shared, and distributed. It functions as centralized repository, like GitHub for source code, where developers can upload their images and download those created by others.</li></ul><p>We are going to containerise both the Flask app and the Django app:</p><p>NOTE: Watch a Docker tutorial to properly install Docker Desktop on your computer. The</p><p>First on the root folder, create <em>requirements-flask.txt</em> and r<em>equirements-django.txt</em> files.</p><pre>flask==3.0.0<br>gunicorn==21.2.0<br>scikit-learn==1.3.2<br>joblib==1.3.2<br>numpy==1.26.2</pre><pre>django==4.2.7<br>djangorestframework==3.14.0<br>gunicorn==21.2.0<br>scikit-learn==1.3.2<br>joblib==1.3.2<br>numpy==1.26.2</pre><p>Now create <em>Dockerfile.django</em> and <em>Dockerfile.flask</em>:</p><pre>FROM python:3.11-slim<br><br>WORKDIR /app<br><br>COPY requirements-flask.txt .<br><br>RUN pip install --no-cache-dir -r requirements-flask.txt <br><br>COPY flask_app.py .<br>COPY model.joblib .<br><br>EXPOSE 8000<br><br>CMD [&quot;gunicorn&quot;, &quot;-w&quot;, &quot;2&quot;, &quot;-b&quot;, &quot;0.0.0.0:8000&quot;, &quot;flask_app:app&quot;]</pre><pre>FROM python:3.11-slim <br><br>WORKDIR /app <br><br>COPY requirements-django.txt .<br><br>RUN pip install --no-cache-dir -r requirements-django.txt <br><br>COPY django_ml_api/ .<br>COPY model.joblib .<br><br>EXPOSE 8001 <br><br>CMD [&quot;gunicorn&quot;, &quot;django_ml_api.wsgi:application&quot;, &quot;--bind&quot;, &quot;0.0.0.0:8001&quot;, &quot;--workers&quot;, &quot;2&quot;]</pre><pre># for building and running flask app as a container<br><br>docker build -t flask-ml-app -f Dockerfile.flask .  # build image<br><br>docker run -p 8000:8000 flask-ml-app  # runs the container</pre><pre># for building and running django app as a container<br><br>docker build -t django-ml-app -f Dockerfile.django .<br><br>docker run -p 8001:8001 django-ml-app</pre><h3>Introduction to Docker Compose</h3><p>Docker is for individual containers, whereas Docker Compose acts as an orchestrator for multiple containers running simultaneously. Think of a Flask API, a database and a Redis cache operating under a unified system and to run them, you just have to just execute one <em>docker-compose.yaml</em> file. That is the magic of Docker Compose.</p><h4>Core Docker Compose Concepts</h4><ol><li><strong>Services </strong><br>Services represent individual components in your application that run on their own isolated containers. You define the services in the <em>docker-compose.yaml</em> file. Each service can be configured with specific parameters, including port mappings, environment variables, volumes, and dependencies on other services. For example, a typical web application might define a ‘<em>web</em>’ service for the frontend, an ‘<em>api</em>’ service for the backend, and ‘<em>db</em>’ service for the database, each running independently but working together as a cohesive system. Service names are crucial because Docker Compose uses them for automatic DNS resolution, allowing containers to reference each other by name rather than IP addresses.</li><li><strong>Networks</strong><br>Docker Compose automatically creates a default private network for all services defined in your compose file, enabling seamless communication between containers. They communicate using their service name as their hostname, as your web application can communicate with the database at <a href="http://db:5432/"><em>http://db:5432</em></a>, where ‘<em>db</em>’ is the service name. You can also add restrictions between containers for more security.</li><li><strong>Volumes</strong><br>Volumes provide persistent data storage outside the container’s short-lived filesystem, ensuring critical data survives. Without volumes, any data written inside a container, such as database records, uploaded files, or application logs, would be lost when there are changes happening to the container. Volumes map storage locations between your physical host machine and container file system, creating a bridge that persists data even when the container restarts, rebuild or undergoes any deletions. Volumes can be shared between multiple containers, enabling the exchange of files and collaboration on shared data.</li></ol><p>Now, using Docker compose we create a single system that runs both the Flask app and the Django app simultaneously. Create a <em>docker-compose.yaml.</em></p><pre>services:<br>  #Service 1: Flask<br>  flask-api:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile.flask<br>    ports:<br>      - &quot;8000:8000&quot;<br>    volumes:<br>      - ./model.joblib:/app/model.joblib <br>    networks:<br>      - ml-network<br><br>  # Service 2: Django <br>  django-api:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile.django <br>    ports:<br>      - &#39;8001:8001&#39;<br>    volumes:<br>      - ./model.joblib:/app/model.joblib<br>    networks:<br>      - ml-network<br><br>networks:<br>  ml-network:<br>    driver: bridge</pre><p>Use the below command to run it:</p><pre>docker-compose up --build<br><br>docker-compose down # for removing the instance</pre><p>This is the most beginner-level blog that you could read to start from creating a development cycle to production-ready ML programs. If you like this blog, please subscribe to my blogs to get more deep dives on topics like these.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbc8f42a3821" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Language Processing (Part 2)]]></title>
            <link>https://medium.com/@orbinsunny/natural-language-processing-part-2-8150e195b4c8?source=rss-8d6c0d0cb381------2</link>
            <guid isPermaLink="false">https://medium.com/p/8150e195b4c8</guid>
            <dc:creator><![CDATA[Orbin Sunny]]></dc:creator>
            <pubDate>Sat, 17 Jan 2026 08:33:03 GMT</pubDate>
            <atom:updated>2026-01-17T08:33:03.480Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello fellow ML practitioners,</p><p>This is the second part of the NLP blogs. In this blog, we will discuss some advanced concepts of NLP. This is the second part. If you haven’t read the first part, it will be difficult to follow, so please read it first before reading this blog. We will be going through Named Entity Relationship, Sentiment Analysis, models and frameworks that do modern-day NLP and related works. So let’s get started.</p><h3>1. Named Entity Relationship (NER)</h3><p>NER is a type of information extraction tool. The main aim is to picture each word as a unit and find in what types of entities it belongs. The entities are person names, organisations, locations(GPE), medical codes, time expressions, quantities, and monetary values. NER is a sequence labelling task; it is not classifying the entire sentence or paragraph, but looking at each word to check which entity suits it better and also the context, the character casing, and the position of a particular word all help the NER models to classify.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXQN1mPoMYKo3HaBCmLGlw.png" /></figure><p>There are rule-based and statistical-based NER, but the most preferred one is the statistical-based ones (Conditional Random Fields, HMM) because it can look for the global context of a word before making a decision. It is also done by transformer models like BERT, where the context-aware embeddings are given, and the final layer is passed to a softmax to find the entity label. This is used across various fields, like in the medical field for biomedical term recognition or in search engines to enrich results for entities in a query or in customer support for automatically scanning customer details like name, order ID, etc.</p><pre>import spacy <br><br>nlp = spacy.load(&#39;en_core_web_sm&#39;)<br><br>text = &#39;Sam works at Google in San Fransisco since 2023&#39;<br><br>doc = nlp(text)<br><br>for ent in doc.ents:<br>  print(f&quot;{ent.text} --&gt; {ent.label_}&quot;)</pre><h3>2. Sentiment Analysis</h3><p>Sentiment Analysis is a part of NLP, whose primary goal is to extract, identify and quantify the subjective side of the text using statistical and computational methods. The main components of sentiment analysis are polarity (good or bad)and subjectivity(whether it is fact or personal opinion).</p><p>Sentiment analysis is generally used in brand monitoring, helping to analyse customer feedback, real-time news or social media to measure brand health, and to generalise the public opinion.</p><p>We have two main ways to do sentiment analysis, yes, rule-based and statistical. Two libraries for rule-based are VADER and TextBlob. We can also use deep learning models, which are more computationally costly, although more accurate.</p><h4>VADER (Valence Aware Dictionary and sEntiment Reasoner)</h4><p>It is a lexicon-based and rule-based model which accounts for both the intensity of words and the context of the group of words. Intensity in the sense that it recognises ‘Extremely Good’ is more positive than just ‘Good’. It has a scoring criterion for [‘Negative’, ‘Neutral’, ‘Positive’], which helps in calculating the compound score, which is finally taken as the polarity score. Typically, a score greater than 0.05 is positive, and a score less than -0.05 is negative.</p><h4>TextBlob</h4><p>When the text is converted to a TextBlob object, it prepares two values: polarity([-1, 1]) and subjectivity ([0, 1] 0 is the least subjective. The main difference is that TextBlob is for formal text, like news articles, and VADER is better for informal texts, which include emojis or slang.</p><pre># Vader <br>from nltk.sentiment import SentimentIntensityAnalyzer<br>import nltk<br><br>sia = SentimentIntensityAnalyzer()<br><br>text = &quot;This product is not amazing! Totally worth the money.&quot;<br><br>score = sia.polarity_scores(text)<br>print(score)<br><br># TextBlob<br>from textblob import TextBlob <br><br>text = &#39;The service was slow and dissappointing&#39;<br><br>blob = TextBlob(text)<br>print(blob.sentiment)</pre><h3>3. Transformer Models</h3><p>Transformer models are widely used for NLP tasks because they give state-of-the-art results when it comes to extracting meaning and generating valuable responses. Unlike RNN, it doesn’t have the vanishing gradient problem while scaling, and each token can interact with each other in parallel, which solves both problems of losing context and sequential processing.</p><h4>BERT (Bi-Directional Encoder Representation from Transformers)</h4><p>BERT only uses the encoder to look at the words left to right as well as right to left. It uses Masked Language Processing to force the model to learn the context and receives two sentences to predict whether the first sentence aligns with the second to help the model learn the relation between two sentences.</p><p>The BERT model uses three types of embeddings. The first one is the token embeddings, which are the representation that is given by WordPiece. The second one is the Segment Embedding, which helps to identify which sentence a token belongs to, and the final one is the positional embeddings, which have the position representation of each token.</p><p>There are special tokens added inside the text to represent certain instructions and meanings, like:<br>[CLS] → which is used before the input sequence.<br>[SEP] → which is used between each sentence for separation. <br>[PAD] → which is used to fill the gap when every sentence is padded to a uniform length.</p><h4>GPT (Generative Pretrained Transformer)</h4><p>GPT is a decoder-only autoregressive model. It is unidirectional, which means the model takes the tokens before prediction and uses them to predict the next token in the sequence. The primary object of the GPT model is to generate text in the most fluent and accurate way. It is trained on a massive corpus of unlabeled text, and it masks the next words and tries to predict them. This forces the model to learn grammar, facts and even basic reasoning without explicit labels.</p><p>So, when scaled like ChatGPT, it could do tasks in one shot. Unlike the extractive summarisation that the BERT gives, GPT understands the semantic meaning and generates a new, condensed version of the text it is trained on (abstractive summarisation), while maintaining the original intent.</p><h3>4. Text Classification</h3><p>Text Classification or Text Categorisation is one of the tasks in which we use NLP techniques to classify text into predefined labels, turning the unstructured data into something interpretable and readable. The main classification use cases are for sentiment analysis, spam detection, language detection, etc. It is useful in solving manual sorting with a machine that is scalable, consistent and can access real-time analysis, which are critical in the internet age.</p><p>There are rule-based approaches like vader and textblob, then there are machine learning approaches, such as using Naive Bayes or SVM to learn patterns from labelled data, or you can go for Deep Learning approaches for more infra-heavy, non-linear, complicated tasks. For DL, we can use CNNs, RNNs, and Transformers like BERT to capture complex context and semantics.</p><h4>Traditional Machine Learning Models used Text Classification:</h4><p><strong>Naive Bayes:</strong> Naive Bayes Classifier can be used as a baseline model for doing text classification because it could gave good outcome with faster training time and with a sparse large dataset. Despite the model recognising the words independently (eg,- New York as two separate words), the model performs best at finding the right class as labelled, even without wrong estimations of the words’ relationship.</p><p><strong>SVM:</strong> As Support Vector Machines treat their data as points in a space, it finds the best line or flat surface or high dimensional seperators which divides non-clustered data. The marginal approach between classes poses SVM as a good option when it comes to classifying high-dimensional data, which is typically text data. SVM is the best option when we need the best accuracy, and the dataset is not prohibitively large.</p><pre># https://github.com/orbin123/Machine_Learning/blob/main/Deep_Learning/NLP/WEEK%203/Datasets/imdb_labelled.csv<br><br>import pandas as pd <br>from sklearn.model_selection import train_test_split <br>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.naive_bayes import MultinomialNB<br>from sklearn.svm import LinearSVC<br>from sklearn.metrics import accuracy_score<br><br>df = pd.read_csv(&#39;imdb_labelled.csv&#39;)<br><br>X_train, X_test, y_train, y_test = train_test_split(df[&#39;sentence&#39;], df[&#39;label&#39;], test_size=0.2, random_state=42)<br><br>tfidf = TfidfVectorizer(stop_words=&#39;english&#39;)<br>X_train_vec = tfidf.fit_transform(X_train)<br>X_test_vec = tfidf.transform(X_test)<br><br>nb = MultinomialNB()<br>nb.fit(X_train_vec, y_train)<br>nb_pred = nb.predict(X_test_vec)<br><br>svm = LinearSVC()<br>svm.fit(X_train_vec, y_train)<br>svm_pred = svm.predict(X_test_vec) <br><br>print(&quot;NB&quot;, accuracy_score(y_test, nb_pred))<br>print(&#39;SVM&#39;, accuracy_score(y_test, svm_pred))</pre><h3>5. Sentiment Analysis using Deep Learning</h3><p>As we have discussed earlier, Sentiment Analysis is a way to teach a computer whether a text gives happy, sad, angry or neutral emotions. While there are rule-based or traditional ML methods to find the sentiment of a text it often lack the ability to understand the nuances of a text. That’s where Deep Learning techniques come in and find the context and tone that even humans may miss. When traditional methods might just see positive terms in the text “Great, another delay!&quot; to assume it to be positive, DL sees sarcasm, and realises its negative. We will go over two main DL approaches:</p><ol><li><strong>LSTM (Long Short-Term Memory):</strong> LSTM process the data sequentially and remembers every detail in the sentence when deciding the sentiment at the end. Use LSTM when a long context in a sequence is important in understanding the text.</li><li><strong>Convolutional Neural Network:</strong> The CNN is another neural network model that is useful in identifying the sentiments because it sees the data through filters and search of specific words like “don’t like”, or “Very Happy”. It will pick up these common patterns to make a decision.</li></ol><h4>Real World Use Cases:</h4><ol><li><strong>E-commerce:</strong> Automatically takes thousands of reviews and summarizes it to tell the customer whether the product is upto the mark.</li><li><strong>Customer Support:</strong> Summarising customer sentiments and needs through scanning through responses and feedback.</li><li><strong>Stock Market:</strong> Analysing news headlines about companies to make informed decisions.</li><li><strong>Social Media Monitoring:</strong> Companies use the responses they get from the comments and replies they get from the audience to be aware of the brand.</li></ol><pre>import pandas as pd <br>from sklearn.model_selection import train_test_split <br>from tensorflow.keras.preprocessing.text import Tokenizer <br>from tensorflow.keras.preprocessing.sequence import pad_sequences <br>from tensorflow.keras.models import Sequential <br>from tensorflow.keras import layers <br><br># Load data<br>df = pd.read_csv(&#39;imdb_labelled.csv&#39;)<br><br>X_train, X_test, y_train, y_test = train_test_split(df[&#39;sentence&#39;], df[&#39;label&#39;], test_size=0.2)<br><br># Tokenization<br>tok = Tokenizer(num_words=5000)<br>tok.fit_on_texts(X_train)<br>X_train = pad_sequences(tok.texts_to_sequences(X_train), maxlen=100)<br>X_test = pad_sequences(tok.texts_to_sequences(X_test), maxlen=100)<br><br># LSTM<br>lstm_model = Sequential([<br>    layers.Embedding(5000, 64, input_length=100),<br>    layers.LSTM(64),<br>    layers.Dense(1, activation=&#39;sigmoid&#39;)<br>])<br>lstm_model.compile(loss=&#39;binary_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])<br>lstm_model.fit(X_train, y_train, epochs=3, batch_size=32)<br>print(&#39;LSTM&#39;, lstm_model.evaluate(X_test, y_test))<br><br>cnn_model = Sequential([<br>    layers.Embedding(5000, 64, input_length=100),<br>    layers.Conv1D(64, 3, activation=&#39;relu&#39;),<br>    layers.GlobalMaxPool1D(),<br>    layers.Dense(1, activation=&#39;sigmoid&#39;)<br>])<br><br>cnn_model.compile(loss=&#39;binary_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])<br>cnn_model.fit(X_train, y_train, epochs=3, batch_size=32)<br>print(&#39;CNN&#39;, cnn_model.evaluate(X_test, y_test))</pre><h3>6. Topic Modelling</h3><p>Suppose you have a huge pile of textual data. It may be a set of news, or documentation, or theory notes, now topic modelling takes this huge pile of text and organises it into categories based on the hidden themes. It doesn’t know the topics beforehand (like ‘Sports’ or ‘Politics’). Instead, it scans through the document and finds words like ‘Football’, ‘Cricket or ‘Russia and Ukraine’ to group them accordingly. It mainly uses probability to guess the main topic. So the main difference between Topic Modeling from Text Classification is that it is unsupervised and it is a probabilistic model.</p><p>First, it assigns words randomly to topics, then iteratively assigns a topic to the words by checking how often the word appears in the current topic (topic-word distribution) and how often the current topic appears in that document (document-topic distribution). After many iterations, the dominant topics will be stabilised without changing.</p><h4>Real-World Use Cases:</h4><ol><li><strong>News Aggregation:</strong> News platforms need to group thousands of articles that are about the same event, even if the headlines are slightly different.</li><li><strong>Legal Discovery:</strong> Lawyers use it to scan millions of legal documents or emails to find relevant pieces of documents that are related to a fraud case or contract breach.</li><li><strong>Recommender Systems: </strong>When you see top recent feed in your social platforms, which you may never follow, in the backgroud it is coming from the organised topics that you have followed.</li></ol><pre>import pandas as pd<br>from gensim import corpora, models <br>from nltk.corpus import stopwords<br>from nltk.tokenize import word_tokenize <br><br>df = pd.read_csv(&#39;imdb_labelled.csv&#39;)<br>df.head()<br><br>stop = set(stopwords.words(&#39;english&#39;))<br>texts = [[w for w in word_tokenize(t.lower()) if w.isalpha() and w not in stop] for t in df[&#39;sentence&#39;]]<br><br>dictionary = corpora.Dictionary(texts) <br>corpus = [dictionary.doc2bow(t) for t in texts]<br><br>lda = models.LdaModel(corpus, num_topics=3, id2word=dictionary, passes=5) <br>print(lda.print_topics())</pre><h3>7. Document Similarity and Search</h3><p>Document Similarity is the process of finding the similarity of two texts with mathematical methods. Think of plotting the articles as a point in a space, and the closeness of the coordinates of ‘Article A’ and ‘Article B’ proves that they have similar kinds of topics discussed.</p><h4>A. Cosine Similarity (The Direction Method):</h4><p>Imagine that every document is an arrow(vector) on a graph, and each arrow is pointing towards its own specific direction. Now we take two documents’ vectors with their directions. We take the angle between them to take that value as the semantic closeness. The formula is the dot product of the vectors by the product of their magnitudes(lengths).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*9wwMg1U_p8tIaPvnDCXD1g.png" /></figure><p><strong>Interpretation</strong>:</p><ul><li><strong>1</strong>: Vectors point in the exact same direction (highly similar).</li><li><strong>0</strong>: Vectors are perpendicular (no similarity).</li><li><strong>-1</strong>: Vectors point in opposite directions (opposite meaning).</li></ul><h4>B. Word Embeddings (The Meaning Method):</h4><p>Techniques like Word2Vec or GloVe convert words into a dense vector format based on the context. It places each word closer to other representations that are semantically similar. An example would be if you take the calculation of “King” — “Man” + “Woman” results in “Queen”, and if one document says about “Car” and another document says about “Automobile”, even though character-wise they are not similar, the model could identify the relation.</p><h4>Real World Use Cases:</h4><ol><li><strong>Plagiarism Checkers:</strong> It compares your essay against millions of others. If the ‘angle’ (similarity score) is too close to an existing paper, it flags it as copied.</li><li><strong>Search Engine:</strong> When you type a query, instead of searching for the keywords, the model finds relevant information that has a high similarity score.</li><li><strong>Q&amp;A Bots:</strong> when you ask a question, it searches for the most similar exisiting similar question in the database through document similarity methods.</li></ol><pre>from gensim.models import Word2Vec<br>import numpy as np<br>from sklearn.metrics.pairwise import cosine_similarity<br><br>w2v = Word2Vec(texts, vector_size=100, window=5, min_count=1)<br><br>def doc_vector(doc):<br>  valid_words = [w2v.wv[w] for w in doc if w in w2v.wv]<br>  if valid_words:<br>    return np.mean(valid_words, axis=0)<br>  else:<br>    return np.zeros(w2v.vector_size)<br>doc_vectors = np.array([doc_vector(t) for t in texts])<br><br>def search(query, top=3):<br>  q = [w for w in word_tokenize(query.lower()) if w.isalpha() and w not in stop]<br>  q_vec = doc_vector(q).reshape(1, -1)<br>  sims = cosine_similarity(q_vec, doc_vectors)[0]<br>  idx = sims.argsort()[-top:][::-1]<br>  return df.iloc[idx][[&#39;sentence&#39;, &#39;label&#39;]]<br><br>print(search(&#39;great movie with good acting&#39;))</pre><h3>8. Text Summarisation</h3><p>Text Summarisation is the process of taking a long piece of text (corpus) and creating a shorter version of it which consolidates all the most important information. There are two ways to summarise a corpus, and these two can be useful in different ways:</p><h4>A. Extractive Summary (using TextRank):</h4><p>It takes the original text, scans for all the important phrases and copies them word-for-word in the summary. It will high most important sentence first and create a shorter version from these sentences.</p><p>TextRank is one of the extractive summary algorithms that uses graph-based ranking to do text summarisation and keyword extraction. The algorithm creates a graph where basic words or sentence is considered as nodes and edges between these nodes are formed iteratively by looking at the overlap between sentences or co-occurence by words within a sliding window. Then, a PageRank is applied to determine the most connected or central words. The main adavantages being no need for training with pre-defined labels and better to be used in critical fields like legal or medical, where the model should not hallucinate.</p><pre>from sumy.parsers.plaintext import PlaintextParser<br>from sumy.nlp.tokenizers import Tokenizer <br>from sumy.summarizers.text_rank import TextRankSummarizer<br><br>text = &quot;&quot;&quot;<br>Artificial Intelligence is transforming every industry. From healthcare to finance,<br>AI systems help humans make better decisions. Machine learning models learn from data<br>and improve automatically. Deep learning allows machines to understand images, speech,<br>and text. In the future, AI will become a daily companion for people across the world.<br>&quot;&quot;&quot;<br><br>parser = PlaintextParser.from_string(text, Tokenizer(&#39;english&#39;))<br>textrank = TextRankSummarizer()<br>tr_summary = &#39; &#39;.join(str(s) for s in textrank(parser.document, 2))<br>print(&#39;textrank summary&#39;, tr_summary)</pre><h4>B. Abstractive Summary (using BERT models):</h4><p>Here, the model tries to understand the meaning of the text and writes a completely new summary using paraphrased words and sentences. It has more creative liberty to connect ideas or rephrase statements, or simplify complications. Mostly, deep learning models like BERT, GPT, and T5 are used for this task because they can understand the language deeply.</p><pre>from transformers import pipeline <br><br>summarizer = pipeline(&#39;summarization&#39;, model=&#39;facebook/bart-large-cnn&#39;)<br>bert_summary = summarizer(text, max_length=60, min_length=30, do_sample=False)[0][&#39;summary_text&#39;]<br>print(&#39;\nBERT Summary: &#39;, bert_summary)</pre><h4>Real-World Use Cases</h4><ol><li><strong>News Apps:</strong> Platforms like Inshorts become popular because of using summarised snippets of the news, making it easy for mobile readers.</li><li><strong>Legal &amp; Medical:</strong> Lawyers and Doctors use it to get a quick evaluation of a long case file or scattered patient records.</li><li><strong>Meeting Notes:</strong> There are AI tools that brief the user when they finish a meeting through Zoom calls or Google Meet.</li></ol><h3>Other NLP Tasks include Speech Processing</h3><p>Speech Processing allows computers to interact with humans using natural voice. There are two directions:</p><ol><li><strong>Speech-to-Text(STT):</strong> In STT, the microphone captures sound waves, and feature extraction converts these sound waves into a visual map called Spectogram. Then a model matches the spectrogram with the correct basic sounds(Phonemes) and uses a Language Model to guess the relating words based on grammar by decoding. A popular tool is Google Speech Recognition API.</li><li><strong>Text-to-Speech(TTS): </strong>First, the text is analysed to understand the rhythm and intonation(eg, raising the pitch for a question mark). Next, it generates artificial sound that mimic human voice. A popular tool is gTTS(Google Text-to-Speech).</li></ol><pre>from gtts import gTTS <br>import speech_recognition as sr <br>from pydub import AudioSegment<br><br>tts = gTTS(text=bert_summary, lang=&#39;en&#39;)<br>tts.save(&#39;summary_audio.mp3&#39;)<br>print(&#39;\nAudio to Text Outpu:\n&#39;)<br><br># Convert MP3 to WAV<br>audio_mp3 = AudioSegment.from_mp3(&#39;summary_audio.mp3&#39;)<br>audio_mp3.export(&#39;summary_audio.wav&#39;, format=&#39;wav&#39;)<br><br># Now use the WAV file with SpeechRecognition<br>r = sr.Recognizer()<br>with sr.AudioFile(&#39;summary_audio.wav&#39;) as source:<br>  audio = r.record(source)<br><br>converted_text = r.recognize_google(audio)<br>print(&#39;Speech to Text Output:&#39;, converted_text)</pre><h4>Real-World Use Cases:</h4><ol><li>Voice Assistants like Siri and Alexa use speech processing to understand the voice information received from the user to respond.</li><li>Speech Translators use real-time language translation and speech generation to communicate in different languages.</li><li>GPS Navigation instructs you via sound about the critical actions while travelling.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8150e195b4c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My GSoC Journal: Part 1]]></title>
            <link>https://medium.com/@orbinsunny/my-gsoc-journal-part-1-77932deaa857?source=rss-8d6c0d0cb381------2</link>
            <guid isPermaLink="false">https://medium.com/p/77932deaa857</guid>
            <dc:creator><![CDATA[Orbin Sunny]]></dc:creator>
            <pubDate>Mon, 29 Dec 2025 07:32:29 GMT</pubDate>
            <atom:updated>2025-12-29T07:32:29.992Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello fellow coders,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*C9gwxXthV3tA-gefgJDaDw.png" /></figure><p>As part of the <a href="https://developers.google.com/open-source/gsoc/timeline#2026_timeline">2026 GSoC timeline</a> release, I am structuring my thoughts and anxieties about participating in GSoC for the first time. To help me get started with the program, I joined the <a href="https://nas.io/wecodecommunity/home">WeCode Malayalam</a> community that has a GSoC program currently running. In this blog, I will share the five tips that you should be aware of if you are starting your GSoC journey yourself. Before reading, it is recommended to watch a 10–15 minute video on GSoC if you have no idea about it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FsPM2WiwA1us%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DsPM2WiwA1us&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FsPM2WiwA1us%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/482133b2c3b062165ae8c8d9bfcb4371/href">https://medium.com/media/482133b2c3b062165ae8c8d9bfcb4371/href</a></iframe><h4>#1 Be aware of the Timeline</h4><p>If you are preparing from now, please visit the above timeline link and pin the important dates to be aware of the procedures that are going to happen before the selections. The main events are publishing the organisations that are going to participate in 2026 GSoC, which are the projects published, and when is the period for proposal submission?</p><h4>#2 Prepare a List of Organisations</h4><p>When I say organisation, it refers to companies like Google DeepMind, Python, Django, Blender, Apache, Mozilla, etc. The one way to prepare now is to visit the <a href="https://summerofcode.withgoogle.com/programs/2025/organizations">2025 organisations</a> and look for the domains and tech stack that you are confident in contributing to. This way, if these organisations are participating in 2026, you could get an upper hand. So, prepare a broad number(6–10) of lists of organisations to have an idea about the potential organisations or types of organisations you may contribute to.</p><p><a href="https://www.gsocorganizations.dev/">GSoC Organizations</a></p><p>From this website, you can easily filter past organisations by tech stack, topics and year. However, I recommend spending enough time to understand 9 –12 organisations that fall under your radar before shortlisting, rather than choosing organisations by just filtering.</p><h4>#3 Read Past Projects and Proposals</h4><p>Now, as you have shortlisted the potential organisations, with those lists, visit every company one by one. First, if you pick one organisation like OpenCV, go to its <a href="https://opencv.org/">official website</a>, read about the company and what tools they provide and applications they have. Secondly, go back to the <a href="https://summerofcode.withgoogle.com/archive/2023/organizations/opencv">organisation’s page</a> and read all the successful projects, only skipping the ones you feel are really tough. This helps to have a good understanding of what problems may come in future iterations. Now, from here, you have to again sort the projects that interest you and are in the scope of your current skills. Maybe the organisations that have the most number of projects sorted could be the organisation that selects you.</p><p>Again, check the projects one by one. You should find previous proposals that may have been posted online to get selected for a particular project. It is pretty hard to find proposals for all the projects, but the popular ones are definitely posted on some GitHub repos or online forums. After getting them, for each project proposed, see how the proposal gives its measures, steps and skeleton of the output. Each proposals showcase both the solution and how that particular developer or student is apt for solving it. So, keep a note on things that you seem interested like the previous pull requests, the way they structure their thoughts on the solution, and how they demonstrate themselves to the maintainer.</p><p>After all this, you would have a deeper understanding of the organisations or the style of organisations that you would love to be a part of.</p><ul><li><a href="https://hepsoftwarefoundation.org/gsoc/2025/summary.html">Summary of GSoC 2025 Proposals</a></li><li><a href="https://summerofcode.withgoogle.com/programs/2025/organizations">Google Summer of Code</a></li></ul><h4># 4 Try to Understand Codebase</h4><p>As I said, after doing this much, you will be confident or curious to know more about 3–5 organisations. Now double down on those organisations (from here onwards, you will need a beginner&#39;s understanding of GitHub). I believe that now you have clarity on the primary programming language, organisations, projects and proposals. The primary aim of this step is to instruct you to practice comprehending code bases, which is a unique skill that makes you 10x better as a programmer. For that, fork some of the repos you are interested in, open the documentation provided by the organisation and try to understand the purpose of the file structure and chunks of code. You could even go through the organisation page in the GSoC past programs and click on a <a href="https://summerofcode.withgoogle.com/archive/2024/projects/UbSBMuRD">project details page</a>, then press view code to see the GitHub repo where they have implemented the completed project. Comprehending these repos gives you enough knowledge about the expected work. Do not get intimidated by the code; instead, try to understand it on an abstract level.</p><h4># 5 Start Contributions Early as Possible</h4><p>If you are reading about GSoC 2–3 months before March 2026, then plan to start contributing to the open-source community earlier. Do not wait for the projects and organisations to be out. Most of the stories about programmers who are getting selected say they started way earlier to show a strong open-source presence, and many of them even had contact with the maintainers or mentors of the organisations before they submitted their proposals, so it is guaranteed that your proposal will surely be seen. For the same reason, it is better to be joined in all community groups that the organisations have, like Discord, Gitter, online forums, etc. Have good communication with the team by making contributions or by being active on their chats.</p><p>Link to my preparation (do not copy-paste it, do your own research, and this one is specifically for machine learning developers):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdocs.google.com%2Fdocument%2Fd%2F1jOi9tYTTcXufZN2wGabSj-3gWQVou96HHmzHh28611A%2Fpreview%3Fembedded%3Dtrue&amp;display_name=Google+Docs&amp;url=https%3A%2F%2Fdocs.google.com%2Fdocument%2Fd%2F1jOi9tYTTcXufZN2wGabSj-3gWQVou96HHmzHh28611A%2Fedit%3Ftab%3Dt.0&amp;image=https%3A%2F%2Flh7-us.googleusercontent.com%2Fdocs%2FAHkbwyL1E7CqHjpc72cndrTT3chfMvFHAuknbRgrTRv53RBQSJI9qvxXjl51RAry2RDvSuND-YRPDWFavI04axcevQXstzKNBs1KkjwK15GNxDySpHTYmtjv%3Dw1200-h630-p&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=google" width="700" height="530" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c708b3dcc0626390ac28891b5f1c012/href">https://medium.com/media/8c708b3dcc0626390ac28891b5f1c012/href</a></iframe><p>If you have enjoyed reading my journal, follow for more parts on a similar subject.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77932deaa857" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Language Processing (NLP)]]></title>
            <link>https://medium.com/@orbinsunny/natural-language-processing-nlp-64a366d9803e?source=rss-8d6c0d0cb381------2</link>
            <guid isPermaLink="false">https://medium.com/p/64a366d9803e</guid>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Orbin Sunny]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 10:45:50 GMT</pubDate>
            <atom:updated>2025-12-27T05:03:44.295Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, fellow ML practitioner,</p><p>Natural Language Processing is a field in which the raw language is processed in a systematic way, in which computers, especially machine learning models, could understand it in order to generate synthetic text that is meaningful and similar to human writings.</p><p>Unlike structured spreadsheet data, language is nuanced and unstructured because it has differences in meaning and sentiment depending on the context. It involves understanding the complexities of grammar, semantics and pragmatics. So NLP allows humans to bridge that gap and communicate with a computer in natural language.</p><h4>Applications of NLP:</h4><p>The main areas are fields that include communication, translation, analysis, error corrections, and information extraction. In communication, NLPs are used in making chatbots for interacting with customers 24/7 or in tools like Alexa, Gemini, and Siri. It is widely used for language translation, like in Google Translate. In fields like finance and health care, it can be useful as an analyst or diagnostician. It could also be used for sentiment analysis to understand customer pain points.</p><h4>Text Data and Its Nuances</h4><p>Text data is the vast amount of information collected from human language, such as books, articles, tweets, blogs, Wikipedia, reviews, etc. The major problems with the unstructured nature of text data are that the same word could mean different things in different contexts, words which sound or even spell closely similar could mean different things, there are phrases which are used figuratively or idiomatically, and the context also depends on the grammar, punctuation, and sentence structure. And even if we check for all these, then also if we try to train on internet data, around the globe, the language has its own dialects, slang, and for younger generations, the language is totally different, where the usage of certain abbreviations and emojis could entirely mean something else. That is why a robust framework for preprocessing textual data is mandatory.</p><p>It is important to note that there are rule-based systems which are built by human experts, who manually and explicitly set operations to respond to text, but the main issue is the inconsistency in data. That is where learning based systems using machine learning models to find patterns and rules of the language on their own to counter every scenario.</p><h4>Overview of the workflow</h4><p>Firstly, the raw text is gathered through various sources like emails, tweets, website articles, transcripts of speech, conversation texts, etc. As these texts are often messy and filled with varying formats, abbreviations, and characters that computers struggle to understand, they should be preprocessed. Processing involves removing jargon parts, normalising, and converting to stem/lemma versions. Now that the text is cleaned, it needs to be converted into a machine-readable numerical format, which is called vectorisation. After that, it could be inputted into a model for training.</p><h4>Text Data Cleaning</h4><p>There is somany noise in textual data that could impact the performance of a model and also make it expensive. Basic text cleaning includes lowercasing, removing numbers, special characters, HTML tags, emojis and whitespace</p><h4>Advanced Text Preprocessing</h4><ol><li><strong>Handling Stop Words: <br></strong>Stopwords are common words used in language. These words are baggage to the model, so we remove them because removing the stopwords would not change any context or semantic meaning of the text, and it helps to focus more on the contentful words and reduce the data size.<br>Examples for stopwords are: a, an, the, is, are, in, of, to, and, for.</li><li><strong>Punctuation and Special Character Removal<br></strong>Unless the punctuation carries special meaning like seperating a statement from a questions, punctuation and special characters are treated as jargon and could bloat the vocabulary so they are removed.</li><li><strong>Case Normalization</strong><br>This is for ensuring that the same words are treated as a single token or else the process will identify ‘Apple’ and ‘apple’ to be two differents words, so all the words are converted to lowercase.</li><li><strong>Removing Whitespace:</strong><br>Cleaning reductant and inconsistent space by removing leading and trail spaces and keep a single space for multiple consecutive spaces. This process ensure that the intepretation of words focused on real words and not on spaces.</li><li><strong>Handling Contractions:</strong><br>Expanding contracted words to its full form. These are necessary to understand the text in depth or else the negating or contradicting statements will be understood differently.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*SuujMk5rz6_YTOKVeInEkA.png" /></figure><p>6. <strong>Spelling Correction:</strong><br>Identifying and correcting common misspellings and typographical errors. Helps to reduce the size of vocabulary, and only includes accurate words for training.</p><h4>Text Preprocessing</h4><p>The steps to preprocess text data are to clean it and normalise it for model usage. The primary steps are Tokenisation -&gt; Stemming or Lemmatisation.</p><ol><li><strong>Text Tokenisation:</strong> <br>It is the process of converting a corpus of text into tokens or a stream of text. These are usually words, subwords, or even characters. <br><strong>a. Sentence Tokenisation or Sentence Segmentation: </strong>dividing a large body of text into constituent sentences. Relies on punctuation markers for segmenting each sentence.<br><strong>b. Word Tokenisation: </strong>splitting a document or a sentence into words. Relies on whitespaces and treats punctuation as a separate token.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*aFcb8csNn0joFKa8YOPS7g.png" /><figcaption>Sentence Tokenisation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*rx-Zy6iIW4udfuZChkdVYw.png" /><figcaption>Word Tokenisation</figcaption></figure><p><strong>1.2 Subword Tokenisation</strong><br>It is a new type of technique used in most LLMs because it can compromise between word level and character level tokenisation. Instead of going with a whole word, which results in OOV or characters, it makes the computation costly; we take the parts of a word that are common, so that even if we miss a word like “unbelievably” in vocabulary, still there is a chance that the vocabulary has “un”, “believe”, “ably”. <br>Two main models which generate subwords are Byte Pair Encoding and WordPiece.</p><p>2. <strong>Stemming: <br></strong>It is a mechanism to chop off the suffix from words that mean the same (like run and running) and turn the words into their stem form, so the vocabulary size gets reduced.<br><strong>a. Porter Stemmer:</strong> This is one of the oldest and simplest methods to get the stem words. It is a rule-based system which cuts off the suffix of a word depending on explicitly mentioned rules, like removing suffixes such as ‘ing’, ‘ed’, or ‘s’. It is computationally fast but often produces words which aren’t real.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*3hJuDENFIp1ZFNnofzRt7w.png" /></figure><p><strong>b. Snowball Stemmer:</strong> It is a more aggressive version of the PorterStemmer one with support for more languages(French, German, Russian). It is more accurate with edge cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obJrYJDtYrtz_oyJDK2RPA.png" /></figure><p>3.<strong> Lemmatisation:</strong> <br>It is the process of converting words into their base or dictionary form, known as a lemma. It is more sophisticated and resource-intensive than stemming but provides better results. It relies on vocabulary and morphological analysis of words, often using parts-of-speech(POS) tagging to correctly identify the word&#39;s role in the sentence. The best part is that the output would be a dictionary word rather than a chopped non-word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*H6Gb6K2D3KTThLo4fhOzPA.png" /></figure><p><strong>WordNet Lemmatiser:<br></strong>It is an English lemmatisation tool implemented using the WordNet Lexical database. It uses the word’s context (POS tag) to identify the lemma from the WordNet’s structured collection of words’ meaning and relations. If you use it without a POS tag, then every word defaults to a noun. It uses a database to handle irregular words.</p><h4>Text Vectorization</h4><p>Vectorisation is the process of converting textual data into numerical vectors or coordinates that a machine learning model can understand. This representation should catch the meaning, importance and frequency of that word.</p><ol><li><strong>One-hot encoding:</strong><br>This is a simple way to convert tokens to numerics. make a matrix on the order of vocabulary, like we do normal one-hot encoding, but apart from being simple, it has major disadvantages like sparse matrix, out of vocabulary, and no semantic meaning between words is captured.</li><li><strong>Bag of Words:</strong><br>For the entire sentence, we are making the vector. First, we will take the frequency of each word. For each word in the vocabulary, if the word is in the sentence, then it will have either 1 or frequency, depending on which method you are using, like binary bag of words and normal bag of words. Disadvantages are again sparse of matrix, order is changed, semantic meaning and out of vocab are problems.</li><li><strong>Term Frequency — Inverse Document Frequency (TF-IDF):</strong><br>This measure is taken to see the relevance of a word wrt the corpus or collection of documents. The measure is calculated by multiplying two terms, which are Term Frequency and Inverse Document Frequency.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*xHjIP-YSaSXaDz0VkGHY6w.png" /></figure><p>Term Frequency computes how frequently the word occurs in each document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X3zS4-zfkh1Ihckxry8e7Q.png" /></figure><p>Inverse Document Frequency computes how important the word is in the entire collection of documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eLyA8Bj8s82Fy0XFXgV6DQ.png" /></figure><h4>Word Embeddings</h4><p>Here, the words are converted into a numerical representation where the distance between each point shows the semantic relationship between them. Embeddings map the words into dense vectors which could capture meaning, semantics, and other relations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*7I5-45RH5D0Cys5kaxNEHQ.png" /></figure><ol><li><strong>Word2vec</strong><br>Word2Vec is published by Google, uses a neural network to associate words with each other to build a collection of embedding vectors.<br>It helps predict the words based on the neighbours (context), and the weights of the hidden layers become the embedded vector.<br><strong>a. CBOW (Continuous Bag of Words):</strong> There will be a window size of words to get trained. Inside that window, size-centred words will be taken as output and others as input. It is faster than skipgram, and it works well with a text that has quite a similar vocabulary.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*sNaycyNFgSN9VlH2Fw2nuA.png" /></figure><p><strong>b. Skipgram: </strong>This is the opposite of CBOW; it takes input as a single word and outputs the context words around it. As the model outputs N training examples from a single word, it captures rare words better than CBOW so it is used for data that has low-frequency words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*SqiHG1M3I41e0NVtbrF0dw.png" /></figure><p><strong>2. GloVe Embedding: </strong>GloVe (Global Vectors for Word Representation), developed by researchers at Stanford. This is an embedding technique that attempts to combine two major familiar models: Count-Based Models and Prediction-Based Models. It focuses on the ratios of co-occurrence probabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/124/1*Tezzd4323UbNFVEX8x9ytg.png" /><figcaption>k represents context and i &amp; j are words</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*u8p6r6qZgpDQmbWDVIgBwA.png" /></figure><h4>N-grams and Context Modelling</h4><p>N-grams are concepts used to model the sequential data and are a simple way to capture local context in language. There are types of N-grams like unigram, Bigram, Trigram and Quadgrams, which basically say how many words or characters are in one token. The unigram model treats ‘ice-cream’ as two separate words ([‘ice’, ‘cream’]), whereas the bigram model treats ‘ice-cream’ as one ([‘ice-cream’]), so that the model understands semantically that it is referring to ice-cream rather than ice and cream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*WYTZRlMfDtYqSuBGswaO4Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64a366d9803e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CycleGAN for Converting Face Sketches to Real Face Images]]></title>
            <link>https://medium.com/@orbinsunny/cyclegan-for-converting-face-sketches-to-real-face-images-8a0ccaffa26e?source=rss-8d6c0d0cb381------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a0ccaffa26e</guid>
            <dc:creator><![CDATA[Orbin Sunny]]></dc:creator>
            <pubDate>Wed, 26 Nov 2025 05:03:24 GMT</pubDate>
            <atom:updated>2025-11-26T05:07:15.728Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello fellow ML practitioner,</p><p>In this blog, you can get a closer look at CycleGAN, which is used to train a Kaggle dataset. So the main prerequisite before reading this is a thorough understanding of the standard GAN. We will be using terms like generator and discriminator, assuming that the reader is already familiar with these concepts. Let’s begin</p><p><a href="https://medium.com/@orbinsunny/hello-to-generative-models-vae-gan-ea9fe5453157">Hello to Generative Models…(VAE, GAN)</a></p><h3>What is CycleGAN?</h3><p>CycleGAN is a variant of GAN used in image-to-image translation tasks. The way it is different is its ability to deal with an unpaired dataset. Now, you might be thinking, what is an unpaired dataset? Think about our problem statement. We are converting sketch images into real images. Each pair of input and its label is from a different domain, so the understanding of the sketch images should be focused on the styles which could be replicated in a real image. CycleGAN as a whole solves this problem. So we will surely get a deep dive into the components of CycleGAN and how it helped the project.</p><h4><strong>Inside the CycleGAN Architecture</strong></h4><p>When we think about the architecture of the CycleGAN, we should explain the generators, discriminators, and the loss functions used. As you can see from the diagram, there are Generators (G, F) and two discriminators. This type of structure makes it cyclic:</p><p><strong>The Generator (ResNet-based): </strong>At first, the input(x) is passed through a generator(G) (usually ResNet), which tries to change the image from domain A(Horse) to domain B(Zebra), and a generator(F) changes vice versa. ResNet is used as the convolutional architecture to preserve the spatial context better, so that the style and domain adaptations are possible.</p><p><strong>The Discriminator (PatchGAN): </strong>There are two main discriminators, which are specialised in their own domain(one in Horse images, one in zebra images). We use PatchGAN inside each discriminator so that it outputs a grid of NxN matrix, where each value corresponds to whether each patch of both images is similar or not, instead of just whether the output is real or fake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U6BwuFR5qmJVyV9JhIOFzw.png" /></figure><h4>Loss Function Summary</h4><p><strong>Adversarial Loss:</strong> The standard GAN loss. Its job is to ensure that the input images and output images look the same. There is a normal Binary Cross-Entropy (BCE) loss and there Least Squares (LSGAN) loss for better gradient behaviour and visual results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jAJGyqkOF2_uLOuhCVbO3w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BWFe7OydmJHj1S_WxWpq8Q.png" /></figure><p><strong>Cycle-Consistency Loss:</strong> If we use just adversarial loss for calculating the</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZ_UAVGcz5Lpv1L-RS2sPg.png" /></figure><p><strong>Identity Loss:</strong> Explain how this prevents the model from changing the color palette too drastically (e.g., if a photo is already a photo, the generator shouldn’t change it).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GLjmVb0DDyCvIeWUNVLvlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hvfmlrrfvDL3XTHFcKa5DQ.png" /></figure><h4><strong>The Dataset: Sketch vs. Photo</strong></h4><p><strong>Domain A (Real Photos):</strong> Domain A contains high-quality face photographs. These images come from the filtered CelebAMask-HQ dataset and consist of 679 photo samples in the test set, with thousands more in the training and validation splits. Each image is clear, front-facing, and free from major occlusions, making it ideal for translation tasks.</p><p><strong>Domain B (Sketches):</strong> Domain B consists of rough face sketches generated programmatically from the corresponding photos. The sketches are created through the following sequential transformations:</p><ul><li>ImageFilter.FIND_EDGES</li><li>ImageFilter.BLUR</li><li>ImageFilter.SHARPEN</li><li>ImageOps.invert()</li><li>ImageEnhance.Contrast().enhance(1.5)</li></ul><p>After generating rough edge maps, the images undergo Sketch Simplification, producing cleaner and more structured sketch-style representations. This gives the dataset a realistic sketch domain suitable for CycleGAN training.</p><h4><strong>Practical Implementation</strong></h4><ol><li><strong>Custom Layers:</strong></li></ol><ul><li><strong>InstanceNormalisation:</strong> In CycleGAN, we use only instance normalisation because, unlike other models, the input is an image, which is converted into feature maps, and the normalisation should be on each image representation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yh5dMRcpQmkjYwLt7Thrbw.png" /></figure><ul><li><strong>Downsample:</strong> It reduces the spatial dimensions while identifying the important patterns and compressing them to a latent space. Here we use a Conv2D layer with strides 2, then an instance normalisation layer and a LeakyReLU activation, mitigating the dying ReLU problem.</li><li><strong>Upsample:</strong> It helps to increase the spatial dimension of the original image size and reconstruct the image from the latent feature representation inside the decoder. It is same as the downsample block with the difference being dimensions and here we added a dropout of 0.5.</li></ul><p><strong>2. Generator:</strong></p><ul><li><strong>The Residual Block (or Skip Connections): </strong>This is a technique used for solving the issue of vanishing gradients. As you can see in the diagram, we will use the weight layers in the middle and pass the input through the layers and over the layers and add both those to give the output.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGTX4IywyfT_IdPMLS0zBw.png" /></figure><ul><li><strong>Build Generator: </strong>The architecture with a convolutional layer, down sampling, residual blocks, upsampling and an output convolutional layer with tanh activation function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gi-UVx9VSvpTUq6fNxqWcQ.png" /></figure><p><strong>3. Discriminator(PatchGAN): </strong>The discriminator takes in the image and using convolutions and downsampling it increases the feature depth with strides. Then, while determining a output which tells an image is fake or real the PatchGAN descriminator gaves a grid of real/fake scores of the patches in the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BpZbDfFFjW4lxlgKLLnbdQ.png" /></figure><p><strong>4. The CycleGAN Model:</strong> Now we have created all the parts we need to build a CycleGAN model. The interesting thing about CycleGAN is that we need to use two generators and two discriminators. There are a bunch of parameters that should be used for each part.</p><p>There are two generators: gen_G and gen_F (one maps Y -&gt; X, the other X -&gt; Y). <br>There are two discriminators: disc_X (for domain X) and disc_Y (for domain Y).</p><p>The train_step computes generator and discriminator losses, gradients them separately and applies four different optimisers.</p><p><strong>5. Training: </strong>The training has been done on reduced parameters because of the weak computational infrastructure. Trained on 10000 pairs of images from the training set and finally saved the model.</p><h4><strong>5. Results and Analysis</strong></h4><p>We prepared a quantitative analysis on the results by taking 100 valuation set images and calculating the FID score, which checks the realism and diversity of the generated images. It scored around 0.6, which is bad, but given the computation limitations we had and the whole project could successfully help to transfer style from one domain to the other is a remarkable achievement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*-_uOJjKKsZTes7S7XL1Uyg.png" /></figure><p><strong>6. Conclusion &amp; Future Scope</strong></p><p>As a recap, the implemented CycleGAN model in Tensorflow translates the style and artistic characters of sketch images to a realistic image, showing the power of adversarial models, which helps hand in hand to improve each other. Finally, it was evaluated on the FID score and thoroughly assessed manually.</p><p><strong>Next Steps:</strong> The major problem we had was the limited infrastructure, so in the future, it could be trained on a high-resolution image having a lot of training time and epochs.</p><p><a href="https://github.com/orbin123/Machine_Learning/tree/main/Deep_Learning/GANs/PROJECT">Machine_Learning/Deep_Learning/GANs/PROJECT at main · orbin123/Machine_Learning</a></p><p><a href="http://journal-iiie-india.com/1_apr_24/5.4_apr.pdf">http://journal-iiie-india.com/1_apr_24/5.4_apr.pdf</a><br><a href="https://engineering.jhu.edu/vpatel36/wp-content/uploads/2018/08/PhotoSketch_FG2018.pdf">https://engineering.jhu.edu/vpatel36/wp-content/uploads/2018/08/PhotoSketch_FG2018.pdf</a><br><a href="https://www.kaggle.com/datasets/almightyj/person-face-sketches">https://www.kaggle.com/datasets/almightyj/person-face-sketches</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a0ccaffa26e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Attention is all you need (in simple terms)]]></title>
            <link>https://medium.com/@orbinsunny/attention-is-all-you-need-in-simple-terms-ee6393956193?source=rss-8d6c0d0cb381------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee6393956193</guid>
            <dc:creator><![CDATA[Orbin Sunny]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 05:10:28 GMT</pubDate>
            <atom:updated>2025-11-17T12:47:10.303Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, fellow ML practitioner,</p><p>This blog will introduce you to the attention mechanism. We will spend enough time diving into the core concepts of the transformer model. If you need to have a really good sense of the following topics, you need to cover some prerequisites like RNN, LSTM, and Seq2Seq. I will only mention these topics, believing that you already have a thorough understanding. Let&#39;s start with the pre-transformer era and how sequential data was processed. A revolutionary architecture was the RNN, which introduced a state mechanism to store the prior knowledge on the sequential data while moving forward. But you have guessed it didn’t have a mechanism to take in useful information and delete unnecessary ones, so LSTMs were introduced, which had 2 states and 3 gates which controlled the flow of the information effectively. But still, it is a rigorous way to do operations on the data, thus resulting in less long-term context. That is when Google DeepMind released a paper, ‘Attention is all you need’, which gave a completely different mechanism called self-attention, later marked as the Transformer architecture, which can train on extensive data, process data in parallel, and give attention to keywords only so that the context can be kept for the long term.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*vM5SITdKxpxg2N0HRwXmLg.png" /></figure><p>Now that we have an idea about the pre-transformer era, we are ready to dive into the topic of Attention.</p><p>The problem with the earlier mechanism, like the Seq2Seq architecture, was, it was computationally costly and static representation of the context. The main thing about attention architectures is, they will provide the decoder with attention input, which is a weight meter to the inputs that have more relation to the next prediction in each timestamp. Imagine we need to translate ‘how are you?’ to Hindi ‘आप कैसे हैं’. In the decoder, the first output will be the word ‘आप’, which has more similarity to the word ‘you’, so the attention input will clearly give more score to the relation ‘you’ while predicting ‘आप’.</p><p>So at each time stamp, a context (c<em>i) </em>is calculated. For calculating it, we need to first calculate the Alignment Score, where s<em>t-1 </em>is the output of the previous state and hi is the current hidden state, and <em>a</em> is a feedforward network that can find the right weight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*kPjBQU333YZx01ocZBHWqQ.png" /></figure><p>That is given to a softmax function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*0lYdrv9zFP1ybsguuEeg6w.png" /></figure><p>Now, Context Vector is computed by a weighted sum of all the hidden states into the Alpha component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*XQJzB1-FYHzCZ54MYW9vRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mi_tFBXjaIoKDiDkR0kmLw.png" /></figure><p><a href="https://machinelearningmastery.com/the-attention-mechanism-from-scratch/">The Attention Mechanism from Scratch - MachineLearningMastery.com</a></p><h3>Bahdanau Attention</h3><p>Before this mechanism, other models used a singles context vector to decode, leading to loss of detail and degraded translation quality. Bahdanau attention (also called “additive attention”) uses a dynamic context vector for each step in the decoder. For every new word, the decoder computes a weighted combination of all encoder hidden states.</p><p>The alignment score is calculated with the measurement of how well the encoder hidden state aligns with decoder’s previous hidden state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*j_qsWx0tkw66ACStZyiTHg.png" /></figure><p>where <em>va</em> and <em>Wa</em> are learnable parameters, and [<em>si</em>−1;<em>hj</em>] is the concatenation of decoder and encoder states.</p><p>Attention Weights is computed by normalizing alignment scores with softmax</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*a9kmlCnhWy8vTzVo1sboQA.png" /></figure><p>After computing these terms you can substitute it to the above Context Vector formula.</p><p><a href="https://www.baeldung.com/cs/attention-luong-vs-bahdanau">https://www.baeldung.com/cs/attention-luong-vs-bahdanau</a></p><h3>Luong Attention</h3><p>It is widely used as an alternative to Bahdanau’s additive attention. Main difference is that instead of using a neural net to compute score, Luong attention use similarity functions of current hidden state and each encoder hidden state. This makes the computation efficient.</p><p>Luong attention computes scores by direct similarity functions (dot product, general, or concat) and uses the <em>current</em> decoder state. Lets see how dot product variants works:</p><p>Score calculation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*elN1gpPSTk0j1vRPaKkVpA.png" /></figure><p>for general form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*jfaQv8Au1zei5qYq5Rqo5w.png" /></figure><p>Here, <em>W</em> is a learnable parameter matrix. Other operations are the same.</p><h3>What is Self-Attention?</h3><p>Now, the problems with full attention mechanisms were that they are not efficient, context-aware, and focus on the input/output pair, which may not have enough context to predict the current prediction. So to solve this, a new attention was introduced, called Self-Attention. This changes the Attention to be more focused on the words before and after it, which are contextually similar and also the similarity of each word to other words changes with the change in the context. Now the question is how? That is what we are going to explain in the next paragraphs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qnPriOMnDFjCEjHaDxBSSQ.png" /></figure><h3>Transformer</h3><p>Before going forward, you should have clarity on how the concepts are explained. It’s really complicated, so what I will do is divide the whole parts into an encoder and decoder, and then further divide it into individual layers, connections, and modules. Looking at the diagram, you could identify the encoder part and the decoder part. I will take the encoder and explain all the nitty-gritty details that make it, and move to the decoder in the same way, because some parts are the same but different in a small way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*-L2Qubd6X7D-5AFTZsbOGA.png" /><figcaption>Nx means there will n number of encoders &amp; decoders.</figcaption></figure><h3><strong>1. Encoder</strong></h3><p>The encoder’s job is to provide context-rich vectors that help the decoder to identify the next word in the sequence. The input goes through embedding, positional encoding, a self-attention head, feed-forward, and normalising to get the final output.</p><p>So, the first part is the input of the encoder,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*zOwgi67FHmLGC4OFWf2-Ow.png" /></figure><h4>1.1 Tokenization</h4><p>Let’s walk through the input part, on how words are transformed into a powerful, context-aware vector, ie the purpose of the encoder. The model takes in words as tokens, which could be words or sub-words. <a href="https://platform.openai.com/tokenizer">https://platform.openai.com/tokenizer</a>-you- You can go to this website to see how words are changed to tokens. Then each token is changed to an integer to create a vocabulary list.</p><h4>1.2 Word Embedding</h4><p>Next is Word Embedding, that are done in two ways to have a semantic relationship between each word. The first way is Static Embeddings(Word2Vec, GloVe), where each vector will have a vector associated with it. These models try to capture the semantic meaning of the words to associate with. ie, why in the diagram left shows a bank near money, but look to the right, here the bank is near to river. This is called Contextual Embedding, which is what the transformer wants because this type of embedding dynamically adapts the embedding to the context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3j-gTRHpLkiFZNGRVBTkPA.png" /></figure><p>There are two types of Contextual Embedding:<br>1. General Contextual Embedding: Embeddings adapt to any text; transferable across tasks (e.g., BERT’s base layers).<br>2. Task-Specific Contextual Embedding: Fine-tuned for particular goals, like sentiment analysis or translation; higher layers specialise for the current objective.</p><h4>1.3 Positional Encoding</h4><p>We know that while training DNN, the position of each datapoint is crucial. The transformer doesn’t process data sequentially like the RNN or LSTM, so the model must be aware of the position of the datapoint. That’s is reason why we add a positional vector to the input vector, so that the model could learn both the context of the data as well as the position of each datapoint. One way is to use the sine and cosine functions for the i(position of input), because if you use a sequence like 1, 2, 3…, N, while normalising, it gives too much variation because N is the number of words used to train.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ob50i9WP_4g4TVcyigtFGw.png" /></figure><p>The transformer paper talks about another equation given below, where position (i) is divided by another term, so that the chance of each positional vector becoming unique increases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*oEyVLlcJRvrcpy1ZYvBKvw.png" /></figure><p>Here, i is the dimension index, and d or d<em>model </em>is the total dimension size<em> </em>of the vector within each embedding vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ep3xMKROrB_UT9T187R5Tg.png" /></figure><h4>1.4 Learnable Weight Matrices</h4><p>Now we convert the encoded vectors into learnable parameters. What do you mean by learnable parameters, which are Query, Key, and Value? The moral of the story is that a query could be seen as “What is the context asking for?”, a key could be seen as “Is the data relevant to the context?”, and value is seen as “I will provide my info to help the prediction”. <br>The vector is passed through three different Linear Layers to give output as Query, Key, and Value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXBbhsuR1p7oyMf6PRQOGQ.png" /></figure><h4>1.5 Multi-Head Self-Attention</h4><p>This is the key module inside a transformer architecture. This is the part where the magic of self-attention happens. Each token is tested against each other to give an output value which represents the context awareness.<br>First, let&#39;s look at how each head operates. Take one input vector, its learnable parameters go through different computations to output a vector that represents the individual attention of the particular input. Likewise, the operation is done for each input, resulting in a list of outputs of the same dimensions as the input. The operation is to get the dot product of the Query and the transpose of the Key to get the Attention score matrix(nxn), which indicates how much attention each token should give to other tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*BM23PW_hBIrzlDKzeSWYDw.png" /></figure><p>Then it scaled down by the square root of the key dimension d<em>k so that the gradient values remain stable. </em>Then applied softmax to the output probability scores, which are taken as the weight attentions related to the tokens. This resulting nxn matrix is multiplied by the value vector. By this, the attention score is calculated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*5MIHBvowwv8cxk1Q9G2zPw.png" /></figure><p>The diagram below shows how one particular instance of Q, K, &amp; V go through one self-attention head.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N-MCq2eTwCugONAhM2FDpw.png" /></figure><p>Now we can look at the diagram and identify how the matrices of Q, K &amp; V are passed through the multi-head self-attention in parallel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQidUry6kIAmZq_8sosV1g.png" /></figure><h4>1.6 Residual Connection</h4><p>Residual Connection in the transformer is to address the issue of vanishing gradient. It allows the information to skip layers and add it to the processed output, then normalises. This mechanism helps the model to learn without losing content while having deep networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*WNGdunP-3GJDXn8f7d2q3Q.png" /></figure><h4>1.7 Layer Normalisation</h4><p>Normalisation is done in a transformer to make the model more stable, because while processing too many layers at once, there is a chance that some of the results of the network will deviate from a normal range. This is called the internal covariate shift. By normalising, the values will become consistent, which helps the model to converge faster.</p><p>First, let&#39;s look at batch normalisation, which is popularly used but not used inside the transformer. You will know why in just a minute. Take the column-wise means and standard deviations of the dataset, next find the normalised value and calculate the final value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*bEcCGScxHpqWysnWxgqFlQ.png" /><figcaption>For LayerNorm mean and std is row-wise</figcaption></figure><p>Here the normalised value is calculated using the mean and standard deviation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*re2wfKSLDIxluzOe0L_PQQ.png" /></figure><p>Then the final value, which replaces the original value, is calculated while training, so the alpha and beta are trainable parameters.</p><p>The main reason batch normalisation never works with the transformer is because of the padding that we gave to the input sequence. Look, the transformer mostly deals with sentences where one sentence could have 10 words and another could have 5, so for proper representation as matrices, the second sentence uses padding means it will add 5 zero-valued vectors to level up with the first sentence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZMVtcicGb4A1bbQVKqtKA.png" /></figure><p>In this representation, we can see that column-wise over the batch dimension and row-wise is over features. If the normalisation is applied column-wise, because of the zeros, it could mislead the model about the information. So, for sequential or parallel style processing, the better option is LayerNorm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wkT7cTCpepV-N-VMrW7s5w.png" /></figure><h4>1.8 Feed-Forward Network</h4><p>Right after doing normalisation to the Multi-Head Self-Attention’s output, the data is passed to a Feed-Forward Network, which consists of 2 Linear layers, the first one with an activation function which could be ReLU or GeLU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*OggHRnsgHxZfjHK52u_mPQ.png" /></figure><p>In the equation, the first linear layer is passed through an activation function, then again processed with another linear layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_SeUNxn-uxI_muFLKXaiYw.png" /></figure><p>This diagram shows how the input is processed through each layer. First, the input data is fed to a massive neural network with 2048 neurons(always approximately around 4x the model’s dimension), which is to make the input ready to give out complex details and depth while doing forward propagation. The activation function could either be ReLU or GeLU(<a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.GELU.html">https://docs.pytorch.org/docs/stable/generated/torch.nn.GELU.html — using GeLU is for getting smoother differential and avoiding a dying ReLU situation)</a>.</p><p>Now the output of the 1st Layer is fed into the second Linear Layer, which outputs a vector similar to the input vector dimensions. This layer is for projecting the non-linear findings of the first layer back to the original dimensions. Then, to that output, the residual connection is again applied.</p><h3>2. Decoder</h3><p>The decoder is the part which takes contextual vectors from the encoder and outputs something that has context and meaning. Compared to the encoder, the parts are pretty similar, but there are some differences that are going to be discussed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*9k-Jxl3BjPB_sR78dg5ryA.png" /></figure><h4>2.1 Output Embedding &amp; Positional Encoding</h4><p>Starting with the input part, here also, you start with tokens, which are converted to output embedding. From the diagram, you can see that the input given to the decoder is the truth labels, which instruct the decoder that it should output when the encoder gives some input. But we have to consider two ways of thinking about the decoder: its training period and inference period. We now look at how training is done.<br>The main difference from the encoder&#39;s input portion is about the output embedding, where the target sequence is shifted right once and often starts with a start token. During the inference time, the current output of the decoder is again added to the target sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lcA3XHGWkwhgHoNhp3iI_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3JDQMGuAYK-XNoNu9kheg.png" /></figure><h4>2.2 Masked Multi-Head Self-Attention</h4><p>This is the first layer in the decoder blocks, which lets in the output embedding as transitioned to Query, Key, and Value. As you have noticed, the name has a masked portion, and that is the main part of the difference from the standard encoder self-attention layer. The masking helps the block to intake the vectors which do not relate to the future tokens. So, it&#39;s masking the relation score of future tokens with the current token using -negative infinity (later will go through the softmax function and become zero), that the model will only learn from the input tokens and predicted ones, in turn, results in predicting the next word effectively without overfitting.</p><p>The score calculation and scaling part is the same, from there it is added to a masked matrix with perfectly placed — infs, next, like the standard way, it is passed to a softmax, where if softmax is applied to a negative infinity, it will result in zero, thus the coordinates which show the relation with the future tokens are neglected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-UiJGMG7HT0hMd3PszJYnQ.png" /></figure><h4>2.3 Cross Multi-Head Attention</h4><p>Cross Attention is used to draw a relationship between two different sequences. In the case of transformer one sequence will be the input sequence and the other will be the output sequence up until the next word to predict. So it takes input from both the encoder output and masked self-attention output. The layer gets its learnable parameters from both sources in order to have an idea about what we should predict and how we should generate it. That’s why:<br>Query comes from the decoder’s masked self-attention layer<br>Key and Value come from the encoder&#39;s output, which acts as a source of info into what makes a new word.<br>After finding the Q, K and V, every step is the same as the standard self-attention layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hmsQIWFP57oUxRGYVOOs3Q.png" /></figure><h4>2.4 Feed-Forward &amp; Normalisation</h4><p>For the feed-forward layer inside the decoder, it is architecturally similar to the encoder. Conceptually, the difference is to find a nonlinear relationship by fusing the input from the encoder and the self-attention layer to an integrated contextual information that helps the linear layer to identify the position of the correct embeddings of the predicted output.</p><p>Layer Normalisation is similar to the encoder, but crucial here to carry the flow of information forward because it travels through</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HxwgOjzUzYHYWndCqt0iig.png" /></figure><h3>Transformer Inference</h3><p>You now have an understanding that the main difference between training and inference is that in training, the model is trained on true labels, but for inference, it needs to use the previous prediction and input to predict the new word. At the inference time, the model uses its own ability for prediction rather the depending on truth labels to teach it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8nfkvFAwk88uJo4kwa5lEg.png" /></figure><h3>Applications of the Transformer</h3><p>Transformer has many applications in the space of Natural Language Processing, Computer Vision, Multimodal Learning, Code Completion and Generation tasks, Scientific Research, Recommender systems, and Decision Transformer.</p><p>In the field of NLP, types of transformers are used:<br>1. Machine Translation: Google Translate, DeepL<br>2. Text Generation: GPT-2, GPT-3, Llama, Mistral for generating articles, stories, and conversations. <br>3. Text Summarisation: BERT, T5<br>4. Q/A: BERT, RoBERT, ALBERT</p><p>In the field of Vision: <br>1. Vision Transformer(ViT), DeiT, VLM<br>2. Object Detection: DETR<br>3. Image Generation: Diffusion Models, Stable Diffusion</p><p>In the field of Multimodal Learning:<br>1. Vision + Language: CLIP, Flamingo, <br>2. Speech Recognition &amp; Generation: Wav2Vec, Speech Transformer</p><p>In the field of AI coding: <br>1. Codex (OpenAI), CodeBERT, StarCoder</p><p>In the field of Scientific Research:<br>1. AlphaFold and ESMFold for Protein Folding and structure prediction<br>2. Modelling DNA/RNA sequences</p><h3>Evaluation Metrics</h3><p>Transformers evaluation changes according to the areas where it is used.<br>If the model&#39;s task is to do Sentimental Analysis, Named Entity Recognition, etc, you could use Accuracy and for data that has imbalance and is multi-classed, evaluations like F1-Score, Precision, &amp; Recall matter. But for other applications, the metrics change.</p><h4>NLP Tasks:</h4><ol><li><strong>BLEU (Bilingual Evaluation Understudy): </strong>This is a score for a machine translation task. It is calculated by comparing the n-grams(sequence of words) of machine-translated sentences to the n-grams of human-translated sentences.</li></ol><p><a href="https://www.geeksforgeeks.org/nlp/nlp-bleu-score-for-evaluating-neural-machine-translation-python/">NLP - BLEU Score for Evaluating Neural Machine Translation - Python - GeeksforGeeks</a></p><p>2. <strong>ROUGE (Recall-Oriented Understudy for Gisting Evaluation):</strong> It is used to evaluate text summaries. It works by comparing the overlapping n-grams between machine-generated and human-written reference summaries.</p><p>3. <strong>Perplexity:</strong> It is used to check the model&#39;s prediction quality of the next token. The lower, the better.</p><h4>Efficiency and Scalability:</h4><ol><li>For these transformers which are trained on large dataset which comples networks and architectute the time taken for inference and training is also an evaluation measure. It is better to find the sweet spot where the model is complex enough to understand non-linear patterns, as well as to reduce the model size as much.</li><li>There is also an evaluation for high robustness, less computational cost, checking the carbon footprint, and energy consumption.</li></ol><h4>Tools for Evaluations:</h4><ol><li>NLP benchmarking testers like GLUE, SuperGLUE, SQuAD, and WMT use textual data to help with evaluation. GLUE and SuperGLUE assess a model’s general understanding of the language. Whereas SQuAD is for extractive question answering. WMT assess the accuracy and fluency of translations across multiple languages.</li><li>For Computer Vision, there are ImageNet, which is often used to test a model’s ability to classify images into one or more of a thousand categories, and COCO(Common Objects in Context) tests a model’s object detection, segmentation and captioning abilities.</li></ol><h3>Advanced Transformer Models(BERT, GPT-3, T5)</h3><ol><li><strong>BERT (Bidirectional Decoders):</strong> It is a transformer model developed by Google to simply understand the context of a text input, considering both left-to-right and vice-versa context using self-attention (thus bidirectional). This model has made a significant impact in the field of NLP.<br>BERT is an encoder-only model, so its main aim is to create a rich vector representation for each word in the input. So it is not a generation model; instead, it is used mainly for Natural Language Understanding tasks like Named Entity Recognition and sentiment analysis. BERT is also used in the Google search engine to be more contextually aware of user queries. The final doubt would be how it is predicting words, the answer to it is just that the encoder architecture is connected to a Classification layer at the end.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VKMeA_LYYa_alLU4D7ARAA.png" /></figure><p>2. <strong>GPT-3 (Auto Regressive Decoders):</strong> This is also a transformer-based model used to make predictions on input text, relying on masked self-attention developed by OpenAI. The main aim of this model is to generate good text output from trained text. It is a Decoder-only model which takes input tokens and trains them using masked layers, so it learns in a better way to make the next prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIWct2853HaXcpQ0bgSPxA.png" /></figure><p>3. <strong>T5 (Transfer Learning with a Unified Text-to-Text Transformer): </strong>The main idea is that we use text as input and text is given as an output, introduced by Google. It is predominantly used for translation and classification tasks. The architecture is based on a standard transformer with both encoder and decoder. T5 is trained on the C4 dataset and has variants ranging from 60M to 11B parameters.</p><ul><li><a href="https://towardsdatascience.com/a-complete-guide-to-bert-with-code-9f87602e4a11/">A Complete Guide to BERT with Code | Towards Data Science</a></li><li><a href="https://en.wikipedia.org/wiki/GPT-1">GPT-1 - Wikipedia</a></li></ul><h3>Practical Challenges and Optimisation</h3><p><strong>Common challenges in training and deploying Transformer models:</strong><br>1. Lack of Standardization: The Transformers benchmark and architecture differ across the domain, tasks and industries it is used. These fragmented results make the model harder to interpret. <br>2. Trade-offs Between Accuracy and Efficiency: To attain high accuracy, the challenge is to have a complex structure and give a large dataset, which makes computation costlier, so the researchers and practitioners find it hard to fit it with optimal parameters to the demand.<br>3. Demand for pre-train, train, post-train.<br>4. Data Bias: if the model is trained on biased data and it is not properly checked, then it could amplify or misinterpret the bias in the wrong way.<br>5. Harder to reproduce.</p><p><strong>Techniques for optimising and scaling Transformer models:</strong><br> 1. Softening the target: We will do label smoothing by setting the target vector like [0.025, 0.025, 0.925, 0.025] instead of [0, 0, 1, 0]. <br>2. Warmup: Gradually increasing the learning rate at the start of training and increasing it slowly across the journey.<br>3. Weight Decay(L2 Regularisation): Penalises excessive parameters to increase generalisation.<br>4. Knowledge Distillation: it is like a big model(teacher) trying to teach a smaller model(student) so that it does not require the same amount of compute at training and inference. <br>5. Dropout: it is randomly turning off some neurons so that the other neurons could have more area to learn.</p><p><a href="https://futureagi.com/blogs/evaluating-transformer-architectures-key-metrics-and-performance-benchmarks">Evaluating Transformer Architectures: Metrics &amp; Benchmarks</a></p><h3>Finetuning in Transformers</h3><p>Finetuning involves several components, like: <br>1. Pre-Trained Model: The starting point for fine-tuning is a pre-trained transformer model like BERT, GPT, T5, RoBERTa, and DistilBERT. This model is already trained on a diverse dataset, so it lays the foundation for specific learning.<br>2. Task-Specific Dataset: <br>3. Optimiser: Optimisers like Adam or AdamW are used to update the model’s weights during fine-tuning. These optimisers ensure efficient training.<br>4. Hardware: Fine-tuning requires computational resources like GPUs or TPUs<br>5. RAG- Retrieval Augmented Generation</p><p>I invite you to connect with me on LinkedIn: <a href="https://www.linkedin.com/in/orbin-sunny/">https://www.linkedin.com/in/orbin-sunny/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee6393956193" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello to Generative Models…(VAE, GAN)]]></title>
            <link>https://medium.com/@orbinsunny/hello-to-generative-models-vae-gan-ea9fe5453157?source=rss-8d6c0d0cb381------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea9fe5453157</guid>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[generative-model]]></category>
            <dc:creator><![CDATA[Orbin Sunny]]></dc:creator>
            <pubDate>Sat, 01 Nov 2025 02:13:17 GMT</pubDate>
            <atom:updated>2025-11-12T11:47:21.039Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello fellow ML practitioner,</p><p>If you are starting on Generative Models like VAE, GAN, this is the perfect blog to get an introductory idea of the domain. Why are Generative Models particularly famous? We have all learned by now that models work on some training data labelled with classes or numbers, which helps them to identify the pattern and make correct predictions on unseen data. While Generative Models do train on training data with or without labels, it is not used for predicting new instances; their job is to generate similar kinds of inputs widely adopted for image and sequential data. <br><a href="https://this-person-does-not-exist.com/en">https://this-person-does-not-exist.com/en</a><br>If you visit this website you will get an idea of how Generative Models work. The site will generate new faces that never existed before, and you could never tell any difference. Let&#39;s understand what is happening in the background of these models, starting with Autoregressive Models.</p><h3>1. Autoregressive Models</h3><p>These models are used for generating new text, images, forecast time series, and so on. The peculiarity of the model is that it learns the data pixel by pixel or text by text(depending on the data) to generate the output with similarities. Each sample is processed sequentially, so the next prediction requires the contextual awareness of the previous samples.</p><h3>2. Variational Autoencoders (VAEs)</h3><p>Variational Autoencoders have three main parts: Encoder, Latent Space, and Decoder. It works by taking in the input image to the encoder, whose duty is to compress the original image to a Latent Space. Data of the image is not compressed to fixed points; rather, it is represented as the probability distribution in the Latent Space. The Latent Space organise the crucial features of the input data in a low-dimensional space, for the decoder to reconstruct. The decoder is learned to reconstruct the latent space given the source from a Gaussian distribution. This helps in learning the image&#39;s key features rather than the image itself, so the decoder tends to output entirely different images with realism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*MqNiuGXL1PQJkQkvAsCGhA.png" /></figure><h4>i. Forward Propagation</h4><p>Now, let&#39;s get a deep dive into the forward pass that happens in a VAE’s architecture. First, take a sample of data, which is a 28x28 pixel array flattened into a single vector. Now this data is fed to an encoder network(eg: CNN) that outputs two vectors, which are the depiction of the distribution of the input data. One is the mean, and the other is the log variance, which creates the fuzzy region required for the latent space to take samples from.</p><figure><img alt="Linear transformations of the input" src="https://cdn-images-1.medium.com/max/654/1*Byp5a2CuZ5qQDowX5QwA8g.png" /></figure><p>We are taking a specific point from the encoder&#39;s output to pass on to the decoder, but it is not picked randomly. For finding the sampled point, there are three variables to be calculated. One is a vector of random noise from a standard normal distribution (mean=0, standard deviation=1). The second variable is for scaling this random noise, ie taken as the learned standard deviation. Thirdly, it&#39;s added to the learned mean, which makes the equation Sampled Point (z) = Learned Mean + Learned Fuzziness * Random Noise . This process is called sampling with reparameterization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*UWWZ1dI0DEkMKwFyw9s7bA.png" /><figcaption>Equation for the Sampled point</figcaption></figure><p>This outputs a single sample vector which resembles most of the features of the input data. The vector is fed into the decoder, whose job is to upsample or reconstruct the original image from the sampled vector and that gives the output image(x-hat).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*PXarkAAHlstU0c5dxgSeoA.png" /></figure><h4>ii. Backward Propagation</h4><p>We have entered the part where we have to calculate the overall loss that occurred while predicting the output. This part is also slightly different from the other model architectures you have seen. There are two losses to be calculated and added as the final loss. There is a reconstructed and a KL-divergence loss that are added to get the total loss.</p><p>Let’s look at why we need two losses. The first loss is the reconstructed loss, which is similar to the normal loss that could be Mean Squared Error or Binary Cross-entropy. This is calculated to identify the difference between the output image (x-hat) with the input image (x). So it will calculate pixel-by-pixel difference of the input and output image using any of the loss functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*fCxGmYfvM0GWQrmQo5oQYQ.png" /></figure><p>Next is the KL Divergence loss, which is to teach the encoder to produce a latent space whose mean is 0 and standard deviation 1. Without this, the latent space will become chaotic, and nearby latent space points will be entirely different, obstructing the smoothness in learning the meaningful features in an image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*_qUZHMJL5kCKxm8L1EOeiQ.png" /><figcaption>learned distribution of the encoder</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*NDdFJv39Ll2ybzCbECaJAw.png" /><figcaption>Simple Gaussian Distribution</figcaption></figure><p>The KL Divergence Formula,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*SOE_QXvEcSuEVbEZKk7ccQ.png" /></figure><p>Adding both KL Divergence and Reconstructed Loss gives the total loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*KyBExXo-an5_lwBU1yQZ-g.png" /></figure><p>The final objective of the backward propagation is to calculate the gradients to update the weights. Here, we need to update the weights of both the encoder and the decoder in order to minimise the loss. So we apply the chain rule to the loss w.r.t every parameter.</p><p>We have already calculated the reconstructed loss, the KL Divergence loss, and the total loss. Now with those losses, we need to calculate the partial derivative w.r.t the weights and biases in the Decoder and Encoder. The difference here is that the decoder is derived using the reconstructed loss, but for the encoder, we use both losses. Why is it? In the case of the decoder, reconstructing an image means the output only depends on the loss gradients, like normal models. But for the encoder, which is creating a latent space, it depends on both the loss gradients and the loss in the properties of the distribution(mean and standard deviation). Hence, to compute gradients of encoder parameters, you need to find the sum of reconstructed loss through reparameterisation of z and the KL Divergence loss w.r.t the mean and the log-variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*485dftwtQ_Yl8VGOk1Qptw.png" /></figure><p>After calculating the gradients, they can be subtracted from the previous weights and biases, thus completing the descent.</p><h4>iii. Evaluation metrics of VAE models</h4><ol><li><strong>Reconstruction Loss:</strong> We have discussed it. It is the measurement of how well the model has reconstructed the image from the input x in latent space.</li><li><strong>KL Divergence: </strong>This we have also discussed. It is a measurement of how much the latent distribution deviates from the prior distribution(normal distribution)</li><li><strong>ELBO (Evidence Lower Bound): </strong>This measurement is a topic in itself, but in the case of VAE, it can be used as a training loss. When training VAE, it will look at the ELBO score because it forces the reconstruction of the image to be accurate and punishes the encoder if it breaks the simple and organised bell curve of the latent space. However good ELBO score does not mean good outputs because there is a trade-off between the two terms.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*hevt8YC4Om4_w7mubvC9vw.png" /></figure><h3>3. Generative Adversarial Networks (GANs)</h3><p>When it comes to Generative Adversarial Networks, there are significant architectural differences from a normal model. Ian Goodfellow, the man who invented GANs, designed it in such a way that instead of the usual Encoder and Decoder, there are Discriminator and Generator, each with a really unique functionality. Before that, let&#39;s explain the G and A in GANs. The model is generative because it generates new data, and it is adversarial because the generator and the discriminator compete with each other to make each other better. Now, if you observe the diagram below, you can find where the generation and competition happen. Here, the input file gives real data x, and the Generator generates fake data that resembles real data, which is x-hat. When both datasets are fed into the Discriminator, it identifies whether fake data is really fake or not. So the competition is when the generator tries to create data that could fool the discriminator as real, and the discriminator tries harder to learn real vs fake data. Then, over time, the generator creates data that are indistinguishable from the real data and fools the discriminator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJy32WuGyBhd7Z2Wb4YzWw.png" /></figure><h4>i. Forward &amp; Backwards Propagation</h4><p>First, you need to understand that generative models see data as a probability distribution, so we could see terms like:<br><em>p_data:</em> represents the real data distribution.<br><em>p_z:</em> represents the initial random distribution that makes z. <br><em>p_g:</em> represents the distribution of the generated data.</p><p><strong>Generator Pass: </strong>from the p_z, a random vector (z) is taken, then fed into the generator, which maps into an image-like output that has the shape of the real image. The generator’s layers upsample the low-dimensional noise into the high-dimensional, structured output that creates the p_g.</p><p><strong>Discriminator Pass: </strong>discriminator takes two inputs, which are fake(p_g, 0) and real data(p_d, 1), which are sampled from the p_g and p_data, respectively. Then their individual loss is calculated as real_loss and fake_loss.<strong> </strong>We use Binary Cross-Entropy for calculating it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*MowgFcw2U_kWf3bz2uw6Ig.png" /><figcaption>eq for calculating real &amp; fake loss</figcaption></figure><p>Then, from real loss and fake loss, the total loss is calculated and used for gradient descent of the discriminator’s layers. After the gradient descent, the weight updated discriminator again takes the fake sample with label as 1(p_g, 1). So the fake sample is given the label that it&#39;s real, so that we need to check whether the discriminator could be fooled. The output is then compared with 1(which means even if it&#39;s fake data, it should be close to 1), and that is how the loss is calculated. This loss is taken as the generator loss, and the gradients of the generator are calculated to update its weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*G1p8TbqWNnZYUQO10Wq_dw.png" /></figure><h4>ii. Evaluation metrics of GAN models</h4><ol><li><strong>FID(Frechet Inception Distance): </strong>It measures the similarity of the statistical fingerprint of both real and fake images. It calculates the features of fake and real images and summarises them into two statistical distributions using the inception classifier. Then it calculates the distance (the Frechet Distance) between both and averages it, so the lower the distance, the better the similarity.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*tHESdZGTyzDL3TL_w3MjNQ.png" /></figure><p><strong>2. IS(Inception Score): </strong>This metric is used purely for evaluation. It focuses on how realistic and diverse the image are your fake images are. The way it works is by using a pretrained classifier (inception-v3) to measure the confidence of an image in its label. The more the measure, the better the generation. It measures how individual clarity is from overall diversity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*U7fVutrpm2CFBaEB43A9Xg.png" /></figure><p><strong>3. Precision and Recall for Generative Models: </strong>As we all know, Precision and Recall are used in Classification problems where you have true labels and the output also matches these labels, so they can be classified easily. But in the case of a generative model, the output is not entirely the same as the data it was trained on or the labels used; it&#39;s a new synthetic generation. So the precision can only check how real the generated image is compared to the training data, and recall to check, out of all the variations in the training data, how much the generated images could capture. However, the good part is that these kinds of analysis can’t be measured using other scores; that’s why using precision and recall for analysis gave us more context to check common failures like mode collapse.<br><a href="https://research.nvidia.com/sites/default/files/pubs/2019-12_Improved-Precision-and/kynkaanniemi2019metric_paper.pdf">https://research.nvidia.com/sites/default/files/pubs/2019-12_Improved-Precision-and/kynkaanniemi2019metric_paper.pdf</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*c-Hz-oveYRIQCPx6GvmI8w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*J3wJubhr8-YCmKaRau59kg.png" /></figure><p><strong>4. Perceptual Path Length (PPL): </strong>It is introduced to quantify the smoothness of the latent space changes. It focuses on how changes in the latent code could result in a corresponding change in the output image.<strong><br></strong>A <strong>low PPL</strong> means the GAN’s latent space is smooth — tiny changes in input cause small, realistic changes in the output.</p><p>A <strong>high PPL</strong> means the latent space is messy — even small input shifts cause big, unnatural changes in the image.</p><p>If you need further clarification, read: <a href="https://apxml.com/courses/generative-adversarial-networks-gans/chapter-5-evaluation-of-gans/perceptual-path-length-ppl">https://apxml.com/courses/generative-adversarial-networks-gans/chapter-5-evaluation-of-gans/perceptual-path-length-ppl</a></p><h3>Types of GANS (DCGAN, CGAN, WGAN)</h3><h4>1. Deep Convolutional GAN (DCGAN)</h4><p>Vanilla GAN has two main problems, mostly for images: First, it is extremely unstable because there is always a chance that either the generator or the discriminator learns miles better than the other. Secondly, if it&#39;s image data, it never focuses on the spatial features of the data. So, we combine CNN with GAN to make DCGAN(meaning replacing most of the dense layers with convolutional layers). But there are other rules too:<br>a. Unlike normal convolutional networks, which use a pooling layer to downsample, we use a convolutional layer with strides &gt; 1.<br>b. For upsample, we use a transposed convolutional layer that learns the best way to convert the latent variable to a large-size output.<br>c. We do batch normalisation between most of the layers in both the generator and the discriminator. <br>d. The activation functions are crucial. For the generator, we use ReLU for hidden layers and tanh for the output layer. Then, for the discriminator, we use LeakyReLU for all the layers because it keeps the training alive, and it allows even small values to pass instead of zero.</p><h4>2. Conditional GAN (CGAN)</h4><p>CGAN is a specialised type of GAN for generating desired output because we gave it the labelled input. Imagine we train the GAN with car images, and we specifically want to output the Ambasador car, that is when we use CGAN, which allows us to output precise and targeted data.</p><p>Here is how you gave inputs to the generator and the discriminator. For the generator, the input is (z, y), and for the discriminator, the input is (x, y), where y is the conditioning you gave, like the input photo is an Ambasador.</p><p>Some of the real world examples:<br>a. StyleGAN: It can used to generate new synthetic images, speech, etc… where the style, tone, shape, theme, texture… of the input data matters to be captured by the network. <br>b. GauGAN(NVIDIA): This can be used for architecture design, games, design, etc, because it allows for generating photorealistic images conditioned on the required setting. <br>c. PixPix: is a well-known CGAN for image-to-image translation. Given sketches, it makes realistic images.<br>d. StackGAN: uses conditional information like text to generate images.</p><h4>3. Wasserstein GAN (WGAN)</h4><p>First, let&#39;s lay some foundation on WGAN because it&#39;s more of an underlying mathematical change rather than changing some parameters or layers. We know that Generative Models work with probability distributions, which is why we have to use the KL Divergence in VAE’s case and the Jensen-Shannon (JS) Divergence in GAN’s case. Now, the idea of WGAN started in order to solve the problems that these equations faced. The first problem is that KLD and JSD are measured equating the vertical distance between two distributions, which won’t be justifiable in some scenarios, so we have to use optimisers. The next problem is that loss measurement ranges badly when the two distributions don’t overlap, as you can see in the figure, and then also the JS gradients get stuck at the local minima, so it will have problems of vanishing gradients and instability. That is where the Wasserstein GAN uses EMD(Earth-Mover Distance).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNTeYIogUzDWKz6lp8BmtA.png" /></figure><p>Conceptually, imagine two piles of dirt (distributions). The Earth-Mover distance is the minimum work required to move mass from one pile to match the other. Here, the focus is more on the horizontal gap between the distributions.</p><p><a href="https://www.alexirpan.com/2017/02/22/wasserstein-gan.html">https://www.alexirpan.com/2017/02/22/wasserstein-gan.html</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*B7VRUdDVMFxFiUQidiGKEw.png" /></figure><p>Notable changes in the equation are that the output is like a score, it could be -1000 or 800, so that there is always room for improvement (that is the reason it is tagged as a critic instead of a discriminator). Keeping the critic’s loss stable, we enforce a Lipschitz constraint on it. In two ways, the continuous values of the loss are constrained. First is by using weight clipping, where the loss is forcibly clipped to the predefined range. This ensures the critic is a 1-Lipschitz function, meaning the gradient never exceeds 1. But clipping has drawbacks such as poor training, vanishing or exploding gradients and difficulty in adding depth to networks.</p><p>That is where a new approach called Gradient Penalty comes into picture, the GAN model itself is called WGAN-GP. Instead of clipping, a penalty is added to the loss if the gradient norm deviates from 1. This is a much more stable approach to even satisfy the Lipschitz constraint without producing inconsistent losses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*c-TZ6StbAQ-HvDv0nEbzwA.png" /></figure><h3>Applications of these models</h3><ol><li>Augmentation of the existing data for training the models to predict more robustly.</li><li>Generate new human faces.</li><li>Generate new photorealistic images of new scenes, objects, or landscapes.</li><li>Image-to-image translation, like an artistic image to a photorealistic image.</li><li>Semantic-to-image, like text or description to image, or other types of visual constructs to images.</li><li>Super Resolution, which turns blurry or eroded images into high-resolution images.</li><li>3D images from 2D images.</li><li>Photo inpainting, which is fixing images by correcting damaged parts or adding more visuaul elements.</li></ol><h3>Challenges and Optimisation in GANs</h3><h4>Challenges:</h4><p><strong>Mode Collapse:</strong> It is when a generator fails to identify the underlying variation of the data distribution, or maybe even concentrates on a few variations of the data; it is called mode dropping. This may fool the generator into thinking that it is doing a great job when it is not. There is also a question of whether the model can capture the variations that are present in the data.</p><p><strong>Non-Convergence (Oscillating Loss):</strong> This is when the generator and the discriminator are going for an arms race. Both are learning exceptionally well that the generator could not catch up with the discriminator in order to fool it. In order to mitigate this issue, we usually set the learning rate of the discriminator slightly lower than the generator.</p><p><strong>Hyper-sensitivity:</strong> GAN is sensitive to all the parameters, architecture choice, data distribution, etc, and there are no proper metrics for identifying each problem first-hand.</p><p><strong>Inconsistency:</strong> without proper setup, like looking for the best optimisation and penalising algorithms, the calculation of loss could deviate unpredictably.</p><h4>Optimisations:</h4><ol><li>Using different loss function terms like the KL-divergence, JS-divergence, and Moving-Earth Distance to check for better performance.</li><li>Using different types of generative models like VAE, GAN, CGAN, DCGAN, and WGAN for fitting use cases.</li><li>Label Smoothing is a technique where we give the label of whether the data is fake or real, as an approximate value closer to 1 or 0 (It could be 0.98, 0.88, etc… instead of 1 and 0.1, 0.3, etc… instead of 0).</li><li>Adding noise to the input data so that the generator struggles to generalise usually makes the model more robust.</li><li>We intentionally make the discriminator converge faster and the generator slow so that the generator can catch up with the discriminator, after the discriminator learned to classify better.</li></ol><h3>Transfer Learning in Generative Models</h3><p>Transfer Learning in GM is about using pretrained models to again train on task-specific datasets, so that the amount of computation is less, and the new model will have a more diverse understanding than its dataset. <br>There are models like ImageNet for images and GPT or BERT for text, which are equipped with generic understanding. For GANs, it&#39;s usually the need to update the generator or, in some cases discriminator too for learning specific features of the new data (e.g StyleGAN on someone&#39;s artwork).</p><p>I invite you to connect with me on LinkedIn: <a href="https://www.linkedin.com/in/orbin-sunny/">https://www.linkedin.com/in/orbin-sunny/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea9fe5453157" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The One Bottleneck of AI]]></title>
            <link>https://medium.com/@orbinsunny/the-one-bottleneck-of-ai-0bd0ab3a8b29?source=rss-8d6c0d0cb381------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bd0ab3a8b29</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[overcoming-challenges]]></category>
            <category><![CDATA[uncertainty]]></category>
            <dc:creator><![CDATA[Orbin Sunny]]></dc:creator>
            <pubDate>Wed, 22 Oct 2025 17:16:23 GMT</pubDate>
            <atom:updated>2025-10-22T17:17:17.493Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*50NQtzmFiOTFNDGJijEORQ.jpeg" /></figure><p>From 2020 onwards, humanity has been promised AGI or Super Intelligence. But the ground reality is always disappointing. In this blog, we can together see why it is the case.</p><p>We all know the revolutionary paper ‘Attention is All You Need”, which started all this hype around AI(Actually, it&#39;s ChatGPT). Investors started pumping billions, Big IT firms started backing off from projects, and shifted their focus. There are many channels and media like this putting content around AI. Now every advancement in AI has more stakes than ever. But it&#39;s believable that the claim for AGI or superintelligence may not come from a chatbot or diffusion models.</p><p>To understand this, we should go back to the early days of Neural Networks. Every training that we see for any of the models follows the principles of Neural Networks, which have weights and biases which get adjusted during training and could deliver predictable outputs. This is the thing that mimics the human brain, but that&#39;s where the problem lies. It’s true that humans rely on neuron firing to store, process, and make decisions on data that we see, hear, and feel. But it&#39;s something more beyond our scientific understanding. When we think about something, there is something uncertain that is happening in our brain that takes the prior data (memory), combines it with experience, and behaves according to the survival principles ingrained in our DNA to produce some output.</p><p>This is the bottleneck I was talking about. AI cracks the part of using prior data (in that case, too much dependence on data), but stumbles on a system that could collect experience and intellect, which is something unique to humans (or animals). In humans, it&#39;s probabilistic; when we decide something, it could be more dependent on the memory, experience or survival triggers. But for machines, it&#39;s always stats and stats deny the part of uncertainty. My belief is that when we find a way to map uncertainty, we could map the brain in full, and for that, we need to think outside the box. Instead of plotting everything in an x and y plane, think of the plane itself as changing in nature. That&#39;s the uncertainty that gets mapped in that moment.</p><p>In conclusion, I am delusional in thinking, but the thoughts get me to places where the empirical world can’t reach. I believe that the theory of uncertainty could bring peace to this chaotic world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bd0ab3a8b29" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>