<?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 ashok .c on Medium]]></title>
        <description><![CDATA[Stories by ashok .c on Medium]]></description>
        <link>https://medium.com/@ashok.1055?source=rss-ba7f82087217------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3hCzLDcGrIS07glLvFv66A.jpeg</url>
            <title>Stories by ashok .c on Medium</title>
            <link>https://medium.com/@ashok.1055?source=rss-ba7f82087217------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 01:14:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashok.1055/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[Building a Sophisticated Natural Language to SQL System with Multi-Agent Architecture and LangGraph]]></title>
            <link>https://medium.com/@ashok.1055/building-a-sophisticated-natural-language-to-sql-system-with-multi-agent-architecture-and-langgraph-c9d9043f0dce?source=rss-ba7f82087217------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9d9043f0dce</guid>
            <category><![CDATA[text-2-sql]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[natural-language-to-sql]]></category>
            <dc:creator><![CDATA[ashok .c]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 07:55:37 GMT</pubDate>
            <atom:updated>2025-08-02T04:14:32.880Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>Imagine asking your database questions like “Give me a list of customers from Delhi state that made at least 1 payment through credit card” and getting back perfectly formatted SQL queries. This isn’t science fiction — it’s what we’ve built using a multi-agent system powered by LangGraph and Large Language Models.</p><p>In this comprehensive guide, I’ll walk you through the process of creating a production-ready Natural Language to SQL (NL2SQL) system that can handle complex, multi-table queries across e-commerce domains. Our system doesn’t just generate SQL; it intelligently routes queries, validates syntax, handles fuzzy matching for entity resolution, and provides comprehensive error handling.</p><h3>System Architecture: The Multi-Agent Approach</h3><p>Our system employs a sophisticated multi-agent architecture where specialized agents handle different aspects of the NL2SQL conversion process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9MQBXtAStrNOQ3XLxVgrQA.png" /><figcaption>Workflow diagram</figcaption></figure><h3>Core Components</h3><ol><li><strong>Router Agent</strong>: Intelligently determines which domain agents should handle the query</li><li><strong>Domain Agents</strong>: Specialized agents for customer, orders, and product domains</li><li><strong>Filter Check Agent</strong>: Identifies when additional filtering is needed</li><li><strong>Fuzzy Match Agent</strong>: Resolves entity mismatches using advanced string matching</li><li><strong>Query Generator</strong>: Constructs SQL from extracted information</li><li><strong>Query Validator</strong>: Ensures final SQL is syntactically correct and logically sound</li></ol><h3>Step-by-Step Implementation</h3><h3>Step 1: Building the Knowledge Base</h3><p>The foundation of our system is a comprehensive knowledge base that stores table schemas, column descriptions, and sample data:</p><pre># Knowledge Base Structure (kb.pkl)<br>knowledge_base = {<br>    &#39;customer&#39;: [<br>        &#39;Customer demographics and location data&#39;,  # Table description<br>        [  # Column descriptions with samples<br>            [&#39;customer_id&#39;, &#39;Unique identifier for customers&#39;, [&#39;12345&#39;, &#39;67890&#39;]],<br>            [&#39;customer_city&#39;, &#39;City where customer is located&#39;, [&#39;Chennai&#39;, &#39;Mumbai&#39;]],<br>            [&#39;customer_state&#39;, &#39;State where customer is located&#39;, [&#39;Tamil Nadu&#39;, &#39;Maharashtra&#39;]]<br>        ]<br>    ],<br>    &#39;orders&#39;: [...],<br>    &#39;products&#39;: [...]<br>}</pre><p>The knowledge base is generated using our knowledge_base.ipynb notebook, which analyzes the database schema and creates structured descriptions that our agents can understand.</p><h3>Step 2: Implementing the Router Agent</h3><p>The Router Agent is the entry point that analyzes incoming queries and determines which domain agents should handle them:</p><pre>def router(state: finalstate):<br>    &quot;&quot;&quot;<br>    Analyzes user query and routes to appropriate domain agents<br>    &quot;&quot;&quot;<br>    q = state[&#39;user_query&#39;]<br>    # Use LLM to classify query and determine needed agents<br>    routing_result = agent_2(q)  # Returns list like [&#39;customer&#39;, &#39;orders&#39;]<br>    return {&quot;router_out&quot;: eval(routing_result)}</pre><p>The router uses a carefully crafted prompt to analyze queries:</p><pre>template = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, &quot;&quot;&quot;<br>    You are an intelligent router that determines which agents <br>    can answer a user question based on agent descriptions.<br>    &quot;&quot;&quot;),<br>    (&quot;human&quot;, &#39;&#39;&#39;<br>    customer agent: Contains customer and seller location details<br>    orders agent: Contains order details, payments, delivery info<br>    product agent: Contains product catalog and category info<br>    <br>    User question: {question}<br>    &#39;&#39;&#39;)<br>])</pre><h3>Step 3: Domain Agents with LangGraph Sub-workflows</h3><p>Each domain agent is implemented as a LangGraph sub-workflow that breaks down the query processing into manageable steps:</p><pre>class overallstate(TypedDict):<br>    user_query: str<br>    table_lst: list[str]<br>    table_extract: Annotated[list[str], add]<br>    column_extract: Annotated[list[str], add]</pre><pre>def customer_agent_workflow():<br>    &quot;&quot;&quot;<br>    Customer domain agent implemented as LangGraph workflow<br>    &quot;&quot;&quot;<br>    builder = StateGraph(overallstate)<br>    <br>    # Add nodes for sub-question generation and column selection<br>    builder.add_node(&quot;subquestion&quot;, sq_node)<br>    builder.add_node(&quot;column_e&quot;, column_node)<br>    <br>    # Define workflow edges<br>    builder.add_edge(START, &quot;subquestion&quot;)<br>    builder.add_edge(&quot;subquestion&quot;, &quot;column_e&quot;)<br>    builder.add_edge(&quot;column_e&quot;, END)<br>    <br>    return builder.compile()</pre><p>Each domain agent:</p><ol><li>Breaks down queries into sub-questions relevant to their domain</li><li>Selects relevant tables based on query requirements</li><li>Identifies necessary columns using the knowledge base</li><li>Returns structured information for the main workflow</li></ol><h3>Step 4: Advanced Filter Detection and Fuzzy Matching</h3><p>One of the most sophisticated parts of our system is handling entity resolution. When users say “chennai” but the database has “Chennai”, our fuzzy matching system resolves this automatically:</p><pre>def fuzzy_match_resolution(filter_values):<br>    &quot;&quot;&quot;<br>    Resolves entity mismatches using RapidFuzz<br>    &quot;&quot;&quot;<br>    final_matches = []<br>    <br>    for table, column, user_values in filter_values:<br>        # Get actual values from database<br>        db_values = get_unique_values(table, column)<br>        <br>        # Find best matches for each user input<br>        for user_val in user_values:<br>            best_match, score = get_best_fuzzy_match(<br>                user_val, db_values, scorer=fuzz.token_set_ratio<br>            )<br>            <br>            if score &gt; 80:  # Confidence threshold<br>                final_matches.append([table, column, best_match])<br>    <br>    return final_matches</pre><h3>Step 5: SQL Query Generation with Validation</h3><p>Our query generation process is a two-stage approach:</p><p>Stage 1: Initial SQL Generation</p><pre>def generate_sql_query(columns, user_query, filters):<br>    &quot;&quot;&quot;<br>    Generate initial SQL query using selected columns and filters<br>    &quot;&quot;&quot;<br>    prompt = f&quot;&quot;&quot;<br>    Generate MySQL query for: {user_query}<br>    Available columns: {columns}<br>    Required filters: {filters}<br>    <br>    Requirements:<br>    - Use ALL provided columns<br>    - Apply specified filters<br>    - Ensure proper JOIN conditions<br>    - Handle aggregations correctly<br>    &quot;&quot;&quot;<br>    <br>    return llm_chain.invoke(prompt)</pre><p>Stage 2: Query Validation and Refinement</p><pre>def validate_and_refine_query(sql_query, columns, user_query, filters):<br>    &quot;&quot;&quot;<br>    Validate generated SQL and fix any issues<br>    &quot;&quot;&quot;<br>    validation_prompt = f&quot;&quot;&quot;<br>    Validate this SQL query:<br>    {sql_query}<br>    <br>    Check for:<br>    - Syntax correctness<br>    - Logical soundness  <br>    - Proper use of all columns: {columns}<br>    - Correct filter application: {filters}<br>    - Reserved keyword conflicts<br>    &quot;&quot;&quot;<br>    <br>    return validation_chain.invoke(validation_prompt)</pre><h3>Real-World Example: Complete Query Processing</h3><p>Let’s trace through a complete example to see our system in action:</p><p>Input Query: <em>“Give me list of customers from chennai state that made atleast 1 payment through credit card”</em></p><h3>Step 1: Router Analysis</h3><pre>Router determines: [&#39;customer&#39;, &#39;orders&#39;] agents needed</pre><h3>Step 2: Domain Agent Processing</h3><pre>Customer Agent extracts:<br>- Tables: [&#39;customer&#39;]  <br>- Columns: [&#39;customer_id&#39;, &#39;customer_city&#39;, &#39;customer_state&#39;]</pre><pre>Orders Agent extracts:<br>- Tables: [&#39;order_payments&#39;, &#39;orders&#39;]<br>- Columns: [&#39;customer_id&#39;, &#39;payment_type&#39;, &#39;order_id&#39;]</pre><h3>Step 3: Filter Detection</h3><pre>Filter Check identifies:<br>- customer_state: &quot;chennai state&quot; <br>- payment_type: &quot;credit card&quot;</pre><h3>Step 4: Fuzzy Matching</h3><pre>Fuzzy Match resolves:<br>- &quot;chennai&quot; → &quot;Chennai&quot; (95% confidence)<br>- &quot;credit card&quot; → &quot;credit_card&quot; (98% confidence)</pre><h3>Step 5: SQL Generation</h3><pre>SELECT DISTINCT c.customer_id, c.customer_city, c.customer_state<br>FROM customer c<br>JOIN orders o ON c.customer_id = o.customer_id  <br>JOIN order_payments op ON o.order_id = op.order_id<br>WHERE c.customer_state = &#39;Chennai&#39;<br>AND op.payment_type = &#39;credit_card&#39;</pre><h3>Step 6: Validation &amp; Refinement</h3><h4>The validator ensures:</h4><ul><li>Syntax is correct</li><li>All required columns are used</li><li>JOIN conditions are proper</li><li>Filters are correctly applied</li></ul><h3>Query Complexity Support</h3><ul><li>Simple queries: “What are the total number of orders?”</li><li>Multi-table joins: Customer-order-payment relationships</li><li>Advanced analytics: “Average review score by state for delayed orders above category average price”</li><li>Conditional logic: “Sellers with 50+ items, highest 5-star percentage, on-time delivery, installment payments”</li></ul><h3>Conclusion</h3><p>Building a production-ready Natural Language to SQL system requires more than just feeding schemas to an LLM. Our multi-agent approach addresses the real-world challenges of:</p><ul><li>Complex domain logic through specialized agents</li><li>Entity resolution via advanced fuzzy matching</li><li>Query quality through multi-stage validation</li><li>System reliability with comprehensive error handling</li><li>Maintainability through modular architecture</li></ul><p>The result is a system that can handle everything from simple “COUNT(*)” queries to complex multi-table analytics with high accuracy and reliability.</p><p>The complete source code is available on GitHub, and I encourage you to experiment with the system and adapt it for your specific use cases. The combination of LangGraph’s orchestration capabilities with specialized AI agents creates a powerful foundation for natural language data interaction.</p><h3>Try It Yourself</h3><h4><a href="https://github.com/ashok426/Natural_language_to_SQL">Github link for the code</a></h4><p>Thanks for reading</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9d9043f0dce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Multimodal RAG System: Integrating Text, Tables, and Images with LangChain &…]]></title>
            <link>https://medium.com/@ashok.1055/building-a-multimodal-rag-system-integrating-text-tables-and-images-with-langchain-b1a555b6a20c?source=rss-ba7f82087217------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1a555b6a20c</guid>
            <category><![CDATA[chromadb]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[multimodal-rag]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[unstructured]]></category>
            <dc:creator><![CDATA[ashok .c]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 08:38:28 GMT</pubDate>
            <atom:updated>2025-07-17T08:38:28.750Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Multimodal RAG System: Integrating Text, Tables, and Images with LangChain &amp; Unstructured</h3><p>Retrieval-Augmented Generation (RAG) is revolutionizing how we build AI assistants and Q&amp;A systems. But most RAG systems focus solely on text — ignoring valuable data in tables and images. In this tutorial, I’ll show you how to <strong>build a Multimodal RAG pipeline</strong> that can retrieve and reason over <strong>text, tables, and images</strong> using <strong>LangChain, Unstructured, and OpenAI models</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oo6UDPIz7-JWsxaeDfxA7Q.png" /><figcaption>Graph,Tables and Text</figcaption></figure><p>We’ll go step-by-step through the code, from data parsing to image processing, and finally serving results that include both <strong>LLM-generated answers</strong> and the <strong>original supporting images</strong>.</p><h4><a href="https://github.com/ashok426/Multimodal_RAG"><strong>Github link for the code</strong></a></h4><h3>Why Multimodal RAG?</h3><p>Financial, scientific, and business documents often present key insights as a combination of:</p><ul><li>Narrative text</li><li>Structured tables</li><li>Graphs, charts, or images</li></ul><p>A truly helpful assistant should <strong>retrieve and summarize all these data types</strong> — not just plain text.</p><h3>1. Parsing PDFs with Unstructured</h3><p>First, we extract <strong>elements</strong> from a PDF — splitting out headers, footers, narrative text, tables, and images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*J2egfjH3USTmSMYmfm2tzQ.png" /></figure><h3>2. Setting Up OpenAI Models and Embeddings</h3><p>We use OpenAI’s <strong>GPT-4o</strong> for reasoning and summarization, and their embedding model for chunk retrieval</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*dNJWF0COSzxYc-feZKNUIQ.png" /></figure><h3>3. Summarizing Tables and Images for Better Retrieval</h3><p><strong>Text and tables</strong> are summarized using an LLM, which helps in embedding concise, retrieval-optimized representations:</p><pre>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.prompts import ChatPromptTemplate</pre><pre>prompt_text = &quot;&quot;&quot;You are an AI Assistant tasked with summarizing tables for retrieval. \<br>Give a concise summary of the table that is well optimized for retrieval. Table: {element} &quot;&quot;&quot;</pre><pre>prompt = ChatPromptTemplate.from_template(prompt_text)<br>summarize_chain = {&quot;element&quot;: lambda x: x} | prompt | model | StrOutputParser()<br>table_summaries = summarize_chain.batch(Table, {&quot;max_concurrency&quot;: 5})</pre><h3>4. Storing Chunks in a Vector Database</h3><p>We use <strong>ChromaDB</strong> as our vector store and <strong>LangChain’s MultiVectorRetriever</strong> to handle multimodal data:</p><pre>def create_multi_vector_retriever(vectorstore, text_summaries, texts, table_summaries, tables, image_summaries, images):<br>    store = InMemoryStore()<br>    id_key = &quot;doc_id&quot;</pre><pre>    retriever = MultiVectorRetriever(<br>        vectorstore=vectorstore,<br>        docstore=store,<br>        id_key=id_key,<br>    )</pre><pre>    def add_documents(retriever, doc_summaries, doc_contents):<br>        doc_ids = [str(uuid.uuid4()) for _ in doc_contents]<br>        summary_docs = [Document(page_content=summary, metadata={id_key: doc_ids[i]}) for i, summary in enumerate(doc_summaries)]<br>        retriever.vectorstore.add_documents(summary_docs)<br>        retriever.docstore.mset(list(zip(doc_ids, doc_contents)))</pre><pre>    if text_summaries: add_documents(retriever, text_summaries, texts)<br>    if table_summaries: add_documents(retriever, table_summaries, tables)<br>    if image_summaries: add_documents(retriever, image_summaries, images)</pre><pre>    return retriever</pre><pre>vectorstore = Chroma(collection_name=&quot;MMRAG&quot;, embedding_function=embedding_model)<br>retriever_multi_vector_img = create_multi_vector_retriever(<br>    vectorstore, NarrativeText, NarrativeText, table_summaries, Table, image_summaries, img_base64_list<br></pre><p>This function, create_multi_vector_retriever, is used to <strong>create a retriever</strong> that can store and search across multiple modalities of data—such as text, tables, and images. It&#39;s using a MultiVectorRetriever with an in-memory docstore to keep track of both vectorized representations (for similarity search) and the original documents.</p><p>This function sets up a system that can search and retrieve not just text, but also tables and images. It links vector-based summaries (for fast search) to their full, original content, so you can use the retriever for advanced applications like multimodal question answering or RAG pipelines.</p><h3>Chaining Everything: The Multimodal RAG Chain</h3><p>Finally, we <strong>combine everything into a LangChain pipeline</strong> that retrieves, splits, formats, and generates answers — while returning the original sources as well:</p><pre>from langchain_core.runnables import RunnablePassthrough, RunnableLambda</pre><pre>def format_multimodal_output(inputs):<br>    return {<br>        &quot;answer&quot;: inputs[&quot;llm_output&quot;],<br>        &quot;source_texts&quot;: inputs[&quot;context&quot;][&quot;texts&quot;],<br>        &quot;source_images&quot;: inputs[&quot;context&quot;][&quot;images&quot;],<br>    }</pre><pre>def multi_modal_rag_chain_with_sources(retriever, model):<br>    chain = (<br>        {&quot;context&quot;: retriever | RunnableLambda(split_image_text_types),<br>         &quot;question&quot;: RunnablePassthrough()}<br>        | RunnableLambda(lambda x: {**x, &quot;llm_prompt&quot;: img_prompt_func(x)})<br>        | RunnableLambda(lambda x: {**x, &quot;llm_output&quot;: model.invoke(x[&quot;llm_prompt&quot;])})<br>        | RunnableLambda(format_multimodal_output)<br>    )<br>    return chain</pre><p>This code builds a step-by-step processing pipeline for a multimodal RAG system, which takes a question, retrieves the most relevant texts and images, asks an LLM to answer using those, and returns both the answer and its sources.</p><h3>Putting It All Together: Querying the Multimodal RAG</h3><p>Now you can run queries and get both the LLM answer and the <strong>source images</strong> and <strong>texts</strong> that the model used!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NBHipDVT1a8MxBYQAEPpMQ.png" /><figcaption>output from llm</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v4SIDORm4GGVkNrScOs4ow.png" /><figcaption>original image</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jILDIBpf6uoxGVm1UPWrCg.png" /><figcaption>Another output from llm</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l9WzK1S8HycBGKeuSlVAFg.png" /><figcaption>Original image retrieved</figcaption></figure><h4><a href="https://github.com/ashok426/Multimodal_RAG">Github link for the code</a></h4><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1a555b6a20c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a RAG Assistant for Daily Stock Market PDFs]]></title>
            <link>https://medium.com/@ashok.1055/building-a-rag-assistant-for-daily-stock-market-pdfs-0dead0837d89?source=rss-ba7f82087217------2</link>
            <guid isPermaLink="false">https://medium.com/p/0dead0837d89</guid>
            <category><![CDATA[ai-assistant]]></category>
            <category><![CDATA[multimodal-rag]]></category>
            <category><![CDATA[qdrant]]></category>
            <category><![CDATA[docling]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[ashok .c]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 05:25:45 GMT</pubDate>
            <atom:updated>2025-07-15T05:25:45.183Z</atom:updated>
            <content:encoded><![CDATA[<p>How I created RAG from My Broker’s Daily Market Reports Using LangChain, Docling, and Qdrant</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wqG2rFOxwrX09RNSI4_36A.png" /><figcaption>MarketPulse RAG</figcaption></figure><h4><strong>Introduction</strong></h4><p>Every morning, my inbox greets me with a hefty PDF from my stock broker, packed with market updates, company result previews, investment picks, and economic outlooks. As valuable as these reports are, reading them cover-to-cover each day is just not practical — especially before the markets open!</p><p>So, I set out to solve my own pain point: <strong>How can I get quick, contextual answers from my broker’s PDFs, instead of wading through pages of tables and dense text?</strong></p><p>That’s where Retrieval-Augmented Generation (RAG) comes in. With RAG, I can query my own documents conversationally and get smart, concise responses. In this post, I’ll share how I built a RAG pipeline specifically for my daily stock market PDF, leveraging <strong>Docling</strong> for parsing, <strong>LangChain</strong> for chunking and embedding, <strong>OpenAI</strong> for LLM magic, and <strong>Qdrant</strong> as a vector database.</p><p><strong>Check out the </strong><a href="https://github.com/ashok426/marketpulse-rag-assistant"><strong>full code on GitHub.</strong></a></p><h4>Why Build a RAG Assistant for PDFs?</h4><p>RAG lets me ask natural questions (“Summarize today’s top investment picks”) and get instant, context-aware answers — saving time and helping me make better decisions.</p><h3>Tech Stack Overview</h3><ul><li><strong>Docling</strong> for parsing both text and tables from PDFs.</li><li><strong>LangChain</strong> framework for chunking and orchestration.</li><li><strong>OpenAI embedding model</strong> for embedding the content.</li><li><strong>Qdrant</strong> is the vector database for fast semantic search.</li><li><strong>OpenAI GPT-4o </strong>for summarizing tables and generating answers.</li></ul><h3>End-to-End Pipeline: How It Works</h3><p>Let’s walk through the code and key steps:</p><h3>1. Parse PDF with Docling</h3><p>The first challenge I faced was accurately extracting both text and tables from my PDF documents. While I experimented with various parsing frameworks like <strong>Unstructured, PyMuPDF, and PyPDF</strong>, I found that Docling outperformed them all. Docling not only converted PDFs — including complex tables — into markdown, but also preserved the correct layout and formatting, making it the most reliable option for my needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*HJT0ss4nvhFbP-e4ztC9vg.png" /><figcaption>Extracted tables from PDF using Docling</figcaption></figure><p>While Docling does a great job overall, it’s not entirely flawless when it comes to parsing tables from PDFs. Occasionally, some row values end up misaligned or blank. In the image below, I’ve highlighted these issues in red.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*BuPfrMXbzLexz-7HCyesgg.png" /></figure><p>But it truly excels at extracting text, especially from documents with multi-column layouts. Below is a sample of the text extracted using Docling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntiZwBWrFzgu-VzKvKZXTQ.png" /><figcaption>Extracted text from pdf</figcaption></figure><h3>Summarize Tables with GPT-4o</h3><p>Tables (like company earnings or investment picks) can be dense, so we extract them and use a prompt-based summary. Instead of stuffing raw tables into embeddings, I ask GPT-4o to <em>summarize</em> each table — turning them into digestible English paragraphs with key insights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*97G54rYcbiQVmRxeusblGQ.png" /><figcaption>Summarize tables</figcaption></figure><h3>Chunk, Embed, and Prepare for Search</h3><p>To enable semantic retrieval, we chunk the text (including the table summaries) and embed them using OpenAI’s text-embedding-3-small.</p><pre>pythonopyEdittext_splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=self.chunk_size,<br>    chunk_overlap=self.chunk_overlap,<br>    length_function=len,<br>    add_start_index=True,<br>)<br>chunks = text_splitter.create_documents([text])<br>chunk_embeddings = self.embeddings.embed_documents(chunk_texts)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MUT6rE_K0RW_zLu2TU856g.png" /><figcaption>Chunking Text</figcaption></figure><h3>5. Store Everything in Qdrant</h3><p>The resulting chunks and embeddings are loaded into a Qdrant collection, making them instantly searchable via semantic similarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*1r4L2JqvvPbZT9Hrpz3Lng.png" /><figcaption>Qdrant Collection</figcaption></figure><h3>How the Retrieval Pipeline Works</h3><h3>1. User Asks a Query</h3><p>Everything starts with a simple question — typed by the user (e.g., “What are today’s top investment picks?”).</p><h3>2. Embed the User’s Query</h3><p>The query is embedded using OpenAI’s embedding model. This converts the question into a dense vector, allowing us to perform a <em>semantic search</em> instead of simple keyword matching.</p><h3>3. Retrieve Top-k Relevant Chunks from Qdrant</h3><p>We search Qdrant for the most relevant chunks based on cosine similarity. This step fetches, for example, the 15 or 20 most related passages from the PDF.</p><h3>4. Maximal Marginal Relevance (MMR) for Diverse Results</h3><p>To avoid redundancy (i.e., getting multiple very similar chunks), we apply <strong>MMR</strong> (Maximal Marginal Relevance). This technique balances <strong>relevance</strong> to the query and <strong>diversity</strong> among retrieved passages, surfacing a diverse yet highly relevant set of context chunks.</p><h3>5. LLM Generates the Final Answer</h3><p>Finally, we send the filtered context chunks, along with the user’s question, to a GPT-4o LLM. The model is instructed to generate an answer <em>only using the provided context</em>, ensuring that responses are grounded in the actual PDF content.</p><h3>Code Walkthrough: Building the Retriever Class</h3><p>Let’s walk through the core class that ties everything together:</p><pre>class Retriever:<br>    def __init__(self, qdrant_host, qdrant_port, collection_name, embedding_model_name=&quot;text-embedding-3-small&quot;):<br>        self.client = QdrantClient(host=qdrant_host, port=qdrant_port)<br>        self.collection_name = collection_name<br>        self.embeddings = OpenAIEmbeddings(model=embedding_model_name, dimensions=512)<br>        self.llm = ChatOpenAI(model=&quot;gpt-4o&quot;)</pre><ul><li><strong>QdrantClient</strong> connects to our local vector database.</li><li><strong>OpenAIEmbeddings</strong> converts both queries and documents into vectors.</li><li><strong>ChatOpenAI</strong> (GPT-4o) powers the answer generation.</li></ul><h3>Top-k Chunk Retrieval</h3><pre>def get_top_k_chunks(self, query, top_k=20):<br>    query_embedding = self.embeddings.embed_query(query)<br>    search_result = self.client.search(<br>        collection_name=self.collection_name,<br>        query_vector=query_embedding,<br>        limit=top_k,<br>        with_payload=True,<br>        with_vectors=True<br>    )<br>    # ...format results as a list of dicts<br>    return results, np.array(query_embedding)</pre><ul><li>Embeds the query.</li><li>Searches Qdrant for the top-k similar document chunks.</li></ul><h3>Applying Maximal Marginal Relevance (MMR)</h3><pre>def mmr(self, query_embedding, docs, lambda_mult=0.7, k=5):<br>    # Calculate similarity scores, then select diverse and relevant chunks.<br>    # Returns k chunks balancing relevance and diversity.</pre><ul><li><strong>MMR</strong> helps avoid getting multiple overlapping or redundant answers.</li><li>It chooses chunks that are not only close to the query but also different from each other.</li></ul><h3>LLM-Driven Answer Generation</h3><pre>def generate_llm_response(self, query, context_chunks):<br>    PROMPT = PromptTemplate.from_template(<br>        &quot;&quot;&quot;You are a helpful assistant. Answer the user&#39;s question using only the given context below.<br>        ... (prompt continues) ...<br>        Context:<br>        {context}<br>        Question:<br>        {question}<br>        Answer:&quot;&quot;&quot;<br>    )<br>    context = &quot;\n\n&quot;.join(context_chunks) if context_chunks else &quot;No context available.&quot;<br>    message = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: PROMPT.format(context=context, question=query)}]<br>    resp = self.llm.invoke(message)<br>    return resp.content.strip()</pre><ul><li>The LLM is <em>restricted</em> to use only the retrieved context, ensuring answers are traceable to the PDF.</li></ul><h3>End-to-End RAG Pipeline</h3><pre>def rag_pipeline(self, user_query, top_k=20, mmr_k=5):<br>    docs, query_emb = self.get_top_k_chunks(user_query, top_k=top_k)<br>    if not docs:<br>        print(&quot;No relevant chunks found.&quot;)<br>        return &quot;&quot;<br>    reranked_chunks = self.mmr(query_emb, docs, lambda_mult=0.7, k=mmr_k)<br>    context_chunks = [doc[&#39;page_content&#39;] for doc in reranked_chunks]<br>    answer = self.generate_llm_response(user_query, context_chunks)<br>    return answer</pre><ul><li>Retrieves, filters, and generates a final answer — all in one call.</li></ul><h3>How to Use It</h3><p>You can interactively ask questions about your daily PDF:</p><pre>if __name__ == &quot;__main__&quot;:<br>    retriever = Retriever(&quot;localhost&quot;, 6333, &quot;document_chunks_rag&quot;)<br>    print(&quot;Enter your query (or type &#39;exit&#39; to quit):&quot;)<br>    while True:<br>        user_query = input(&quot;Query: &quot;)<br>        if user_query.lower() == &quot;exit&quot;:<br>            break<br>        answer = retriever.rag_pipeline(user_query, top_k=15, mmr_k=5)<br>        print(&quot;\n--- LLM Final Answer ---\n&quot;, answer)</pre><p><strong>Example queries:</strong></p><ul><li>“Summarize today’s company result previews.”</li><li>“What are the latest investment picks?”</li><li>“Give me the market outlook in 3 lines.”</li></ul><h3>Adding a Chat Web App with FastAPI</h3><p>To make my RAG assistant more user-friendly, I built a simple web chat interface using <strong>FastAPI</strong> and <strong>Jinja2</strong> templates. This lets me ask questions directly in my browser, with answers generated on the fly from my daily PDF</p><h3>FastAPI Web Server Code</h3><pre>from fastapi import FastAPI, Request, Form<br>from fastapi.responses import HTMLResponse, JSONResponse<br>from fastapi.staticfiles import StaticFiles<br>from fastapi.templating import Jinja2Templates<br>from data_retriever.retriever import Retriever</pre><pre>app = FastAPI()<br>app.mount(&quot;/static&quot;, StaticFiles(directory=&quot;static&quot;), name=&quot;static&quot;)<br>templates = Jinja2Templates(directory=&quot;template&quot;)</pre><pre># Initialize retriever (points to Qdrant and PDF chunks)<br>retriever = Retriever(&quot;localhost&quot;, 6333, &quot;document_chunks_rag&quot;)</pre><pre>@app.get(&quot;/&quot;, response_class=HTMLResponse)<br>async def chat_page(request: Request):<br>    return templates.TemplateResponse(&quot;chat.html&quot;, {&quot;request&quot;: request})</pre><pre>@app.post(&quot;/get&quot;)<br>async def get_response(msg: str = Form(...)):<br>    answer = retriever.rag_pipeline(msg, top_k=15, mmr_k=5)<br>    return JSONResponse(content=answer)</pre><h3><strong>UI App Demo:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wqG2rFOxwrX09RNSI4_36A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*h_hiWcDzb_-ub56sYqjdKA.png" /><figcaption>Query and Answer</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*WUM29zVJhm08ewgZtzEoiQ.png" /><figcaption>Query and Answer</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*2n9RZE45Ia-QP3ezAJjO3g.png" /><figcaption>Query and Answer</figcaption></figure><h3>Future Improvements</h3><p>As I continue to develop this RAG assistant, here are some key enhancements I’m planning:</p><ol><li><strong>Automated Data Ingestion:</strong><br> I aim to fully automate the ingestion pipeline, so new PDFs and reports are processed and indexed as soon as they arrive — no manual steps required.</li><li><strong>Support for Multiple Document Types:</strong><br> I plan to extend the system to handle various document formats, including DOCX, HTML, and images, making the assistant even more versatile.</li><li><strong>Cloud Deployment with CI/CD &amp; Docker:</strong><br> I intend to containerize the entire application with Docker and set up continuous integration and deployment (CI/CD) pipelines, allowing for seamless and scalable cloud deployment.</li></ol><p><strong>Check out the </strong><a href="https://github.com/ashok426/marketpulse-rag-assistant"><strong>full code on GitHub.</strong></a></p><p>Thanks for reading! If you found this useful, please consider clapping or leaving a comment below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0dead0837d89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Title: Time Series Forecasting with LSTM in PyTorch: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@ashok.1055/title-time-series-forecasting-with-lstm-in-pytorch-a-step-by-step-guide-f25f81eaf8df?source=rss-ba7f82087217------2</link>
            <guid isPermaLink="false">https://medium.com/p/f25f81eaf8df</guid>
            <category><![CDATA[univariate-forecasting]]></category>
            <category><![CDATA[single-step-forecasting]]></category>
            <category><![CDATA[lstm-time-series]]></category>
            <category><![CDATA[timeseries-forecasting]]></category>
            <dc:creator><![CDATA[ashok .c]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 09:53:57 GMT</pubDate>
            <atom:updated>2025-07-03T09:53:57.163Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong><br> Time series forecasting is crucial in many industries such as retail, finance, and weather prediction. When historical data has temporal dependencies, traditional machine learning models may struggle. This is where Recurrent Neural Networks (RNNs), especially Long Short-Term Memory (LSTM) models, excel. In this blog, we’ll walk through implementing a time series forecasting model using LSTM in PyTorch.</p><p>You can find the complete code for this use case on <a href="https://github.com/ashok426/TimeSeriesForecasting"><strong>GITHUB</strong></a></p><p><strong>Dataset Overview</strong><br> We assume you have a CSV file with two columns:</p><p>date:Daily dates for one year</p><p>sales: Corresponding daily sales figures</p><p>We’ll use this data to forecast future sales based on historical patterns.</p><p><strong>1. Loading and Preprocessing the Data</strong></p><pre>import pandas as pd<br>import numpy as np<br>from sklearn.preprocessing import MinMaxScaler</pre><pre>df = pd.read_csv(&quot;sales.csv&quot;, parse_dates=[&quot;date&quot;])<br>df = df.sort_values(&quot;date&quot;)<br>sales = df[&quot;sales&quot;].values.reshape(-1, 1)</pre><pre>scaler = MinMaxScaler()<br>sales_norm = scaler.fit_transform(sales)</pre><p>We read the CSV, sort it chronologically, and normalize the sales values to the [0, 1] range using MinMaxScaler. This helps improve model convergence.</p><p><strong>2. Creating Sequences</strong></p><pre>def create_sequences(data, seq_len):<br>    xs, ys = [], []<br>    for i in range(len(data) - seq_len):<br>        xs.append(data[i:i+seq_len])<br>        ys.append(data[i+seq_len])<br>    return np.array(xs), np.array(ys)</pre><pre>seq_len = 30<br>X, y = create_sequences(sales_norm, seq_len)</pre><p>We convert the time series into supervised learning format:</p><p>Inputs: Last 30 days of sales</p><p>Targets: The next day’s sales</p><p><strong>3. Creating Dataset and DataLoader</strong></p><pre>import torch<br>from torch.utils.data import Dataset, DataLoader</pre><pre>class SalesDataset(Dataset):<br>    def __init__(self, X, y):<br>        self.X = torch.from_numpy(X).float()<br>        self.y = torch.from_numpy(y).float()</pre><pre>    def __len__(self):<br>        return len(self.X)</pre><pre>    def __getitem__(self, idx):<br>        return self.X[idx], self.y[idx]</pre><pre>split = int(len(X) * 0.8)<br>train_ds = SalesDataset(X[:split], y[:split])<br>val_ds = SalesDataset(X[split:], y[split:])</pre><pre>train_loader = DataLoader(train_ds, batch_size=16, shuffle=True)<br>val_loader = DataLoader(val_ds, batch_size=16)</pre><p>This step wraps our data in PyTorch’s Dataset and DataLoader classes for efficient batching and training.</p><p><strong>4. Building the LSTM Model</strong></p><pre>import torch.nn as nn</pre><pre>class LSTMForecast(nn.Module):<br>    def __init__(self, n_features=1, hidden_size=50, num_layers=2):<br>        super().__init__()<br>        self.lstm = nn.LSTM(n_features, hidden_size, num_layers, batch_first=True)<br>        self.fc = nn.Linear(hidden_size, 1)</pre><pre>    def forward(self, x):<br>        out, _ = self.lstm(x)<br>        return self.fc(out[:, -1, :])</pre><p>n_features: Number of input features per timestep (1 for univariate series)</p><p>hidden_size: Number of units in LSTM</p><p>num_layers: Number of stacked LSTM layers</p><p>The model returns only the output at the last timestep.</p><p><strong>5. Training the Model</strong></p><pre>model = LSTMForecast()<br>criterion = nn.MSELoss()<br>optimizer = torch.optim.Adam(model.parameters(), lr=0.001)</pre><pre>for epoch in range(20):<br>    model.train()<br>    total_loss = 0<br>    for xb, yb in train_loader:<br>        optimizer.zero_grad()<br>        pred = model(xb)<br>        loss = criterion(pred, yb)<br>        loss.backward()<br>        optimizer.step()<br>        total_loss += loss.item()</pre><pre>    model.eval()<br>    val_loss = np.mean([criterion(model(xb), yb).item() for xb, yb in val_loader])<br>    print(f&quot;{epoch+1} → train {total_loss:.4f}, val {val_loss:.4f}&quot;)</pre><p>Train mode enables weight updates</p><p>For each batch: predict, calculate loss, backpropagate, and update weights</p><p>Evaluate model on validation data using model.eval()</p><p><strong>6. Making Forecasts</strong></p><pre>model.eval()<br>last_seq = sales_norm[-seq_len:]<br>preds = []</pre><pre>for _ in range(7):<br>    inp = torch.from_numpy(last_seq.reshape(1, seq_len, 1)).float()<br>    pred = model(inp).item()<br>    preds.append(pred)<br>    last_seq = np.roll(last_seq, -1)<br>    last_seq[-1] = pred</pre><pre>preds = scaler.inverse_transform(np.array(preds).reshape(-1,1))<br>print(&quot;Next 7-day forecast:&quot;, preds.flatten())</pre><p>We use the last 30 days to predict the next 7 days. Each new prediction is fed back into the sequence for future forecasting.</p><p><strong>Conclusion</strong></p><p>You’ve now built a complete time series forecasting model using LSTM in PyTorch. From preprocessing and sequence generation to training and prediction, every step mirrors real-world forecasting challenges.</p><p>This approach can be extended to multi-step forecasting, multivariate series, or used with GRU and Transformer models. Stay tuned for future blogs diving deeper into those advanced techniques.</p><p><strong>Happy Forecasting!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f25f81eaf8df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-Tuning BERT for Aspect-Based Sentiment Analysis (ABSA) Using TensorFlow]]></title>
            <link>https://medium.com/@ashok.1055/fine-tuning-bert-for-aspect-based-sentiment-analysis-absa-using-tensorflow-0875e1e5c839?source=rss-ba7f82087217------2</link>
            <guid isPermaLink="false">https://medium.com/p/0875e1e5c839</guid>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[bert-fine-tunig]]></category>
            <category><![CDATA[absa]]></category>
            <category><![CDATA[aspect-based-sentiment]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <dc:creator><![CDATA[ashok .c]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 19:09:37 GMT</pubDate>
            <atom:updated>2025-06-23T19:25:07.502Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0vlAF2L9xTdX29AtOxqK7A.jpeg" /><figcaption>Aspect Based Sentiment Analysis</figcaption></figure><p>Aspect-Based Sentiment Analysis (ABSA) is a granular form of sentiment analysis that aims to identify the sentiment towards specific aspects (terms) within a sentence. In this blog, we’ll walk through how to fine-tune a pre-trained BERT model to solve an ABSA task using TensorFlow and Hugging Face’s Transformers library.</p><p>You can find the complete code for this use case on <a href="https://github.com/ashok426/aspect_based_sentiment_analysis_Finetuning"><strong>GitHub</strong></a>.</p><h3>Dataset Preparation</h3><p>We use three datasets:</p><ul><li>MAMS</li><li>SemEval Laptop</li><li>SemEval Restaurant</li></ul><p>These datasets consist of entries with:</p><ul><li>textThe full sentence</li><li>term: the aspect (e.g., &quot;battery life&quot;)</li><li>polarity: the sentiment (positive, neutral, negative)</li></ul><pre>def load_mams_data(path):<br>    df = pd.read_csv(path)<br>    return df[[&#39;text&#39;, &#39;term&#39;, &#39;polarity&#39;]]</pre><pre># For SemEval datasets, we process the data line-by-line</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*7UfB_uu26unvOP93FftMkA.png" /><figcaption>Training Data ssamples</figcaption></figure><h3>Data Preprocessing</h3><p>We load all three datasets, combine them, remove neutral sentiments (for binary classification), and encode the labels.</p><pre>pol2idx = {&#39;positive&#39;: 1, &#39;negative&#39;: 0}<br>train_data[&#39;polarity&#39;] = train_data[&#39;polarity&#39;].apply(lambda x: pol2idx[x])</pre><p>We also lowercase the text and aspect terms and remove duplicates.</p><h3>Tokenization and Encoding</h3><p>We concatenate the aspect and text with special tokens for BERT.</p><pre>text = f&quot;[CLS] {aspect} [SEP] {sentence} [SEP]&quot;</pre><p>The above is the input text in a format BERT understands:</p><ul><li>[CLS] – special token used by BERT for classification tasks.</li><li>{aspect} – the specific aspect term (e.g., &quot;battery&quot;, &quot;service&quot;, etc.).</li><li>[SEP] – used to separate different segments (aspect and sentence).</li><li>{sentence} – the full sentence containing the aspect.</li><li>Final [SEP] – ends the input.</li></ul><p>This format helps BERT <strong>focus on the aspect</strong> within the context of the sentence.</p><h3>Use Case Example</h3><p>For a sentence like:</p><p><em>&quot;The battery life is amazing&quot; with aspect </em><em>&quot;battery&quot;</em></p><p>The model input becomes:<br> [CLS] battery [SEP] The battery life is amazing [SEP]</p><p>This helps the model learn <strong>sentiment specifically toward “battery”</strong>, not the sentence in general. Encoding the input this way helps the model understand that we are interested in the sentiment <strong>about the given aspect</strong>, not just the overall tone of the sentence.</p><p>Then we tokenize and encode:</p><pre>encoded = tokenizer.encode_plus(<br>    text,<br>    add_special_tokens=False,<br>    max_length=100,<br>    padding=&#39;max_length&#39;,<br>    truncation=True,<br>    return_attention_mask=True,<br>    return_tensors=&#39;tf&#39;<br>)</pre><h3>Create TensorFlow Datasets</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*T2zSXmve2qdq2FbM3XYzAw.png" /><figcaption>Encoded code</figcaption></figure><h3>Purpose</h3><p>To take a DataFrame of:</p><ul><li>Sentences (text)</li><li>Aspects (term)</li><li>Labels (polarity)</li></ul><p>…and return:</p><ul><li>input_ids: token IDs for BERT</li><li>attention_mask: Which tokens are real vs padding. 1s for actual tokens, 0s for padding</li><li>label: sentiment label for each example</li></ul><p>All of these are returned as <strong>TensorFlow tensors</strong>, ready to be passed into a model. We use tf.data.Dataset for efficient training.</p><pre>train_dataset = tf.data.Dataset.from_tensor_slices((inputs, labels)).shuffle(1000).batch(16)</pre><h3>Model Setup and Training</h3><p>We use TFBertForSequenceClassification with 2 output labels (positive and negative).</p><pre>model = TFBertForSequenceClassification.from_pretrained(&#39;bert-base-uncased&#39;, num_labels=2)</pre><p>We create an optimizer with learning rate scheduling:</p><pre>optimizer, schedule = create_optimizer(init_lr=2e-5, num_train_steps=5000, num_warmup_steps=500)</pre><p>Compile and train:</p><pre>model.compile(optimizer=optimizer, loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=[&#39;accuracy&#39;])<br>model.fit(train_dataset, epochs=3, validation_data=val_dataset)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9dD2vQtw9q0haITkQIusaw.png" /><figcaption>Training Epoch</figcaption></figure><h3>Save the Model and Tokenizer</h3><pre>model.save_pretrained(&#39;fine_tuned_bert_absa&#39;)<br>tokenizer.save_pretrained(&#39;fine_tuned_bert_absa&#39;)</pre><h3>Predict Sentiment for New Input</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*XrUnhn7svkn4EyeocJSPPg.png" /><figcaption>Loading the Fine-Tuned Model</figcaption></figure><p>Loaded the Fine-Tuned model and then we defined a function that predicts sentiment based on the aspect and sentence:</p><pre>def predict_sentiment(sentence, aspect):<br>    encoded = tokenizer.encode_plus(...)<br>    predictions = model(encoded)<br>    return predicted_class</pre><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tCz000laKLVbvl7cDY6mag.png" /><figcaption>Sample Prediction</figcaption></figure><h3>Evaluate Model Performance</h3><p>We use accuracy and classification report:</p><pre>from sklearn.metrics import classification_report, accuracy_score</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*7MmN0_PYa5gKNsg3Vh9x1Q.png" /><figcaption>Evaluation Code</figcaption></figure><h3>Final Thoughts</h3><p>In this blog, we fine-tuned a BERT model for ABSA using real-world datasets. This approach can be extended to other domains like product reviews, service feedback, etc. By using a combination of aspect-focused encoding and BERT’s contextual power, we can achieve high performance on nuanced sentiment classification tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0875e1e5c839" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying AI Agents: What They Are and Why They Matter]]></title>
            <link>https://medium.com/@ashok.1055/demystifying-ai-agents-what-they-are-and-why-they-matter-e8d658bcf6cb?source=rss-ba7f82087217------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8d658bcf6cb</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agents-with-langchain]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[ashok .c]]></dc:creator>
            <pubDate>Sat, 14 Dec 2024 06:12:20 GMT</pubDate>
            <atom:updated>2024-12-14T06:12:20.226Z</atom:updated>
            <content:encoded><![CDATA[<p>Artificial Intelligence (AI) agents are more than just a buzzword; they represent a revolutionary shift in how we design and implement intelligent systems. In this blog, we’ll delve deep into what makes AI agents unique, their architecture, and why they’re a game-changer for data science professionals.</p><p><strong>What Are AI Agents?</strong><br>At their core, AI agents are applications designed to achieve specific goals by observing and acting upon their environment. Unlike static models that respond passively to inputs, AI agents are dynamic, autonomous, and proactive. They can plan their next steps, make decisions in real time, and adapt to changing environments. Think of a self-driving car: it constantly processes data from its surroundings (traffic, pedestrians, and traffic lights), makes decisions, and executes them to achieve its goal of navigating safely and efficiently.</p><p>This autonomy sets agents apart from traditional models, which are limited by their training data. AI agents go beyond by integrating external information and tools, allowing for a more flexible and powerful approach to problem-solving.</p><p><strong>The Cognitive Architecture of AI Agents:</strong><br>AI agents operate through a well-orchestrated system that integrates three key components:</p><p><strong>1. The Model</strong><br> The model acts as the decision-maker — the “brain” of the agent. Leveraging reasoning frameworks like Chain of Thought (CoT) and React, it processes information, plans actions, and determines the best course forward. These frameworks help the agent think systematically and make informed decisions, much like a strategist analyzing data and devising a game plan.</p><p><strong>2. Tools</strong><br> Tools are the agent’s “hands” — they enable it to interact with the world. By connecting to external APIs, databases, and services, tools allow the agent to gather and manipulate information beyond its training data. Whether fetching stock prices, analyzing weather patterns, or accessing a vector database, tools significantly expand an agent’s capabilities.</p><p><strong>3. The Orchestration Layer</strong><br> This is the “operating system” of the agent. It coordinates the agent’s cycle of sensing, reasoning, and acting. By managing interactions between the model and tools, the orchestration layer ensures seamless functionality, enabling the agent to adapt dynamically to new data and challenges.</p><p><strong>Enhancing Capabilities with Extensions, Functions, and Data Stores</strong><br>To supercharge their performance, AI agents rely on additional mechanisms like extensions, functions, and data stores:</p><p>-<strong>Extensions</strong>: These act as standardized bridges to external APIs. Instead of writing custom code to parse API responses, agents use extensions to handle communication efficiently. For instance, an extension can fetch stock prices or weather updates without manual intervention, simplifying maintenance and enhancing flexibility.</p><p>-<strong>Functions</strong>: Functions allow agents to execute custom code on demand, enabling tailored computations or processes. These are particularly useful when predefined extensions don’t cover a specific need, offering flexibility and control.</p><p>-<strong>Data Stores:</strong> These provide agents with access to constantly updated, real-time information. By connecting to sources like vector databases or dynamic datasets, agents can enrich their understanding and make more informed decisions. This is akin to giving the agent a library of up-to-date knowledge to draw from.</p><p><strong>Learning to Use Tools Effectively</strong><br>Equipping agents with tools is only half the battle; ensuring they know how to use them is crucial. This is where targeted learning techniques come into play. The three main approaches include:</p><p><strong>1. In-Context Learning</strong><br> Agents adapt by observing examples provided during inference, allowing them to learn on the fly. This is like a chef improvising with a recipe based on available ingredients.</p><p><strong>2. Retrieval-Based In-Context Learning</strong><br> Here, agents access external data sources dynamically, pulling in relevant information to solve a problem. Think of a chef consulting a cookbook or pantry for inspiration while preparing a dish.</p><p><strong>3. Fine-Tuning</strong><br> Agents undergo additional training on specialized datasets, giving them domain-specific expertise. This is akin to sending a chef to culinary school to master advanced techniques.</p><p>By combining these methods, agents become highly versatile, adapting to diverse challenges with precision.</p><p><strong>Building AI Agents with LangChain</strong><br>LangChain is a powerful framework for orchestrating AI agents. It simplifies the process of integrating models, tools, and data stores into seamless workflows. For instance, to build an agent that answers complex questions, LangChain enables:</p><p>- Fetching data using extensions like SERP API for web scraping.<br>- Performing calculations with custom-defined functions.<br>- Presenting results dynamically through flexible output formats.</p><p>LangChain’s open-source nature makes it accessible for experimentation, offering data science professionals an intuitive way to build intelligent, task-specific agents.</p><p><strong>Final Thoughts</strong><br>AI agents are transforming the AI landscape, offering unparalleled adaptability and intelligence. By understanding their architecture, leveraging tools and extensions, and exploring frameworks like LangChain, data professionals can unlock new possibilities in automation and problem-solving. The future is here, and it’s powered by AI agents. What groundbreaking solution will you build next?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8d658bcf6cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of Embeddings and Vector Stores: A Deep Dive]]></title>
            <link>https://medium.com/@ashok.1055/unlocking-the-power-of-embeddings-and-vector-stores-a-deep-dive-3383323ce5e5?source=rss-ba7f82087217------2</link>
            <guid isPermaLink="false">https://medium.com/p/3383323ce5e5</guid>
            <category><![CDATA[text-embedding]]></category>
            <category><![CDATA[vector-store]]></category>
            <category><![CDATA[semantic-search]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[embeddings-search]]></category>
            <dc:creator><![CDATA[ashok .c]]></dc:creator>
            <pubDate>Wed, 13 Nov 2024 03:28:27 GMT</pubDate>
            <atom:updated>2024-11-13T03:28:27.384Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of data science and machine learning, few innovations have had as transformative an impact as embeddings and vector stores. These technologies are revolutionizing how we process, store, and retrieve data across a wide array of applications. This article delves into the concepts of embeddings and vector stores, their types, and how they are shaping the future of technology.</p><h3>What Are Embeddings?</h3><p>At their core, embeddings are a way to represent data in a numerical format that machines can understand. Whether it’s text, images, or even audio, embeddings translate complex information into vectors — multidimensional numerical arrays. This allows computers to identify relationships and similarities in a way that was previously unattainable.</p><p>For example:</p><ul><li><strong>Text Embeddings:</strong> Algorithms like Word2Vec and GloVe analyze the context of words to group similar words together in the vector space.</li><li><strong>Image Embeddings:</strong> Convolutional Neural Networks (CNNs) extract essential features from images to create embeddings.</li><li><strong>Multimodal Embeddings:</strong> Combine embeddings from multiple data types, such as aligning images with descriptive text.</li></ul><h3>Why Are Embeddings So Important?</h3><p>Embeddings unlock powerful capabilities:</p><ol><li><strong>Semantic Search:</strong> Unlike traditional keyword searches, embeddings enable search by meaning. For instance, searching for “feline” could return results involving “cats” or “kittens.”</li><li><strong>Recommendation Systems:</strong> By comparing user preferences and content in the same vector space, embeddings improve personalization.</li><li><strong>Anomaly Detection:</strong> In systems monitoring vast amounts of data, embeddings highlight unusual patterns by identifying deviations from normal behavior.</li></ol><h3>From Embeddings to Vector Stores</h3><p>Managing and querying these embeddings efficiently requires specialized databases — vector stores. Unlike traditional relational databases that handle structured data, vector stores are designed for high-dimensional data.</p><p>Key functionalities of vector stores include:</p><ul><li><strong>Storage and Retrieval:</strong> Vector databases store embeddings and provide quick access through optimized search algorithms.</li><li><strong>Search Algorithms:</strong> Techniques, like Approximate Nearest Neighbor (ANN) searches (e.g., KD Trees, HNSW), make querying fast and scalable, even with billions of vectors.</li></ul><h3>Practical Applications</h3><p><strong>1. Search Engines:</strong> Semantic search powered by embeddings delivers more accurate and contextually relevant results, transforming how users interact with information.</p><p><strong>2. E-commerce Recommendations:</strong> Embedding-based recommendation engines analyze user behavior, product descriptions, and reviews to suggest items that align closely with a user’s preferences.</p><p><strong>3. Large Language Models (LLMs) and Retrieval-Augmented Generation (RAG):</strong> Combining LLMs with vector searches allows models to access real-time data, enhancing the accuracy and reliability of their responses. This is critical in preventing hallucinations, where models generate factually incorrect information.</p><h3>Choosing the Right Vector Store</h3><p>Selecting a vector store depends on:</p><ul><li><strong>Data Volume:</strong> Large-scale applications might require specialized solutions like Pinecone or Weaviate.</li><li><strong>Query Complexity:</strong> Depending on the task, a hybrid approach combining traditional and vector databases could be optimal.</li><li><strong>Cost and Performance:</strong> Cloud platforms like Google’s Vertex AI or AlloyDB offer scalable options tailored for various workloads.</li></ul><h3>Conclusion</h3><p>Embeddings and vector stores are not just buzzwords — they are foundational technologies reshaping industries from search and e-commerce to finance and healthcare. As these tools evolve, they promise to unlock even more sophisticated and intuitive ways of interacting with data. For developers and businesses alike, now is the time to harness their power and stay ahead in this rapidly advancing field.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3383323ce5e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Predictive Text to Multimodal Marvels: The Evolution of GPT and Large Language Models]]></title>
            <link>https://medium.com/@ashok.1055/from-predictive-text-to-multimodal-marvels-the-evolution-of-gpt-and-large-language-models-d030c9615331?source=rss-ba7f82087217------2</link>
            <guid isPermaLink="false">https://medium.com/p/d030c9615331</guid>
            <category><![CDATA[foundation-of-llms]]></category>
            <category><![CDATA[gpt-family]]></category>
            <category><![CDATA[evolution-of-gpt]]></category>
            <category><![CDATA[architecture-of-gpt]]></category>
            <category><![CDATA[the-evolution-of-llms]]></category>
            <dc:creator><![CDATA[ashok .c]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 05:51:27 GMT</pubDate>
            <atom:updated>2024-11-11T05:51:27.725Z</atom:updated>
            <content:encoded><![CDATA[<p>The evolution of large language models (LLMs) is a testament to the rapid advancements in artificial intelligence. From early text prediction systems to today’s multimodal powerhouses like Gemini, these models have redefined what machines can accomplish. This article explores the fascinating journey of LLMs, unpacking their architectures, breakthroughs, and real-world applications.</p><h3>The Foundation of Large Language Models</h3><p>At the core of LLMs is a deceptively simple idea: predicting the next word in a sentence. This foundational concept has given rise to systems capable of translating languages, solving complex math problems, and even generating creative content.</p><h4>From RNNs to Transformers</h4><p>Early LLMs, such as Recurrent Neural Networks (RNNs), could only process text sequentially, limiting their efficiency and scope. The introduction of Transformers revolutionized the field with their self-attention mechanism. This allowed models to analyze entire paragraphs simultaneously, capturing intricate word relationships and context.</p><h3>The Architecture of Modern LLMs</h3><p>Transformers operate through a sophisticated pipeline:</p><ul><li><strong>Tokenization</strong>: Text is broken into manageable chunks.</li><li><strong>Embedding</strong>: These chunks are transformed into numerical data.</li><li><strong>Positional Encoding</strong>: Ensures the model understands word order.</li><li><strong>Multihead Attention</strong>: Analyzes relationships between words, akin to a detective piecing together clues.</li></ul><p>This architecture enables models like GPT and BERT to excel in various tasks, from storytelling to context understanding.</p><h3>Milestones in the GPT Family</h3><h4>GPT-1: The Pioneer</h4><p>Introduced unsupervised pre-training, enabling the model to learn from vast amounts of unlabeled text.</p><h4>GPT-2: The Growth Spurt</h4><p>Trained on 10 times more data, GPT-2 demonstrated impressive text generation capabilities, producing coherent and human-like outputs.</p><h4>GPT-3: The Giant</h4><p>With 175 billion parameters, GPT-3 mastered few-shot learning, requiring minimal examples to perform new tasks.</p><h4>GPT-4: The Multimodal Innovator</h4><p>Introduced the ability to process images alongside text, pushing the boundaries of what LLMs can interpret and generate.</p><h3>Competing Giants: Google’s LLMs</h3><p>Google has been a key player, contributing models like:</p><ul><li><strong>LaMDA</strong>: Designed for engaging, natural conversations.</li><li><strong>PaLM</strong>: A versatile model excelling in reasoning and complex tasks.</li><li><strong>Gemini</strong>: A multimodal model integrating text, images, audio, and video, with remarkable contextual understanding.</li></ul><h3>The Role of Open Source in LLM Evolution</h3><p>Organizations like Meta and Mistral AI are democratizing LLM technology through open-source initiatives. These models provide researchers and developers with tools to innovate and explore new frontiers in AI.</p><h3>Fine-Tuning and Specialization</h3><p>Fine-tuning transforms general-purpose LLMs into domain-specific experts. Techniques include:</p><ul><li><strong>Supervised Fine-Tuning (SFT)</strong>: Training models on specialized datasets.</li><li><strong>Reinforcement Learning from Human Feedback (RLHF)</strong>: Using human judgment to improve responses.</li><li><strong>Parameter-Efficient Fine-Tuning (PFT)</strong>: Optimizing specific model components without retraining the entire system.</li></ul><h3>Practical Challenges and Optimization</h3><p>As LLMs grow, so do the challenges of deploying them efficiently. Techniques like quantization, distillation, and speculative decoding help streamline inference, making powerful AI more accessible and cost-effective.</p><h3>Real-World Applications</h3><p>LLMs are transforming industries:</p><ul><li><strong>Coding</strong>: Enhancing development with code generation, debugging, and refactoring.</li><li><strong>Mathematics</strong>: Solving complex problems with logical precision.</li><li><strong>Translation</strong>: Delivering fluent, context-aware language translations.</li><li><strong>Creative Content</strong>: Assisting in writing, marketing, and personalized messaging.</li></ul><h3>The Future: Multimodal and Beyond</h3><p>The next frontier is multimodal LLMs, capable of interpreting and generating across text, images, and video. This advancement promises breakthroughs in fields like education, healthcare, and interactive media.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d030c9615331" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Impact of Scale on Covariance and Pearson Correlation:]]></title>
            <link>https://medium.com/@ashok.1055/understanding-the-impact-of-scale-on-covariance-and-pearson-correlation-2fad5dab0ff4?source=rss-ba7f82087217------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fad5dab0ff4</guid>
            <category><![CDATA[correlation-vs-covariance]]></category>
            <category><![CDATA[pearson-correlation]]></category>
            <category><![CDATA[covariance]]></category>
            <category><![CDATA[scaling-impact]]></category>
            <dc:creator><![CDATA[ashok .c]]></dc:creator>
            <pubDate>Fri, 02 Aug 2024 08:00:18 GMT</pubDate>
            <atom:updated>2024-08-02T08:08:03.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*qPaI1k-wgfFgTgTOfPtqtg.png" /><figcaption>Scatter plot</figcaption></figure><h4>Introduction:</h4><p>Covariance and Pearson correlation are two key metrics used to measure the relationship between variables. While both metrics are often used interchangeably, they have distinct differences that make them suitable for different scenarios. One of the most significant differences lies in how they are affected by the variables&#39; scale. In this blog, we’ll delve into how they are influenced by scaling, and understand why Pearson correlation is often preferred over covariance in many situations.</p><h4>The Problem with Covariance: Scale Dependence</h4><p>Covariance is a measure that indicates the direction of the linear relationship between two variables. If the covariance is positive, it means that as one variable increases, the other tends to increase as well. Conversely, a negative covariance suggests that as one variable increases, the other tends to decrease. However, one of the major drawbacks of covariance is its dependence on the scale of the variables.</p><h4>Example:</h4><p>Suppose you have two features, X and Y, with the following values:</p><p>X = [2, 4, 6, 8, 10]<br>Y = [3, 6, 9, 12, 15]</p><p>Let’s calculate the covariance for these variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*LXrFLEfGq1K31cdKfE2X2Q.png" /><figcaption>Covariance Formula</figcaption></figure><p>the covariance would be 14.</p><p>Now, if we scale the feature X by multiplying all its values by 2 to get a new variable X’, the covariance changes:</p><p>X’ = [4, 8, 12, 16, 20]</p><p>If we calculate the covariance between X’ and Y, we’ll find the covariance would be 28. As you can see, the covariance has doubled from 14 to 28 when we multiply all values in `X` by 2. This illustrates that covariance is dependent on the scale of the variables.</p><p>This happens because covariance is not standardized and is directly affected by the units and scale of the variables involved. As a result, comparing covariances across different units and drawing conclusions about the strength of relationships can be misleading.</p><h4>Pearson Correlation and Scale Independence:</h4><p>Pearson correlation addresses the issue of scale dependence by normalizing the covariance. It measures the strength and direction of the linear relationship between two variables, but unlike covariance, it is scale-independent. This means that even if the variables are scaled (e.g., multiplied by a constant), the Pearson correlation remains unchanged because it standardizes the covariance by dividing it by the product of the standard deviations of the two variables.</p><h4>Example 2: Understanding Pearson Correlation:</h4><p>Using the same original X and Y values:</p><p>X = [2, 4, 6, 8, 10]<br>Y = [3, 6, 9, 12, 15]</p><p>First, we calculate the standard deviations:</p><p>Standard deviation of X = 3.16<br>Standard deviation of Y = 4.74</p><p>The Pearson correlation between X and Y is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*Jsf6w-Uv8LR7C0KjNMDaTQ.png" /><figcaption>Pearson Correlation Formula</figcaption></figure><p>Pearson correlation would be 0.93</p><p>Now, let’s calculate the Pearson correlation between scaled features X’ (X’ = 2X) and Y:</p><p>First, the standard deviation of X’ = 2 * 3.16(Standard Deviation of X) and the Mean of X’ would be 2 * Mean of X. So the person correlation would be 0.93.</p><p>Despite doubling the scale of X, the Pearson correlation remains approximately the same (0.93). This is because both the mean and the standard deviation scale linearly with the unit number 2, and the conversion factor cancels out when we divide it by standard deviation of X’</p><p>This consistency makes Pearson correlation a more reliable metric when comparing relationships across different features or when variables are expressed in different units.</p><h4>Summary</h4><p>In summary, while covariance is useful for understanding the direction of the relationship between two variables, its dependence on scale can be a limitation. Pearson correlation, on the other hand, standardizes this relationship. This makes Pearson correlation a more robust and interpretable metric for analyzing the strength and direction of linear relationships, especially when comparing across different contexts or datasets.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fad5dab0ff4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Setback to Comeback: Chennai Super Kings’ Performance Analysis in IPL 2022 and 2023]]></title>
            <link>https://medium.com/@ashok.1055/from-setback-to-comeback-chennai-super-kings-performance-analysis-in-ipl-2022-and-2023-8f2a68895814?source=rss-ba7f82087217------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f2a68895814</guid>
            <category><![CDATA[csk-performance]]></category>
            <category><![CDATA[ipl-2023]]></category>
            <category><![CDATA[ipl2022]]></category>
            <category><![CDATA[csk]]></category>
            <category><![CDATA[chennai-super-kings]]></category>
            <dc:creator><![CDATA[ashok .c]]></dc:creator>
            <pubDate>Wed, 08 May 2024 18:07:28 GMT</pubDate>
            <atom:updated>2024-05-08T18:07:28.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2VovYNNuadftRk1Oy5VW7A.png" /><figcaption>CSK Performance Analysis 2023</figcaption></figure><p>In the fast-paced world of the Indian Premier League, the fortunes of a team can <strong>shift dramatically between seasons</strong>. This was exemplified by the contrasting performances of Chennai Super Kings (CSK) in 2022 and 2023.</p><p>In this article, we delve into the contrasting fortunes of the Chennai Super Kings in the IPL seasons of 2022 and 2023. In this deep dive, we explore the strategic shifts and standout performances that defined CSK’s journey from underachievers to champions.</p><h4>Dataset:</h4><p>We have used the IPL 2022 and 2023 datasets from Kaggle to analysis the performance. Both datasets contain ball-by-ball and match-wise information.</p><h4>Key Performance Indicator(KPI):</h4><p>Analyzing team performance involves examining various key performance indicators (KPIs) to gain insights into the team’s strengths, weaknesses, and overall effectiveness. Here are some essential KPIs to consider when comparing performance between two tournaments:</p><ul><li>Batting Powerplay Runs</li><li>Bowling Powerplay Wickets</li><li>Batting Strike Rate</li><li>Centuries and Half-Centuries</li><li>Batting Powerplay Wickets</li></ul><p><strong>Batting Powerplay Runs:</strong></p><p>Batting powerplay runs are the runs CSK batters scored during the batting powerplay. The batting powerplay runs of each match in 2022 and 2023 are given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eIwCDhHt6rFq9jmJXCTy1w.png" /><figcaption><strong>CSK Batting Powerplay Comparision in 2022 &amp; 2023</strong></figcaption></figure><p>The plot shown above represents the batting performance of the CSK team during the powerplay against different opponents. It is clear from the plot that the team’s batting performance in 2023 has been significantly better than in 2022, across all matches in powerplay. This performance improvement is a positive sign and led to many victories for CSK in 2023.</p><p>A crucial phase in T20 cricket, the powerplay showed significant improvement in 2023. <strong>CSK’s average runs during this period jumped from 45 in 2022 to 56 in 2023</strong>, reflecting a more aggressive and successful approach at the start of their innings.</p><p><strong>Batting Powerplay Wickets:</strong></p><p>Batting powerplay wickets indicates the number of wickets lost by CSK in the powerplay while batting against opponent teams. Below are the batting powerplay wickets for each match in 2022 and 2023.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*xJ508pgE4N2787UZb8DeKw.png" /><figcaption>Number of Wickets Lost in Powerplay against each opponent.</figcaption></figure><p>A total of 14 matches were played in each league game in the years 2022 and 2023.<strong> The number of wickets lost in powerplay during 2022 was higher compared to the wickets lost in 2023.</strong> In the year 2023, only two wickets were lost in one match, while in seven matches, CSK lost only one wicket in powerplay batting. In the remaining five matches, no wickets were lost.</p><p>The stability at the start was further underscored by a reduction in wickets lost during the powerplay, <strong>dropping dramatically in 2023</strong>.</p><p><strong>Batting Strike Rate:</strong></p><p>Batting strike rate is a measure of how quickly a batsman scores runs. It is calculated by dividing the total number of runs scored by the total number of balls faced in the entire league game. The plot below compares CSK batters strike rates in 2022 &amp; 2023.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QW-8f_i3FjdbEXThzeuW6A.png" /></figure><p>The above plot shows that Ruturaj Gaikwad, Jadeja, MS Dhoni, and Shivam Dube strike rate increased in 2023 compared to 2022. <strong>The form of key players like Devon Conway and Ruturaj Gaikwad and the all-round contributions from players like Moeen Ali played a significant role in 2023.</strong> In contrast, 2022 saw many key players not performing to their potential.</p><p><strong>Half-Centuries:</strong></p><p>CSK batters scored 13 half-centuries in the entire league matches of 2022 and 16 half-centuries in the entire league matches of 2023. The increase in half-centuries<strong> from 13 in 2022 to 16 in 2023 </strong>indicates a<strong> </strong>more consistent batting lineup.</p><p><strong>Bowling Powerplay Wickets:</strong></p><p>Bowling powerplay wickets will show the CSK bowler&#39;s performance in the powerplay of league matches. The below plot shows how many wickets were taken by CSK bowlers against each opponent in 2022 and 2023.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1q6f34O8eQrvQ617RBv7OQ.png" /><figcaption>The numbers inside the bar plot represent wickets taken.</figcaption></figure><p>It is evident from the plot that CSK bowlers took at least one wicket during powerplay in each match of 2023, whereas in some matches of 2022, they failed to do so.</p><p><strong>CSK bowlers were more successful in extracting early wickets in 2023’s powerplay</strong>, setting back opposing teams early in their innings.</p><p><strong>Key Insights:</strong></p><ul><li><strong>Improved Opener Performance</strong>: The openers’ enhanced performance in 2023 was a game-changer, laying solid foundations for big scores.</li><li><strong>Strategic Bowling during Powerplays</strong>: CSK’s bowlers capitalized on the initial overs more effectively in 2023, snagging crucial early wickets to stymie opposition innings.</li></ul><p>I performed all the analytics using Power BI and have attached a screenshot of my report for you to review.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SZXHr84od4_FSB8zghTEjg.png" /><figcaption>CSK Performance Report of 2022</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*924Z8xXpua6mnGkbC-XwSg.png" /><figcaption>CSK Performance Report of 2023</figcaption></figure><p><strong>Conclusion</strong>:</p><p>The transformation of Chennai Super Kings between these two seasons serves as a compelling narrative of strategic adaptation and execution. By enhancing their powerplay performances, both with bat and ball, and through key players rediscovering form at crucial junctures, CSK not only improved but excelled, capturing the elusive trophy in 2023 after a dismal 2022.</p><p><strong>There are still many KPIs and insights that need to be added in this article. I will update it with more in the coming days.</strong></p><p><strong>Thanks For Reading.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f2a68895814" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>