<?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 Shankar Sharma on Medium]]></title>
        <description><![CDATA[Stories by Shankar Sharma on Medium]]></description>
        <link>https://medium.com/@shankar138089?source=rss-bb0b1b36776d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wXcQSv_JP6XFesVDuFm3jg.jpeg</url>
            <title>Stories by Shankar Sharma on Medium</title>
            <link>https://medium.com/@shankar138089?source=rss-bb0b1b36776d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:14:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shankar138089/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[Turning Handwritten Notes into a Pre-filled Cart ]]></title>
            <link>https://shankar138089.medium.com/turning-handwritten-notes-into-a-pre-filled-cart-d0d0a9044d56?source=rss-bb0b1b36776d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0d0a9044d56</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ocr-tesseract]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[ocr]]></category>
            <dc:creator><![CDATA[Shankar Sharma]]></dc:creator>
            <pubDate>Wed, 30 Oct 2024 06:34:32 GMT</pubDate>
            <atom:updated>2024-10-30T06:34:32.309Z</atom:updated>
            <content:encoded><![CDATA[<p>In the age of convenience, we all want a seamless shopping experience. Inspired by Swiggy Instamart’s new “Shopping Lists” feature, I set out to create a similar functionality: upload a handwritten shopping list, extract the items from it, and generate a cart with recommended products. This post dives into the tech behind this feature and how it can make your shopping journey smoother than ever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*qjtyGd0RrQ2-HcRufJg3Pw.gif" /></figure><h3>Why Build a Shopping List Feature?</h3><p>Imagine you scribbled a quick shopping list on paper. Instead of manually searching for each item online, you could snap a photo, upload it, and instantly see a cart with all the items filled in. For busy users, this feature saves time and reduces friction, while for platforms, it enhances user engagement and convenience. Let’s break down how I developed it using Python, Tesseract OCR, and Streamlit.</p><h3>Step 1: Extracting Text from Handwritten Images</h3><p>The first hurdle was to turn handwritten text into something a computer can understand. For this, I used <strong>Optical Character Recognition (OCR)</strong> with Tesseract, a powerful open-source OCR engine. Tesseract can identify and convert characters from an image to text, whether typed or handwritten.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*nNII4VkQXpJR31lX1dt_Hg.png" /></figure><p>Using the pytesseract library, I wrote a small function to load and process the image:</p><pre>import pytesseract<br>from PIL import Image<br><br>def extract_text_from_image(image_path):<br>    image = Image.open(image_path)<br>    return pytesseract.image_to_string(image)</pre><h3>Step 2: Parsing the Extracted Text</h3><p>OCR results can be messy, especially with handwritten text. After extracting text, I needed to clean it up — removing any extraneous text and standardizing item names. My goal was to parse each line to isolate product names and quantities for a clean, usable shopping list.</p><pre># Example parsing code<br>shopping_list_text = extract_text_from_image(&quot;shopping_list.png&quot;)<br>items = [line for line in shopping_list_text.splitlines() if line.strip() != &quot;&quot;]</pre><p>At this point, I had a structured list of items with quantities, such as:</p><pre>Paneer 2kg<br>Basmati Rice 1kg<br>Chicken Boneless 1kg</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T8t22d2lDkXJbOndG9qguw.png" /></figure><h3>Step 3: Generating Product Recommendations</h3><p>With the items extracted, the next challenge was to provide product recommendations for each item. For this, I created a dictionary with recommended products based on each item name. This dictionary includes details like product name, price, and an image URL for each item.</p><pre>recommended_products = {<br>    &quot;Paneer&quot;: [<br>        {&quot;name&quot;: &quot;Amul Fresh Paneer&quot;, &quot;price&quot;: &quot;₹275&quot;, &quot;image&quot;: &quot;https://link-to-image1&quot;},<br>        {&quot;name&quot;: &quot;Milky Mist Paneer&quot;, &quot;price&quot;: &quot;₹250&quot;, &quot;image&quot;: &quot;https://link-to-image2&quot;}<br>    ],<br>    # Additional items...<br>}</pre><p>This allowed me to dynamically pull up relevant options for each item on the list, providing users with a choice of brands and quantities similar to a real shopping experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*GVxme2v8mNOWID_5rPGGdA.gif" /></figure><h3>Step 4: Creating a User Interface with Streamlit</h3><p>To build an interactive UI, I used <strong>Streamlit</strong>, an open-source app framework for data science. Streamlit enabled me to create a simple, intuitive web app where users can upload an image, view extracted items, and see recommendations in a familiar format.</p><p>Here’s how the layout works:</p><ol><li><strong>Upload Section</strong>: Users upload an image of their handwritten shopping list.</li><li><strong>Extracted List</strong>: A checklist displays the extracted items, allowing users to confirm or deselect items.</li><li><strong>Recommendations</strong>: For each item, a row of recommended products is displayed, each with an “Add” button to simulate adding the item to a cart.</li></ol><pre>import streamlit as st<br><br># Display extracted items<br>st.title(&quot;Your Shopping List&quot;)<br>for item in items:<br>    st.checkbox(item, value=True)<br><br># Show recommendations<br>st.subheader(&quot;Shopping Cart Recommendations&quot;)<br>for item in items:<br>    st.write(f&quot;Recommendations for {item}:&quot;)<br>    for recommendation in recommended_products.get(item.split()[0], []):<br>        st.image(recommendation[&quot;image&quot;], width=100)<br>        st.write(f&quot;{recommendation[&#39;name&#39;]} - {recommendation[&#39;price&#39;]}&quot;)<br>        st.button(&quot;Add&quot;, key=f&quot;{recommendation[&#39;name&#39;]}&quot;)</pre><p>With this setup, I could mimic a shopping platform where users select items based on OCR results and view multiple brand options per product.</p><p>check the complete code here :</p><p><a href="https://github.com/shankarsharma8089/Turning-Handwritten-Notes-into-a-Pre-filled-Cart/tree/main">https://github.com/shankarsharma8089/Turning-Handwritten-Notes-into-a-Pre-filled-Cart/tree/main</a></p><h3>Final Thoughts</h3><p>Creating this feature was not only a fun exercise but also a practical solution with real-world applications. By automating shopping list conversions, we can provide users with a smoother, faster way to prepare their carts and streamline their shopping experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0d0a9044d56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harnessing OCR and OpenAI: A Structural Guide to Passport Text Extraction]]></title>
            <link>https://shankar138089.medium.com/harnessing-ocr-and-openai-a-structural-guide-to-passport-text-extraction-3591e99310db?source=rss-bb0b1b36776d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3591e99310db</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytesseract]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Shankar Sharma]]></dc:creator>
            <pubDate>Fri, 04 Oct 2024 22:41:01 GMT</pubDate>
            <atom:updated>2024-10-04T22:58:41.862Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="😁😂😭" src="https://cdn-images-1.medium.com/max/1024/1*nu-D3iBuOR98BPX-atIPjg.png" /></figure><p>Input Image ☝️</p><p>In this blog post, I will walk you through a Python function designed to summarize the architecture of a Streamlit application that extracts text from passport images. This application leverages Optical Character Recognition (OCR) and OpenAI’s API for advanced text formatting. Understanding this architecture is crucial for anyone looking to develop similar applications or enhance their current implementations.</p><h3>Function Overview</h3><p>The function we’ll be discussing is called explain_code_architecture. Its purpose is to provide a structured overview of the code used for passport text extraction, detailing the components, parameters, returns, and the flow of execution. Below is the complete function definition:</p><pre>def explain_code_architecture():<br>    &quot;&quot;&quot;<br>    Explains the architecture of the passport text extraction and formatting code.<br><br>    Returns:<br>        str: A detailed explanation of the code structure, including parameters, return values, and flow for each function.<br>    &quot;&quot;&quot;<br>    <br>    explanation = &quot;&quot;&quot;<br>    The code is designed to extracts text from an uploaded passport image using Optical Character Recognition (OCR) and formats the extracted text using the OpenAI API.<br>    <br>    1. **Function: extract_text_from_image**<br>    <br>        Parameters:<br>        - image: An image file (in PIL format) uploaded by the user.<br>    <br>        Returns:<br>        - normalized_text: A string containing the normalized text extracted from the image.<br>    <br>        Flow:<br>        1. Convert the uploaded image from PIL format to OpenCV format.<br>        2. Convert the image to grayscale to enhance the OCR process.<br>        3. Apply thresholding to create a binary image, improving OCR accuracy.<br>        4. Use pytesseract to extract text from the thresholded image.<br>        5. Normalize specific characters in the extracted text.<br>        6. Concatenate normalized lines into a single string and return.<br>    <br>    2. **Function: process_text_with_openai**<br>    <br>        Parameters:<br>        - text: The extracted text to be processed.<br>        - prompt_template: A template string used to format the input text for the OpenAI API.<br>    <br>        Returns:<br>        - A string containing the formatted output from the OpenAI API.<br>    <br>        Flow:<br>        1. Set the OpenAI API key for authorization.<br>        2. Format the provided text into a specific prompt template.<br>        3. Call the OpenAI API with the formatted prompt to obtain a response.<br>        4. Extract and return the relevant formatted information from the response.<br>    <br>    3. **Function: main**<br>    <br>        Parameters:<br>        - None<br>    <br>        Returns:<br>        - None (directly interacts with the Streamlit interface).<br>    <br>        Flow:<br>        1. Set the app title in the Streamlit interface.<br>        2. Create a sidebar for file upload, allowing users to upload an image of the passport.<br>        3. Display the uploaded image in the sidebar.<br>        4. Call the extract_text_from_image function to extract text from the uploaded image.<br>        5. Display the extracted text in a text area for user visibility.<br>        6. Define a prompt template for formatting the extracted text.<br>        7. Call the process_text_with_openai function to format the extracted text.<br>        8. Display the formatted output in another text area for user visibility.<br>    <br>    Summary:<br>    - The code consists of three main components: two functions for processing (text extraction and text processing) and a main function that ties together the user interface and the processing logic. <br>    - The architecture effectively utilizes Streamlit for the web interface, OpenCV and Pytesseract for image processing, and OpenAI&#39;s API for advanced text processing and formatting.<br>    &quot;&quot;&quot;<br>    <br>    return explanation.strip()</pre><h4>Understanding the Function Components</h4><h4>1. Extracting Text from Images</h4><p>The extract_text_from_image function is responsible for processing the uploaded image. It converts the image format, applies grayscale transformation, and uses thresholding techniques to enhance OCR accuracy. The extracted text is then normalized to correct any specific character misinterpretations that may occur during the OCR process.</p><h4>2. Processing Text with OpenAI</h4><p>The process_text_with_openai function takes the extracted text and formats it for OpenAI’s API. This function sets the necessary API key, constructs a prompt based on the text input, and sends a request to OpenAI. It receives a formatted response that is easy to read and understand, which is critical for displaying passport details correctly.</p><h4>3. Streamlit Application Structure</h4><p>The main function serves as the entry point of the application. It sets up the user interface, allowing users to upload passport images and displaying both the extracted and formatted text. This function integrates the other components, ensuring a smooth user experience and proper data flow from image upload to text extraction and formatting.</p><h4>Extracted Text from Image:</h4><pre>TS AND LIMITAT<br><br>oma<br>PASSPORT OR]<br>mIERSSEPORT: TypelType _Issuing Country/Pays émetteur Passport No./N* de passeport<br>© amon CAN 6coo0000<br><br>SANTA<br><br>Given names/Prénoms<br><br>CLAUS<br><br>Nationality’Nationaité<br>LAPAND/CANADIENNE<br><br>Date of birth/Date de naissance<br><br>25 DEC /DEC O00<br><br>Sex/Sexe Place of bith/Lieu de naissance<br><br>M/F wwW.EDITABLE-TEMPLATES.cc<br><br>Date o ssue/Date de déivrance<br><br>25 DEC /DEC 00<br><br>Date of expiryDate expiration<br><br>25 DEC /DEC 00<br>Issuing Authoriy/Autorté de délvrance<br><br>LAPAND NOVA SCOTIA<br><br>44490?<br><br>P&lt;CANSANTA&lt;KCLAUS &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;K KKK KKK KKK KKK KKK<br>GCOOD000&lt;OCANODD0000M0000000&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;00<br><br>NS ET RESTRICTIONS,</pre><h4>Formatted Output from Image:</h4><pre>- Type: P<br>- Country code: CAN<br>- Passport No: GCOO0000<br>- Surname: Claus<br>- Given Name(s): Santa<br>- Nationality: Lapland/Canadian<br>- Sex: M<br>- Date of Birth: 25 Dec 2000<br>- Place of Birth: Lapland<br>- Place of Issue: Nova Scotia<br>- Date of Issue: 25 Dec 2000<br>- Date of Expiry: 25 Dec 2000<br>- Machine Readable Zone: GCOOD000&lt;OCANODD0000M0000000</pre><p>The explain_code_architecture function is a powerful tool for understanding the underlying structure and functionality of the passport text extraction application. By summarizing the code’s architecture, it provides clarity and serves as a valuable reference for developers aiming to build or enhance similar applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3591e99310db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate SQL Query Generation with Mistral-7B]]></title>
            <link>https://shankar138089.medium.com/automate-sql-query-generation-with-mistral-7b-260f5e59fe95?source=rss-bb0b1b36776d------2</link>
            <guid isPermaLink="false">https://medium.com/p/260f5e59fe95</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mistral-7b]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Shankar Sharma]]></dc:creator>
            <pubDate>Fri, 04 Oct 2024 21:51:41 GMT</pubDate>
            <atom:updated>2024-10-04T21:51:41.289Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*0rTDoLcljSCCx1EKySLv9A.png" /></figure><p>SQL queries are essential for extracting meaningful insights from databases, but writing them can be complex and time-consuming. In this post, we’ll explore how to use the Mistral-7B language model to automatically generate SQL queries from natural language questions. This approach is particularly useful for non-technical users who may not be familiar with SQL.</p><h4>Why Mistral-7B?</h4><h4>Mistral-7B is a powerful large language model designed to handle complex tasks, including text generation and natural language understanding. With fine-tuning and prompt engineering, it can also be used to generate SQL queries from user inputs.</h4><p>Key features of its architecture include:</p><ul><li><strong>Transformer-based Architecture</strong>: Like most modern LLMs, Mistral 7B is built on the transformer architecture, which is highly effective for handling sequential data such as text.</li><li><strong>Instruction Fine-tuning</strong>: Mistral 7B is specifically tuned to follow natural language instructions, making it well-suited for tasks where a clear question or directive is provided, such as SQL generation or conversational agents.</li></ul><h4>Step-by-Step Guide</h4><h4>1. Setting Up the Environment</h4><p>To get started, you need to install the necessary libraries and load the Mistral-7B model. You can use HuggingFace’s transformers library along with LangChain for prompt management.</p><pre>!pip install git+https://github.com/huggingface/transformers.git<br>!pip install deepspeed --upgrade<br>!pip install accelerate<br>!pip install langchain<br>!pip install torch<br>!pip install bitsandbytes</pre><h4>2. Loading the Mistral-7B Model</h4><p>Once the dependencies are installed, we load the base Mistral-7B model and tokenizer. We use the model to handle the language generation tasks required for converting natural language to SQL.</p><pre>from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline<br>from langchain import LLMChain, PromptTemplate<br>from langchain.llms import HuggingFacePipeline<br><br># Load the model and tokenizer<br>base_model = AutoModelForCausalLM.from_pretrained(<br>    &quot;mistralai/Mistral-7B-Instruct-v0.1&quot;,<br>    device_map=&#39;auto&#39;,<br>)<br>tokenizer = AutoTokenizer.from_pretrained(&quot;mistralai/Mistral-7B-Instruct-v0.1&quot;)<br><br># Create a text-generation pipeline<br>pipe = pipeline(<br>    &quot;text-generation&quot;,<br>    model=base_model,<br>    tokenizer=tokenizer,<br>    max_length=500,<br>    temperature=0.3,<br>    top_p=0.95,<br>    repetition_penalty=1.2,<br>)<br>local_llm = HuggingFacePipeline(pipeline=pipe)</pre><h4>3. Extracting Database Schema</h4><p>To generate SQL queries, we need the structure of the database. This structure, known as the schema, can be extracted from DDL statements.</p><pre>def parse_ddl(ddl):<br>    tables = {}<br>    current_table = None<br>    ddl_lines = ddl.splitlines()<br><br>    for line in ddl_lines:<br>        line = line.strip()<br>        if line.startswith(&quot;CREATE TABLE&quot;):<br>            match = re.search(r&#39;CREATE TABLE (\w+)&#39;, line)<br>            if match:<br>                table_name = match.group(1)<br>                tables[table_name] = []<br>                current_table = table_name<br>        elif current_table:<br>            if line.endswith(&quot;);&quot;):<br>                current_table = None<br>            else:<br>                columns = re.findall(r&#39;(\w+)&#39;, line)<br>                if columns:<br>                    tables[current_table].extend(columns)<br><br>    return tables<br><br><br>schema = parse_ddl(ddl)</pre><h4>4. Generating SQL Queries with Mistral-7B</h4><p>Now, we use Mistral-7B to generate SQL queries from natural language questions. We employ LangChain to help structure the interaction between the schema and the language model.</p><pre>def query_generator(schema, question):<br>    schema_str = &quot;\n&quot;.join([f&quot;{table}: {&#39;, &#39;.join(cols)}&quot; for table, cols in schema.items()])<br>    template = &quot;&quot;&quot;Generate a SQL query using the following tables and columns:<br>    {schema}<br>    to answer the following question:<br>    {question}.<br>    Output Query:<br>    &quot;&quot;&quot;<br>    <br>    prompt = PromptTemplate(template=template, input_variables=[&quot;schema&quot;, &quot;question&quot;])<br>    llm_chain = LLMChain(prompt=prompt, llm=local_llm)<br>    response = llm_chain.run({&quot;schema&quot;: schema_str, &quot;question&quot;: question})<br><br>    return response<br><br># Example: Generating a query<br>question = &quot;What are my sales in 2013?&quot;<br>query = query_generator(schema, question)<br>print(query)</pre><h4>5. Matching User Questions with Column Names</h4><p>Sometimes, user queries may not exactly match the column names in the schema. We use the SequenceMatcher to ensure the user’s query aligns with the database schema, even if there are slight mismatches.</p><pre>from difflib import SequenceMatcher<br>import re<br><br>def find_columns_match(question, input_dict):<br>    try:<br>        question_list = re.split(r&#39;\s|,|\.&#39;, question)<br>        for index, string2 in enumerate(question_list):<br>            for string1 in input_dict:<br>                score = SequenceMatcher(None, string1.lower(), string2.lower()).ratio() * 100<br>                if score &gt; 91:<br>                    question_list[index] = string1 + &quot;,&quot;<br>        return &quot; &quot;.join(question_list)<br>    except Exception as e:<br>        return question</pre><h3>Results</h3><p>When the model processes a question like “What are my sales in 2013?”, it generates an SQL query using the available schema, such as:</p><pre>SELECT sale_id, sale_date, sale_amount <br>FROM sales <br>WHERE sale_date BETWEEN &#39;2013-01-01&#39; AND &#39;2013-12-31&#39;;</pre><p>Mistral-7B can be a game-changer for anyone working with large datasets and needing SQL queries. It allows for seamless natural language interactions with databases, enabling non-technical users to extract the insights they need without writing a single line of SQL. With tools like LangChain, this setup becomes even more powerful, flexible, and accessible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=260f5e59fe95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Choose the Right LangChain Memory for Data-Driven Conversational AI]]></title>
            <link>https://shankar138089.medium.com/how-to-choose-the-right-langchain-memory-for-data-driven-conversational-ai-033e02d4688c?source=rss-bb0b1b36776d------2</link>
            <guid isPermaLink="false">https://medium.com/p/033e02d4688c</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[Shankar Sharma]]></dc:creator>
            <pubDate>Fri, 04 Oct 2024 21:21:36 GMT</pubDate>
            <atom:updated>2024-10-04T21:21:36.590Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*ws4hslxMsf70wlXs7G88PQ.png" /></figure><h4><strong>The Role of Memory in Conversational AI</strong></h4><p>In conversational AI, memory is a key factor that determines how well an assistant can track context and provide coherent responses. Managing memory becomes even more challenging when the conversation involves complex questions or large datasets.</p><p>LangChain offers various memory mechanisms, from simple buffer memory to more advanced knowledge graph memory. However, choosing the right memory type isn’t always straightforward, especially when dealing with real-world applications.</p><p>The challenge is to balance performance and accuracy, especially when working with large datasets or when the questions asked are highly complex.</p><p>Here are the key factors you need to consider:</p><ul><li><strong>Data Size</strong>: A conversation based on a small dataset may not need sophisticated memory mechanisms, while larger datasets require more robust memory strategies.</li><li><strong>Question Complexity</strong>: A simple question might be handled by basic memory, but more complex, multi-faceted queries might require more advanced memory models.</li></ul><p>In my approach, I developed a function that evaluates these factors and dynamically selects the appropriate memory type.</p><h3>Memory Types in LangChain: An Overview</h3><p>Before diving into the function, let’s quickly review the memory options LangChain provides:</p><ul><li><strong>ConversationBufferMemory</strong>: Stores all conversation history.</li><li><strong>ConversationBufferWindowMemory</strong>: Keeps only the last few interactions, based on a defined window size.</li><li><strong>ConversationSummaryMemory</strong>: Summarizes long conversations, providing key context without storing every detail.</li><li><strong>ConversationKnowledgeGraphMemory</strong>: Tracks relationships between entities, ideal for knowledge-based queries.</li><li><strong>VectorStoreMemory</strong>: Uses a vector store to manage conversation history efficiently, great for high-dimensional data.</li></ul><p>Each memory type has its strengths, and the goal of my function is to dynamically choose the best one for a given context.</p><p>Here’s the heart of the blog, where you explain the code step-by-step.</p><pre>def select_memory_function(self, df: pd.DataFrame, question: str):<br>    &quot;&quot;&quot;<br>    Select the best LangChain memory function based on the DataFrame and question complexity.<br>    &quot;&quot;&quot;<br>    # Analyze the DataFrame size and structure<br>    num_rows = df.shape[0]<br>    num_columns = df.shape[1]<br>    column_names = df.columns.tolist()<br><br>    # Determine complexity of the question by length<br>    question_length = len(question)<br><br>    # Heuristics for selecting memory type based on DF and question<br>    if num_rows &lt; 50 and num_columns &lt; 10 and question_length &lt; 100:<br>        return ConversationBufferMemory()<br><br>    elif num_rows &gt; 500 or question_length &gt; 300:<br>        return ConversationSummaryMemory(llm=self.llm)<br><br>    elif num_rows &gt; 50 or question_length &gt; 150:<br>        return ConversationBufferWindowMemory(window_size=10)<br><br>    elif &#39;knowledge&#39; in question.lower() or &#39;relation&#39; in question.lower():<br>        return ConversationKnowledgeGraphMemory(llm=self.llm)<br><br>    elif num_columns &gt; 20:<br>        return VectorStoreMemory()<br><br>    else:<br>        return ConversationBufferMemory()</pre><h3>Explanation:</h3><ul><li><strong>Step 1: Data Analysis</strong>: We analyze the size of the DataFrame (num_rows and num_columns) and the question complexity (question_length). This forms the basis for deciding which memory type is best suited.</li><li><strong>Step 2: Small Data, Simple Question</strong>: If both the data and the question are simple, we opt for ConversationBufferMemory, which stores all conversations without much overhead.</li><li><strong>Step 3: Large Data or Complex Question</strong>: For larger datasets or complex questions, ConversationSummaryMemory is used. This helps to reduce memory overhead while maintaining a summary of the conversation.</li><li><strong>Step 4: Medium Complexity</strong>: For cases where the data is moderately large, or the question is somewhat complex, we use ConversationBufferWindowMemory. It retains only a limited number of past conversations to balance performance and memory usage.</li><li><strong>Step 5: Knowledge-based Queries</strong>: When the question revolves around relationships, we use ConversationKnowledgeGraphMemory to track entities and their relations.</li><li><strong>Step 6: High-dimensional Data</strong>: If the DataFrame has many columns, we select VectorStoreMemory to manage context efficiently in high-dimensional space.</li></ul><h3><strong>Potential Improvements:</strong></h3><p><strong>Threshold Tuning</strong>:</p><ul><li>The current thresholds for data size (50 rows, 500 rows, 20 columns) and question length (100 characters, 150 characters, 300 characters) may not work universally for all datasets or use cases. You could make these thresholds configurable, either by passing them as parameters or by adjusting them based on historical data/usage patterns.</li></ul><pre>def select_memory_function(self, df: pd.DataFrame, question: str, <br>                           row_threshold: int = 50, col_threshold: int = 20, <br>                           question_len_threshold: int = 100):<br>    # Now the thresholds can be passed when calling the function</pre><p><strong>Granularity for Question Complexity</strong>:</p><ul><li>While length is a good indicator of complexity, it may not capture certain nuances (e.g., multi-part questions or semantic complexity). You could enhance this by using natural language processing (NLP) to assess the complexity of the question, such as checking for compound structures, entities, or knowledge requirements.</li></ul><pre>def get_question_complexity(question: str):<br>    # Use NLP to detect question structure, entities, relationships<br>    # For example: Use a named entity recognition (NER) model to count entities<br>    # or parse the question for compound sentences<br>    complexity_score = len(question)  # Starting with length but could add more analysis<br>    return complexity_score</pre><h3>Real-World Use Cases</h3><p>In this section, you can explain various scenarios where this dynamic function could be helpful:</p><ol><li><strong>E-commerce Assistant</strong>: An assistant helping users find products in a massive catalog needs to adapt its memory strategy. For simple queries like “Show me shoes,” basic buffer memory works. But when asked, “What shoes did I view last week, and how do they compare to today’s discounts?”, a more complex memory like ConversationSummaryMemory or VectorStoreMemory is better.</li><li><strong>Healthcare Chatbot</strong>: A healthcare assistant answering detailed medical questions must track relationships between symptoms and diagnoses. Using ConversationKnowledgeGraphMemory, the assistant can provide accurate follow-ups based on prior conversations.</li><li><strong>Customer Support Bot</strong>: For long conversations with many interactions, ConversationSummaryMemory helps keep track of the discussion while reducing memory consumption.</li></ol><p>By leveraging LangChain’s different memory models and selecting the appropriate one dynamically, we can build conversational systems that are both intelligent and efficient. This approach ensures that the assistant scales with increasing data complexity while maintaining high-quality, context-aware responses.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=033e02d4688c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Forecasting Simulations]]></title>
            <link>https://shankar138089.medium.com/exploring-forecasting-simulations-af45c1fced6d?source=rss-bb0b1b36776d------2</link>
            <guid isPermaLink="false">https://medium.com/p/af45c1fced6d</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[arima]]></category>
            <dc:creator><![CDATA[Shankar Sharma]]></dc:creator>
            <pubDate>Fri, 04 Oct 2024 21:01:05 GMT</pubDate>
            <atom:updated>2024-10-04T21:01:05.453Z</atom:updated>
            <content:encoded><![CDATA[<p>In this section, we will explore a collection of essential functions designed for time series forecasting using various statistical and simulation methods. These functions leverage powerful techniques to analyze historical data, identify patterns, and generate future forecasts. Understanding these functions will provide you with the tools needed to effectively model and predict trends in your data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yR1IAed-IG0kpZWT2Dkigw.png" /></figure><h4>1. ARIMA Order Selection</h4><p>The <strong>select_best_arima_order</strong> function identifies the most suitable order for the ARIMA (AutoRegressive Integrated Moving Average) model based on the Akaike Information Criterion (AIC). By exploring different combinations of parameters, this function helps ensure that the model captures the underlying patterns of the data while avoiding overfitting.</p><pre>def select_best_arima_order(df, column):<br>    &quot;&quot;&quot;<br>    Selects the best ARIMA order based on the Akaike Information Criterion (AIC).<br>    <br>    Parameters:<br>        df (pd.DataFrame): The input DataFrame containing time series data.<br>        column (str): The name of the column to analyze.<br>    <br>    Returns:<br>        best_order (tuple): The (p, d, q) order of the best ARIMA model.<br>    <br>    Flow:<br>        1. Define ranges for the parameters p (autoregressive), d (integrated), and q (moving average).<br>        2. Iterate through all combinations of p, d, and q to fit ARIMA models.<br>        3. Calculate the AIC for each model.<br>        4. Identify and return the model with the lowest AIC as the best order.<br>    &quot;&quot;&quot;<br>    pass</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ZgTlXOd-3Oz9R6s0-LEdQ.png" /></figure><h4>2. Decomposition Model Selection</h4><p>The <strong>select_decomposition_model</strong> function evaluates the variance of the time series data to determine the appropriate decomposition model—either additive or multiplicative. This step is crucial for understanding how different components (trend, seasonality, and residuals) contribute to the overall behavior of the time series.</p><pre>def select_decomposition_model(data):<br>    &quot;&quot;&quot;<br>    Determines the appropriate decomposition model (&#39;additive&#39; or &#39;multiplicative&#39;) <br>    based on the variance of the time series data.<br>    <br>    Parameters:<br>        data (pd.Series): The input time series data.<br>    <br>    Returns:<br>        model_type (str): The selected model type (&#39;additive&#39; or &#39;multiplicative&#39;).<br>    <br>    Flow:<br>        1. Analyze the variance of the time series data.<br>        2. If the variance is stable over time, select &#39;additive&#39;.<br>        3. If the variance increases with the level of the series, select &#39;multiplicative&#39;.<br>    &quot;&quot;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDYP8af-2b7_7YPkIPxtWA.png" /></figure><h4>3. ACF Plot Generation</h4><p>To analyze the autocorrelation of the data, the <strong>generate_correlogram</strong> function produces an autocorrelation function (ACF) plot. This visual representation helps identify significant lags, revealing the strength and direction of relationships within the data over time.</p><pre>def generate_correlogram(data):<br>    &quot;&quot;&quot;<br>    Generates and plots the autocorrelation function (ACF) for the given time series data.<br>    <br>    Parameters:<br>        data (pd.Series): The input time series data.<br>    <br>    Returns:<br>        None: Displays the ACF plot.<br>    <br>    Flow:<br>        1. Calculate the autocorrelation coefficients for different lags.<br>        2. Plot the ACF with confidence intervals.<br>    &quot;&quot;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZK4vufpG0xlzurHVxqPDg.png" /></figure><h4>4. PACF Plot Generation</h4><p>Complementing the ACF, the <strong>generate_pacf</strong> function creates a partial autocorrelation function (PACF) plot. This plot is instrumental in determining the appropriate lag order for the ARIMA model by illustrating the direct relationships between a time series and its past values.</p><pre>def generate_pacf(data):<br>    &quot;&quot;&quot;<br>    Generates and plots the partial autocorrelation function (PACF) for the given time series data.<br>    <br>    Parameters:<br>        data (pd.Series): The input time series data.<br>    <br>    Returns:<br>        None: Displays the PACF plot.<br>    <br>    Flow:<br>        1. Calculate the partial autocorrelation coefficients for different lags.<br>        2. Plot the PACF with confidence intervals.<br>    &quot;&quot;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QYhc_Wo7U2D2lTZKAD9d9g.png" /></figure><h4>5. Monte Carlo Simulation for Forecasts</h4><p>The <strong>monte_carlo_simulation</strong> function employs Monte Carlo techniques to simulate multiple forecast paths based on the fitted ARIMA model. By generating a range of possible future scenarios, this function provides insights into the uncertainty surrounding forecasts.</p><pre>def monte_carlo_simulation(df, column, best_order, forecast_period=36, simulations=100):<br>    &quot;&quot;&quot;<br>    Performs Monte Carlo simulations for forecasting using the ARIMA model.<br>    <br>    Parameters:<br>        df (pd.DataFrame): The input data containing time series.<br>        column (str): The name of the column to analyze.<br>        best_order (tuple): The (p, d, q) order of the ARIMA model.<br>        forecast_period (int): The number of periods to forecast (default is 36).<br>        simulations (int): The number of simulation paths to generate (default is 100).<br>    <br>    Returns:<br>        forecast (pd.DataFrame): The simulated forecast paths.<br>    <br>    Flow:<br>        1. Fit the ARIMA model using the best_order on the time series data.<br>        2. Generate forecast for the specified number of periods.<br>        3. Simulate multiple future paths based on the forecasted values.<br>        4. Plot the simulation results.<br>    &quot;&quot;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L75yvOBGRV92cK-O94Fi9A.png" /></figure><h4>6. MCMC Forecasting</h4><p>Using Markov Chain Monte Carlo (MCMC) methods, the <strong>mcmc_forecast</strong> function generates forecasts while accounting for uncertainty in the parameter estimates. This approach allows for robust modeling and visualization of predicted trends with confidence intervals.</p><pre>def mcmc_forecast(df, column, forecast_period=36, num_samples=1000, burn_in=100):<br>    &quot;&quot;&quot;<br>    Performs MCMC sampling to generate forecasts for the specified time series.<br>    <br>    Parameters:<br>        df (pd.DataFrame): The input data containing time series.<br>        column (str): The name of the column to analyze.<br>        forecast_period (int): The number of periods to forecast (default is 36).<br>        num_samples (int): The total number of MCMC samples to generate (default is 1000).<br>        burn_in (int): The number of initial samples to discard (default is 100).<br>    <br>    Returns:<br>        forecast (pd.Series): The mean forecasted values.<br>    <br>    Flow:<br>        1. Perform MCMC sampling on the time series data to estimate model parameters.<br>        2. Generate forecasted values using the sampled parameters.<br>        3. Plot the mean forecast along with confidence intervals.<br>    &quot;&quot;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kOJuHy2cJwqUfOtBBavdAw.png" /></figure><h4>7. Discrete Event Simulation</h4><p>The <strong>discrete_event_simulation</strong> function simulates events as a Poisson process, which is particularly useful for analyzing time series data with irregular intervals. This method provides a unique perspective on potential future occurrences based on historical patterns.</p><pre>def discrete_event_simulation(df, column, forecast_period=36):<br>    &quot;&quot;&quot;<br>    Simulates events as a Poisson process and generates forecast results.<br>    <br>    Parameters:<br>        df (pd.DataFrame): The input data containing time series.<br>        column (str): The name of the column to analyze.<br>        forecast_period (int): The number of periods to simulate (default is 36).<br>    <br>    Returns:<br>        results (pd.Series): The simulated event counts for the forecast period.<br>    <br>    Flow:<br>        1. Define the rate of events based on historical data.<br>        2. Simulate event occurrences using a Poisson process for the specified forecast period.<br>        3. Return the simulated results.<br>    &quot;&quot;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nbd4d8_GACkP7CVGkkaT9w.png" /></figure><h4>8. Scenario Generation</h4><p>With the <strong>generate_scenarios</strong> function, users can adjust base forecasts to account for various hypothetical situations. This flexibility allows analysts to explore the impact of different assumptions on future outcomes.</p><pre>def generate_scenarios(base_forecast, scenarios):<br>    &quot;&quot;&quot;<br>    Generates adjusted forecasts based on different scenarios for analysis.<br>    <br>    Parameters:<br>        base_forecast (pd.Series): The base forecast values.<br>        scenarios (dict): A dictionary of scenarios to adjust the base forecasts.<br>    <br>    Returns:<br>        adjusted_forecasts (pd.DataFrame): The forecasts adjusted for each scenario.<br>    <br>    Flow:<br>        1. Iterate through each scenario and apply adjustments to the base forecast.<br>        2. Store the adjusted forecasts in a DataFrame.<br>        3. Return the DataFrame with adjusted forecasts for analysis.<br>    &quot;&quot;&quot;</pre><h4>9. Scenario Analysis</h4><p>Finally, the <strong>scenario_analysis</strong> function integrates the previous functionalities by fitting an ARIMA model and generating forecasts under different scenarios. This comprehensive analysis enables users to visualize and compare how varying conditions affect the projected results.</p><pre>def scenario_analysis(df, column, best_order, forecast_period=36):<br>    &quot;&quot;&quot;<br>    Conducts scenario analysis by fitting an ARIMA model and generating forecasts <br>    under different scenarios.<br>    <br>    Parameters:<br>        df (pd.DataFrame): The input data containing time series.<br>        column (str): The name of the column to analyze.<br>        best_order (tuple): The (p, d, q) order of the ARIMA model.<br>        forecast_period (int): The number of periods to forecast (default is 36).<br>    <br>    Returns:<br>        scenario_forecasts (pd.DataFrame): The forecasts for each scenario.<br>    <br>    Flow:<br>        1. Fit the ARIMA model using the best_order on the time series data.<br>        2. Generate base forecasts for the specified period.<br>        3. Create and plot forecasts for different scenarios based on the base forecast.<br>    &quot;&quot;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LRaZOfVmxYlru_wW6uzHOw.png" /></figure><h3>Conclusion</h3><p>These functions form a robust toolkit for performing time series forecasting, providing insights that can inform decision-making in various domains, from finance to inventory management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af45c1fced6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chat with Multiple PDFs using Langchain: Building a Conversational Retrieval System]]></title>
            <link>https://shankar138089.medium.com/chat-with-multiple-pdfs-using-langchain-building-a-conversational-retrieval-system-dce886e7f325?source=rss-bb0b1b36776d------2</link>
            <guid isPermaLink="false">https://medium.com/p/dce886e7f325</guid>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Shankar Sharma]]></dc:creator>
            <pubDate>Mon, 13 May 2024 19:12:12 GMT</pubDate>
            <atom:updated>2024-05-14T09:38:01.884Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c7ZYlkiRol4jlSCmsDs0Iw.png" /></figure><p>In today’s data-driven world, accessing and extracting information from large repositories of documents efficiently is crucial. Conversational retrieval systems provide a user-friendly interface for interacting with such data, enabling users to ask questions or provide prompts in natural language and receive relevant responses. In this blog post, we’ll explore how to build a conversational retrieval system capable of extracting information from multiple PDF documents using Langchain, a comprehensive toolkit for natural language processing (NLP) tasks.</p><h3>Setting up the Environment</h3><pre>pip install langchain</pre><p>Additionally, you’ll need an API key from OpenAI to access their language models. You can obtain an API key by signing up for an account on the OpenAI website.</p><p>Now, let’s break down the code step by step to understand how our conversational retrieval system works.</p><h4>Imports necessary libraries and modules.</h4><pre>import os<br>import sys<br>import openai<br>from langchain.chains import ConversationalRetrievalChain<br>from langchain.chat_models import ChatOpenAI<br>from langchain.document_loaders import PyPDFLoader<br>from langchain.embeddings import OpenAIEmbeddings<br>from langchain.indexes import VectorstoreIndexCreator, VectorStoreIndexWrapper<br>from langchain.vectorstores import Chroma<br>import apikeyp</pre><p>importing modules from Langchain for handling conversation, document loading, embeddings, indexes, and models, as well as the OpenAI library for accessing their language models.</p><h4>Setting up API Key and Source Data Folder</h4><pre>os.environ[&quot;OPENAI_API_KEY&quot;] = apikey.APIKEY<br>source_folder = &quot;/path/to/source_data&quot;</pre><p>We set up the OpenAI API key using the provided API key from an external file. We also define the file path to the PDF document , Here the pdf document i am using is the Constitution of India.</p><h4>PERSIST Flag and Command Line Argument Handling</h4><pre>PERSIST = False<br>query = None<br>if len(sys.argv) &gt; 1:<br>    query = sys.argv[1]</pre><p>We define a flag PERSIST to determine whether to save the model to disk for reuse. We also check for command line arguments, allowing users to provide a query directly from the command line.</p><h4>Loading PDF Documents</h4><pre>loaders = []<br>for filename in os.listdir(source_folder):<br>    if filename.endswith(&quot;.pdf&quot;):<br>        file_path = os.path.join(source_folder, filename)<br>        loader = PyPDFLoader(file_path)<br>        loaders.append(loader)</pre><p>We load the Constitution of India PDF document using the PyPDFLoader class and store it in a list.</p><h4>Index Creation</h4><pre>index = None<br>if PERSIST and os.path.exists(&quot;persist&quot;):<br>    vectorstore = Chroma(persist_directory=&quot;persist&quot;, embedding_function=OpenAIEmbeddings())<br>    index = VectorStoreIndexWrapper(vectorstore=vectorstore)<br>else:<br>    index = VectorstoreIndexCreator().from_loaders(loaders)</pre><p>Depending on the value of the PERSIST flag, we either load a persisted index from disk or create a new index from the PDF loaders.</p><h4>Initializing the Conversational Retrieval Chain</h4><pre>chain = ConversationalRetrievalChain.from_llm(<br>    llm=ChatOpenAI(model=&quot;gpt-3.5-turbo&quot;),<br>    retriever=index.vectorstore.as_retriever(search_kwargs={&quot;k&quot;: 1}),<br>)</pre><h4>Chat Loop</h4><pre>chat_history = []<br>while True:<br>    if not query:<br>        query = input(&quot;Prompt: &quot;)<br>    if query in [&#39;quit&#39;, &#39;q&#39;, &#39;exit&#39;]:<br>        sys.exit()<br>    result = chain({&quot;question&quot;: query, &quot;chat_history&quot;: chat_history})<br>    print(result[&#39;answer&#39;])<br><br>    chat_history.append((query, result[&#39;answer&#39;]))<br>    query = None</pre><p>We enter an infinite loop where users can input prompts. If the user inputs ‘quit’, ‘q’, or ‘exit’, the script exits. Otherwise, the system queries the conversational retrieval chain with the user input, prints the answer, and appends the query and answer to the chat history.</p><p><strong>Github_repo :</strong><br><a href="https://github.com/shankarsharma8089/Chat-with-Multiple-PDFs-using-Langchain-Building-a-Conversational-Retrieval-System.git">https://github.com/shankarsharma8089/Chat-with-Multiple-PDFs-using-Langchain-Building-a-Conversational-Retrieval-System.git</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UvDlf1uOjHp3RDWQglbVPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxgkUkIf6SfH_7nJihPayA.png" /></figure><p>This system has numerous potential applications, from research assistance to customer support automation, and demonstrates the exciting possibilities of conversational AI in information retrieval tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dce886e7f325" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Identify Animals in Images Using GPT-4 Vision]]></title>
            <link>https://shankar138089.medium.com/how-to-identify-animals-in-images-using-gpt-4-vision-640a8aff6bc3?source=rss-bb0b1b36776d------2</link>
            <guid isPermaLink="false">https://medium.com/p/640a8aff6bc3</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[gpt-vision]]></category>
            <dc:creator><![CDATA[Shankar Sharma]]></dc:creator>
            <pubDate>Sun, 12 May 2024 15:23:38 GMT</pubDate>
            <atom:updated>2024-05-12T15:23:38.469Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lUbyRue519O7s2zbLr-cNg.png" /></figure><p>GPT-4 Vision is an iteration of OpenAI’s Generative Pre-trained Transformer (GPT) models, specifically tailored for image recognition tasks. Unlike traditional computer vision models that rely on handcrafted features and algorithms, GPT-4 Vision utilizes deep learning techniques to understand and interpret images in a more nuanced manner. With its immense computational power and extensive training data, GPT-4 Vision can accurately recognize a wide range of objects, including animals, in images.</p><p>Before we dive into the code, let’s ensure that we have the necessary tools and environment set up to work with GPT-4 Vision. First, you’ll need to obtain an API key from OpenAI to access their services. You can sign up for an API key on the OpenAI website. Once you have your API key, install the required Python libraries, including requests, openai, PIL, and json.</p><p>This Python script will identify animals in images using the GPT-4 Vision model and generating insights about them using the GPT-3.5 Turbo Instruct model.</p><pre>import base64<br>import requests<br>import openai<br>from PIL import Image<br>from io import BytesIO<br>import json<br>import os<br><br># Set your OpenAI API key<br>api_key = &quot;API_KEY&quot;<br>openai.api_key = api_key<br><br># Function to encode the image<br>def encode_image(image_data):<br>    return base64.b64encode(image_data).decode(&#39;utf-8&#39;)<br><br># Function to perform animal identification using GPT-4 Vision<br>def identify_animal(image_data):<br>    base64_image = encode_image(image_data)<br><br>    headers = {<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        &quot;Authorization&quot;: f&quot;Bearer {api_key}&quot;<br>    }<br><br>    payload = {<br>        &quot;model&quot;: &quot;gpt-4-vision-preview&quot;,<br>        &#39;messages&#39;: [<br>            {<br>                &#39;role&#39;: &#39;system&#39;,<br>                &#39;content&#39;: &#39;You have to give concise and short answers&#39;<br>            },<br>            {<br>                &#39;role&#39;: &#39;user&#39;,<br>                &#39;content&#39;: [<br>                    {<br>                        &#39;type&#39;: &#39;text&#39;,<br>                        &#39;text&#39;: &#39;GPT, your task is to identify which animal it is with precision. Analyze any image of animal i provide and respond strictly with the name of the animal, and nothing else—no explanations, no additional text. If a condition is unrecognizable, reply with \&#39;I don\&#39;t know\&#39;. If the image is not animal-related, say \&#39;Please pick another image\&#39;&#39;,<br>                    },<br>                    {<br>                        &#39;type&#39;: &#39;image_url&#39;,<br>                        &#39;image_url&#39;: {<br>                            &quot;url&quot;: f&quot;data:image/jpeg;base64,{base64_image}&quot;,<br>                        },<br>                    },<br>                ],<br>            },<br>        ],<br>        &quot;max_tokens&quot;: 50<br>    }<br><br>    # Make API request for animal identification<br>    response = requests.post(&quot;https://api.openai.com/v1/chat/completions&quot;, headers=headers, json=payload)<br><br>    # Assuming the JSON is stored in the variable &#39;response&#39;<br>    json_data = response.json()<br><br>    # Extracting &#39;content&#39; from the JSON<br>    content_value = json_data[&#39;choices&#39;][0][&#39;message&#39;][&#39;content&#39;]<br><br>    return content_value<br><br># Function to generate insights using GPT-3.5 Turbo Instruct<br>def generate_insights(animal_name):<br>    prompt = f&quot;&quot;&quot;<br>    \n**Scientific name:** Share the scientific name of {animal_name}.<br>    \n**Description :** Give a 2 line description of the animal {animal_name}.<br>    &quot;&quot;&quot;,<br>        <br>    response = openai.Completion.create(<br>        engine=&quot;gpt-3.5-turbo-instruct&quot;,<br>        prompt=prompt,<br>        max_tokens=800,<br>        n=1,<br>        stop=None,<br>        temperature=0.1,<br>    )<br><br>    insights = response.choices[0].text.strip()<br><br>    # Remove original questions from the generated insights<br>    insights = insights.replace(&quot;Briefly describe the animal:&quot;, &quot;&quot;)<br>    <br>    return insights<br><br># Function to save conversation log<br>def log_conversation(image_data, animal_name, insights):<br>    log = {<br>        &quot;image_data&quot;: base64.b64encode(image_data).decode(&#39;utf-8&#39;),<br>        &quot;animal_name&quot;: animal_name,<br>        &quot;insights&quot;: insights<br>    }<br><br>    # Save log to a file<br>    filename = &quot;conversation_log.json&quot;<br>    if os.path.exists(filename):<br>        with open(filename, &quot;r&quot;) as file:<br>            data = json.load(file)<br>            data.append(log)<br>        with open(filename, &quot;w&quot;) as file:<br>            json.dump(data, file, indent=4)<br>    else:<br>        with open(filename, &quot;w&quot;) as file:<br>            json.dump([log], file, indent=4)<br><br>def main():<br>    # Example usage<br>    image_path = &quot;images.jpeg&quot;<br>    with open(image_path, &quot;rb&quot;) as file:<br>        image_data = file.read()<br><br>    # Identify animal using GPT-4 Vision<br>    animal_name = identify_animal(image_data)<br>    print(&quot;Animal Name:&quot;, animal_name)<br><br>    # Generate insights using GPT-3.5 Turbo Instruct<br>    insights = generate_insights(animal_name)<br>    print(&quot;Insights and Observations:&quot;, insights)<br><br>    # Log conversation<br>    log_conversation(image_data, animal_name, insights)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Output after running the above code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GuY7ojLTfevkEvcR8RGY-w.png" /></figure><p>The log_conversation function wil save conversation log, including the uploaded image, identified animal name, and generated insights, into a JSON file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6vmzrJWDn8RHaucL0vcliA.png" /><figcaption>view of conversation log in streamlit app</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=640a8aff6bc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Word2Vec: A Dive into Vectorized Word Representations]]></title>
            <link>https://shankar138089.medium.com/understanding-word2vec-a-dive-into-vectorized-word-representations-2602ac421fc8?source=rss-bb0b1b36776d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2602ac421fc8</guid>
            <category><![CDATA[skip-gram]]></category>
            <category><![CDATA[cbow]]></category>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Shankar Sharma]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 18:50:59 GMT</pubDate>
            <atom:updated>2023-11-13T18:50:59.248Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LO1t3Vt20ljKe8OsAJVzYg.png" /></figure><p>In the realm of Natural Language Processing (NLP), representing words as vectors has become a cornerstone for various applications. One powerful technique for this purpose is Word2Vec, which transforms words into high-dimensional vectors, typically 32 dimensions or more. The primary motivation behind using Word2Vec lies in its ability to preserve relationships between words, handle the addition of new words to the vocabulary, and deliver superior results in a wide array of deep learning applications.</p><h3>Why Word2Vec?</h3><h4>1. Relationship Preservation</h4><p>Word2Vec excels in capturing semantic relationships between words. For instance, in the sentences “The kid said he would be a footballer” and “The child said he would be a footballer,” Word2Vec recognizes that ‘Kid’ and ‘Child’ share a similar context and attempts to represent them as vectors with similar directions.</p><h4>2. Dynamic Vocabulary</h4><p>It accommodates the addition of new words to the vocabulary. This adaptability is crucial in real-world applications where language is constantly evolving.</p><h4>3. Improved Results</h4><p>Word2Vec’s vectorized representations yield enhanced performance in various deep learning tasks, making it a valuable tool in natural language understanding.</p><h3>How Relationships are Formed</h3><p>Word2Vec builds relationships by ensuring that words with similar contexts have similar embeddings. Two key algorithms, <strong>Continuous Bag of Words (CBOW)</strong> and <strong>Skip Gram</strong>, are employed for this purpose.</p><h3>Continuous Bag of Words (CBOW)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9uABHkwxtgTzJDpSAJyQAA.jpeg" /></figure><h3>Working of CBOW:</h3><p>Certainly! Let’s walk through the Continuous Bag of Words (CBOW) model using the example “<strong>Liverpool FC are a football team</strong>.”</p><h4>CBOW Example:</h4><h4>Encoding Words:</h4><p>Encode each word in the sentence as a one-hot vector.</p><h4>Example:</h4><ul><li>“Liverpool”:<strong> [1, 0, 0, 0]</strong></li><li>“FC”: <strong>[0, 1, 0, 0]</strong></li><li>“are”:<strong> [0, 0, 1, 0]</strong></li><li>“a”:<strong> [0, 0, 0, 1]</strong></li></ul><h4>Selecting Window Size:</h4><p>Choose a window size for iterating over the sentence. Let’s consider a window size of 2 for this example.</p><h4>Neural Network Prediction:</h4><p>For each word in the sentence, use the surrounding context words to predict the target word.</p><p>Example: For the center word “FC,” use the context words “Liverpool” and “are” to predict it.</p><pre>Input: [1, 0, 0, 0] + [0, 0, 1, 0]   --&gt;   Output: [0, 1, 0, 0]   (Predict &quot;FC&quot;)</pre><p>Update the weights in the neural network based on the predicted target word.</p><h4>Weight Update:</h4><p>Update the weights in the neural network using backpropagation and the error between the predicted and actual target word.</p><h4>Sliding Window:</h4><p>Slide the window to the next center word (e.g., “Liverpool”) and repeat the process.</p><h4>Repeat Iterations:</h4><p>Continue iterating over the entire sentence, updating weights, and generating vectors for each word in the vocabulary.</p><p>In summary, CBOW predicts the target word (center word) based on the surrounding context words. The model learns to associate the context with the target word, updating its weights to improve predictions. This process is repeated iteratively, resulting in vector representations for each word in the vocabulary.</p><h3>Skip-Gram</h3><p>In contrast to CBOW, Skip-Gram predicts context words from a given target. It follows a similar process of window iteration, neural network prediction, and weight updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-PNxNSywTck0F1XUj-OFQ.jpeg" /></figure><h3>Working of Skip-Gram :</h3><p>Let’s delve into the Skip-Gram model using the example “<strong>Liverpool FC are a football team</strong>.”</p><h4>Skip-Gram Example:</h4><h4>Encoding Words:</h4><p>Start by encoding each word as a one-hot vector. Each word in the sentence gets a unique one-hot representation.</p><h4>Example:</h4><ul><li>“Liverpool”: <strong>[1, 0, 0, 0]</strong></li><li>“FC”: <strong>[0, 1, 0, 0]</strong></li><li>“are”:<strong> [0, 0, 1, 0]</strong></li><li>“a”: <strong>[0, 0, 0, 1]</strong></li></ul><h4>Selecting Window Size:</h4><p>Similar to CBOW, choose a window size for iterating over the sentence. Let’s consider a window size of 2 for this example.</p><h4>Neural Network Prediction:</h4><p>For each word in the sentence, use the selected word as the target and predict the surrounding context words.</p><p>Example:</p><p>For the target word “FC,” predict the context words “Liverpool” and “are.”</p><pre>Input: [0, 1, 0, 0]   --&gt;   Output: [1, 0, 0, 0]   (Predict &quot;Liverpool&quot;)<br>Input: [0, 1, 0, 0]   --&gt;   Output: [0, 0, 1, 0]   (Predict &quot;are&quot;)</pre><p>Update the weights in the neural network based on the predicted context words.</p><h4>Weight Update:</h4><p>Update the weights in the neural network using backpropagation and the error between the predicted and actual context words.</p><h4>Sliding Window:</h4><p>Slide the window to the next target word (e.g., “Liverpool”) and repeat the process.</p><h4>Repeat Iterations:</h4><p>Continue iterating over the entire sentence, updating weights, and generating vectors for each word in the vocabulary.</p><p>In essence, Skip-Gram, unlike CBOW, predicts context words given a target word. It aims to learn the relationships between words by training the model to predict the context based on a given center word. This process is repeated throughout the training data, refining the vector representations for each word in the vocabulary.</p><h3><strong>Code:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ie07kZLNEx1rNy-OVVg0rw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avRxfY4KeFIYSag3OYcISA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AoDGd4YFmk6BQjDm3FFM8Q.png" /></figure><p>In conclusion, Word2Vec, through algorithms like CBOW and Skip-Gram, offers a robust approach to represent words in a vectorized form, capturing intricate semantic relationships. By understanding its working principles and optimizing parameters, practitioners can harness the power of Word2Vec for various natural language processing tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2602ac421fc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Segment Anything Model(SAM) Unveiled: A Deep Dive into Object Segmentation with PyTorch and SAM”]]></title>
            <link>https://shankar138089.medium.com/segment-anything-model-sam-unveiled-a-deep-dive-into-object-segmentation-with-pytorch-and-sam-3820cd47ba27?source=rss-bb0b1b36776d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3820cd47ba27</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[onnx-runtime]]></category>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[object-segmentation]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Shankar Sharma]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 05:26:11 GMT</pubDate>
            <atom:updated>2023-11-13T05:26:11.787Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog takes you on an immersive journey, unraveling the nuances of setting up the environment, installing dependencies, and harnessing SAM’s capabilities for advanced object segmentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hO2XAsK0Upr_cMotAnC3QQ.jpeg" /></figure><p>The Segment Anything Model (SAM) is a deep learning model designed for image segmentation, trained on an extensive dataset known as the Segment Anything dataset. Operating on the U-Net architecture, SAM is a single-shot object detection model that distinguishes itself by its prompt-based approach. Drawing inspiration from Language Model (LLM) paradigms, SAM allows users to guide segmentation tasks through prompts, such as clicking on a point, drawing a boundary box, or sketching a rough mask on an object. This pioneering model serves as a foundation for image segmentation, bridging the gap between natural language prompts and visual understanding. SAM’s versatility is evident in its ability to handle various types of segmentation tasks, adapting to new challenges through user-defined prompts. Trained to provide valid segmentation masks even in ambiguous scenarios, SAM aligns with the prompting philosophy seen in LLMs, where responses are generated based on unclear prompts. Additionally, SAM’s promptable segmentation extends its utility to novel tasks, making it a valuable asset in combination with existing object detectors for diverse applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HCirDIShr4EsxwiiPXpStw.png" /></figure><h4>Building the PyTorch Playground</h4><p>Begin your exploration by setting up the PyTorch playground. Navigate through the essentials of importing libraries, configuring your workspace, and establishing the groundwork for seamless development.</p><pre><br>import cv2 #import computer vision lib<br>import numpy as np #import numpy as np<br>import torch #import pytorch<br>import matplotlib.pyplot as plt<br>import os #importing operating system , this module provides a way to interact with operating system including accesssing env var and changing the working directory<br>HOME = os.getcwd()  #get the current work directory using the getcwd(), and assign it to home var<br>print(&quot;HOME:&quot;, HOME)<br>%cd {HOME}. #this line changes the current working directory to the value of the HOME<br><br><br>using_colab = True<br>if using_colab:<br>    import torch<br>    import torchvision<br>    print(&quot;PyTorch version:&quot;, torch.__version__)<br>    print(&quot;Torchvision version:&quot;, torchvision.__version__)<br>    print(&quot;CUDA is available:&quot;, torch.cuda.is_available())<br>    import sys<br>    !{sys.executable} -m pip install opencv-python matplotlib onnx onnxruntime<br>    !{sys.executable} -m pip install &#39;git+https://github.com/facebookresearch/segment-anything.git&#39;<br><br>    !mkdir images<br>    !wget -P images https://raw.githubusercontent.com/facebookresearch/segment-anything/main/notebooks/images/truck.jpg<br><br>    !wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth<br><br>from segment_anything import sam_model_registry, SamPredictor<br>from segment_anything.utils.onnx import SamOnnxModel<br>import onnxruntime<br>from onnxruntime.quantization import QuantType<br>from onnxruntime.quantization.quantize import quantize_dynamic</pre><p>-Let’s explore three essential functions designed to breathe life into object segmentation results: show_mask, show_points, and show_box.</p><h4>show_mask: Coloring the Canva</h4><pre>def show_mask(mask, ax):<br>    # Takes a binary mask and an axis object, displaying the mask as an image on the axis.<br>    color = np.array([30/255, 144/255, 255/255, 0.6])<br>    h, w = mask.shape[-2:]# Create a colored mask_image overlay for highlighting regions or objects.<br>    mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)# Display the colored mask_image on the axis.<br>    ax.imshow(mask_image)</pre><ul><li>This function encapsulates the magic of turning a binary mask into a visual masterpiece. The resulting mask_image serves as an overlay, allowing you to spotlight specific areas on an image.</li></ul><h4>show_points: Plotting Stars in the Sky</h4><pre>def show_points(coords, labels, ax, marker_size=375):<br>    # Takes coordinates, labels, and an axis object, plotting points based on their labels.<br>    pos_points = coords[labels == 1]<br>    neg_points = coords[labels == 0]<br><br>    # Plot positive points in green and negative points in red, using stars as markers.<br>    ax.scatter(pos_points[:, 0], pos_points[:, 1], color=&#39;green&#39;, marker=&#39;*&#39;, s=marker_size, edgecolor=&#39;white&#39;, linewidth=1.25)<br>    ax.scatter(neg_points[:, 0], neg_points[:, 1], color=&#39;red&#39;, marker=&#39;*&#39;, s=marker_size, edgecolor=&#39;white&#39;, linewidth=1.25)</pre><p>This function transforms coordinates and labels into a celestial display of stars. Positive points shine in green, negatives twinkle in red, all contributing to the visual narrative.</p><h4><strong>show_box: Framing the Scene</strong></h4><pre>def show_box(box, ax):<br>    # Takes a bounding box and an axis object, displaying the box on the axis.<br>    x0, y0 = box[0], box[1]<br>    w, h = box[2] - box[0], box[3] - box[1]<br><br>    # Add a transparent rectangle to represent the bounding box.<br>    ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor=&#39;green&#39;, facecolor=(0, 0, 0, 0), lw=1))</pre><p>Here, the function paints a transparent rectangle on the canvas, framing the specified region with a touch of green.</p><h4><strong>Setting the Stage with a Pre-Trained ViT-H Model</strong></h4><pre>checkpoint = &quot;/content/sam_vit_h_4b8939.pth&quot;<br>model_type = &quot;vit_h&quot;<br><br># Checkpoint contains the path to a pre-trained ViT-H model.<br># Let&#39;s initialize our SAM model using the specified checkpoint and model type.<br>sam = sam_model_registry[model_type](checkpoint=checkpoint)</pre><p>Here, the checkpoint variable serves as our ticket to a pre-trained ViT-H model. SAM&#39;s model registry effortlessly maps the model type to its corresponding class.</p><h4><strong>SAM Model Instance</strong></h4><pre># Now, we create an instance of the SAM model using the initialized parameters.<br>predictor = SamPredictor(sam)<br></pre><h4>From SAM to ONNX: A Journey of Model Export and Quantization</h4><p>We navigate through the intricacies of exporting a Segment Anything Model (SAM) to the Open Neural Network Exchange (ONNX) format, followed by the transformative process of quantization.</p><h4><strong>Exporting SAM to ONNX</strong></h4><pre>onnx_model_path = &quot;sam_onnx_example.onnx&quot;<br>onnx_model = SamOnnxModel(sam, return_single_mask=True)<br><br># Defining dynamic axes for variable-length input data<br>dynamic_axes = {<br>    &quot;point_coords&quot;: {1: &quot;num_points&quot;},<br>    &quot;point_labels&quot;: {1: &quot;num_points&quot;},<br>}<br><br># Preparing dummy inputs for export<br>dummy_inputs = {<br>    &quot;image_embeddings&quot;: torch.randn(1, embed_dim, *embed_size, dtype=torch.float),<br>    &quot;point_coords&quot;: torch.randint(low=0, high=1024, size=(1, 5, 2), dtype=torch.float),<br>    &quot;point_labels&quot;: torch.randint(low=0, high=4, size=(1, 5), dtype=torch.float),<br>    &quot;mask_input&quot;: torch.randn(1, 1, *mask_input_size, dtype=torch.float),<br>    &quot;has_mask_input&quot;: torch.tensor([1], dtype=torch.float),<br>    &quot;orig_im_size&quot;: torch.tensor([1500, 2250], dtype=torch.float),<br>}<br><br># Specifying output tensor names<br>output_names = [&quot;masks&quot;, &quot;iou_predictions&quot;, &quot;low_res_masks&quot;]<br><br># Exporting the ONNX model<br>with warnings.catch_warnings():<br>    warnings.filterwarnings(&quot;ignore&quot;, category=torch.jit.TracerWarning)<br>    warnings.filterwarnings(&quot;ignore&quot;, category=UserWarning)<br>    with open(onnx_model_path, &quot;wb&quot;) as f:<br>        torch.onnx.export(<br>            onnx_model,<br>            tuple(dummy_inputs.values()),<br>            f,<br>            export_params=True,<br>            verbose=False,<br>            opset_version=17,<br>            do_constant_folding=True,<br>            input_names=list(dummy_inputs.keys()),<br>            output_names=output_names,<br>            dynamic_axes=dynamic_axes,<br>        )<br></pre><h4>Quantizing the ONNX Model</h4><pre>onnx_model_quantized_path = &quot;sam_onnx_quantized_example.onnx&quot;<br><br># Quantizing the ONNX model<br>quantize_dynamic(<br>    model_input=onnx_model_path,<br>    model_output=onnx_model_quantized_path,<br>    optimize_model=True,<br>    per_channel=False,<br>    reduce_range=False,<br>    weight_type=QuantType.QUInt8,<br>)<br><br>onnx_model_path = onnx_model_quantized_path</pre><p>Quantizing is performed to enhance its inference speed and reduce memory footprint. The resulting quantized ONNX model is now equipped for deployment in resource-constrained environments.</p><h4>Uploading image</h4><pre><br>image = cv2.imread(&#39;/content/230121121737-01-nfl-playoffs-preview.jpg&#39;)<br>image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)<br>plt.figure(figsize=(10,10))<br>plt.imshow(image)<br>plt.axis(&#39;on&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c8I8sx8sIRa-RYGFKNlQQw.png" /></figure><pre><br>#creating an ONNX runtime session using the onnxruntime.InferenceSession() func and loads the ONNX model using the sam model<br>ort_session = onnxruntime.InferenceSession(onnx_model_path)<br><br><br>sam.to(device=&#39;cuda&#39;)<br>predictor = SamPredictor(sam)#this creates a SamPredictor object using the sam model<br>predictor.set_image(image)#set image() method of SamPredictor object is used to set the image<br>image_embedding = predictor.get_image_embedding().cpu().numpy()# get_image_embedding() method of SamPredictor object is used to get the image embedding , the cpu() method is used to move the tensor to cpu ,and the numpy() method is used to convert the tensor to a nnumpy array<br>image_embedding.shape</pre><h4>Selecting a single mask</h4><pre><br>input_point = np.array([[1648,640]]) #var which is a numpy array with shape(1,2) that contains x,y coordinates of a point<br>input_label = np.array([1])# this var is a numpy array with shape(1,) that contains the label of the point<br><br>#Add a batch index, concatenate a padding point, and transform.<br>#this lines add batch index to the point coordinates and labels , concatenate a padding point with label -1 and transform the point coordinates using the predictor.transform.apply_coord() method<br>#onnx_coord and onnx_label are created by adding a batch index to the point coordinates and labels , and concatenate a padding point with label -1 .<br>#the batch index is added by introducing a new axis  using none . this is done because DL model usually process daa in batches so even if there&#39;s only one point , it needs to be in the shape of a batch<br>onnx_coord = np.concatenate([input_point, np.array([[0.0, 0.0]])], axis=0)[None, :, :]<br>onnx_label = np.concatenate([input_label, np.array([-1])], axis=0)[None, :].astype(np.float32)<br>#the coordinates are then transformed using predictor.transform.apply_coords methid , this is a normalization or scaling operation to ensure the coordinates are in a suitable range for the model<br>onnx_coord = predictor.transform.apply_coords(onnx_coord, image.shape[:2]).astype(np.float32)<br><br>#Create an empty mask input and an indicator for no mask.<br><br>onnx_mask_input = np.zeros((1, 1, 256, 256), dtype=np.float32)<br>onnx_has_mask_input = np.zeros(1, dtype=np.float32)<br>#Package the inputs to run in the onnx model<br><br>ort_inputs = {<br>    &quot;image_embeddings&quot;: image_embedding,<br>    &quot;point_coords&quot;: onnx_coord,<br>    &quot;point_labels&quot;: onnx_label,<br>    &quot;mask_input&quot;: onnx_mask_input,<br>    &quot;has_mask_input&quot;: onnx_has_mask_input,<br>    &quot;orig_im_size&quot;: np.array(image.shape[:2], dtype=np.float32)<br>}<br><br>#Predict a mask and threshold it.<br><br>masks, _, low_res_logits = ort_session.run(None, ort_inputs)<br>masks = masks &gt; predictor.model.mask_threshold<br>print(masks.shape)<br>plt.figure(figsize=(10,10))<br>plt.imshow(image)<br>show_mask(masks, plt.gca())<br>show_points(input_point, input_label, plt.gca())<br>plt.axis(&#39;on&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FNRcFqmN-ewyFqiRvnaExA.png" /></figure><h4>Selecting multiple mask</h4><pre><br>#Example mask input<br>input_point = np.array([[1648,640],[1609,931]])<br>input_label = np.array([1,1])<br><br># Use the mask output from the previous run. It is already in the correct form for input to the ONNX model.<br>onnx_mask_input = low_res_logits<br>#Transform the points as in the previous example.<br><br>onnx_coord = np.concatenate([input_point, np.array([[0.0, 0.0]])], axis=0)[None, :, :]<br>onnx_label = np.concatenate([input_label, np.array([-1])], axis=0)[None, :].astype(np.float32)<br><br>onnx_coord = predictor.transform.apply_coords(onnx_coord, image.shape[:2]).astype(np.float32)<br>#The has_mask_input indicator is now 1.<br><br>onnx_has_mask_input = np.ones(1, dtype=np.float32)<br>#Package inputs, then predict and threshold the mask.<br><br>ort_inputs = {<br>    &quot;image_embeddings&quot;: image_embedding,<br>    &quot;point_coords&quot;: onnx_coord,<br>    &quot;point_labels&quot;: onnx_label,<br>    &quot;mask_input&quot;: onnx_mask_input,<br>    &quot;has_mask_input&quot;: onnx_has_mask_input,<br>    &quot;orig_im_size&quot;: np.array(image.shape[:2], dtype=np.float32)<br>}<br><br>masks, _, _ = ort_session.run(None, ort_inputs)<br>masks = masks &gt; predictor.model.mask_threshold<br>plt.figure(figsize=(10,10))<br>plt.imshow(image)<br>show_mask(masks, plt.gca())<br>show_points(input_point, input_label, plt.gca())<br>plt.axis(&#39;off&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UK-6RdxonnYnYCIc_PJ7A.png" /></figure><pre>#To exclude the helmet and specify just the face , a background point (with label 0, here shown in red) can be supplied.<br><br>input_point = np.array([[1707, 312], [1711, 206]])<br>input_label = np.array([1, 0])<br><br>mask_input = logits[np.argmax(scores), :, :]  # Choose the model&#39;s best mask<br>masks, _, _ = predictor.predict(<br>    point_coords=input_point,<br>    point_labels=input_label,<br>    mask_input=mask_input[None, :, :],<br>    multimask_output=False,<br>)<br>plt.figure(figsize=(10, 10))<br>plt.imshow(image)<br>show_mask(masks, plt.gca())<br>show_points(input_point, input_label, plt.gca())<br>plt.axis(&#39;off&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AzpZLHDJ5EuYvUpwP6VlHw.png" /></figure><h4>Selecting object with box</h4><pre>#Specifying a specific object with a box<br>input_box = np.array([1302,178,1961,1631])<br>masks, _, _ = predictor.predict(<br>    point_coords=None,<br>    point_labels=None,<br>    box=input_box[None, :],<br>    multimask_output=False,<br>)<br>plt.figure(figsize=(10, 10))<br>plt.imshow(image)<br>show_mask(masks[0], plt.gca())<br>show_box(input_box, plt.gca())<br>plt.axis(&#39;off&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4VqslDuapgDSNKOVGiA3g.png" /></figure><h4>Selecting object with box and point</h4><pre>#Combining points and boxes<br>input_box = np.array([1302,178,1961,1631])<br>input_point = np.array([[1648,640],[1609,931]])<br>input_label = np.array([1,1])<br>masks, _, _ = predictor.predict(<br>    point_coords=input_point,<br>    point_labels=input_label,<br>    box=input_box,<br>    multimask_output=False,<br>)<br>plt.figure(figsize=(10, 10))<br>plt.imshow(image)<br>show_mask(masks[0], plt.gca())<br>show_box(input_box, plt.gca())<br>show_points(input_point, input_label, plt.gca())<br>plt.axis(&#39;on&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B75p5OVjPC3YSSnKIG-DdA.png" /></figure><h4>Selecting multiple objects with box</h4><pre><br>#Batched prompt inputs<br>input_boxes = torch.tensor([<br>    [1334, 171, 1919, 1618],<br>    [1103,790,1174,854],<br>    [1992,778,2835,1687,],<br>    [689,1536,871,1659],<br>], device=predictor.device)<br><br><br>transformed_boxes = predictor.transform.apply_boxes_torch(input_boxes, image.shape[:2])<br>masks, _, _ = predictor.predict_torch(<br>    point_coords=None,<br>    point_labels=None,<br>    boxes=transformed_boxes,<br>    multimask_output=False,<br>)<br>masks.shape  # (batch_size) x (num_predicted_masks_per_input) x H x W<br><br><br>plt.figure(figsize=(10, 10))<br>plt.imshow(image)<br>for mask in masks:<br>    show_mask(mask.cpu().numpy(), plt.gca())<br>for box in input_boxes:<br>    show_box(box.cpu().numpy(), plt.gca())<br>plt.axis(&#39;off&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j45P3a27wy4GLDOlnVE4IQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3820cd47ba27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling the Power of Attention Mechanism Using Numpy: A Dive into Selective Focus in Neural…]]></title>
            <link>https://shankar138089.medium.com/unveiling-the-power-of-attention-mechanism-using-numpy-a-dive-into-selective-focus-in-neural-00dc297f487f?source=rss-bb0b1b36776d------2</link>
            <guid isPermaLink="false">https://medium.com/p/00dc297f487f</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[transformer-model]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shankar Sharma]]></dc:creator>
            <pubDate>Sun, 12 Nov 2023 13:52:20 GMT</pubDate>
            <atom:updated>2023-11-12T13:52:20.883Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unveiling the Power of Attention Mechanism Using Numpy: A Dive into Selective Focus in Neural Networks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mWmqsD6PrgD62hZjCVjDsg.jpeg" /></figure><p>In the realm of neural networks, the attention mechanism stands as a formidable tool, enabling models to selectively focus on specific elements of input data when making predictions. Drawing inspiration from human attention, which instinctively fixates on certain aspects when presented with multiple stimuli, attention mechanisms have found profound applications in natural language processing tasks such as machine translation, text classification, and question answering.</p><p><strong>Understanding Attention Mechanism: A Spotlight on Neural Networks</strong></p><p>At its core, attention models leverage a function that maps a query and a set of key-value pairs to generate a nuanced output. These elements, including the query, keys, values, and the final output, are all represented as vectors. The magic happens as the model calculates the output by taking a weighted sum of the values. The weights are determined by a compatibility function, evaluating the similarity between the query and the corresponding key.</p><p><strong>Analogous to Human Perception: “High-Resolution” and “Low-Resolution” Understanding</strong></p><p>To grasp the essence of attention mechanisms, envision a person viewing a complex scene. Their eyes fixate intensely on a specific point, akin to a “high-resolution” understanding of that focal area, while the surrounding regions are perceived with less detail — a form of “low-resolution” understanding. As the neural network gains a more profound comprehension of the input data, it dynamically adjusts its focal point, mirroring the adaptability of human attention.</p><p><strong>Coding the Attention Mechanism with Numpy: A Practical Example</strong></p><p>Let’s dive into a hands-on example using Python and the powerful Numpy library to implement an attention mechanism. In this scenario, we’ll use a simple sentence, “I miss the old Kanye,” and represent each word with randomly generated word embeddings.</p><pre>import numpy as np<br><br># Define the sentence<br>sentence = &quot;i miss the old kanye&quot;<br><br># Define the vocabulary<br>vocabulary = set(sentence.split())<br><br># Define the word embeddings<br>word_embeddings = {}<br>for word in vocabulary:<br>    word_embeddings[word] = np.random.rand(3)  # Generate random embeddings<br><br># Encode the sentence as a sequence of word embeddings<br>encoded_sentence = [word_embeddings[word] for word in sentence.split()]<br><br># Assign the encoded sentence to variables<br>i = encoded_sentence[0]<br>miss = encoded_sentence[1]<br>the = encoded_sentence[2]<br>old = encoded_sentence[3]<br>kanye = encoded_sentence[4]<br><br># Print the variables<br>print(&#39;Creating word embedding&#39;)<br>print(f&quot;i: {i}&quot;)<br>print(f&quot;miss: {miss}&quot;)<br>print(f&quot;the: {the}&quot;)<br>print(f&quot;old: {old}&quot;)<br>print(f&quot;kanye: {kanye}&quot;)<br><br># word embeddings.<br>words = np.array([i , miss , the , old , kanye])<br><br>#Next, we generate the weight matrices that will be multiplied with the word embeddings to obtain the queries, keys, and values. For this example, we randomly generate these weight matrices, but in real scenarios, they would be learned during training.<br>np.random.seed(42) <br>W_Query = np.random.randint(3, size=(3, 3))<br>W_Key = np.random.randint(3, size=(3, 3))<br>W_Value = np.random.randint(3, size=(3, 3))<br><br># Generating the queries, keys, and values.<br>Q = np.dot(words, W_Query)<br>K = np.dot(words, W_Key)<br>V = np.dot(words, W_Value)<br><br># Scoring vector query.<br>scores = np.dot(Q, K.T)<br><br># Computing the weights by applying a softmax operation.<br>weights = softmax(scores / np.sqrt(K.shape[1]), axis=1)<br><br># Computing the attention by calculating the weighted sum of the value vectors.<br>attention = np.dot(weights, V)<br>print(&quot;Attention&quot;)<br>print(attention)<br><br>#output<br>Creating word embedding<br>i: [0.46676289 0.85994041 0.68030754]<br>miss: [0.52477466 0.39986097 0.04666566]<br>the: [0.45049925 0.01326496 0.94220176]<br>old: [0.97375552 0.23277134 0.09060643]<br>kanye: [0.61838601 0.38246199 0.98323089]<br>Attention<br>[[0.81676354 1.14873475 0.33197121]<br> [0.71861207 1.07919157 0.3605795 ]<br> [0.74203343 1.13656778 0.39453435]<br> [0.75607715 1.11278575 0.3567086 ]<br> [0.79709991 1.15043165 0.35333174]]</pre><p>In this code snippet, we define the sentence, create word embeddings, and generate weight matrices for queries, keys, and values. We then compute attention by applying a softmax operation to scores obtained from the compatibility function.</p><p><strong>Results and Insights: Unveiling the Attention</strong></p><p>The output of our attention mechanism reveals the weighted sum of the value vectors, showcasing how the model focuses on different parts of the input sentence. This hands-on implementation provides a tangible understanding of the inner workings of attention mechanisms in neural networks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00dc297f487f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>