<?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 Tahasin islam on Medium]]></title>
        <description><![CDATA[Stories by Tahasin islam on Medium]]></description>
        <link>https://medium.com/@tahasinahoni2?source=rss-7b3109fc909a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8C6BJEYDUrgmfAaX2G15Hg.jpeg</url>
            <title>Stories by Tahasin islam on Medium</title>
            <link>https://medium.com/@tahasinahoni2?source=rss-7b3109fc909a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 15:38:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tahasinahoni2/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[My Map Looks Terrible ! Here’s how I fixed it]]></title>
            <link>https://medium.com/@tahasinahoni2/my-map-looks-terrible-heres-how-i-fixed-it-be2861c7ec5a?source=rss-7b3109fc909a------2</link>
            <guid isPermaLink="false">https://medium.com/p/be2861c7ec5a</guid>
            <category><![CDATA[bangladesh]]></category>
            <category><![CDATA[mapping]]></category>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[urban-planning]]></category>
            <category><![CDATA[arcgis-pro]]></category>
            <dc:creator><![CDATA[Tahasin islam]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 15:38:54 GMT</pubDate>
            <atom:updated>2026-11-04T15:38:54.342Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6bEI90TDXsRJ2akQUzN0Yw.png" /><figcaption>Caption: Original Map For Sharappur Union</figcaption></figure><p>This was my first attempt at mapping Sharappur Union</p><p>Look at it for a second. Can you tell where the union is? Neither could I.</p><blockquote>I’m a student of Urban and Regional Planning at KUET in Khulna. I had the data, the software and the deadline. What I didn’t have was a map anyone could read. Roads, rivers and land use ran in every direction, and my study area was buried somewhere in the middle.</blockquote><p>That’s when I learned something nobody told me in class: <strong>a map isn’t finished when the data is on it. It’s finished when the reader knows where to look.</strong></p><p>Here’s how I fixed mine.</p><h3>Fix 1: Stop Drawing Everything Everywhere</h3><p>My roads, waterways and land use layers covered the entire region. But I only cared about one union.</p><p>So I clipped each layer to the Sharafpur boundary. Now the roads, rivers and land use existed only inside my study area.</p><p>It was a small change, and it made the biggest difference.</p><h3>Fix 2: Fade The Outside</h3><p>Clipping alone leaves a lot of empty space, and I wanted the surroundings to stay visible for context. I just didn’t want them to compete for attention.</p><p>The trick is a mask. I drew a big polygon around the union, cut a hole in it in the shape of my study area, and filled it with semi-transparent white. Everything outside went soft and quiet. Everything inside stayed sharp.</p><p>That’s the moment my map finally started to look like a map.</p><h3>Fix 3: The Mistake I Made (So you don’t)</h3><p>I’ll be honest here. Before I found the mask method, I used a shortcut that clips the whole map display to the boundary.</p><p>The result was a union floating in a sea of white. No basemap, no context and no sense of place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*ktzhd3eYC5lKGZQK2sfCaA.png" /><figcaption>Floating Clipped Version</figcaption></figure><p>I laughed at it, then I undid it. The lesson was simple: clip your data layers, not your whole map.</p><h3>Fix 4: Give The Reader A Sense Of Place</h3><p>Even a perfect map of one union means nothing if people don’t know where Sharafpur is.</p><p>So I added a small locator map in the corner. It shows the district around it, a red box marking my study area, and a little yellow label that says exactly what it is.</p><p>Readers glance at it for two seconds and they know where they are. That’s all it needs to do.</p><h3>Fix 5: The Small Details That Make It Look Professional</h3><p>None of these are exciting. All of them matter:</p><ul><li><strong>A graticule with clean labels.</strong> I limited it to about six labels per side, so it doesn’t crowd the frame.</li><li><strong>A simple legend.</strong> It lists only what’s actually on the map.</li><li><strong>A scale bar and north arrow.</strong> They’re boring, but a map without them feels unfinished.</li><li><strong>A short title.</strong> No long words, just what the map is.</li><li><strong>Data credit.</strong> My roads and waterways came from OpenStreetMap, so I credited the contributors. If you use their data, you should too.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJLUug_oVuDXVQLKVM3jMQ.png" /><figcaption>Final Output</figcaption></figure><h3>What I’d tell a Beginner</h3><p><strong>1. Start with a question.</strong> Ask what the reader should notice first. Then design everything around that answer.</p><p><strong>2. Fade what doesn’t matter.</strong> Context should whisper, not shout.</p><p><strong>3. Expect ugly versions.</strong> My first map was bad, my third was worse, and my fifth was good. That’s how it goes.</p><p><strong>4. Check your own labels.</strong> I found three different spellings of my own study area on one map. Readers notice these things.</p><h3>Final Thought</h3><p>I started this thinking GIS was about software. It turns out it’s about decisions: what to show, what to hide and what to quiet down.</p><p>If you’re making your first map and it looks like a mess, you’re not doing it wrong. You’re doing it the way everyone does it.</p><p>Keep going. Then fade the background. 😄</p><p><em>If this helped, clap, follow, or tell me what you’re mapping next. I’d love to see it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be2861c7ec5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing SST Prediction in Bangladesh Waters Using Wavelet-LSTM Hybrid Models]]></title>
            <link>https://medium.com/@tahasinahoni2/enhancing-sst-prediction-in-bangladesh-waters-using-wavelet-lstm-hybrid-models-9fd59a473788?source=rss-7b3109fc909a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fd59a473788</guid>
            <category><![CDATA[wavelet-transformation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Tahasin islam]]></dc:creator>
            <pubDate>Fri, 15 May 2026 17:11:24 GMT</pubDate>
            <atom:updated>2026-05-15T17:11:24.594Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nfMsw0Z52d4xMSR39IV4tQ.png" /><figcaption>Images by Authors</figcaption></figure><h3>The Challenge of Predicting Sea Surface Temperature in the Bay of Bengal</h3><p>Bangladesh, a deltaic nation crisscrossed by rivers and fronting the northern Bay of Bengal, depends critically on accurate sea surface temperature (SST) forecasts. SST influences monsoon intensity, cyclone formation, fish migration, and coastal livelihoods.</p><p>Yet the Bay of Bengal is notoriously chaotic — fed by massive freshwater discharge, subjected to seasonal monsoon reversals, and frequently churned by tropical cyclones. Traditional forecasting models struggle with such nonlinear, non‑stationary time series.</p><p>In this study, I reimplemented a hybrid wavelet‑LSTM approach, originally tested in the Mediterranean, to see if it can extract meaningful predictive gains for Bangladesh’s unique climatic setting. The results? <strong>Consistent improvement over standalone LSTM, with error reductions ranging from 1.4% to 10.3% across seasons.</strong></p><h3>Data &amp; Study Area</h3><ul><li><strong>Region</strong>: Bangladesh coastal waters (Bay of Bengal)</li><li><strong>Data source</strong>: NASA/OCEANDATA/MODIS-Aqua (L3SMI)</li><li><strong>Time period</strong>: 2013–2023</li><li><strong>Variable</strong>: Daily Sea Surface Temperature (°C)</li><li><strong>Seasons</strong>:</li><li>Spring (Mar–May)</li><li>Summer (Jun–Aug)</li><li>Autumn (Sep–Nov)</li><li>Winter (Dec–Feb)</li></ul><p>The raw data were cleaned, gap‑filled via interpolation, and normalized before analysis.</p><h3>Step 1: Understanding Seasonal SST Behaviour</h3><p>Before building any model, I examined the seasonal distribution of SST using box plots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*WAk-Ny4zyaNSAk238jl37g.png" /><figcaption>Seasonal SST distribution</figcaption></figure><p><strong>Key observations:</strong></p><ul><li>Spring shows the widest spread and highest extremes (up to 33°C) — likely pre‑monsoon heating.</li><li>Winter is coolest but still mild (minimum 25°C), typical for tropical latitudes.</li><li>Outliers in every season suggest short‑term heat spikes (e.g., calm days before a cyclone).</li></ul><p>This high intra‑seasonal variability is exactly why wavelet decomposition might help: it separates short‑term spikes (noise) from underlying seasonal trends.</p><h3>Step 2: Methodology — Wavelet + LSTM Hybrid</h3><h4>-&gt; Why wavelet?</h4><p>The Discrete Wavelet Transform (DWT) decomposes a time series into multiple frequency components:</p><ul><li><strong>d1</strong> — High‑frequency details (daily fluctuations, noise)</li><li><strong>d2</strong> — Mesoscale variations (weather systems, weekly cycles)</li><li><strong>d3</strong> — Low‑frequency trend (seasonal warming/cooling)</li></ul><p>By feeding these components as extra features, a Long Short‑Term Memory (LSTM) network can learn patterns at different scales independently.</p><h4>Model architecture</h4><ul><li><strong>Standalone LSTM</strong>: trained on raw SST only.</li><li><strong>Hybrid Wavelet‑LSTM</strong>: trained on raw SST + d1 + d2 + d3 coefficients.</li><li>Training/validation/test split: 70/15/15 (chronologically).</li><li>Hyperparameters: 2 LSTM layers (64 units each), Adam optimizer, MSE loss.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vQfqXPGE_BeOQ37_tITtgw.png" /><figcaption>Wavelet Transformation(Raw + d1+d2+d3)</figcaption></figure><p>The high‑frequency detail (d1) captures daily noise, while the long‑term trend follows the annual cycle.</p><h3>Step 3: Prediction Results — Seasonal Breakdown</h3><p>I evaluated both models on a 7‑day forecast horizon for each season. Below are the Root Mean Square Error (RMSE) and Mean Absolute Error (MAE) comparisons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*6plqh1U1rqUW1BaZZTHZfQ.png" /><figcaption>Metric: RMSE &amp; MAE</figcaption></figure><p><strong>Overall:</strong> The hybrid model outperforms standalone LSTM in <em>every</em> season, with the largest gains in spring and summer (≈9% RMSE reduction). Autumn shows modest improvement, likely due to transitional weather patterns (post‑monsoon, pre‑winter) that are harder to decompose cleanly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PkM_BlwX3isEXc7StgF05w.png" /><figcaption>Forecast vs Actual</figcaption></figure><p>This visualization shows the 7‑day forecast for winter: the hybrid (Wavelet‑LSTM) curve follows the actual SST more closely than standalone LSTM, especially on days 3–5.</p><h3>Step 4: Error Reduction Visualization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2K966kqxgHT7XoLVtRWD4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*RdzJxcoV1IlqVCt475ibfw.png" /><figcaption>Error Comparison (left) | Error Reduction (Right)</figcaption></figure><p>These figures summaries the improvements but —</p><blockquote><strong><em>Why does summer perform well?</em></strong><br>Summer in Bangladesh (June–August) is the peak monsoon. SST remains relatively stable (27.5–29.5°C) but with intermittent cooling from storms. Wavelet decomposition effectively separates the storm‑induced dips (high‑frequency) from the background monsoon warmth (low‑frequency), helping the LSTM avoid overreacting to every wind squall.</blockquote><blockquote><strong><em>Why does autumn lag?</em></strong><br>Autumn (September–November) is post‑monsoon and pre‑cyclone season. SST can drop sharply after a cyclone or rise during calm periods. The transition is swift and often non‑linear. A fixed 3‑level wavelet decomposition may not capture the abrupt shifts as well as it does the smoother changes in other seasons.</blockquote><h3>Conclusion</h3><p>This study successfully demonstrates that a hybrid wavelet‑LSTM model improves SST prediction over a standalone LSTM for Bangladesh coastal waters. The improvements are <strong>season‑dependent but always positive</strong> — ranging from 1.4% (autumn RMSE) to 10.3% (spring MAE). The largest gains occur in spring and summer, seasons critical for pre‑monsoon planning and monsoon fisheries.</p><p>While the Mediterranean study reported 10–30% error reductions, the Bay of Bengal’s higher intrinsic variability means smaller but still meaningful gains. For a country where every fraction of a degree matters to millions of coastal residents, a 5–10% reduction in forecast error is a valuable step forward.</p><p><strong>Next steps:</strong> I plan to open‑source the code and data pipeline so other researchers can test wavelet‑LSTM on other climate variables in tropical deltas. If you’re working on similar problems, feel free to reach out or adapt the methodology.</p><p>Note: Original Paper link- <a href="https://isprs-archives.copernicus.org/articles/XLVIII-4-W18-2025/379/2026/isprs-archives-XLVIII-4-W18-2025-379-2026.pdf">https://isprs-archives.copernicus.org/articles/XLVIII-4-W18-2025/379/2026/isprs-archives-XLVIII-4-W18-2025-379-2026.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fd59a473788" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Memory Profiling Made Simple: tracemalloc vs psutil]]></title>
            <link>https://medium.com/@tahasinahoni2/python-memory-profiling-made-simple-tracemalloc-vs-psutil-ee82617c1833?source=rss-7b3109fc909a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee82617c1833</guid>
            <category><![CDATA[psutil]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Tahasin islam]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 05:40:40 GMT</pubDate>
            <atom:updated>2025-12-05T05:40:40.259Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aszWE0Ok4NwYS5rBSqQ2eA.png" /><figcaption>Images by Authors</figcaption></figure><h4>Why it matters:</h4><blockquote>Memory issues slow apps, crash services, and cause hidden bugs. Profiling helps you catch inefficient code early and understand how your program grows during execution.</blockquote><h4>Overview:</h4><p>Python manages memory through its own allocator on top of the OS. Objects, lists, and temporary variables sit in a managed heap, and this adds overhead that isn’t always visible unless you measure it.</p><h4>What tracemalloc does and where it shines:</h4><p>tracemalloc tracks memory <em>at the line level</em>, so you see exactly which part of the code is allocating space. It’s ideal for debugging leaks, optimizing functions, and analysing how memory behaves during development.</p><h4>Demo Code:</h4><pre>import tracemalloc<br><br>tracemalloc.start()<br><br>def generate_data():<br>    return [i ** 2 for i in range(500000)]<br><br>generate_data()<br>snapshot = tracemalloc.take_snapshot()<br>stats = snapshot.statistics(&#39;lineno&#39;)[:3]<br><br>for stat in stats:<br>    print(stat)<br><br>tracemalloc.stop()</pre><h4>Limitations:</h4><p>It slows down execution, stores large snapshots, and tracks only Python-level allocations. This makes it useful for development but unsuitable for live systems.</p><h3>Why psutil is better for real-world monitoring:</h3><p>psutil reads memory directly from the <em>process</em>, giving real-time usage with almost <em>no overhead</em>. It is stable in production and works well for dashboards, alerts, and container-based deployments.</p><h4>Demo:</h4><pre>import psutil, os<br><br>p = psutil.Process(os.getpid())<br>print(p.memory_info().rss / (1024 * 1024), &quot;MB&quot;)</pre><p><em>Output example:</em><br> 42.13 MB</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee82617c1833" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[30 Data Science Projects to Sharpen Your Skills and Build a Standout Portfolio]]></title>
            <link>https://medium.com/@tahasinahoni2/30-data-science-projects-to-sharpen-your-skills-and-build-a-standout-portfolio-3cca4f5314d6?source=rss-7b3109fc909a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cca4f5314d6</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science-projects]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[recommendations]]></category>
            <dc:creator><![CDATA[Tahasin islam]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 13:02:29 GMT</pubDate>
            <atom:updated>2025-11-05T13:02:29.412Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/459/0*syEKoffcLZox0aLL.jpg" /><figcaption><strong>Image by Author’s</strong></figcaption></figure><p>Let’s be honest. I’ve been exactly where you are — trying to find those “real” data science projects that actually help you get hired.</p><p>But here’s the truth no one talks about:</p><blockquote>There’s no single magic project that guarantees a job.</blockquote><p>Learning data science is a lot like going to the gym for the first time. You start lifting light weights — learning backpropagation, linear regression, activation functions, optimizers — and you feel confident.</p><p>You think you’ve mastered the skills needed to perform on the big stage ?</p><p>But the real test begins when you start building projects that mirror how things work in the industry.</p><p>Not just importing datasets, running a few functions, and printing a result.</p><p>Real work happens when you think about structure, modularity, and deployment — the parts that make your code useful beyond a notebook.</p><p>That’s why I’ve collected these projects. They’re not random Kaggle exercises. Each one teaches you something practical, something that will push you closer to how professionals build systems.</p><h3>Type A: Covid-19 Related Projects</h3><p>These projects let you explore how data science applies to real-world healthcare and social challenges. You deal with messy, high-stakes data where interpretability matters as much as accuracy.</p><p>1.Bing Coronavirus Queries — classify queries as specific (like about a location) or generic.<br>2. Covid Clinical Data — rank high-risk patients using interpretable machine learning models.</p><p>You can find more related datasets on Kaggle’s Covid-19 section, which is full of opportunities to practice.</p><h3>Type B: Text-Based Projects</h3><p>Text-based or NLP projects are great for learning how to extract meaning from language. You’ll work with tagging, classification, keyword extraction, and translation.</p><p>Autonomous Tagging of StackOverflow Questions — automatically assign relevant tags.<br>1.<strong><em> Keyword Identification</em></strong> — extract key concepts from large text datasets.<br>2. <strong><em>Fake News Detection</em></strong> — classify whether an article is fake or real.<br>3. <strong><em>Language Translation </em></strong>— build a neural translation model for English to French or any other pair.</p><h3>Type C: Natural Language Understanding</h3><p>These projects move beyond simple text classification to understanding context, emotion, and intent. They’re the backbone of chatbots, content moderation, and smart assistants.</p><p>Sentence Similarity — detect duplicate or related questions.<br>1. <strong><em>Toxic Comment Detection</em></strong><em> </em>— classify text as abusive or harmless.<br>2. <strong><em>Text Summarization </em></strong>— automatically summarize long news articles.<br>3. <strong><em>Sentiment Analysis</em></strong> — study how opinions change over time.<br>4. <strong><em>Customer Support Chatbot </em></strong>— automate responses to frequent customer queries.</p><h3>Type D: Forecasting Projects</h3><p>Forecasting teaches you to predict future trends using past data. It’s a must for careers in finance, logistics, and climate analysis.</p><p>Rainfall Prediction — model long-term rainfall trends.<br>1. <strong><em>Air Quality Forecasting </em></strong>— predict pollution levels based on weather data.<br>2. <strong><em>Electricity Load Forecasting </em></strong>— estimate household power usage.<br>3. <strong><em>Stock Price Prediction</em></strong> — combine time series data with sentiment analysis.<br> Traffic Flow Forecasting — predict congestion using real-time data.</p><h3>Type E: Recommendation Systems</h3><p>Recommendation systems are at the core of most digital platforms. They use behavioural data to predict what users want next.</p><p>=&gt; <strong><em>Movie Recommendation</em></strong> — predict how users will rate a film.<br> =&gt; <strong><em>E-commerce Product Suggestion </em></strong>— recommend products based on browsing or purchase history.<br> =&gt; <strong><em>Influencer Detection </em></strong>— identify top-performing users in social networks.</p><h3>Final Thoughts</h3><p>Don’t just complete projects for the sake of having them on your portfolio. Build them like an engineer would. Think end-to-end — from data collection to model deployment. Use Docker and FastAPI to make your work modular. Track experiments with MLflow or DagsHub. Practice CI/CD and host your demos on free platforms like Streamlit Cloud.</p><p>Over time, contribute to open-source, share your learnings, and document every step. Each project becomes more than a portfolio item — it becomes proof of how you think, how you learn, and how you execute.</p><p>Keep building. Stay curious. And let your work tell your story.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cca4f5314d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Database to Vectors: Using PostgreSQL + PGVector with LangChain]]></title>
            <link>https://medium.com/@tahasinahoni2/from-database-to-vectors-using-postgresql-pgvector-with-langchain-743a6842f14b?source=rss-7b3109fc909a------2</link>
            <guid isPermaLink="false">https://medium.com/p/743a6842f14b</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[questionanswer]]></category>
            <dc:creator><![CDATA[Tahasin islam]]></dc:creator>
            <pubDate>Fri, 19 Sep 2025 06:10:11 GMT</pubDate>
            <atom:updated>2025-09-19T06:10:11.253Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HpjXnHyU2utQVsWzvZ0LlA.png" /><figcaption>Image by Authors</figcaption></figure><h3>INSTALLATION:-</h3><p>First we should download docker desktop into local computer . To do this simply got to <a href="https://docs.docker.com/desktop/setup/install/windows-install/"><strong><em>docker-installer</em></strong></a>.</p><p>Then Open-up the terminal and run :</p><pre>docker --version</pre><p>If you see this in terminal than you successfully downloaded the docker desktop .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*nXVhAwO6rNKY5DAwqHlx7Q.png" /><figcaption>Caption: Docker version Check-up</figcaption></figure><p>Next, pull the Docker image <strong>ankane/pgvector</strong> by running the following command in your terminal:</p><pre>docker pull ankane/pgvector</pre><p>Since this is your first time using Docker Desktop, you won’t have any images locally. Docker will automatically pull it from <strong>Docker Hub</strong>. After that, simply run the following command in your terminal:</p><pre>docker images</pre><p>You’ll now see that <strong>ankane/pgvector</strong> has been added to your local Docker images. To run it, you need to create a container using the following command</p><pre>docker run --name pgvector-demo -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d ankane/pgvector</pre><p>In this command, we use the ankane/pgvector image we just pulled to run a container, and we give the container a name, set the POSTGRES_PASSWORD environment variable, and map port 5432 between the container and host.</p><p>Verify that this is running with: docker ps</p><p>Now, we need a GUI(Graphical User Interface) to work with Postgres database. To do this navigate to this <a href="https://pgadmin-archive.postgresql.org/pgadmin4/v9.8/windows/index.html"><strong><em>Pg-Admin4</em></strong></a><strong><em> </em></strong>and download it.</p><p>Then right click on the server and create a new server</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*1KgcGWNi2ootOZIhXwTZ0A.png" /><figcaption>Caption: Pg-admin server creating front</figcaption></figure><p>Give it a name and hit enter . Now you have to establish a connection with the docker container . To do this right click on the new created server group and register a new connection .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*p_gXhesUqkckyYm_kNkvtw.png" /><figcaption>Caption: The preview of Postgres server register</figcaption></figure><p>Then head over to the <em>connection </em>tab and set up <em>localhost </em>and password will be the previously run docker command contained in your case(if you use this command) than it is “<em>mysecretpassword’’ .</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*jYvU5nq5RiKYGQw_-IoZ1g.png" /><figcaption>Caption: Connection with Postgres</figcaption></figure><p>Then hit save . After that you notice some thing like this in the created server group . initially you will have One default database(postgres) .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*YxlX4MZ7jVg_tsJfI-I62w.png" /><figcaption>Caption: Database Look up</figcaption></figure><p>To create a new one right clink on the <em>Databases </em>section and create a new database . Like this :-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*AT0ntlKiyRbyvG3dYwqO1w.png" /><figcaption>Caption: Database-Check</figcaption></figure><h3>CONNECTION WITH PYTHON + LANGCHAIN INTEGRATION : —</h3><p>To connect with Python, you’ll need to install a few dependencies in your environment. Here’s the list:</p><pre>!pip install psycopg2-binary pgvector</pre><p>Next, you’ll need a <strong>connection string</strong> to connect to the database from Python. Here it is:</p><pre>postgresql://postgres:{your_given_password}@localhost:5432/{your_created_database_name}</pre><p>Now, let’s dive into the coding!</p><pre>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)<br>from langchain_community.vectorstores import PGVector<br>from langchain_community.document_loaders import TextLoader<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI<br>from dotenv import load_dotenv, find_dotenv<br>import os<br>import asyncio<br>import numpy as np<br>from typing_extensions import Optional, Any<br><br>load_dotenv(find_dotenv())<br><br>class LangPost:<br>    def __init__(self):<br>        self.loader = TextLoader(file_path= &#39;notes.txt&#39;, encoding= &quot;utf-8&quot;)<br>        self.splitter = RecursiveCharacterTextSplitter(chunk_size = 1000 , chunk_overlap = 20)<br>        self.embedding = GoogleGenerativeAIEmbeddings(model= os.getenv(&#39;EMBEDDING_MODEL_NAME&#39;), google_api_key= os.getenv(&#39;GOOGLE_API_KEY&#39;))<br>        self.conn_string = os.getenv(&#39;POSTGRES_CONNECTION_STRING&#39;)<br>        self.collection_name = os.getenv(&#39;COLLECTION_NAME&#39;)<br>        self.model = ChatGoogleGenerativeAI(model = &quot;gemini-2.0-flash&quot;)<br>    <br>    def convert_into_doc(self) -&gt; object:<br>        documents = self.loader.load()<br><br>        return documents<br>    <br>    def split_into_texts(self, docs: object) -&gt; str:<br><br>        texts = self.splitter.split_documents(documents= docs)<br><br>        return texts<br>    <br>    def connectandsave(self, texts: str) -&gt; Optional[Any]:<br>        db = PGVector.from_documents(<br>            documents= texts,<br>            embedding= self.embedding,<br>            collection_name= self.collection_name,<br>            connection_string = self.conn_string<br>        )<br><br>        return db<br><br>    def retrive_docs(self, query: str, db: Any) -&gt; list[str]:<br>        similar = db.similarity_search_with_score(query, k = 2)<br><br>        docs = []<br>        for doc in similar:<br>            docs.append(doc)<br><br>        return docs<br>    <br>    def main(self):<br>        documents =  self.convert_into_doc()<br><br>        texts = self.split_into_texts(docs= documents)<br><br>        db =  self.connectandsave(texts= texts)<br><br>        retrieved_docs =  self.retrive_docs(query= &quot;Revenue of Acme Tech Inc company during the fiscal year of 2025?&quot;, db= db)<br><br>        print(retrieved_docs) <br><br><br>if __name__ == &quot;__main__&quot;:<br>    lang_post = LangPost()<br>    lang_post.main()</pre><h4>📌 Explanation of LangPost Class</h4><p>The LangPost class is a pipeline that:</p><ol><li><strong>Loads documents</strong> from a text file.</li><li><strong>Splits documents</strong> into smaller chunks for processing.</li><li><strong>Generates embeddings</strong> using Google’s Generative AI Embeddings model.</li><li><strong>Stores embeddings</strong> inside PostgreSQL with the PGVector extension.</li><li><strong>Performs similarity search</strong> to retrieve relevant documents.</li><li><strong>Uses LangChain integration</strong> with Google Gemini for conversational models.</li></ol><h4>🔎 Breakdown of Each Part</h4><h4>Constructor (__init__)</h4><ul><li>Initializes key components:</li><li>TextLoader: loads notes.txt.</li><li>RecursiveCharacterTextSplitter: splits text into chunks of 1000 characters with 20 character overlap.</li><li>GoogleGenerativeAIEmbeddings: generates vector embeddings using Google’s embedding model.</li><li>PGVector connection details (conn_string, collection_name).</li><li>ChatGoogleGenerativeAI: Gemini chat model for future interaction.</li></ul><h4>convert_into_doc(self)</h4><ul><li>Loads the raw text from notes.txt.</li><li>Returns the loaded document(s).</li></ul><h4>split_into_texts(self, docs)</h4><ul><li>Takes documents as input.</li><li>Splits them into smaller, overlapping chunks using RecursiveCharacterTextSplitter.</li><li>Returns the list of text chunks.</li></ul><h4>connectandsave(self, texts)</h4><ul><li>Takes the list of text chunks.</li><li>Converts them into embeddings using the Google model.</li><li>Saves them into PostgreSQL using PGVector.</li><li>Returns the database object for later retrieval.</li></ul><h4>retrive_docs(self, query, db)</h4><ul><li>Accepts a <strong>query string</strong> and the vector database (db).</li><li>Performs <strong>similarity search</strong> with db.similarity_search_with_score().</li><li>Retrieves the <strong>top 2 most relevant documents</strong> along with similarity scores.</li><li>Returns the matching documents in a list.</li></ul><h4>main(self)</h4><ul><li>Full workflow in order:</li></ul><ol><li>Load text file → convert_into_doc()</li><li>Split into chunks → split_into_texts()</li><li>Save embeddings into PGVector → connectandsave()</li><li>Run a query (e.g., company revenue) → retrive_docs()</li><li>Print retrieved documents.</li></ol><h4>Execution (if __name__ == &quot;__main__&quot;:)</h4><ul><li>Creates an instance of LangPost.</li><li>Calls main() to run the full pipeline end-to-end.</li></ul><h4>🚀 In Short</h4><p>This class automates the process of:<br> <strong>📄 Loading → ✂️ Splitting → 🔢 Embedding → 🗄️ Storing → 🔍 Retrieving documents</strong><br> using <strong>LangChain + Google Generative AI + PGVector (Postgres)</strong>.</p><h3>THE RETREIVE RESULT:-</h3><p>The output should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jNapJR-SE55hZJ7UsTTN8A.png" /><figcaption>Caption: Retrieval result</figcaption></figure><h3>POTENTIAL ISSUES</h3><ol><li>If you encounter an error like &#39;pgvector&#39; not found, make sure to run the following command in your SQL query tool:</li></ol><pre>CREATE EXTENSION pgvector</pre><p>2. Always make sure to <strong>run your Docker container</strong> before working with PostgreSQL via LangChain; otherwise, you’ll encounter connection errors.</p><h3>BENEFITS WITH LLM</h3><p>So we have a data-store containing all our vectors. This can be used when we have a lot of context, and want to only select the most relevant or similar chunks as context when querying and prompting language-models.</p><p>Language models tend to have a <strong>context length</strong> or <strong>context window</strong>, that limits the number of tokens they can consider at a time.</p><p>If we upload a repository of 1000 documents, we cannot realistically pass all that context in a call to the language-model. The vector database allows us to <strong>select chunks</strong> that closely match what we’ve provided in the prompt, and only pass certain segments of the text.</p><p>This is powerful, as it allows us to take advantage of greater amounts of text content. We can embed a large corpus of documents into chunks, and can select the relevant segments in our code.</p><h3>SUMMARY</h3><p>This tutorial covered <strong>setting up a PostgreSQL vector database with Docker</strong> and connecting it to Python. We pulled the <strong>ankane/pgvector</strong> image, created a container, installed dependencies, and configured a connection string. Remember to always run the Docker container before connecting, and run CREATE EXTENSION pgvector if you encounter errors.</p><p>Vector databases let us <strong>efficiently handle large document repositories</strong> by storing text as vectors and retrieving only the most relevant chunks. This ensures language models work within their context limits while still leveraging large amounts of data effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=743a6842f14b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Skewness & Kurtosis Explained: The Must-Know Stats for Every Data Nerd]]></title>
            <link>https://medium.com/@tahasinahoni2/skewness-kurtosis-explained-the-must-know-stats-for-every-data-nerd-9d73e873248c?source=rss-7b3109fc909a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d73e873248c</guid>
            <category><![CDATA[skewness]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-scienc]]></category>
            <category><![CDATA[kurtosis]]></category>
            <dc:creator><![CDATA[Tahasin islam]]></dc:creator>
            <pubDate>Sat, 09 Aug 2025 18:12:32 GMT</pubDate>
            <atom:updated>2025-08-09T18:12:32.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*htA_nmxvTV9SIYCsYwETsw.png" /><figcaption>Image by Authors</figcaption></figure><p>Skewness and kurtosis are more than statistical jargon — they reveal the shape, symmetry, and tail behavior of data. In this post, we’ll cover what they mean, how to calculate them manually, and how to interpret results — whether data is left/right-skewed or leptokurtic, mesokurtic, or platykurtic.</p><p>In data science and machine learning, these metrics are essential for diagnosing distribution issues, detecting outliers, and guiding preprocessing decisions. Skewness may indicate the need for transformations, while kurtosis highlights extreme values that could impact model stability. Mastering them leads to cleaner data, stronger models, and more reliable insights .</p><h3>SKEWNESS</h3><p><strong>Skewness</strong> describes the asymmetry of a data distribution, typically visualized with <strong>categories on the x-axis</strong> and <strong>frequency on the y-axis</strong>. In essence, it shows whether data is symmetrically distributed or not.</p><p>For example, in income data, a symmetrical distribution suggests most people earn around a central range, with few extremes. In such cases, the <strong>mean</strong>, <strong>median</strong>, and <strong>mode</strong> align closely. However, interpreting skewness also depends on <strong>domain knowledge</strong>.</p><p>There are three main types:</p><ol><li><strong>Left-skewed (negative skew)</strong> — Tail extends longer on the left.</li><li><strong>Right-skewed (positive skew)</strong> — Tail extends longer on the right.</li><li><strong>Normal distribution</strong> — Symmetrical bell curve, with no significant skew.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z0wk2ut5quB4bArWWFJ9Sw.png" /><figcaption>Figure 01: Left | normal | right skewed</figcaption></figure><h4>SKEWNESS CALCULATION</h4><p>Skewness can be calculated in two main ways:</p><ol><li><strong>By Moments:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*6JgFAoKPhvLix44HyvQ41Q.png" /><figcaption>Fig1.1- Rule for skewness coefficient</figcaption></figure><p>Where the <em>k</em>-th moment about the mean is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*H0fRVXgcuYEmXmQ0kZZG2A.png" /><figcaption>Fig 1.2- IN detailed glimpse</figcaption></figure><p>2. <strong>By Pearson’s Method (Using Mean and Mode):</strong></p><p>Here you will use , mean , median , standard deviation to calculate skewness. It is generally happen when you are given a table .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*wgeUFqr_4ldfJF3O46QASw.png" /><figcaption>Fig 1,3- Using pearson rule</figcaption></figure><p><strong>INPRETATION:</strong></p><p>According to value of output we define what category should be assigned for our input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*OchwVBl0qvQS_3hv70Tyog.png" /><figcaption>Fig 1.4- Category distribution</figcaption></figure><h3>KURTOSIS</h3><p><strong>Kurtosis</strong> measures the <em>peakedness</em> or <em>flatness</em> of a data distribution compared to a normal curve. It reflects how concentrated or spread out the values are around the mean.</p><p>The three main types are:</p><ol><li><strong>Mesokurtic</strong> — Baseline shape, similar to the normal distribution.</li><li><strong>Leptokurtic</strong> — Sharper peak with heavier tails, indicating more extreme values.</li><li><strong>Platykurtic</strong> — Flatter peak with lighter tails, indicating fewer extremes.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6GpRaBxzs98hRGnNWnZag.png" /><figcaption>Figure 02: Types of kurtosis</figcaption></figure><h4>CALCULATION OF KURTOSIS</h4><p>Kurtosis is computed using the <strong>fourth</strong> and <strong>second moments</strong> about the mean:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*2LdnL9qeoFcpjFPCqdn4RA.png" /><figcaption>Fig 2.1- Glimpse of kurtosis rule</figcaption></figure><p>Where the <em>k</em>-th moment about the mean is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*8NL2hifYbZWV9xYzMgn4GQ.png" /><figcaption>Fig 2.2: (Mentioned earlier)</figcaption></figure><p><strong>INPRETATION:</strong></p><p>It is simple even from skewness categorization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*fXfJ-0sTqwiWPNDnJGHtig.png" /><figcaption>Fig 2.3- Categorization</figcaption></figure><h3>CONCLUSION</h3><p>Skewness and kurtosis are key statistical tools that help us understand the shape and nuances of our data. Skewness tells us whether data is balanced or leans to one side, giving insight into the direction and extent of asymmetry. Whether calculated using moments or simpler formulas involving mean and mode, knowing how to interpret skewness helps identify if the data is left-skewed, right-skewed, or roughly symmetrical.</p><p>Kurtosis goes a step further by measuring the “peakedness” of the distribution — showing whether data clusters tightly around the mean or has heavier tails with more extreme values. By comparing the fourth moment to the squared second moment, we can classify distributions as mesokurtic (normal), leptokurtic (peaked), or platykurtic (flat).</p><p>In data science and machine learning, these measures aren’t just theoretical — they’re practical tools. Skewness may signal the need for data transformation, and kurtosis highlights the presence of outliers that could affect model stability. Understanding and applying these concepts helps create cleaner datasets, choose the right algorithms, and build models that perform better and are more reliable.</p><p>Ultimately, going beyond built-in functions and truly grasping skewness and kurtosis lets you unlock deeper insights from your data, making your analyses and models stronger and more meaningful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d73e873248c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DAY 02: Previewing Machine Learning Interview Questions]]></title>
            <link>https://medium.com/@tahasinahoni2/day-02-previewing-machine-learning-interview-questions-561f690561c2?source=rss-7b3109fc909a------2</link>
            <guid isPermaLink="false">https://medium.com/p/561f690561c2</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Tahasin islam]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 21:06:43 GMT</pubDate>
            <atom:updated>2025-08-01T21:06:43.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNP3cg55mqQkQoxNsiSUdw.png" /><figcaption><strong>Image by Authors</strong></figcaption></figure><p>Continuing my journey into data science and machine learning interview preparation — it’s officially <strong>Day 2</strong>. I know I’m a bit late documenting it, but I wanted to start recording this process not just for myself, but also for anyone out there who’s passionate about revisiting and strengthening their core ML concepts.</p><p>Whether you’re just starting out or brushing up before interviews, I hope this series helps you stay motivated and focused — just like I’m trying to do.</p><p><strong>Question 11</strong>: In what scenario decision tree should be preferred over random forest?</p><p><strong>Answer</strong>: Mainly in 3 cases-</p><ol><li>Explain-ability : Decision tree &gt; random forest (when breaking down logic step by step)</li><li>Data set is clean and small: Decision tree &gt; random forest (because less concern in over-fitting )</li><li>Quick-prototyping: If condition are to justify the prediction → decision tree . If condition needs higher performance → random forest</li></ol><p><strong>Question 12:</strong> Why Logistic Regression is called regression?</p><p><strong>Answer:</strong> Because under the hood , logistic regression provides continuous values with a range between 0 to 1 (as used regression formula). Then classify 0 if value &gt; 0.5 , either 1</p><p><strong>Question 13: </strong>What is Online Machine Learning? How is it different from Offline machine learning? List some of it’s applications.</p><p>Answer: Where data comes incrementally and asynchronously model learn from data and got trained to predict is called online machine learning .</p><p>It is different because , model don’t trained with all over the data at a time.</p><p>Some applications:- 1. Real time recommendation 2.Fraud case detection 3. Stock price Prediction 4. Dynamic bidding system.</p><p><strong>Question 14: </strong>What is No Free Lunch Theorem?</p><p><strong>Answer:</strong> The theorem said , not all ML models work best in every situation or problem . Different algorithm work best in different tasks like- regression / classification</p><p><strong>Question 15:</strong> Imagine you are working with a laptop of 2GB RAM, how would you process a dataset of 10GB?</p><p><strong>Answer:</strong> I would follow some strategies to load this type of huge dataset. Strategies:</p><ol><li>I would use python vaex library.</li><li>Load dataset with a specific chunk size like- 10000 at a time.</li><li>Create a data generator to yield one batches after another</li></ol><p><strong>Question 16:</strong> What are the main differences between Structured and Unstructured Data?</p><p><strong>Answer:</strong> Structured — have a tabular format and Clean ( best for ML algorithm like- logistic regression , Boost); Unstructured — Needs to pre-process before making models friendly ( Tf-idf for text , CNN for images).</p><p><strong>Question 17:</strong> What are the main points of difference between Bagging and Boosting?</p><p><strong>Answer: </strong>Difference —</p><ol><li>Bagging — 1. Train the models on random subsets 2. Reduce variance 3. Less chance on overfitting (due to averaging ). Like- Random-forest</li><li>Boosting — 1. Train models sequentially 2. Reduce biases 3. Higher chance on overfitting . Like- Adaboost, gradient boosting</li></ol><blockquote><em>If I’m dealing with high variance, I go for </em><strong><em>Bagging</em></strong><em>.<br>If I need to squeeze out more accuracy by reducing bias, I prefer </em><strong><em>Boosting</em></strong><em>.</em></blockquote><p><strong>Question 18:</strong> What are the assumptions of linear regression?</p><p><strong>Answer:</strong> 1. Input features should not be similar 2. Error should have a same variance , a normal distribution 3. Relationship between input and output features is linear .</p><p><strong>Question 19: </strong>How do you measure the accuracy of a Clustering Algorithm?</p><p><strong>Answer: </strong>To measure the accuracy of a clustering algorithm, we usually don’t use accuracy like in classification, because clustering is unsupervised and we don’t have true labels.</p><p>But if labels are available, we can use metrics like <strong>Adjusted Rand Index (ARI)</strong> or <strong>Normalized Mutual Information (NMI)</strong> to compare the clusters with the actual classes.</p><p>If labels are not available, we use internal metrics like the <strong>Silhouette Score</strong>, which tells how well a point fits into its own cluster, or <strong>Inertia</strong>, which checks how close the points are within the same cluster. These help us understand if the clusters make sense or not.</p><p><strong>Question 20: </strong>What is Matrix Factorization and where is it used in Machine Learning?</p><p><strong>Answer:</strong> <strong>Matrix Factorization </strong>is a technique used to break down a large matrix into smaller matrices that, when multiplied, can approximate the original one.</p><p>In machine learning, it’s mainly used in recommendation systems, like Netflix or Amazon, to predict missing values in a user-item rating matrix. Since most users haven’t rated all items, the matrix has many missing entries. Matrix Factorization helps uncover hidden patterns between users and items by learning the underlying factors that influence their interactions. This way, it can recommend items a user is likely to enjoy based on past behavior.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=561f690561c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built an LSTM Model to Predict Words with 95% Accuracy — A Practical NLP Refresher]]></title>
            <link>https://medium.com/@tahasinahoni2/how-i-built-an-lstm-model-to-predict-words-with-95-accuracy-a-practical-nlp-refresher-963024c50fac?source=rss-7b3109fc909a------2</link>
            <guid isPermaLink="false">https://medium.com/p/963024c50fac</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[next-word-prediction]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Tahasin islam]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 20:56:01 GMT</pubDate>
            <atom:updated>2025-07-30T20:56:01.192Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I Built an LSTM Model to Predict Words with 95% Accuracy — A Practical NLP Refresher</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SXZd9UADseUY2WFFyYbVxw.png" /><figcaption>Image by Authors</figcaption></figure><h3>OVERVIEW</h3><p>Today while revising LSTM, I paused and thought: <em>What’s the best way to really understand this?</em> Instead of just reading theory, I decided to build something.</p><p>I chose to implement a <strong>Next Word Predictor</strong>.</p><p>Why? Because traditional RNNs struggle with vanishing gradients — they fail to retain long-term context. LSTMs solve this by carrying memory through gated neurons, making them ideal for tasks that require context retention.</p><p>And what better way to test that than predicting the next word in a sequence? It forces the model to <em>remember</em> what came before — exactly what LSTMs are built for.</p><p>This small project turned out to be one of the best ways to revise and apply LSTM in action.</p><h3>IMPORT MODULES AND BASIC CONFIGURATION</h3><p>First, we imported the necessary libraries to handle tokenization and prepare our text data for the model.</p><pre>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>import numpy as np<br>from collections import Counter<br>from torch.utils.data import Dataset, DataLoader<br>from nltk.tokenize import word_tokenize<br>import nltk<br><br># Tokenization<br>nltk.download(&#39;punkt&#39;)<br>nltk.download(&#39;punkt_tab&#39;)</pre><p>Then take a raw document for training model.</p><pre>document = &quot;&quot;&quot;About the Program<br>What is the course fee for  Data Science Mentorship Program (DSMP 2023)<br>The course follows a monthly subscription model where you have to make monthly payments of Rs 799/month.<br>What is the total duration of the course?<br>The total duration of the course is 7 months. So the total course fee becomes 799*7 = Rs 5600(approx.)<br>What is the syllabus of the mentorship program?<br>We will be covering the following modules:<br>Python Fundamentals<br>Python libraries for Data Science<br>Data Analysis<br>SQL for Data Science<br>Maths for Machine Learning<br>ML Algorithms<br>Practical ML<br>MLOPs<br>Case studies<br>You can check the detailed syllabus here - https://learnwith.campusx.in/courses/CampusX-Data-Science-Mentorship-Program-637339afe4b0615a1bbed390<br>Will Deep Learning and NLP be a part of this program?<br>No, NLP and Deep Learning both are not a part of this program’s curriculum.<br>What if I miss a live session? Will I get a recording of the session?<br>Yes all our sessions are recorded, so even if you miss a session you can go back and watch the recording.<br>Where can I find the class schedule?<br>Checkout this google sheet to see month by month time table of the course - https://docs.google.com/spreadsheets/d/16OoTax_A6ORAeCg4emgexhqqPv3noQPYKU7RJ6ArOzk/edit?usp=sharing.<br>What is the time duration of all the live sessions?<br>Roughly, all the sessions last 2 hours.<br>What is the language spoken by the instructor during the sessions?<br>Hinglish<br>How will I be informed about the upcoming class?<br>You will get a mail from our side before every paid session once you become a paid user.<br>Can I do this course if I am from a non-tech background?<br>Yes, absolutely.<br>I am late, can I join the program in the middle?<br>Absolutely, you can join the program anytime.<br>If I join/pay in the middle, will I be able to see all the past lectures?<br>Yes, once you make the payment you will be able to see all the past content in your dashboard.<br>Where do I have to submit the task?<br>You don’t have to submit the task. We will provide you with the solutions, you have to self evaluate the task yourself.<br>Will we do case studies in the program?<br>Yes.<br>Where can we contact you?<br>You can mail us at nitish.campusx@gmail.com<br>Payment/Registration related questions<br>Where do we have to make our payments? Your YouTube channel or website?<br>You have to make all your monthly payments on our website. Here is the link for our website - https://learnwith.campusx.in/<br>Can we pay the entire amount of Rs 5600 all at once?<br>Unfortunately no, the program follows a monthly subscription model.<br>What is the validity of monthly subscription? Suppose if I pay on 15th Jan, then do I have to pay again on 1st Feb or 15th Feb<br>15th Feb. The validity period is 30 days from the day you make the payment. So essentially you can join anytime you don’t have to wait for a month to end.<br>What if I don’t like the course after making the payment. What is the refund policy?<br>You get a 7 days refund period from the day you have made the payment.<br>I am living outside India and I am not able to make the payment on the website, what should I do?<br>You have to contact us by sending a mail at nitish.campusx@gmail.com<br>Post registration queries<br>Till when can I view the paid videos on the website?<br>This one is tricky, so read carefully. You can watch the videos till your subscription is valid. Suppose you have purchased subscription on 21st Jan, you will be able to watch all the past paid sessions in the period of 21st Jan to 20th Feb. But after 21st Feb you will have to purchase the subscription again.<br>But once the course is over and you have paid us Rs 5600(or 7 installments of Rs 799) you will be able to watch the paid sessions till Aug 2024.<br>Why lifetime validity is not provided?<br>Because of the low course fee.<br>Where can I reach out in case of a doubt after the session?<br>You will have to fill a google form provided in your dashboard and our team will contact you for a 1 on 1 doubt clearance session<br>If I join the program late, can I still ask past week doubts?<br>Yes, just select past week doubt in the doubt clearance google form.<br>I am living outside India and I am not able to make the payment on the website, what should I do?<br>You have to contact us by sending a mail at nitish.campusx@gmai.com<br>Certificate and Placement Assistance related queries<br>What is the criteria to get the certificate?<br>There are 2 criterias:<br>You have to pay the entire fee of Rs 5600<br>You have to attempt all the course assessments.<br>I am joining late. How can I pay payment of the earlier months?<br>You will get a link to pay fee of earlier months in your dashboard once you pay for the current month.<br>I have read that Placement assistance is a part of this program. What comes under Placement assistance?<br>This is to clarify that Placement assistance does not mean Placement guarantee. So we dont guarantee you any jobs or for that matter even interview calls. So if you are planning to join this course just for placements, I am afraid you will be disappointed. Here is what comes under placement assistance<br>Portfolio Building sessions<br>Soft skill sessions<br>Sessions with industry mentors<br>Discussion on Job hunting strategies<br>&quot;&quot;&quot;</pre><p>Before diving into any model training, the very first thing you want to do is break down your raw text into smaller, meaningful chunks — tokens. Tokenization helps your model understand the text better by splitting it into words, phrases, or even characters. Think of it as preparing your ingredients before cooking; without this, nothing else will work smoothly.</p><pre># tokenize<br>tokens = word_tokenize(document.lower())<br><br>token</pre><p>the preview look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/111/1*vqfok7rULZjvbkaSDHTyBQ.png" /><figcaption>Figure 01: tokens glimpse</figcaption></figure><p>Once you’ve tokenized the text, it’s time to create a vocabulary — a list of unique tokens along with how many times each appears. This vocabulary is your map to converting sentences into numbers, which is how models actually learn from text. Think of it like turning words into a secret code your model can decode!</p><pre># build vocab<br>vocab = {&#39;&lt;unk&gt;&#39;:0}<br><br>for token in Counter(tokens).keys():<br>  if token not in vocab:<br>    vocab[token] = len(vocab)<br><br>vocab</pre><p>It’s basically a list of unique words paired with their counts — like this:<br> {&#39;word1&#39;: 15, &#39;word2&#39;: 8, &#39;word3&#39;: 22, ...}<br> This dictionary helps your model understand which words matter and how often they show up in your data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*BHnTQQyTrhQQhTM51zncYA.png" /><figcaption>Figure 02: vocab glimpse</figcaption></figure><p>Next, we split the raw document into sequences of numbers using the vocabulary you built. Each word gets replaced by its unique count from the dictionary. To do this, we start with an empty list and keep appending these numbers one by one. This transforms your text into a format your model can crunch easily.</p><p>Here’s a quick example to get you started:</p><pre>input_numerical_sentences = []<br><br>for sentence in input_sentences:<br>  input_numerical_sentences.append(text_to_indices(word_tokenize(sentence.lower()), vocab))<br><br>input_numerical_sentences</pre><p>After running the conversion, you’ll see your text perfectly transformed into numerical sequences — ready and waiting for the model to learn from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/58/1*n7_85cu6lkCHBgaTztF8Cw.png" /><figcaption>Figure 03: Counted sequence list</figcaption></figure><p>Now that your text is in number form, it’s time to build training sequences. These sequences help the model predict the next word based on the previous ones — basically teaching it context and flow.</p><p>Here’s exactly how I created these sequences:</p><pre>training_sequence = []<br>for sentence in input_numerical_sentences:<br><br>  for i in range(1, len(sentence)):<br>    <br>    training_sequence.append(sentence[:i+1])<br>training_sequence</pre><p>the output look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*uIyVStR33aPX81TE8reYFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*Js_N9Rk1aMvC_QrCV8xH-A.png" /><figcaption>Figure 04: glimpse of training sequence</figcaption></figure><h3>PADDING</h3><pre>len_list = []<br><br>for sequence in training_sequence:<br>  len_list.append(len(sequence))<br><br>padded_training_sequence = []<br>for sequence in training_sequence:<br><br>  padded_training_sequence.append([0]*(max(len_list) - len(sequence)) + sequence)<br><br># convert into tensor<br>padded_training_sequence = torch.tensor(padded_training_sequence, dtype=torch.long)</pre><p>To keep all sequences the same length, I padded shorter ones with null values after subtracting their length from the max sequence length. This way, the model focuses only on the real data — not the padding — making training more efficient.</p><p>Then, I converted everything into tensors since we’re working with PyTorch. This step transforms the data from unsupervised (raw text) into supervised learning format — where <strong>X</strong> is the input features and <strong>y</strong> is the label the model needs to predict.</p><pre>X = padded_training_sequence[:, :-1]<br>y = padded_training_sequence[:,-1]</pre><p>You can see the overlook in here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*qG7hjZZ98OROwy7uZFseMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*vl3Usiy8WziLfpvati6jcQ.png" /><figcaption>Figure 05: Feature and label as tensor</figcaption></figure><h3>CREATE DATASET AND DATALOADER</h3><p>Next, I created a custom dataset and paired it with a DataLoader. This setup efficiently feeds batches of your prepared data into the model during training — making the whole process faster and smoother.</p><pre>class CustomDataset(Dataset):<br><br>  def __init__(self, X, y):<br>    self.X = X<br>    self.y = y<br><br>  def __len__(self):<br>    return self.X.shape[0]<br><br>  def __getitem__(self, idx):<br>    return self.X[idx], self.y[idx]<br><br>dataset = CustomDataset(X,y)<br><br>dataloader = DataLoader(dataset, batch_size=32, shuffle=True)</pre><h3>TRAIN MODEL AND TRAIN</h3><p>Moving forward, I designed an LSTM model class that includes an embedding layer, the LSTM layer itself, and a final fully connected layer. This architecture helps the model learn word relationships, remember context, and make accurate predictions.</p><pre>class LSTMModel(nn.Module):<br><br>  def __init__(self, vocab_size):<br>    super().__init__()<br>    self.embedding = nn.Embedding(vocab_size, 100)<br>    self.lstm = nn.LSTM(100, 150, batch_first=True)<br>    self.fc = nn.Linear(150, vocab_size)<br><br>  def forward(self, x):<br>    embedded = self.embedding(x)<br>    intermediate_hidden_states, (final_hidden_state, final_cell_state) = self.lstm(embedded)<br>    output = self.fc(final_hidden_state.squeeze(0))<br>    return output<br><br># initialize the model<br>model = LSTMModel(len(vocab))<br><br># set device to gpu if cpu is not available<br>device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br><br># error, optimizer and loss function calculation<br>epochs = 50<br>learning_rate = 0.001<br><br>criterion = nn.CrossEntropyLoss()<br><br>optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)<br><br># training loop<br><br>for epoch in range(epochs):<br>  total_loss = 0<br><br>  for batch_x, batch_y in dataloader:<br><br>    batch_x, batch_y = batch_x.to(device), batch_y.to(device)<br><br>    optimizer.zero_grad()<br><br>    output = model(batch_x)<br><br>    loss = criterion(output, batch_y)<br><br>    loss.backward()<br><br>    optimizer.step()<br><br>    total_loss = total_loss + loss.item()<br><br>  print(f&quot;Epoch: {epoch + 1}, Loss: {total_loss:.4f}&quot;)</pre><h3>PREDICTION</h3><p>Finally, I built a prediction function that takes your input document and vocabulary to predict the next word. This lets the model generate text step-by-step, bringing your training to life!</p><pre># prediction<br><br>def prediction(model, vocab, text):<br><br>  # tokenize<br>  tokenized_text = word_tokenize(text.lower())<br><br>  # text -&gt; numerical indices<br>  numerical_text = text_to_indices(tokenized_text, vocab)<br><br>  # padding<br>  padded_text = torch.tensor([0] * (61 - len(numerical_text)) + numerical_text, dtype=torch.long).unsqueeze(0)<br><br>  # send to model<br>  output = model(padded_text)<br><br>  # predicted index<br>  value, index = torch.max(output, dim=1)<br><br>  # merge with text<br>  return text + &quot; &quot; + list(vocab.keys())[index]<br><br># making prediction<br>prediction(model, vocab, &quot;The course follows a monthly subscription model where you have to make monthly&quot;)</pre><p>the output look like this:</p><pre>The course follows a monthly subscription model where you have to make monthly <strong><em>payments</em></strong></pre><h3>ACCURACY</h3><p>To check how well the model’s doing, I created another DataLoader for validation. We feed batches of input data (batch_x) into the model, get the predicted word indices, and compare them with the true labels (batch_y) to see how accurate the predictions are.</p><pre># Function to calculate accuracy<br>def calculate_accuracy(model, dataloader, device):<br>    model.eval()  # Set the model to evaluation mode<br>    correct = 0<br>    total = 0<br><br>    with torch.no_grad():  # No need to compute gradients<br>        for batch_x, batch_y in dataloader1:<br>            batch_x, batch_y = batch_x.to(device), batch_y.to(device)<br><br>            # Get model predictions<br>            outputs = model(batch_x)<br><br>            # Get the predicted word indices<br>            _, predicted = torch.max(outputs, dim=1)<br><br>            # Compare with actual labels<br>            correct += (predicted == batch_y).sum().item()<br>            total += batch_y.size(0)<br><br>    accuracy = correct / total * 100<br>    return accuracy<br><br># Compute accuracy<br>accuracy = calculate_accuracy(model, dataloader, device)<br>print(f&quot;Model Accuracy: {accuracy:.2f}%&quot;)</pre><p>Output :</p><pre>Model Accuracy: 95.65%</pre><p>The model hit an impressive 95% accuracy, which is solid for a first run. Want to boost it even more? Just train longer with more epochs and feed the model higher-quality data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=963024c50fac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Confusion to Clarity: Explaining Loan Rejections Using SHAPASH]]></title>
            <link>https://medium.com/@tahasinahoni2/from-confusion-to-clarity-explaining-loan-rejections-using-shapash-dbbaf6d88d05?source=rss-7b3109fc909a------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbbaf6d88d05</guid>
            <category><![CDATA[business-strategy]]></category>
            <category><![CDATA[shapash]]></category>
            <category><![CDATA[custmers-need]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Tahasin islam]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 20:12:45 GMT</pubDate>
            <atom:updated>2025-07-25T20:12:45.972Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*4rjD3q7UJprqwA9CJ6PyOA.png" /><figcaption>Image by (Authors)</figcaption></figure><p>Today I explored SHAPASH — a Python library that makes black-box models explainable. Instead of chasing accuracy, I built a simple classification model to highlight what SHAPASH does best: turning complex decisions into clear, human-readable insights. In this post, I’ll walk you through how I used SHAPASH to break down model logic step by step.</p><h3>PROBLEM STATEMENT</h3><p><strong>Small loan </strong>companies and digital lenders in many parts of the world — like <em>India, Africa, and Southeast Asia</em> — are using machine learning to decide who gets a loan. But here’s the issue:</p><p>People get rejected and have <strong>no idea why</strong>.<br>Even the company staff can’t explain it clearly because the ML models are too <strong>complex</strong>. This causes:</p><ul><li><strong>Distrust</strong> from customers</li><li><strong>Complaints</strong> and <strong>legal pressure</strong> from regulators</li><li>A bad reputation for the company</li></ul><h3>APPROACH</h3><p>While thinking through the problem, a simple yet powerful idea hit me: <em>What if we could show customers exactly why their loan was rejected?</em> This level of transparency could not only reduce distrust, but also ease legal pressure by offering clear, data-backed explanations.</p><p>That’s when I came across <strong>SHAPASH</strong> on Twitter — it instantly clicked. I started thinking about how to apply it from a <strong>business perspective</strong> to drive real value.</p><p>To explore this, I downloaded a <strong>credit risk loan approval dataset</strong>, since the use case fit perfectly. Then I fired up pandas to dive into the data and understand the features.</p><pre>import pandas as pd <br><br>df = pd.read_csv(&quot;C:/Users/USER/.cache/kagglehub/datasets/laotse/credit-risk-dataset/versions/1/credit_risk_dataset.csv&quot;)<br><br>df.head(2)</pre><p>Here is the glimpse:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*WuX0chkiu6AX1VbdWcFkjA.png" /><figcaption>Figure 01; Glimpse of first two records</figcaption></figure><h3>PREPROCESSING</h3><p>Once I had the dataset, the first thing I did was check its shape to understand the <strong>volume of records</strong> I’d be working with. It’s a quick sanity check that helps set expectations before diving deeper.</p><pre>df.shape</pre><p>The dataset had <strong>32,581 rows and 12 columns</strong> — a decent size for experimenting with SHAPASH. More than enough to simulate a real-world scenario.</p><p>Next, I cleaned things up by dropping two irrelevant columns that didn’t add value to the explanation pipeline.</p><pre>df.drop(columns= [&quot;cb_person_default_on_file&quot;, &quot;cb_person_cred_hist_length&quot;], inplace= True)</pre><p>While inspecting the data types, I noticed something off — person_emp_length (employment duration) was stored as a <strong>float</strong>, which doesn’t really make sense for a feature that should be a whole number.</p><p>So, I handled the missing values and converted it to an <strong>integer</strong>, making the data cleaner and more reliable for interpretation later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*iqZenPaXGHzOASQILuaYNQ.png" /><figcaption>Figure 02: Float data type</figcaption></figure><p>Next, I checked for <strong>missing values</strong> across the dataset to understand where data might be incomplete. Here’s a quick look at the null distribution I found — an essential step before prepping features for modeling or explainability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*Qys5D-XCw32wjZMJF0cEIw.png" /><figcaption>Figure 03: Null status</figcaption></figure><p>Instead of blindly dropping columns with missing values, I wanted to be intentional — especially with person_emp_length, which had a significant number of nulls. Dropping it would’ve meant losing valuable context.</p><p>So, I imported <strong>Seaborn</strong> and plotted a histogram to visualize its distribution. Rather than defaulting to mean or median, I chose to fill nulls using the <strong>minimum and maximum values</strong>, aligning the imputation with the <strong>business goal</strong> of reflecting edge-case employment histories.</p><pre>import seaborn as  sns <br>import matplotlib.pyplot as plt<br><br>sns.histplot(data= df, x= &quot;person_emp_length&quot;, kde= True)<br>plt.show()</pre><p>the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*LCgPy0t1jEyq2XSVEmzllA.png" /><figcaption>Figure 04; Left-skewed distribution</figcaption></figure><p>From the histogram, it was clear — person_emp_length had a <strong>left-skewed distribution</strong>, with most values falling between <strong>0 and 20</strong>. Outliers were pushing the tail, so using the <strong>mean</strong> would have skewed the imputation.</p><p>Instead, I went with the <strong>median</strong>, a safer and more robust choice to preserve data integrity while minimizing distortion from outliers.</p><pre>df[&#39;person_emp_length&#39;].fillna(df[&#39;person_emp_length&#39;].median(), inplace= True)</pre><p>The second major column with missing data was loan_int_rate, which had the <strong>highest number of nulls</strong> in the dataset. Just like before, I visualized its distribution using a <strong>Seaborn histogram</strong> to better understand how to approach imputation without introducing bias.</p><pre>sns.histplot(data= df, x= &#39;loan_int_rate&#39;)<br>plt.show()</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*n9GOLnKTun5kyMUq9JCF2Q.png" /><figcaption>Figure 05: Double distribution</figcaption></figure><p>The histogram revealed two main clusters: one between <strong>5.0–10.0</strong> and a larger group from <strong>10.0–20.0</strong>. Since most values skewed right, I chose to fill the missing values with a <strong>constant 11.5</strong>, right in the middle of the dominant range — keeping the imputation simple and representative.</p><pre>df[&#39;loan_int_rate&#39;] = df[&#39;loan_int_rate&#39;].fillna(11.5)</pre><p>With nulls handled, I noticed three columns were clearly <strong>categorical</strong>. To prep them for modeling, I first converted them to the category data type—making it easier to <strong>encode them into numerical values</strong> later on while preserving their semantic meaning.</p><pre>df[&#39;person_home_ownership&#39;] = df[&#39;person_home_ownership&#39;].astype(&quot;category&quot;)<br><br>df[&#39;loan_intent&#39;] = df[&#39;loan_intent&#39;].astype(&quot;category&quot;)<br><br>df[&#39;loan_grade&#39;] = df[&#39;loan_grade&#39;].astype(&quot;category&quot;)</pre><p>With the columns set as categorical, I applied a straightforward encoding step to convert them into <strong>numerical format</strong> — ready for model training without losing their original intent.</p><pre>df[&#39;person_home_ownership&#39;] = df[&#39;person_home_ownership&#39;].cat.codes<br><br>df[&#39;loan_intent&#39;] = df[&#39;loan_intent&#39;].cat.codes<br><br>df[&#39;loan_grade&#39;] = df[&#39;loan_grade&#39;].cat.codes</pre><h3>CREATE PARTS AND FIT MODEL</h3><p>With a clean and preprocessed dataset, I defined X (features) and y (target), then split the data into <strong>training and testing sets</strong>—laying the foundation for building and evaluating the classification model.</p><pre>X = df.drop(columns= [&#39;loan_status&#39;])<br>y = df[&#39;loan_status&#39;]</pre><p>Since this was a classification problem, I brought in the <strong>RandomForestClassifier</strong>—a solid, interpretable baseline model. I then trained it using the previously split <strong>train-test data</strong>, setting the stage for evaluation and explanation with SHAPASH.</p><pre>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.model_selection import train_test_split<br><br>x_train , x_test , y_train , y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)</pre><p>I initialized the RandomForestClassifier and fit it on the training data. With the model trained, it was now ready to make predictions—and more importantly, to be explained using SHAPASH.</p><pre>clf = RandomForestClassifier()<br><br>clf.fit(x_train, y_train)</pre><h3>SHAPASH GLIMPSE</h3><p>To start using SHAPASH, I imported SmartExplainer—the core class that powers its interactive explainability. I initialized it and passed in the trained RandomForestClassifier as the model to be explained. This sets the stage for generating a <strong>web-based interface</strong> that makes model decisions fully transparent.</p><pre>from shapash.explainer.smart_explainer import SmartExplainer<br><br>xpl = SmartExplainer(model= clf)</pre><p>Next, I compiled the SmartExplainer using the X_test set. This step connects the explainer to both the <strong>model</strong> and the <strong>data it will interpret</strong>, allowing SHAPASH to generate predictions and explanations side-by-side for real test cases.</p><pre>xpl.compile(x= x_test)</pre><p>Finally, I ran the SHAPASH web app — and just like that, a fully interactive explanation dashboard was live at <strong>localhost:8080</strong>. You can now explore predictions, feature impacts, and understand <strong>why</strong> the model made each decision—in real time.</p><pre>app = xpl.run_app(port= &quot;8080&quot;, host= &quot;0.0.0.0&quot;, title_story= &quot;credits_risk&quot;)</pre><p>Once you’re done exploring, you can simply <strong>stop the app</strong> from your terminal to shut down the local server. Quick and clean — just like the insights SHAPASH delivers.</p><pre>app.kill()</pre><h3>INTERPRETATION</h3><p>Once the app is live, SHAPASH gives you a <strong>clean, interactive dashboard</strong> where you can explore:</p><ul><li>Predictions for each individual case</li><li>Feature importance for every decision</li><li>A global view of model behavior and logic</li></ul><p>Here’s a quick look at the interface you’ll see running on localhost:8080:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hReuERAZ0hSWCwdBTasUjQ.png" /><figcaption>Figure 06: Shapash monitor for monitoring</figcaption></figure><p>It’s intuitive, no-code, and built to make black-box models explainable — even for non-technical users.</p><p>Now, you might be wondering what you’re seeing. Let me break it down:</p><ul><li><strong>Top right corner:</strong> The predicted output — either 0 (not approved) or 1 (approved). You can switch between these using the dropdown.</li><li><strong>Top left corner:</strong> A bar plot showing <strong>feature importance</strong> — which factors influence the prediction more than others.</li><li><strong>Bottom left corner:</strong> A scatter plot with loan grades on the x-axis and their contributions on the y-axis — yellow points lean toward approval (1), blue toward rejection (0). For example, the model is cautious approving grade 0 between 0–0.3 and mostly predicts rejection for other grades.</li><li><strong>Bottom right corner:</strong> A local explainability graph showing positive (yellow) and negative (blue) feature contributions for a specific case.</li></ul><h3>BUSINESS SOLUTION</h3><p>For rejected loans, here’s what’s driving the decision:</p><h4><strong>Negative contributors:</strong></h4><ul><li>Low income (moderate feature importance)</li><li>Low loan-to-income ratio (mostly in the 0.1–0.2 range on the scatter plot)</li><li>Low loan grade (not the worst, but with strong negative influence)</li><li>Minimal impact from interest rate, age, and loan intent</li></ul><h4><strong>Positive contributors (allowed factors):</strong></h4><ul><li>Higher loan amount (decent importance)</li><li>Homeownership (a strong sign of financial stability)</li><li>Employment length barely affects the decision</li></ul><p>Think of it like <em>a car at a fork </em>in the road. Some factors push it toward approval, others toward rejection. Since the <strong>weights favor rejection more heavily</strong>, the final call is “REJECTED.”</p><p>This clarity lets customers understand exactly <strong>why</strong> their loan was denied, reducing distrust and easing legal pressures by providing transparent, data-driven reasons.</p><h3>APPENDIX</h3><p>Documentation: <a href="https://maif.github.io/shapash/">https://maif.github.io/shapash/</a></p><h3>CONCLUSION</h3><p>Using SHAPASH, we can open the black box of machine learning models and clearly explain decisions — like why a loan gets approved or rejected. This transparency builds trust with customers and helps businesses reduce confusion and legal risks. It’s a powerful way to turn complex data into understandable, actionable insights.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbbaf6d88d05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlock RAG Based YouTube Videos with AI: Step-by-Step Guide to Video Q&A Bots]]></title>
            <link>https://medium.com/@tahasinahoni2/unlock-rag-based-youtube-videos-with-ai-step-by-step-guide-to-video-q-a-bots-4c5d87966111?source=rss-7b3109fc909a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c5d87966111</guid>
            <category><![CDATA[youtube-bot]]></category>
            <category><![CDATA[langchain-agents]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Tahasin islam]]></dc:creator>
            <pubDate>Thu, 24 Jul 2025 06:57:10 GMT</pubDate>
            <atom:updated>2025-07-24T06:57:10.012Z</atom:updated>
            <content:encoded><![CDATA[<p>YouTube is a treasure trove of knowledge, but sifting through long videos to find precise answers can be tedious. What if you could ask questions and get instant, accurate responses directly from a video’s transcript? That’s exactly what I set out to build — a smart AI-powered pipeline that extracts video data, intelligently retrieves relevant content, and leverages large language models (LLMs) to deliver clear answers.</p><p>In this post, I’ll walk you through each step of creating this seamless YouTube Q&amp;A bot, sharing insights on how to transform raw video transcripts into actionable knowledge with cutting-edge AI techniques.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*I7yKfX_bcy7DWAv73X3GPA.png" /><figcaption>Image By (Authors)</figcaption></figure><p>I kicked things off by importing the essentials and defining a persistent Graph State—the brain that carries context across the entire flow. To keep things traceable, I wired up a logger so I can watch the pipeline unfold in real time like a live ops dashboard.</p><pre>from langchain_groq import ChatGroq<br>from dotenv import load_dotenv<br>from typing_extensions import TypedDict, List, Optional<br>import logging<br>from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_huggingface import HuggingFaceEmbeddings<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_community.vectorstores import Chroma<br>from langgraph.graph import StateGraph, END<br><br><br># Basic setup - logs to console<br>logging.basicConfig(<br>    level=logging.INFO,<br>    format=&#39;%(asctime)s - %(levelname)s - %(message)s&#39;<br>)<br><br># Create logger<br>logger = logging.getLogger(__name__)<br>load_dotenv()<br><br><br>class GraphState(TypedDict):<br>    &quot;&quot;&quot;State of the graph&quot;&quot;&quot;<br>    messages: List[str]<br>    query: str<br>    rewritten_query: str<br>    video_url: str<br>    video_id: str<br>    transcript: str<br>    retrieved_docs: Optional[List[dict]]<br>    multi_query: List[str]<br>    retriever: Optional[object]<br>    final_answer: str<br>    response: str</pre><p>Next, I set up a clean constructor to initialize all the key modules — keeping everything modular, scalable, and ready for extension.</p><pre>class MainGraph:<br>    &quot;&quot;&quot;Main Runnable Graph&quot;&quot;&quot;<br>    <br>    def __init__(self) -&gt; None:<br>        self.llm = ChatGroq(model=&quot;llama-3.1-8b-instant&quot;)<br>        self.embeddings = HuggingFaceEmbeddings(model_name=&quot;all-MiniLM-L6-v2&quot;)<br>        self.splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)</pre><p>Inside the main graph class, I crafted a get_video_id() method to extract the video ID straight from any YouTube URL. Then, I paired it with get_transcript_from_id() to fetch the full transcript—setting the stage for smart video processing.</p><pre>def get_video_id(self, state: GraphState) -&gt; GraphState:<br>        &quot;&quot;&quot;Retrieve video-id from a url&quot;&quot;&quot;<br>        logger.info(&quot;Entered into get_video_id function&quot;)<br>        try:<br>            # Get the current state of video url<br>            video_url = state[&#39;video_url&#39;]<br><br>            # Extract video id from different YouTube URL formats<br>            if &quot;watch?v=&quot; in video_url:<br>                video_id = video_url.split(&quot;watch?v=&quot;)[-1].split(&quot;&amp;&quot;)[0]<br>            elif &quot;youtu.be/&quot; in video_url:<br>                video_id = video_url.split(&quot;youtu.be/&quot;)[-1].split(&quot;?&quot;)[0]<br>            else:<br>                raise ValueError(&quot;Invalid YouTube URL format&quot;)<br><br>            # Save it for next node<br>            state[&#39;video_id&#39;] = video_id<br><br>            # Update messages<br>            state[&#39;messages&#39;].append(f&quot;[get_video_id] Retrieved video ID: {video_id}&quot;)<br><br>            return state<br>        <br>        except Exception as e:<br>            logger.error(f&quot;Error encountered while getting video id: {e}&quot;)<br>            state[&#39;messages&#39;].append(f&quot;[get_video_id] Error: {str(e)}&quot;)<br>            return state<br>        finally:<br>            logger.info(&quot;Exited from get_video_id function&quot;)<br>    <br>    def get_transcript_from_id(self, state: GraphState) -&gt; GraphState:<br>        &quot;&quot;&quot;Retrieve transcript from a video-id&quot;&quot;&quot;<br>        logger.info(&quot;Entered into get_transcript_from_id function&quot;)<br>        try:<br>            # Get current state of video_id<br>            video_id = state[&#39;video_id&#39;]<br>            # Fetch transcript in English<br>            transcript = YouTubeTranscriptApi().fetch(video_id= video_id, languages=[&#39;en&#39;])<br>            <br>            # Extract text from transcript entries<br>            text_parts = [entry.text for entry in transcript]<br>            text = &#39; &#39;.join(text_parts)<br><br>            # Update state<br>            state[&#39;transcript&#39;] = text<br>            state[&#39;messages&#39;].append(f&quot;[get_transcript_from_id] Retrieved transcript ({len(text)} characters)&quot;)<br><br>            return state<br>        <br>        except TranscriptsDisabled:<br>            logger.error(&quot;Transcripts are disabled for this video&quot;)<br>            state[&#39;messages&#39;].append(&quot;[get_transcript_from_id] Error: Transcripts disabled&quot;)<br>            return state<br>        except Exception as e:<br>            logger.error(f&quot;Error encountered while getting transcript: {e}&quot;)<br>            state[&#39;messages&#39;].append(f&quot;[get_transcript_from_id] Error: {str(e)}&quot;)<br>            return state<br>        finally:<br>            logger.info(&quot;Exited from get_transcript_from_id function&quot;)</pre><p>I added a <strong>query rewriter</strong> to smartly rephrase user questions — making them optimized for pulling the most relevant chunks from the vector store. It feeds the LLM two key ingredients:</p><ol><li>The original <strong>user query</strong></li><li>The <strong>video transcript</strong> as context</li></ol><p>This boosts retrieval precision and keeps the responses laser-focused.</p><pre>def query_rewriter(self, state: GraphState) -&gt; GraphState:<br>        &quot;&quot;&quot;Rewrite query by LLM&quot;&quot;&quot;<br>        logger.info(&quot;Entered into query_rewriter function&quot;)<br>        try:<br>            # Get question retrieved from state<br>            query = state[&#39;query&#39;]<br><br>            # Get transcipt<br>            context = state[&#39;transcript&#39;]<br><br>            prompt = ChatPromptTemplate.from_messages([<br>                (&quot;system&quot;, &quot;&quot;&quot;You are a query optimization specialist. Your job is to transform user queries into optimized versions that will retrieve the most relevant information from a vector database.Instructions<br>Analyze the original query and context, then return an optimized query that:<br><br>Preserves Intent: Maintains the core meaning and purpose of the original query<br>Adds Specificity: Incorporates relevant details from the context to make the query more specific<br>Uses Clear Keywords: Includes important keywords and terminology that are likely to match relevant documents<br>Removes Ambiguity: Eliminates vague terms and clarifies unclear references<br>Optimizes for Semantic Search: Structures the query to work well with vector similarity matching<br><br>Optimization Guidelines:<br><br>Replace pronouns (he, she, it, they) with specific nouns from the context<br>Add relevant technical terms, names, or specific concepts mentioned in the transcript<br>Remove conversational filler words (um, well, you know, etc.)<br>Expand abbreviations if context provides full forms<br>Include synonyms or related terms that might appear in relevant documents<br>Structure as a clear, focused statement or question<br>Keep the query concise but comprehensive (typically 10-30 words)<br><br>Output Format<br>Return only the optimized query without explanation or additional text.<br>Example<br>Original Query: &quot;How does that algorithm work?&quot;<br>Context: &quot;We were discussing the QuickSort algorithm implementation in Java for sorting large datasets...&quot;<br>Optimized Query: &quot;QuickSort algorithm implementation Java sorting large datasets mechanism process&quot;&quot;&quot;),<br>                (&quot;human&quot;, &quot;&quot;&quot;Original Query: {query}<br>Transcript Context: {context}&quot;&quot;&quot;)<br>            ])<br><br>            # Create chain for invoke<br>            chain = prompt | self.llm<br><br>            # Get response from llm<br>            response = chain.invoke({&quot;query&quot;: query, &quot;context&quot;: context})<br><br>            # Update state for rewritten_query <br>            state[&#39;rewritten_query&#39;] = response.content<br><br>            # Update messages state <br>            state[&quot;messages&quot;].append(f&quot;[query_rewriter] Rewritten query stored in state&quot;)<br><br>            return state<br>        <br>        except Exception as e:<br>            logger.error(f&quot;Encountered error while rewriting query: {e}&quot;)<br>            state[&#39;messages&#39;].append(f&quot;[query_rewriter] Error: {str(e)}&quot;)<br>            return state<br>        finally:<br>            logger.info(&quot;Exited from query_rewriter function&quot;)</pre><p>To level up the retrieval game, I built a <strong>multi-query generator</strong>. Instead of relying on a single shot, it fires multiple reformulated queries into the vector database — ensuring we extract only the <strong>most relevant</strong> and <strong>context-rich</strong> information every time.</p><pre>def multi_query_generator(self, state: GraphState) -&gt; GraphState:<br>        &quot;&quot;&quot;Generate multi query to retrieve from database&quot;&quot;&quot;<br>        logger.info(&quot;Entered into multi_query_generator function&quot;)<br>        try:<br>            # Get updated state from rewritten query<br>            rewritten_query = state[&#39;rewritten_query&#39;]<br>    <br>            prompt = ChatPromptTemplate.from_messages([<br>                (&quot;system&quot;, &quot;&quot;&quot;You are a helpful assistant that generates a list of similar queries based on the given query. <br>                Generate 3-5 variations of the query to help retrieve relevant documents from a vector database.<br>                Return only the queries, one per line, without numbering or bullets.&quot;&quot;&quot;),<br>                (&quot;human&quot;, &quot;User query: {query}&quot;)<br>            ])<br><br>            # Form the chain <br>            chain = prompt | self.llm<br><br>            # Invoke to get response<br>            response = chain.invoke({&quot;query&quot;: rewritten_query})<br><br>            # Parse the response into a list of queries<br>            query_lines = [line.strip() for line in response.content.split(&#39;\n&#39;) if line.strip()]<br>            <br>            # Include the original rewritten query<br>            multi_queries = [rewritten_query] + query_lines<br><br>            # Update the state <br>            state[&#39;multi_query&#39;] = multi_queries<br><br>            # Update the messages state <br>            state[&#39;messages&#39;].append(f&quot;[multi_query_generator] Generated {len(multi_queries)} queries&quot;)<br><br>            return state<br>        <br>        except Exception as e:<br>            logger.error(f&quot;Error encountered while processing multi query function: {e}&quot;)<br>            state[&#39;messages&#39;].append(f&quot;[multi_query_generator] Error: {str(e)}&quot;)<br>            # Fallback to using rewritten query<br>            state[&#39;multi_query&#39;] = [state.get(&#39;rewritten_query&#39;, state[&#39;query&#39;])]<br>            return state<br>        finally:<br>            logger.info(&quot;Exited from multi_query_generator function&quot;)</pre><p>Next up, I set up a vector database using <strong>Chroma</strong>, where the video transcript becomes the core document. I chunked it with a size of 1000 tokens and an overlap of 200—ensuring smooth context flow between parts.</p><p>After loading the docs, I created a <strong>retriever</strong> powered by MMR (Maximal Marginal Relevance) to balance diversity and relevance. It pulls back the top <strong>8 most relevant chunks</strong> for each query—sharpening the context for the LLM.</p><pre>def create_vector_database(self, state: GraphState) -&gt; GraphState:<br>        &quot;&quot;&quot;Create a vector database&quot;&quot;&quot;<br>        logger.info(&quot;Entered into create_vector_database function&quot;)<br>        try:<br>            # Get transcript as documents<br>            documents = state[&#39;transcript&#39;]<br><br>            if not documents:<br>                raise ValueError(&quot;No transcript available to create vector database&quot;)<br><br>            def chunk_docs(documents):<br>                &quot;&quot;&quot;Chunk the documents into smaller size&quot;&quot;&quot;<br>                chunks = self.splitter.create_documents([documents])<br>                return chunks<br>            <br>            # Create vector store<br>            vecstore = Chroma.from_documents(<br>                documents=chunk_docs(documents=documents), <br>                embedding=self.embeddings<br>            )<br><br>            # Create a retriever for vecstore<br>            retriever = vecstore.as_retriever(search_type=&quot;mmr&quot;, search_kwargs={&quot;k&quot;: 8})<br><br>            # Update retriever in state<br>            state[&#39;retriever&#39;] = retriever<br><br>            # Update message state <br>            state[&#39;messages&#39;].append(&quot;[create_vector_database] Vector database created and retriever added to state&quot;)<br><br>            return state<br>        <br>        except Exception as e:<br>            logger.error(f&quot;Error encountered while creating vector database: {e}&quot;)<br>            state[&#39;messages&#39;].append(f&quot;[create_vector_database] Error: {str(e)}&quot;)<br>            return state<br>        finally:<br>            logger.info(&quot;Exited from create_vector_database function&quot;)</pre><p>After multi-querying the vector store, I made sure we <strong>don’t get duplicate docs cluttering the results</strong>. How? By generating a <strong>unique hash for each document</strong> and only appending it if its hash hadn’t been seen before. Clean, relevant, non-redundant context — guaranteed.</p><pre>def retrieve_docs(self, state: GraphState) -&gt; GraphState:<br>        &quot;&quot;&quot;Retrieve documents from vector database&quot;&quot;&quot;<br>        logger.info(&quot;Entered into retrieve_docs function&quot;)<br>        try:<br>            # Get the retriever from state <br>            retriever = state[&#39;retriever&#39;]<br>            <br>            if not retriever:<br>                raise ValueError(&quot;No retriever available&quot;)<br><br>            # Get multiple queries for invoking <br>            multi_query = state[&#39;multi_query&#39;]<br><br>            # Initialize retrieved_docs if not exists<br>            if state[&#39;retrieved_docs&#39;] is None:<br>                state[&#39;retrieved_docs&#39;] = []<br><br>            # Retrieve documents for each query<br>            all_docs = []<br>            for query in multi_query:<br>                try:<br>                    docs = retriever.invoke(query)<br>                    all_docs.extend(docs)<br>                except Exception as e:<br>                    logger.warning(f&quot;Error retrieving docs for query &#39;{query}&#39;: {e}&quot;)<br><br>            # Remove duplicates based on content<br>            unique_docs = []<br>            seen_content = set()<br>            for doc in all_docs:<br>                content_hash = hash(doc.page_content)<br>                if content_hash not in seen_content:<br>                    unique_docs.append(doc)<br>                    seen_content.add(content_hash)<br><br>            state[&#39;retrieved_docs&#39;] = unique_docs<br><br>            # Update state of messages <br>            state[&#39;messages&#39;].append(f&quot;[retrieve_docs] Retrieved {len(unique_docs)} unique documents&quot;)<br>        <br>            return state<br>        <br>        except Exception as e:<br>            logger.error(f&quot;Error encountered while retrieving documents: {e}&quot;)<br>            state[&#39;messages&#39;].append(f&quot;[retrieve_docs] Error: {str(e)}&quot;)<br>            return state<br>        finally:<br>            logger.info(&quot;Exited from retrieve_docs function&quot;)</pre><p>Once the docs were retrieved, I calculated <strong>cosine similarity</strong> between the <strong>embedded user query</strong> and each <strong>embedded document</strong>. Based on that, each doc got a relevance score, and I <strong>sorted and selected the top 8</strong> most aligned results.</p><p>To validate the filtering, I also calculated an <strong>overall similarity score</strong> — a sanity check to ensure we’re surfacing only the most meaningful context.</p><pre>def rerank_docs(self, state: GraphState) -&gt; GraphState:<br>        &quot;&quot;&quot;Rerank the docs by semantic and llm based search&quot;&quot;&quot;<br>        logger.info(&quot;Entered into rerank_docs function&quot;)<br>        try:<br>            # Get retreived docs<br>            docs = state[&#39;retrieved_docs&#39;]<br><br>            # Get rewrotten query <br>            rewrotten_query = state[&#39;rewritten_query&#39;]<br><br>            if not docs:<br>                state[&#39;messages&#39;].append(&quot;Document not available for ranking&quot;)<br>                return state<br>            <br>            reranked_docs = self._semantic_reranking(docs, rewrotten_query)<br><br>            state[&#39;retrieved_docs&#39;] = reranked_docs<br><br>            state[&#39;messages&#39;].append(f&quot;[rerank_documents] Reranked {len(reranked_docs)} documents&quot;)<br>            <br>            return state<br>        <br>        except Exception as e:<br>            logger.error(f&quot;Error encountered while reranking documents: {e}&quot;)<br>            state[&#39;messages&#39;].append(f&quot;[rerank_documents] Error: {str(e)}&quot;)<br>            return state<br>        finally:<br>            logger.info(&quot;Exited from rerank_documents function&quot;)<br><br>    def _semantic_reranking(self , documents ,query):<br>        &quot;&quot;&quot;Re-rank documents based on cosine similarity&quot;&quot;&quot;<br>        from sklearn.metrics.pairwise import cosine_similarity<br>        import numpy as np<br>        <br>        try:<br>            # Get embeddings for query and documents<br>            query_embedding = self.embeddings.embed_query(query)<br>            doc_embeddings = self.embeddings.embed_documents([doc.page_content for doc in documents])<br>            <br>            # Calculate similarity scores<br>            similarities = cosine_similarity([query_embedding], doc_embeddings)[0]<br>            <br>            # Create doc-score pairs and sort by similarity<br>            doc_scores = list(zip(documents, similarities))<br>            doc_scores.sort(key=lambda x: x[1], reverse=True)<br>            <br>            # Return top documents with similarity scores<br>            reranked_docs = []<br>            for doc, score in doc_scores[:8]:  # Top 8 documents<br>                # Add similarity score as metadata<br>                doc.metadata[&#39;similarity_score&#39;] = float(score)<br>                reranked_docs.append(doc)<br>                <br>            return reranked_docs<br>            <br>        except Exception as e:<br>            logger.warning(f&quot;Error in semantic reranking: {e}&quot;)<br>            return documents</pre><p>After ranking, I applied a <strong>similarity threshold of 0.1</strong> — filtering out low-relevance docs. Only the ones scoring above the line made the cut. These are the <strong>authentic, high-signal documents</strong> we’ll feed into the LLM. No fluff. Just pure, contextual gold.</p><pre>def filter_docs(self, state: GraphState) -&gt; GraphState:<br>        &quot;&quot;&quot;Get docs that maintains a threshold&quot;&quot;&quot;<br>        logger.info(&quot;Entered into filter ranked docs function&quot;)<br>        try:<br>            retrieved_docs = state[&#39;retrieved_docs&#39;]<br>            <br>            if not retrieved_docs:<br>                state[&#39;messages&#39;].append(&quot;[filter_docs] No documents to filter&quot;)<br>                return state<br>            <br>            # Initialize filtered docs list<br>            filtered_docs = []<br>            <br>            # Count documents that meet criteria<br>            total_docs = len(retrieved_docs)<br>            passed_similarity = 0<br>            <br>            for doc in retrieved_docs:<br>                similarity_score = doc.metadata.get(&#39;similarity_score&#39;, 0.0)<br>                <br>                # Check individual criteria<br>                sim_pass = similarity_score &gt; 0.1<br>                <br>                if sim_pass:<br>                    passed_similarity += 1<br>            <br>                # Apply threshold filtering (both conditions must be met)<br>                if sim_pass:<br>                    filtered_docs.append(doc)<br>                    logger.info(f&quot;Document passed - Similarity: {similarity_score:.3f}&quot;)<br>                else:<br>                    logger.info(f&quot;Document filtered out - Similarity: {similarity_score:.3f}&quot;)<br>            <br>            # Update state with filtered documents<br>            state[&#39;retrieved_docs&#39;] = filtered_docs<br>            <br>            # Detailed logging<br>            logger.info(f&quot;Filtering results: {total_docs} total, {passed_similarity} passed similarity&quot;)<br>            <br>            # Update messages state with detailed info<br>            state[&#39;messages&#39;].append(<br>                f&quot;[filter_docs] Filtered {total_docs} documents -&gt; {len(filtered_docs)} remaining &quot;<br>            )<br>            <br>            return state<br>            <br>        except Exception as e:<br>            logger.error(f&quot;Error encountered while filtering documents: {e}&quot;)<br>            state[&#39;messages&#39;].append(f&quot;[filter_docs] Error: {str(e)}&quot;)<br>            return state<br>        finally:<br>            logger.info(&quot;Exited from filtering_documents function&quot;)</pre><p>To avoid overwhelming the model with extra fluff, I compressed the filtered documents — trimming down context length while keeping the essence intact. This way, the LLM gets a <strong>concise, power-packed summary</strong> that’s laser-focused on what matters most.</p><pre>def contextual_compression(self, state: GraphState) -&gt; GraphState:<br>        &quot;&quot;&quot;Compression extra contexts based on query context&quot;&quot;&quot;<br>        logger.info(&quot;Entered into contextual compression function&quot;)<br>        try:<br>            # Get rewrtitten_query <br>            rewritten_query = state[&#39;rewritten_query&#39;]<br><br>            docs = state[&#39;retrieved_docs&#39;]<br><br>            prompt = ChatPromptTemplate.from_messages([<br>                (&quot;system&quot;, &quot;&quot;&quot;&quot;You are a context compression system. Your ONLY job is to extract and preserve relevant sentences from the provided documents that relate to the user&#39;s query.<br><br>STRICT RULES:<br>1. ONLY extract sentences that DIRECTLY/CONTEXTUALLY relate to the user&#39;s query<br>2. NEVER add, modify, or rephrase any content<br>3. NEVER generate new sentences or explanations<br>8. NEVER provide summaries or interpretations<br>5. NEVER add connecting words or transitions<br>6. Keep the EXACT original wording from the documents<br>7. If no relevant content exists, JUST REPLY WITH &quot;NO_RELEVANT_CONTENT&quot;, NOT ANYTHING ELSE<br><br>TASK: Extract ONLY the sentences from the documents that answer or relate to the query.&quot;&quot;&quot;), <br>(&quot;human&quot;, &quot;QUERY: {query} DOCUMENTS: {documents} COMPRESSED CONTEXT (extract relevant sentences only):&quot;)<br>            ])<br><br>            chain = prompt | self.llm<br><br>            response = chain.invoke({&quot;query&quot;: rewritten_query, &quot;documents&quot;: docs})<br><br>            state[&#39;retrieved_docs&#39;] = response.content<br><br>            state[&#39;messages&#39;].append(&quot;[compressed_context] Provided context are compressed&quot;)<br><br>            return state<br>        except Exception as e:<br>            logger.error(f&quot;Error encountered while compressing context: {e}&quot;)<br>            state[&#39;messages&#39;].append(f&quot;[Error] compressed_context: {e}&quot;)<br>            return state<br>        <br>        finally:<br>            logger.info(&quot;Exited from contextual compression function&quot;)</pre><p>I built a <strong>document router</strong> to intelligently choose the next step based on context availability.</p><ul><li>If <strong>relevant documents are found</strong>, it routes the flow to <strong>“retrieve_docs”</strong> for deeper info extraction.</li><li>If no strong context exists, it directly moves to <strong>“invoking_to_llm”</strong>, letting the model handle the query without extra context.</li></ul><p>This dynamic routing ensures efficiency — only pulling in docs when they truly add value.</p><pre>def document_router(self, state: GraphState):<br>        &quot;&quot;&quot;A router that route to right decision&quot;&quot;&quot;<br>        logger.info(&quot;Entered into document router node&quot;)<br>        try:<br>            docs = state[&#39;retrieved_docs&#39;]<br><br>            <br>            if isinstance(docs, str) and docs == &quot;NO_RELEVANT_CONTENT&quot;:<br>                # No relevant content found, should end or try different approach<br>                return &quot;retrieve_docs&quot; <br>            else:<br>                # No docs retrieved, might want to retry or end<br>                return &quot;invkoing_to_llm&quot;  <br>        except Exception as e:<br>            logger.error(f&quot;Encountered error while routing documents: {e}&quot;)<br>            return &quot;retrieve_docs&quot; </pre><p>At last, I created the final function that sends the refined query and the curated context to the LLM — triggering the AI to generate the precise, informed answer we’ve been working toward. This is where all the prep pays off and the magic happens.</p><pre>def invkoing_to_llm(self, state: GraphState) -&gt; GraphState:<br>        &quot;&quot;&quot;Invoke context and query to get meaningfull answer&quot;&quot;&quot;<br>        logger.info(&quot;Entered into invking_tol_llm function&quot;)<br>        try:<br><br>            docs = state[&#39;retrieved_docs&#39;]<br><br>            qustion = state[&#39;rewritten_query&#39;]<br><br>            GROUNDED_QA_PROMPT = ChatPromptTemplate.from_messages([(&quot;ai&quot;, &quot;&quot;&quot;You are a document-based question answering system. Answer the query using ONLY the information provided in the documents.<br><br>STRICT RULES:<br>1. Use ONLY information explicitly stated in the provided documents<br>2. Every factual claim MUST include a citation: [Document X: &quot;exact quote from document&quot;]<br>3. If the answer is not in the documents, respond: &quot;The provided documents do not contain information to answer this query.&quot;<br>8. DO NOT use external knowledge, assumptions, or information not in the documents<br>5. Quote the exact text that supports each part of your answer<br>6. DONT PROVIDE ANY THINGS ELSE without DOCUMENTS<br>7. DON&#39;T MAKE any GUESS OR ANY CODE, INFORMATION BY YOURSELF (IMPORTANT!)/ DONT give me example answer<br><br>EXAMPLE:<br>Query: &quot;What is machine learning?&quot;<br>Documents:<br>Document 1: &quot;Machine learning is a subset of artificial intelligence that allows computers to learn from data without being explicitly programmed.&quot;<br>Document 2: &quot;There are three main types of machine learning: supervised, unsupervised, and reinforcement learning.&quot;<br><br>CORRECT Answer:<br>Machine learning is defined as [Document 1: &quot;a subset of artificial intelligence that allows computers to learn from data without being explicitly programmed&quot;]. The field includes [Document 2: &quot;three main types of machine learning: supervised, unsupervised, and reinforcement learning&quot;].<br><br>INCORRECT Answer:<br>Machine learning is a popular technology used by many companies today... (NO CITATION - WRONG!)&quot;&quot;&quot;), <br><br>(&quot;human&quot;, &quot;&quot;&quot;Query: {query}<br><br>Documents:<br>{documents}<br><br>Answer with citations:&quot;&quot;&quot;)<br><br>])<br>            chain = GROUNDED_QA_PROMPT | self.llm<br><br>            logger.info(docs)<br><br>            response = chain.invoke({&quot;query&quot;: qustion, &quot;documents&quot;: docs})<br><br>            state[&#39;final_answer&#39;] = response.content<br><br>            state[&#39;messages&#39;].append(&quot;Answer generated successfully&quot;)<br>            <br>            return state<br>        except Exception as e:<br>            logger.error(f&quot;Error encountered while invoking to llm: {e}&quot;)<br>            state[&#39;messages&#39;].append(f&quot;[Invking to llm] Error: {e}&quot;)<br>            return state<br>        finally:<br>            logger.info(&quot;Exited from invoking to llm function&quot;)</pre><p>To keep the pipeline smooth and organized, I drafted code for <strong>graph nodes and edges</strong> — the building blocks that represent discrete tasks and their connections. This graph structure maintains the flow, ensures each step triggers the next seamlessly, and makes the whole system scalable and easy to debug.</p><pre>def _create_node_and_edge(self):<br>        &quot;&quot;&quot;Create the graph with nodes and edges&quot;&quot;&quot;<br>        graph = StateGraph(state_schema=GraphState)<br><br>        # Add nodes<br>        graph.add_node(&quot;get_video_id&quot;, self.get_video_id)<br>        graph.add_node(&quot;get_transcript_from_id&quot;, self.get_transcript_from_id)<br>        graph.add_node(&quot;query_rewriter&quot;, self.query_rewriter)<br>        graph.add_node(&quot;multi_query_generator&quot;, self.multi_query_generator)<br>        graph.add_node(&quot;create_vector_db&quot;, self.create_vector_database)<br>        graph.add_node(&quot;retrieve_docs&quot;, self.retrieve_docs)<br>        graph.add_node(&quot;rerank_docs&quot;, self.rerank_docs)<br>        graph.add_node(&quot;filter_docs&quot;, self.filter_docs)<br>        graph.add_node(&quot;contextual_compression&quot;, self.contextual_compression)<br>        graph.add_node(&quot;invkoing_to_llm&quot;, self.invkoing_to_llm)<br><br>        # Set entry point<br>        graph.set_entry_point(&quot;get_video_id&quot;)<br>        <br>        # Add edges<br>        graph.add_edge(&quot;get_video_id&quot;, &quot;get_transcript_from_id&quot;)<br>        graph.add_edge(&quot;get_transcript_from_id&quot;, &quot;query_rewriter&quot;)<br>        graph.add_edge(&quot;query_rewriter&quot;, &quot;multi_query_generator&quot;)<br>        graph.add_edge(&quot;multi_query_generator&quot;, &quot;create_vector_db&quot;)<br>        graph.add_edge(&quot;create_vector_db&quot;, &quot;retrieve_docs&quot;)<br>        graph.add_edge(&quot;retrieve_docs&quot;, &quot;rerank_docs&quot;)<br>        graph.add_edge(&quot;rerank_docs&quot;, &quot;filter_docs&quot;)<br>        graph.add_edge(&quot;filter_docs&quot;, &quot;contextual_compression&quot;)<br>        graph.add_conditional_edges(&quot;contextual_compression&quot;, self.document_router, {&quot;retrieve_docs&quot;: &quot;retrieve_docs&quot;, &quot;invkoing_to_llm&quot;: &quot;invkoing_to_llm&quot;})<br>        graph.add_edge(&quot;invkoing_to_llm&quot;, END)<br><br>        app = graph.compile()<br>        return app</pre><p>Finally, I built the <strong>main method</strong> that ties everything together. It takes a YouTube video URL, triggers the entire pipeline — from extracting the video ID and transcript, through smart retrieval and ranking, all the way to invoking the LLM — and returns a sharp, context-aware answer. This method is the command center powering your seamless YouTube video Q&amp;A experience.</p><pre>def generate_answer(self, video_url: str, query: str):<br>        &quot;&quot;&quot;Main method to generate answer from YouTube video&quot;&quot;&quot;<br>        <br>        app = self._create_node_and_edge()<br><br>        # Initialize state with all required fields<br>        state = {<br>            &quot;video_url&quot;: video_url,<br>            &quot;query&quot;: query,<br>            &quot;messages&quot;: [],<br>            &quot;rewritten_query&quot;: &quot;&quot;,<br>            &quot;video_id&quot;: &quot;&quot;,<br>            &quot;transcript&quot;: &quot;&quot;,<br>            &quot;retrieved_docs&quot;: [],<br>            &quot;multi_query&quot;: [],<br>            &quot;retriever&quot;: None,<br>            &quot;final_answer&quot;: &quot;&quot;<br>        }<br><br>        try:<br>            response = app.invoke(input=state)<br>            return {<br>                &quot;messages&quot;: response.get(&#39;messages&#39;, []),<br>                &quot;video_id&quot;: response.get(&#39;video_id&#39;, &#39;&#39;),<br>                &quot;multi_query&quot;: response.get(&quot;multi_query&quot;, []),<br>                &quot;retrieved_docs&quot;: response.get(&quot;retrieved_docs&quot;, []),<br>                &quot;final_answer&quot;: response.get(&quot;final_answer&quot;, &quot;&quot;)<br>            }<br>        except Exception as e:<br>            logger.error(f&quot;Error in generate_answer: {e}&quot;)<br>            return {<br>                &quot;multi_query&quot;: f&quot;Error processing request: {str(e)}&quot;,<br>                &quot;messages&quot;: [f&quot;Error: {str(e)}&quot;],<br>                &quot;video_id&quot;: &quot;&quot;<br>            }</pre><p>To wrap it all up, I created a <strong>main function</strong> that kicks off the entire process. This entry point orchestrates the flow from start to finish, ensuring every component fires in the right order — making your YouTube video Q&amp;A system easy to run and maintain with a single call.</p><pre><br>def main():<br>    &quot;&quot;&quot;Main function to test the YouTube summarizer&quot;&quot;&quot;<br>    main_graph = MainGraph()<br>    <br>    # Test with a YouTube video<br>    video_url = &quot;https://www.youtube.com/watch?v=jXXOI01IuPs&quot;<br>    query = &quot;What are the key points of this video?&quot;<br>    <br>    result = main_graph.generate_answer(video_url, query)<br> <br>    print(&quot;\n=== PROCESSING MESSAGES ===&quot;)<br>    for message in result[&#39;messages&#39;]:<br>        print(message)<br><br>    print(result[&quot;final_answer&quot;])<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>After all the behind-the-scenes magic, here’s a glimpse of the sharp, relevant answer the system generates — cutting through noise and delivering exactly what you asked about the YouTube video. It’s concise, context-rich, and impressively on point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*1SCoLUf1F_qDYIo5NxkMBQ.png" /><figcaption>Figure 01:; Glimpse output from Graph</figcaption></figure><h3>Conclusion: Turning Videos into Instant Knowledge</h3><p>Building this YouTube Q&amp;A pipeline showed how powerful combining video transcripts, smart retrieval, and LLMs can be. By carefully structuring the flow — from extracting video data to ranking and filtering relevant info — we created a system that delivers precise, context-rich answers instantly. This approach doesn’t just unlock video content; it transforms how we interact with knowledge, making information accessible, fast, and reliable.</p><p>The future of video understanding is here — are you ready to build yours?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c5d87966111" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>