<?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 Surabhi on Medium]]></title>
        <description><![CDATA[Stories by Surabhi on Medium]]></description>
        <link>https://medium.com/@surbhi.8?source=rss-adbb58d30b57------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aOH6x3-1UN4Z29X-TqUGHw.jpeg</url>
            <title>Stories by Surabhi on Medium</title>
            <link>https://medium.com/@surbhi.8?source=rss-adbb58d30b57------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:19:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@surbhi.8/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[Simplicity of defaultdict in python]]></title>
            <link>https://medium.com/@surbhi.8/simplicity-of-defaultdict-in-python-44c665c51320?source=rss-adbb58d30b57------2</link>
            <guid isPermaLink="false">https://medium.com/p/44c665c51320</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dictionary]]></category>
            <dc:creator><![CDATA[Surabhi]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 05:41:40 GMT</pubDate>
            <atom:updated>2024-09-04T05:41:40.772Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*RoaXcnKuw_491GR71LZyBA.png" /></figure><p><strong>defaultdict </strong>is a container datatype belonging to collections in python.</p><p>so what is different in defaultdict from dict?</p><p>A defaultdict functions just like a standard dict, but with one key difference: it’s initialized with a function (i.e.defaultdict(int/list)) that provides a default value for any missing keys. This means that a defaultdict will never raise a KeyError when you try to access a key that doesn&#39;t exist.</p><p><em>class </em>collections.<strong>defaultdict</strong>(<em>default_factory=None</em>, <em>/</em>[, <em>…</em>])</p><p>Return a new dictionary-like object. <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict">defaultdict</a> is a subclass of the built-in <a href="https://docs.python.org/3/library/stdtypes.html#dict">dict</a> class. It overrides one method and adds one writable instance variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*ipYhMqt5_TAWM_FxjsMkvA.png" /><figcaption>fig 1:defaultdict vs dict</figcaption></figure><p><strong>use cases:</strong></p><p>1.In frequency based problems</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*uqOUWNcZZelXgqCwrqim1w.png" /></figure><p>defaultdict is intialized by default value 0 and for each value which is found in “hello world” are counted and assigned to a dictionary.</p><p>2. Value based grouping:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*H2cCle95iYoe60VHKWDGsA.png" /><figcaption>fig 2: value based grouping</figcaption></figure><p>3. In nested list based problems:</p><p>i.e anagrams grouping</p><p>Input: strs = [“act”,”pots”,”tops”,”cat”,”stop”,”hat”]</p><p>Output: [[“hat”],[“act”, “cat”],[“stop”, “pots”, “tops”]]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*Ospfq0T5YBx4Ry-CiZptrg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44c665c51320" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semantic search and Language Modeling]]></title>
            <link>https://medium.com/@surbhi.8/semantic-search-and-language-modeling-76fbac7b37bd?source=rss-adbb58d30b57------2</link>
            <guid isPermaLink="false">https://medium.com/p/76fbac7b37bd</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[retrieval]]></category>
            <category><![CDATA[reranking]]></category>
            <dc:creator><![CDATA[Surabhi]]></dc:creator>
            <pubDate>Tue, 16 Jul 2024 14:04:15 GMT</pubDate>
            <atom:updated>2024-07-16T14:04:15.109Z</atom:updated>
            <content:encoded><![CDATA[<p>The evolution of large language models marks a pivotal advancement in the realm of Natural Language Processing (NLP), underscoring a convergence of critical factors and groundbreaking innovations that have reshaped modern AI.</p><p>Semantic search leverages advanced natural language processing techniques to understand the meaning behind queries and documents, enabling more precise retrieval of information based on semantic relevance rather than just keyword matching.</p><p>Language modeling, on the other hand, involves training models to predict and generate human-like text, incorporating contextual understanding to enhance tasks such as semantic search by improving query understanding and document relevance assessment. Together, these advancements are revolutionizing information retrieval by making it more intuitive and effective in understanding and responding to human language queries.</p><h3>Early Foundations:</h3><ol><li><strong>Statistical NLP (1990s-2000s):</strong></li></ol><ul><li>Early approaches in NLP relied on statistical methods and machine learning techniques applied to large text corpora.</li><li>Techniques such as n-grams, Hidden Markov Models (HMMs), and probabilistic context-free grammars (PCFGs) were foundational in tasks like speech recognition, machine translation, and information retrieval</li></ul><h3>Emergence of Large Language Models:</h3><p><strong>1.Deep Learning Revolution (2010s):</strong></p><p>The resurgence of neural networks and the development of deep learning architectures led to significant breakthroughs in NLP.</p><p><strong>Word Embeddings:</strong> Models like Word2Vec and GloVe introduced distributed representations of words, capturing semantic relationships.</p><p><strong>Sequence Models:</strong> Recurrent Neural Networks (RNNs) and later Long Short-Term Memory networks (LSTMs) enabled better handling of sequential data, crucial for tasks like language modeling and machine translation.</p><p><strong>2.Transformer Architecture (2017):</strong></p><ul><li>The introduction of the Transformer architecture, proposed in the paper “Attention is All You Need” by Vaswani et al. (2017), marked a paradigm shift in NLP.</li><li>Transformers replaced RNNs with attention mechanisms, allowing models to capture long-range dependencies more effectively and in parallel.</li><li>Transformers enabled significant improvements in tasks such as machine translation (e.g., Google’s Transformer-based model) and language understanding.</li></ul><p><strong>Rise of Large language Models:</strong></p><ol><li><strong>BERT (Bidirectional Encoder Representations from Transformers, 2018)</strong>:</li></ol><ul><li>BERT, introduced by Google in 2018, demonstrated the power of large-scale pre-training and transfer learning in NLP.</li><li>BERT was pre-trained on vast amounts of text data using unsupervised learning, enabling it to capture deep contextual representations of language.</li><li>Fine-tuning BERT on specific tasks showed remarkable performance improvements across a wide range of NLP benchmarks, including question answering, sentiment analysis, and more.</li></ul><p><strong>2. GPT Series (Generative Pre-trained Transformers, 2018–Present):</strong></p><ul><li>OpenAI’s GPT series (GPT-1, GPT-2, GPT-3,GPT-4) further pushed the boundaries of language modeling and generation.</li><li>These models were trained on even larger datasets and demonstrated capabilities in generating human-like text, answering questions, and performing various language tasks without task-specific fine-tuning.</li></ul><p>3.<strong>DALL·E (2021):</strong></p><ul><li>DALL·E, also developed by OpenAI, extends the capabilities of large language models to generate images from textual descriptions.</li><li>It uses a variant of the GPT architecture trained on a dataset of text-image pairs to generate high-quality images based on specific prompts or descriptions.</li><li>DALL·E showcases the potential of integrating language and vision modalities, opening new avenues for creative AI applications.</li></ul><p>4.<strong>LLama (Large Language Model Metalearning,2023):</strong></p><ul><li>LLama is an initiative by Salesforce Research aimed at advancing large-scale language modeling.</li><li>It focuses on meta-learning techniques to improve the performance and efficiency of large language models across diverse NLP tasks.</li><li>LLama contributes to the development of more robust and adaptable language models that can generalize well to new tasks and domains.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*cdjX9go5prZ38zOm.png" /><figcaption>Figure 1:Evolution of LLM</figcaption></figure><p><strong>Semantic Search:</strong></p><p>Semantic search is a technique used in information retrieval (IR) and natural language processing (NLP) to improve the accuracy of search engines by understanding the intent and context of the user’s query rather than just matching keywords.</p><p>Semantic search based LLM Systems:</p><h3>Dense Retrieval:</h3><p><strong>Dense retrieval</strong> refers to a retrieval method in information retrieval (IR) where both queries and documents are embedded into dense vector spaces.</p><p><strong>Techniques:</strong></p><ul><li><strong>Embeddings:</strong> Both queries and documents are represented as dense embeddings (vectors) using techniques like Word2Vec, GloVe, or more advanced models like BERT embeddings.</li><li><strong>Similarity Measures:</strong> Retrieval is based on similarity measures such as cosine similarity or dot product in the dense vector space, where higher similarity scores indicate better matches between queries and documents.</li></ul><h3>Reranking:</h3><p><strong>Reranking</strong> refers to the process of reordering a ranked list of search results to improve their relevance or alignment with specific criteria, typically after an initial retrieval stage. Rerankers are different from dense retrieval where they take an additional input, a set of search results from a previous step in the search pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*L6VUMJDqNeAVaQLcTZT-oA.png" /><figcaption>Figure 2: Rerankers (<a href="https://cohere.com/blog/rerank">https://cohere.com/blog/rerank</a>)</figcaption></figure><h3>Generative Search:</h3><p><strong>Generative search</strong> refers to a type of search method where the system generates new content based on user queries or preferences, rather than retrieving and ranking existing documents or information. This approach is often associated with AI-powered systems that can generate text, images, or other media in response to user input. i.e generative LLM</p><p>Generative LLM produces a lot of <strong>hallucination</strong> sometimes , generating coherent texts but not actual facts.</p><p>In summary, while <strong>dense retrieval</strong> enhances search efficiency and relevance through dense vector representations, <strong>reranking</strong> optimizes the order of search results based on user criteria or feedback. <strong>Generative search</strong>, on the other hand, involves generating new content based on user queries or preferences, offering personalized and contextually relevant information.</p><pre>from transformers import BertTokenizer, BertModel<br>from sklearn.metrics.pairwise import cosine_similarity<br>import torch<br>import numpy as np<br><br># Example document collection (can be replaced with actual API call)<br>documents = [<br>    &quot;Albert Einstein was a German-born theoretical physicist who developed the theory of relativity.&quot;,<br>    &quot;Marie Curie was a physicist and chemist who conducted pioneering research on radioactivity.&quot;,<br>    &quot;Isaac Newton was an English mathematician, physicist, astronomer, and author who is widely recognized as one of the greatest mathematicians and most influential scientists of all time.&quot;,<br>    &quot;Charles Darwin was an English naturalist, geologist, and biologist, best known for his contributions to the science of evolution.&quot;,<br>    &quot;Ada Lovelace was an English mathematician and writer, chiefly known for her work on Charles Babbage&#39;s early mechanical general-purpose computer, the Analytical Engine.&quot;,<br>]<br><br># Initialize BERT tokenizer and model<br>tokenizer = BertTokenizer.from_pretrained(&#39;bert-base-uncased&#39;)<br>model = BertModel.from_pretrained(&#39;bert-base-uncased&#39;)<br><br># Function for dense retrieval (simulated with a list)<br>def dense_retrieval(query):<br>    key_terms = [&quot;physics&quot;, &quot;physicist&quot;, &quot;contributions&quot;, &quot;theory&quot;]  # Key terms related to the query<br>    retrieved_documents = []<br>    for doc in documents:<br>        if any(term in doc.lower() for term in key_terms):<br>            retrieved_documents.append(doc)<br>    return retrieved_documents<br><br># Function for reranking based on BERT embeddings and cosine similarity<br>def rerank_documents(query, retrieved_documents):<br>    # Encode query into BERT embedding<br>    query_embedding = encode_text(query)<br>    <br>    # Encode all retrieved documents into BERT embeddings<br>    document_embeddings = []<br>    for doc in retrieved_documents:<br>        doc_embedding = encode_text(doc)<br>        document_embeddings.append(doc_embedding)<br>    <br>    # Convert to numpy array for cosine similarity calculation<br>    document_embeddings = np.array(document_embeddings)<br>    <br>    # Compute cosine similarity between query embedding and document embeddings<br>    similarities = cosine_similarity(query_embedding.reshape(1, -1), document_embeddings)[0]<br>    <br>    # Rerank documents based on cosine similarity scores<br>    reranked_indices = np.argsort(similarities)[::-1]  # Indices sorted by descending similarity scores<br>    reranked_documents = [retrieved_documents[i] for i in reranked_indices]<br>    reranked_scores = similarities[reranked_indices]<br>    <br>    return reranked_documents, reranked_scores<br><br># Function to encode text into BERT embeddings<br>def encode_text(text):<br>    input_ids = tokenizer.encode(text, add_special_tokens=True, return_tensors=&#39;pt&#39;)<br>    with torch.no_grad():<br>        outputs = model(input_ids)<br>        last_hidden_states = outputs.last_hidden_state<br>        # Average pooling over tokens to get a single vector representation<br>        pooled = torch.mean(last_hidden_states, dim=1).squeeze()<br>    return pooled.numpy()<br><br># Example query<br>query = &quot;who was physicist?&quot;<br><br># Perform dense retrieval<br>retrieved_documents = dense_retrieval(query)<br><br># Check if documents were retrieved<br>if retrieved_documents:<br>    print(f&quot;Dense Retrieved Documents for query: &#39;{query}&#39;:&quot;)<br>    for idx, doc in enumerate(retrieved_documents, 1):<br>        print(f&quot;Dense Rank {idx}:&quot;)<br>        print(f&quot;Document: {doc}&quot;)<br>        print(&quot;------------------------&quot;)<br><br>    # Rerank retrieved documents based on BERT embeddings and cosine similarity<br>    reranked_documents, reranked_scores = rerank_documents(query, retrieved_documents)<br><br>    # Print reranked results<br>    print(&quot;\nReranked Documents:&quot;)<br>    for rank, (doc, score) in enumerate(zip(reranked_documents, reranked_scores), 1):<br>        print(f&quot;Reranked Rank {rank}:&quot;)<br>        print(f&quot;Document: {doc}&quot;)<br>        print(f&quot;Cosine Similarity Score: {score:.4f}&quot;)<br>        print(&quot;------------------------&quot;)<br>else:<br>    print(f&quot;No documents matched the query: &#39;{query}&#39; using dense retrieval.&quot;)<br></pre><figure><img alt="Figure 3: dense and reranking retrieval" src="https://cdn-images-1.medium.com/max/1024/1*bSXayjQsnR_41UdZ5Xo9Hw.png" /></figure><p><strong>API’s used for Dense and Reranking retrieval:</strong></p><p><strong>Hugging Face Transformers API</strong>:</p><ul><li>Hugging Face provides a powerful API for accessing a wide range of pre-trained language models, including BERT, RoBERTa, and more. You can use this API to encode text into embeddings and perform similarity search.</li></ul><p><a href="https://huggingface.co/">Hugging Face API</a></p><p><strong>Cohere API</strong>:</p><ul><li>Cohere offers an API that supports dense retrieval and similarity search using large-scale language models. It allows you to retrieve documents based on queries and also supports fine-tuning models for custom tasks.</li></ul><p><a href="https://cohere.ai/">Cohere API</a></p><p><strong>OpenAI API</strong>:</p><ul><li>OpenAI provides an API that includes access to their GPT models, which can be used for text generation, summarization, and retrieval tasks. While primarily known for generative tasks, their models can also be used for retrieval tasks.</li></ul><p><a href="https://beta.openai.com/">OpenAI API</a></p><p><strong>Elasticsearch with Dense Vector Plugin</strong>:</p><ul><li>Elasticsearch is a popular open-source search engine that supports dense vector indexing and searching through plugins like elasticsearch-vector-scoring. This allows you to index embeddings directly and perform efficient similarity search.</li></ul><p><a href="https://www.elastic.co/">Elasticsearch</a></p><p><strong>ANN-Benchmarks</strong>:</p><ul><li>ANN-Benchmarks is not an API itself but a collection of benchmarks and implementations for approximate nearest neighbor (ANN) search algorithms. It includes implementations that are compatible with embedding-based retrieval tasks.</li></ul><p><a href="https://github.com/erikbern/ann-benchmarks">ANN-Benchmarks</a></p><p><strong>Faiss</strong>:</p><ul><li>Facebook AI Similarity Search (Faiss) is a library for efficient similarity search and clustering of dense vectors. It’s highly optimized for GPU-based indexing and searching of large-scale embeddings.</li></ul><p><em>GitHub</em>: <a href="https://github.com/facebookresearch/faiss">Faiss</a></p><p><strong>Elasticsearch with Learning to Rank Plugin</strong>:</p><ul><li>Elasticsearch, when combined with plugins like the Learning to Rank plugin, allows for the integration of machine learning models to rerank search results based on various features. This can include relevance scores derived from models trained on user feedback.</li></ul><p><a href="https://www.elastic.co/">Elasticsearch Learning to Rank</a></p><p><strong>BERT and Similarity Search APIs</strong>:</p><ul><li>APIs that provide access to BERT and similar models (e.g., sentence-transformers) can be used for reranking by computing semantic similarity scores between query embeddings and retrieved document embeddings.</li><li><a href="https://www.sbert.net/">Sentence Transformers</a></li><li><a href="https://github.com/hanxiao/bert-as-service">BERT-as-a-Service</a></li></ul><p>These retrieval models are implemented in RAG(Retrieval Augmented Generation)</p><h3><strong>Metrics:</strong></h3><h4>Mean Average Precision (MAP)</h4><p>MAP is a measure of the average precision values for a set of queries or information retrieval tasks. It evaluates how well a ranking algorithm orders relevant items (documents, web pages, etc.) compared to non-relevant ones.</p><p>Useful in web search engines where users expect a mix of relevant and irrelevant results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*pvREDGYw--aM-Jm2a3xLmw.png" /><figcaption>Figure 3 : Calculating MAP</figcaption></figure><h4>Mean Reciprocal Rank (MRR)</h4><p>MRR is another evaluation metric that focuses on the rank of the first relevant document retrieved. It measures the effectiveness of ranking algorithms by considering the position of the highest-ranked relevant document.</p><p>Commonly used in question answering systems, where finding the most relevant answer quickly is crucial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*qlhOSACC5Hn4aJTUzKQ2cA.png" /><figcaption>Figure 4:Calculating MRR</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76fbac7b37bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>