<?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 Vivekschaurasia on Medium]]></title>
        <description><![CDATA[Stories by Vivekschaurasia on Medium]]></description>
        <link>https://medium.com/@vivekschaurasia?source=rss-3bdb1be656cb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JNNJMHP00kEEZm5G</url>
            <title>Stories by Vivekschaurasia on Medium</title>
            <link>https://medium.com/@vivekschaurasia?source=rss-3bdb1be656cb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:44:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vivekschaurasia/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[Github2Blog: Automating Blog Generation from GitHub Repos Using LangGraph, LangChain, and OpenAI]]></title>
            <link>https://medium.com/@vivekschaurasia/github2blog-automating-blog-generation-from-github-repos-using-langgraph-langchain-and-openai-169d69ff9fe2?source=rss-3bdb1be656cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/169d69ff9fe2</guid>
            <dc:creator><![CDATA[Vivekschaurasia]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 18:02:23 GMT</pubDate>
            <atom:updated>2025-04-22T18:02:23.686Z</atom:updated>
            <content:encoded><![CDATA[<p>How I built a fully automated pipeline to convert GitHub repositories into structured and insightful blog posts using cutting-edge LLM frameworks.</p><p>This blog is manually written to explain the Github2Blog project, as the AI system requires a refined prompt for generating high-quality overview blogs. However, the blog post linked below is an example of what Github2Blog can produce:<br>(<a href="https://dev.to/vivek_chaurasia_5e4b55e7f/exploring-a-python-project-on-github-3n9n">https://dev.to/vivek_chaurasia_5e4b55e7f/exploring-a-python-project-on-github-3n9n</a>)</p><h3><strong>Motivation</strong></h3><p>Maintaining technical documentation and writing blogs about our open-source contributions is incredibly valuable , both for community engagement and personal branding. But let’s face it: most developers are too busy building cool things to sit down and write about them.</p><p>So I asked myself: <em>Can a machine do it for me?</em></p><p>That’s how <strong>Github2Blog</strong> was born, a fully automated system that:</p><ul><li>Fetches code and metadata from any public GitHub repo,</li><li>Summarizes its key components using LLMs,</li><li>Generates a well-structured blog post,</li><li>Publishes it directly to <a href="https://dev.to/">Dev.to</a> .</li></ul><p>All in a single command.</p><h3>Architecture and Workflow</h3><p>Here’s a high-level breakdown of the system architecture:</p><pre>┌────────────┐<br>│ Orchestrator│<br>└─────┬──────┘<br>      ↓<br>┌─────────────┐<br>│Code Retriever│────────┐<br>└────┬────────┘         │<br>     ↓                  │<br>┌──────────────┐        │<br>│Metadata Parser│────┐  │<br>└────┬──────────┘    │  │<br>     ↓               ↓  ↓<br>┌────────────────────────┐<br>│ Component Summarizer   │<br>└────────────┬───────────┘<br>             ↓<br>     ┌────────────┐<br>     │Blog Generator│<br>     └────┬────────┘<br>          ↓<br>   ┌────────────┐<br>   │ Publisher  │ → Dev.to<br>   └────────────┘</pre><h3>Detailed Workflow</h3><h3>1. State Management with LangGraph</h3><p>LangGraph allows us to define stateful, multi-agent workflows using TypedDict. Our WorkflowState tracks:</p><pre>class WorkflowState(TypedDict):<br>    repo_url: Annotated[str, merge_strings]<br>    file_structure: Annotated[dict, merge_dict]<br>    metadata: Annotated[dict, merge_dict]<br>    transcript: Annotated[str, merge_strings]<br>    blog_content: Annotated[str, merge_strings]<br>    post_url: Annotated[str, merge_strings]</pre><p>Reducers (merge_strings, merge_dict) ensure concurrent branches write to state safely.</p><h3>2. Repo Ingestion: Code Retriever</h3><p>This node uses PyGithub to:</p><ul><li>Parse repo contents,</li><li>Categorize files into: source, docs, config, other,</li><li>Extract and decode content (basic decoding + fallback for binary/invalid files).</li></ul><pre>category = &quot;source&quot; if content.name.endswith(&quot;.py&quot;) else ...</pre><p>This gives us a structured file_structure dictionary with filenames, types, and contents.</p><h3>3. Metadata Parser</h3><p>This node pulls repo-level metadata:</p><pre>metadata = {<br>    &quot;stars&quot;: repo.stargazers_count,<br>    &quot;forks&quot;: repo.forks_count,<br>    &quot;language&quot;: repo.language,<br>    &quot;description&quot;: repo.description,<br>    &quot;last_updated&quot;: repo.updated_at,<br>}</pre><p>This metadata is later used for enriching summaries and forming blog SEO tags.</p><h3>4. Component Summarizer (LLM-Powered)</h3><p>This is where the magic begins. Using PromptTemplate and OpenAI’s GPT, we summarize:</p><ul><li>File content (truncated for token limits),</li><li>Metadata (language, stars, forks, etc.).</li></ul><pre>template=&quot;Summarize the key components of this GitHub repo:\n\nFiles:\n{files}\n\nMetadata:\n{metadata}&quot;</pre><p>The result is a <strong>structured transcript</strong> that outlines:</p><ul><li>Project purpose</li><li>Key scripts or modules</li><li>Configs or workflows</li><li>Any README insights</li></ul><h3>5. Blog Generator (LLM-Powered)</h3><p>We feed the transcript into another prompt asking the LLM to format it into a blog:</p><pre>template=&quot;Create a Dev.to blog post from this transcript...&quot;</pre><p>This output contains:</p><ul><li>Introduction</li><li>Summary of files and code snippets</li><li>Usage examples or commands</li><li>Final thoughts / conclusion</li></ul><p>The final output is a complete blog in <strong>Markdown format</strong>, ready for publishing.</p><h3>Conclusion</h3><p>Github2Blog automates a task that developers often procrastinate — writing blogs about their awesome work. With a mix of LangGraph, LangChain, and OpenAI, this system transforms codebases into blogs that others can read, learn from, and share.</p><h3>Challenges:</h3><p><strong>Binary Files</strong>: Some repositories included non-text files (e.g., images), causing decoding errors. We can add checks to skip such files and log warnings.</p><h3>GitHub Repo</h3><p><a href="https://github.com/vivekschaurasia/Github2blog">https://github.com/vivekschaurasia/Github2blog</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=169d69ff9fe2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-Tuning BERT for Snarky Emails: Passive-Aggressive Rewriting with GPT-2 & LoRA]]></title>
            <link>https://medium.com/@vivekschaurasia/fine-tuning-bert-for-snarky-emails-passive-aggressive-rewriting-with-gpt-2-lora-b62b41359c3d?source=rss-3bdb1be656cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b62b41359c3d</guid>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[llama-3]]></category>
            <dc:creator><![CDATA[Vivekschaurasia]]></dc:creator>
            <pubDate>Sat, 29 Mar 2025 19:14:28 GMT</pubDate>
            <atom:updated>2025-03-29T19:14:28.763Z</atom:updated>
            <content:encoded><![CDATA[<p>As a data scientist passionate about natural language processing (NLP), I’ve been working on a fun yet challenging project: transforming emails into passive-aggressive masterpieces. Imagine getting an email like “Please submit your report by tomorrow” and having an AI rewrite it as “I guess it’d be nice if you could submit your report by tomorrow, if it’s not too much trouble.” This blend of tone detection and creative text generation is the heart of my latest experiment, and I’m excited to share the first milestone — fine-tuning BERT for tone classification — while teasing the next step with LLaMA and LoRA.</p><h3>The Big Picture: Two-Part NLP Pipeline</h3><p>The goal is simple but ambitious: build a system that (1) detects the tone of an email (positive, neutral, or negative) and (2) rewrites it in a passive-aggressive style. Why? Beyond the humor, it’s a practical exercise in combining classification and generation tasks — two pillars of modern NLP. Think of it as a tool for understanding intent and then playfully subverting it, with potential applications in sentiment analysis, automated communication, or even creative writing aids.</p><p>The pipeline splits into:</p><ul><li><strong>Tone Detection</strong>: Classify the email’s tone using a fine-tuned BERT model.</li><li><strong>Rewriting</strong>: Generate a passive-aggressive version using a language model (first GPT-2, soon LLaMA with LoRA).</li></ul><p><strong>Step 1: Fine-Tuning BERT for Tone Detection</strong></p><p>I started with tone detection, leveraging <a href="https://huggingface.co/google-bert/bert-base-uncased"><strong>bert-base-uncased </strong></a>— a lightweight yet powerful model for classification tasks. My dataset, tone_dataset.csv, contains 147 email examples, each with an original_email, a Tone label (positive, neutral, negative), and a pre-written passive-aggressiv rewrite. For this step, I focused on the first two columns to train BERT to predict tone.</p><p>Here’s how it went:</p><ul><li><strong>Data Prep</strong>: Shuffled the dataset, tokenized emails with BERT’s tokenizer (max length 128), and mapped tones to labels (negative: 0, neutral: 1, positive: 2). Split it 80/20 into 117 training and 30 evaluation samples.</li><li><strong>Training</strong>: Fine-tuned BERT for 3 epochs with a batch size of 8, using Hugging Face’s Trainer API. Added custom metrics (accuracy, precision, recall, F1) to track performance.</li><li><strong>Results</strong>: After ~9 minutes on Colab’s GPU, the model hit 93.33% accuracy, 94.36% precision, and 93.42% F1 on the eval set. Training loss dropped from 1.04 to 0.26, and eval loss settled at 0.23 — solid signs of convergence.</li></ul><p>The output? BERT reliably labels emails like “Your absence was noted” as negative or “Thank you for your input” as positive. This lays a robust foundation for the pipeline , knowing the tone helps decide how to twist it later.</p><p><strong>Step 2 Fine-Tuning GPT-2 with LoRA for Rewriting</strong></p><p>Next, I tackled rewriting with GPT-2, pairing original_email with passive-aggressiv as input-output. To keep things efficient, I used LoRA (Low-Rank Adaptation) — a technique that fine-tunes only a small subset of parameters, saving memory and time.</p><p>The process:</p><ul><li><strong>Data</strong>: Same 147 samples, prefixed inputs with “Rewrite this email in a passive-aggressive tone:”.</li><li><strong>Training</strong>: Fine-tuned GPT-2 with LoRA for 3 epochs, batch size 2. Loss dropped from 0.71 to 0.56.</li><li><strong>Output</strong>: It’s a start — e.g., “Please submit your report by tomorrow” becomes “Thank you for maybe submitting your report by tomorrow.” Not snarky enough yet, but promising!</li></ul><p>LoRA made this feasible on modest hardware, adapting GPT-2 without retraining its full 124M parameters.</p><p><strong>Challenges and Insights</strong></p><ul><li><strong>BERT</strong>: The small dataset (147 samples) worked thanks to BERT’s pre-training, but longer emails might need a higher max_length. No separate test set yet — next on my list.</li><li><strong>GPT-2 with LoRA</strong>: The small batch size (2) and dataset limited the passive-aggressive flair. Outputs improved with LoRA vs. full fine-tuning, but there’s room to sharpen the tone — maybe more epochs or data.</li></ul><p><strong>Why This Matters</strong></p><p>This isn’t just about snarky emails (though that’s a perk). Combining BERT’s classification with GPT-2’s generation shows how NLP can layer understanding and creativity. LoRA’s efficiency opens doors for fine-tuning on resource-constrained setups — a game-changer for hobbyists and pros alike.</p><p><strong>What’s Next?</strong></p><p>I’m refining GPT-2’s outputs — tweaking LoRA configs, adding data, or integrating BERT’s tone predictions to guide the rewrites (e.g., “Tone: neutral → amp up the sass”). I will also try to fine Tune LLama for rewriting. The code’s on <a href="https://github.com/vivekschaurasia/Passive-Aggressive-Email-Rewriter">GitHub </a>, and I’ll post updates as it evolves.</p><h4>Takeaways for NLP Fans</h4><ul><li>BERT shines for classification, even with small datasets.</li><li>LoRA + GPT-2 is a lightweight way to tackle generation tasks.</li><li>Two-model pipelines can unlock fun, practical applications.</li></ul><p>Got ideas for sassier rewrites or LoRA tips? Drop them in the comments, I’d love to hear your thoughts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b62b41359c3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI Powered Image-to-Text Captioning System with Xception and LSTM]]></title>
            <link>https://medium.com/@vivekschaurasia/building-an-ai-powered-image-to-text-captioning-system-with-xception-and-lstm-8047925d877b?source=rss-3bdb1be656cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/8047925d877b</guid>
            <category><![CDATA[image-captioning]]></category>
            <category><![CDATA[xceptio]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[multimodal]]></category>
            <dc:creator><![CDATA[Vivekschaurasia]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 22:28:38 GMT</pubDate>
            <atom:updated>2025-03-02T22:28:38.623Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In an era where artificial intelligence (AI) is transforming how we interact with digital content, the ability to automatically generate descriptive captions for images has emerged as a groundbreaking application. My project, the Image-to-Text Captioning System, leverages advanced deep learning techniques to bridge the gap between visual and textual data, creating contextually relevant captions for images. This blog will walk you through the development, features, implementation, and potential of this system, which integrates the Xception convolutional neural network (CNN) for image feature extraction and Long Short-Term Memory (LSTM) networks for text generation.</p><h3>Project Overview</h3><p>The system combines two deep learning paradigms:</p><ol><li><strong>Computer Vision</strong>: Uses the pre-trained Xception model to extract high-level features from images.</li><li><strong>Natural Language Processing</strong>: Employs an LSTM-based sequence model to generate human-readable captions.</li></ol><h3>Key Features</h3><ul><li><strong>Xception Model</strong>: Efficiently extracts image features using depthwise separable convolutions.</li><li><strong>LSTM Network</strong>: Generates contextually relevant captions by learning sequential patterns.</li><li><strong>BLEU Score Evaluation</strong>: Quantifies caption quality using NLP metrics.</li><li><strong>Modular Design</strong>: Easy integration with newer architectures or datasets.</li></ul><h3>Dataset: Flickr8k</h3><p>The project uses the <strong>Flickr8k dataset</strong>, which includes:</p><ul><li><strong>8,000 images</strong> spanning diverse scenarios (sports, animals, activities).</li><li><strong>5 captions per image</strong> for robust training.</li></ul><pre>Dataset/  <br>├── Images/               <br>└── captions.txt  </pre><h3>Model Architecture</h3><p>The model architecture combines two powerful components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*SGtpKCq0LERkKbfmrUBKkw.png" /><figcaption>Architecture</figcaption></figure><p><strong>1. LSTM for Text Generation</strong>:</p><ul><li>The LSTM network generates captions by taking the image feature vector as an initial input, followed by tokenized words to predict subsequent words in the sequence.</li><li>The LSTM processes sequences using softmax layers to output probability distributions over the vocabulary, enabling word-by-word prediction until an &lt;end&gt; token is generated.</li></ul><p><strong>2. Xception for Image Feature Extraction</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uzPQtygFF4J31MsZ5EnstA.png" /><figcaption>Xception Architecture</figcaption></figure><ul><li>Xception, a pre-trained CNN from Keras Applications, is used to extract high-level visual features from images. It employs depthwise separable convolutions, which separate spatial and channel-wise convolutions, reducing computational complexity while maintaining performance.</li><li>The network processes images through an entry flow (initial downsampling), a middle flow (feature extraction via repeated depthwise separable convolutions), and an exit flow (final downsampling and feature vector computation). The output is a fixed-dimensional feature vector (e.g., 2048 dimensions) from the penultimate layer.</li><li>Advantages include efficiency, scalability, and modularity, as detailed in the project documentation.</li></ul><h3>Implementation Workflow</h3><h4>1. Feature Extraction with Xception</h4><p>The Xception model (pre-trained on ImageNet) processes images to extract <strong>2,048-dimensional feature vectors</strong>. These features capture essential visual patterns, such as edges, textures, and object shapes</p><pre>from tensorflow.keras.applications.xception import Xception, preprocess_input  <br><br>model = Xception(weights=&quot;imagenet&quot;, include_top=False, pooling=&quot;avg&quot;)  <br>features = model.predict(preprocessed_image)</pre><h3>2. Caption Generation with LSTM</h3><p>The LSTM network learns to map image features to sequences of words. It uses:</p><ul><li><strong>Embedding Layer</strong>: Converts words into dense vectors.</li><li><strong>Dropout Layers</strong>: Prevent overfitting.</li></ul><pre>from tensorflow.keras.layers import LSTM, Embedding, Dense  <br><br>model.add(Embedding(vocab_size, 256, input_length=max_length))  <br>model.add(LSTM(256))  <br>model.add(Dense(vocab_size, activation=&quot;softmax&quot;))  </pre><h3>3. Training Pipeline</h3><ul><li><strong>Preprocessing</strong>: Resize images, tokenize captions, and create sequences.</li><li><strong>Model Training</strong>: Optimize using categorical cross-entropy and Adam optimizer.</li><li><strong>Checkpointing</strong>: Save the best model weights.</li></ul><p><strong>Default Hyperparameters</strong>:</p><ul><li>Epochs: 13</li><li>Batch Size: 32</li></ul><h3>4. Evaluation</h3><p>Evaluation is performed using the BLEU score, which measures n-gram overlap between generated captions and reference captions. However, as noted in the documentation, BLEU scores can be low due to the subjective nature of captions, prompting the consideration of alternative metrics like METEOR or CIDEr.</p><h3>Results</h3><p>An example of the system’s output for an image might look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*djvCFgMsQhwCY3s34CAMpw.png" /><figcaption>Example from the Dataset</figcaption></figure><ul><li><strong>Generated Caption</strong>: “A boy is smiling underwater.”</li><li><strong>Reference Captions</strong> (Ground Truth):</li></ul><ol><li>“A boy smiles underwater.”</li><li>“A red-headed boy swimming underwater.”</li><li>“A small boy swimming underwater.”</li><li>“A smiling boy swims underwater in a pool.”</li></ol><h3>BLEU Score</h3><p>The project achieved a BLEU score of 0.66 on the training set, indicating moderate performance. However, as discussed in the documentation, low BLEU scores can occur due to the diversity and subjectivity of human-generated captions, especially for complex scenes with multiple objects.</p><h3>Limitations</h3><p>Despite its promising results, the Image-to-Text Captioning System faces several limitations:</p><ul><li><strong>Subjective Captions</strong>: The BLEU score may not accurately reflect caption quality due to the subjective nature of human descriptions.</li><li><strong>Complex Scenes</strong>: The model struggles with images containing multiple objects or intricate details, often generating inaccurate or incomplete captions.</li></ul><h3>Future Enhancements</h3><p>To address these limitations and improve the system, future work could include:</p><ul><li><strong>Advanced Architectures</strong>: Experiment with Vision Transformers (ViT) or GPT-based models to capture global image features and enhance language generation with better contextual understanding.</li><li><strong>Larger Datasets</strong>: Incorporate datasets like COCO or Visual Genome, which offer richer visual-textual pairs for improved generalization.</li><li><strong>Multilingual Captioning</strong>: Extend the system to generate captions in multiple languages, enhancing accessibility and applicability across diverse regions.</li></ul><h3>Conclusion</h3><p>This project demonstrates the potential of combining CNNs and LSTMs for image captioning. While the current BLEU score is modest, the modular design allows easy experimentation with newer models like ViT or BERT. By scaling to larger datasets and refining the architecture, we can build systems that generate captions indistinguishable from human descriptions.</p><p>For those interested in deployment, integrating CI/CD pipelines (e.g., Jenkins) and cloud platforms (AWS) can transform this prototype into a production-ready tool.</p><p><strong>GitHub Repository</strong></p><p><a href="https://github.com/vivekschaurasia/Image2Text">https://github.com/vivekschaurasia/Image2Text</a></p><p><strong>Connect with me</strong>:</p><p><a href="/service/mailto:vivekschaurasia@gmail.com">vivekschaurasia@gmail.com</a><br><a href="https://www.linkedin.com/in/vivek-santosh-chaurasia/">https://www.linkedin.com/in/vivek-santosh-chaurasia/</a><br><a href="https://github.com/vivekschaurasia">https://github.com/vivekschaurasia</a> <br><a href="https://medium.com/@vivekschaurasia">https://medium.com/@vivekschaurasia</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8047925d877b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a News Q&A Bot : A Step-by-Step Guide to Real-Time Retrieval-Augmented Generation (RAG)]]></title>
            <link>https://medium.com/@vivekschaurasia/building-a-news-q-a-bot-a-step-by-step-guide-to-real-time-retrieval-augmented-generation-rag-783630c580ab?source=rss-3bdb1be656cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/783630c580ab</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[llm-agent]]></category>
            <dc:creator><![CDATA[Vivekschaurasia]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 15:21:58 GMT</pubDate>
            <atom:updated>2024-11-11T15:21:58.357Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a News Q&amp;A Bot : A Step-by-Step Guide to Real-Time Retrieval-Augmented Generation (RAG)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Uv8hw4WSY3TJZMoJplvxA.jpeg" /><figcaption>Question and Answering Bot</figcaption></figure><p>In this blog, we will see how to create a RAG model that can summarize and answer to your question regarding the News you want.</p><p>Tools:</p><ol><li>LangChain</li><li>OpenAI API</li><li>Python’s OS library</li><li>FAISS</li><li>dotenv</li><li>Numpy</li></ol><p>In the previous <a href="https://medium.com/@vivekschaurasia/a-rag-model-for-summarizing-news-with-langchain-and-openai-301faefae7ef">blog</a>, we saw how to create a RAG Model for summarizing News with LangChain and OpenAI. For vector storage and retrieval, we used <a href="https://python.langchain.com/docs/integrations/vectorstores/chroma/">Chroma db</a> but in this project, we will use FAISS (Facebook AI Similarity Search) for vector storage and retrieval.</p><p>FAISS vs ChromaDb:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b16e723cc8bd112833c48b05541fd6f3/href">https://medium.com/media/b16e723cc8bd112833c48b05541fd6f3/href</a></iframe><p><strong>Why FAISS?</strong></p><p>In this project, we opted for FAISS as our vector storage and retrieval solution due to its efficiency in high-dimensional similarity searches and flexibility for local deployment. While ChromaDB is a great tool with a focus on embedding databases and offers features like persistence and cloud integrations, FAISS shines when it comes to speed and scalability, especially with large datasets. It’s ideal for scenarios where you need real-time processing on a local setup, like in our news Q&amp;A bot.</p><p><strong>Dataset:</strong></p><p>You can get the News data from this <a href="https://github.com/vivekschaurasia/Getting_latest_news">GitHub repository</a>. After this, you will have a folder named “NEWS_data” and all the latest news regarding the specific will be stored in that news.</p><p><strong>Step 1: Load and Process News Data</strong></p><p>To start, we’ll load and clean our news articles, removing any unsuccessful retrievals. The text will be split into chunks that are easier to handle for embedding generation, allowing us to index and search more effectively. Below is the code.</p><pre># Step 1: Load and Preprocess News Articles<br>folder_path = &quot;put the path where the NEWS articles are stored&quot;<br><br>documents = [<br>    open(os.path.join(folder_path, filename), &#39;r&#39;, encoding=&#39;utf-8&#39;).read()<br>    for filename in os.listdir(folder_path) if filename.endswith(&quot;.txt&quot;)<br>]<br><br># Filter out failed retrieval messages<br>news_documents = [doc for doc in documents if doc != &quot;Failed to retrieve the webpage.&quot;]</pre><p><strong>Step 2: Split Documents into Chunks</strong></p><p>Once we have the news articles loaded, we need to split them into smaller, manageable chunks. This ensures that each chunk fits within the token limits of our model, allowing us to handle larger documents efficiently. For this, we use LangChain’s CharacterTextSplitter. Here’s the code to perform the text splitting:</p><pre># Step 2: Split Documents into Chunks<br>text_splitter = CharacterTextSplitter(separator=&quot;\n&quot;, chunk_size=1000, chunk_overlap=200)<br><br>all_chunks = [chunk for doc in news_documents for chunk in text_splitter.split_text(doc)]</pre><p>With this setup, each document is split into chunks of 1000 characters with an overlap of 200 characters, preserving context across chunks.</p><p><strong>Step 3: Embedding the Text Chunks</strong></p><p>Next, we need to transform these chunks into embeddings using OpenAI’s API. Embeddings convert text into dense vector representations, allowing us to perform similarity searches on our text data. We use the text-embedding-ada-002 model for this purpose. Here’s how to generate embeddings for each chunk:</p><pre># Step 3: Load Embeddings<br>embeddings = OpenAIEmbeddings(model=&quot;text-embedding-ada-002&quot;, api_key=&quot;your API key&quot;)<br><br># Generate embeddings for each chunk<br>chunk_embeddings = embeddings.embed_documents(all_chunks)</pre><p><strong>Step 4: Initializing FAISS Index</strong></p><p>With the embeddings created, we now set up our FAISS index. FAISS enables fast similarity search over high-dimensional vectors, making it ideal for our retrieval system. Here’s the code to initialize FAISS with the embeddings:</p><pre># Set up FAISS index for L2 distance (Euclidean)<br>embedding_dim = len(chunk_embeddings[0])  # Embedding dimension<br>index = faiss.IndexFlatL2(embedding_dim)<br><br># Convert embeddings to a NumPy array and add to FAISS index<br>chunk_embeddings_np = np.array(chunk_embeddings).astype(&quot;float32&quot;)<br>index.add(chunk_embeddings_np)</pre><p><strong>Step 5: Defining the Retrieval Function</strong></p><p>Now that our FAISS index is ready, we can define a retrieval function to fetch the most relevant chunks for a given query. This function will take a user query, embed it, and retrieve the most similar chunks from the index:</p><pre># Step 5: Define the FAISS-Based Retriever<br>def retrieve_similar_chunks(query, k=5):<br>    query_embedding = np.array(embeddings.embed_documents([query])).astype(&quot;float32&quot;)<br>    <br>    if query_embedding.shape != (1, embedding_dim):<br>        query_embedding = query_embedding.reshape(1, embedding_dim)<br>    <br>    distances, indices = index.search(query_embedding, k)<br>    <br>    relevant_chunks = [<br>        all_chunks[i] for i in indices[0] <br>        if i &lt; len(all_chunks) and distances[0][indices[0].tolist().index(i)] &lt; 0.7<br>    ]<br>    <br>    return relevant_chunks</pre><p>This function returns the top k chunks that are most similar to the query, filtered by a distance threshold for relevance.</p><p><strong>Step 6: Defining the Q&amp;A Function</strong></p><p>To answer a user’s question, we combine the query with the retrieved document content and prompt OpenAI’s language model to generate a response. Here’s the code for our Q&amp;A function:</p><pre># Step 6: Define the QA Function<br>def answer_question(query):<br>    relevant_docs = retrieve_similar_chunks(query)<br><br>    # Combine the query with relevant document content<br>    combined_input = (<br>        &quot;Answer the following question based only on the provided documents: &quot;<br>        + query<br>        + &quot;\n\nRelevant Documents:\n&quot;<br>        + &quot;\n\n&quot;.join(relevant_docs)<br>        + &quot;\n\nIf the answer is not found in the documents, respond with &#39;I&#39;m not sure&#39;.&quot;<br>    )<br><br>    <br>    messages = [<br>        SystemMessage(content=&quot;You are a helpful assistant for answering questions based on news documents.&quot;),<br>        HumanMessage(content=combined_input),<br>    ]<br><br>    # ChatOpenAI model to generate the answer<br>    result = llm.invoke(messages)<br>    <br>    return result.content</pre><p>This function outputs a concise answer based on the relevant news chunks.</p><p><strong>Step 7: Testing the Q&amp;A Bot</strong></p><p>Now that everything is set up, we can test our bot with a sample query. The bot will output an answer or indicate if it couldn’t find relevant information. Here’s how to test it:</p><pre># Step 7: Create the LLM Model<br>llm = ChatOpenAI(model=&quot;gpt-4o&quot;, api_key=&quot;your API&quot;)<br><br>query = input(&quot;What is your query? &quot;).lower()<br><br>while query != &quot;exit&quot;:<br>    answer = answer_question(query)<br>    print(&quot;\n--- Answer ---&quot;)<br>    print(answer)<br>    query = input(&quot;What is your query? &quot;).lower()</pre><p>With this loop, the bot is ready to handle any query until you type “exit”.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nepY2RzOoRxOzBU8X-JoWQ.png" /><figcaption>Model response :)</figcaption></figure><p><strong>Conclusion</strong></p><p>In this guide, we’ve covered how to create a real-time news Q&amp;A bot using a Retrieval-Augmented Generation (RAG) approach with FAISS, LangChain, and OpenAI. This setup can quickly retrieve and synthesize answers from a large set of news articles, providing a scalable, efficient solution for question-answering tasks.</p><p><strong>Future Work</strong></p><p>For Future work, we can incorporate a feedback loop where users can rate the bot’s responses, helping you continuously refine the retrieval and response generation. To make the bot accessible to a broader audience, we can deploy it as an API or a web app.</p><h3>Contact:</h3><ul><li><a href="https://www.linkedin.com/in/vivek-santosh-chaurasia-567b15197/">Linkedin</a></li><li>G<a href="https://github.com/vivekschaurasia">ithub</a></li><li>vc4654@rit.edu</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=783630c580ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A RAG Model for Summarizing News with LangChain and OpenAI]]></title>
            <link>https://medium.com/@vivekschaurasia/a-rag-model-for-summarizing-news-with-langchain-and-openai-301faefae7ef?source=rss-3bdb1be656cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/301faefae7ef</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Vivekschaurasia]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 18:37:21 GMT</pubDate>
            <atom:updated>2024-10-26T19:24:49.745Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r3w6HvInc6cgN1UmgcT6Rw.png" /><figcaption>Futuristic RAG Model for News Summarization</figcaption></figure><h3>Introduction</h3><p>A lot of things happen in the world every day, and it’s hard to keep up with everything we care about. Some people like to follow news about politics, while others want the latest gossip about their favorite actor or actress. But not everyone has the time to read a bunch of different articles. That’s where my <strong>RAG (Retrieval-Augmented Generation) model</strong> comes in. We just tell it what kind of news we are looking for, and it will grab the latest updates and give us a quick summary in just a few seconds.</p><p>In this blog, I’ll walk you through how I developed a <strong>Retrieval-Augmented Generation (RAG)</strong> model that uses Google News, LangChain, and OpenAI’s GPT models to provide concise summaries of the latest news topics.</p><h3>What is a RAG Model?</h3><p>Retrieval-Augmented Generation (RAG) is a combination of information retrieval and language generation. RAG models are used in virtual assistants to retrieve information from large knowledge bases, like in legal tech or customer service bots, to provide accurate responses on the fly. In this model, relevant documents are first retrieved based on a user query, and a generative model summarizes the retrieved content. This approach improves relevance and accuracy, especially when summarizing topics based on external data sources.</p><p><strong>RAG Components:</strong></p><ol><li><strong>Retrieval System:</strong> Retrieves relevant documents based on a query.</li><li><strong>Generative Model:</strong> Summarizes the content retrieved by the first step.</li></ol><h3>Tech Stack</h3><ul><li><strong>Python</strong> for scripting</li><li><strong>LangChain</strong> for chunking, embeddings, and model orchestration</li><li><strong>OpenAI</strong> GPT models for text generation</li><li><strong>Chroma</strong> for vector database management</li><li><strong>Google News</strong> library to retrieve live news links</li><li><strong>BeautifulSoup</strong> for web scraping</li><li><strong>tqdm</strong> for tracking the status of scraping</li></ul><h3>How It Works</h3><p>Below is the step-by-step process of the model, from retrieving the latest news to summarizing it using OpenAI’s GPT model.</p><h3>Step 1: Fetching the Latest News Articles</h3><p>Using the GoogleNews library, we can search for the latest news articles based on the topic the user provides. The code retrieves news links and pulls the content from those links. Below is the code where the user gives a topic, and the model searches for news related to it. In the end, we store everything in a DataFrame for easy handling.</p><p><strong>Note:</strong> We don’t have to use a DataFrame — storing the news in a list works just fine too.</p><pre><br>from GoogleNews import GoogleNews<br>import pandas as pd<br><br>user_request = input(str(&quot;Give me a topic: &quot; ))<br><br>googlenews = GoogleNews(period=&#39;7d&#39;)<br>googlenews.search(user_request)<br><br>all_results = []<br>for i in range(1, 50):<br>    googlenews.getpage(i)<br>    result = googlenews.result()<br>    <br>    if result:<br>        all_results.extend(result)<br><br>    if len(all_results) &gt;= 100:<br>        break<br><br>df = pd.DataFrame(all_results).drop_duplicates(subset=[&#39;title&#39;], keep=&#39;last&#39;).head(100)<br>df.reset_index(drop=True, inplace=True)<br></pre><p>Dropping the unwanted columns.</p><pre>data = df.drop(columns = [&#39;media&#39;, &#39;date&#39;, &#39;datetime&#39;, &#39;desc&#39;, &#39;img&#39;])</pre><h3>Step 2: Extracting News Content</h3><p>The News links we got from the GoogleNews weren’t in the right format, so we had to clean them by removing everything after “&amp;ved”.</p><pre>latest_links = [re.split(&quot;&amp;ved&quot;, link)[0] for link in df[&#39;link&#39;]]</pre><p>After fetching the news links, we use <strong>BeautifulSoup</strong> to scrape the content from the webpages. This step ensures that we extract meaningful content from each link. At the end we add description in our DataFrame.</p><pre>import requests<br>from bs4 import BeautifulSoup<br>import re<br>import time, random<br><br>description = []<br><br><br>for i in latest_link:<br><br>    try:<br>        response = requests.get(i, timeout=10)<br><br>        if response.status_code == 200:<br>            html_content = response.text<br>        else:<br>            print(f&quot;Failed to retrieve: {i} (Status code: {response.status_code})&quot;)<br>            description.append(&quot;Failed to retrieve the webpage.&quot;)<br>            continue  <br>       <br>        soup = BeautifulSoup(html_content, &quot;html.parser&quot;)<br>        paragraphs = soup.find_all(&quot;p&quot;)<br><br>        page_description = &quot; &quot;.join([p.get_text() for p in paragraphs])<br>        description.append(page_description)<br><br>    except requests.exceptions.RequestException as e:<br>        print(f&quot;Error retrieving {i}: {e}&quot;)<br>        description.append(&quot;Failed to retrieve the webpage.&quot;)<br>        continue <br>    <br>    time.sleep(random.uniform(1, 3))<br><br>print(description)<br><br>data[&quot;description&quot;] = description</pre><p><strong>Note:</strong> Be cautious of rate limits when scraping. To avoid getting blocked, the code introduces random delays between requests. This helps simulate human behavior and reduces the chances of triggering anti-scraping mechanisms.</p><h3>Step 3: Saving News Descriptions as Text Files</h3><p>The scraped news articles are saved as text files, which will be processed by the RAG model for summarization.</p><pre>import os<br><br>folder_name = &quot;NEWS_data&quot;<br>os.makedirs(folder_name, exist_ok=True)<br><br>for index, row in df.iterrows():<br>    with open(os.path.join(folder_name, f&quot;description_{index + 1}.txt&quot;), &quot;w&quot;, encoding=&quot;utf-8&quot;) as f:<br>        f.write(row[&#39;description&#39;])<br><br>print(&quot;Descriptions have been saved in the &#39;NEWS_data&#39; folder.&quot;)</pre><h3>Step 4: Chunking the News Articles with LangChain</h3><p>Using <strong>LangChain’s CharacterTextSplitter</strong>, we split the articles into smaller chunks. This helps maintain context and ensures that the input size matches the token limits of GPT models.</p><pre>from langchain.text_splitter import CharacterTextSplitter<br><br>text_splitter = CharacterTextSplitter(separator=&quot;\n&quot;, chunk_size=1000, chunk_overlap=200)<br><br>documents = []<br>for filename in os.listdir(&quot;NEWS_data&quot;):<br>    if filename.endswith(&quot;.txt&quot;):<br>        with open(os.path.join(&quot;NEWS_data&quot;, filename), &#39;r&#39;, encoding=&#39;utf-8&#39;) as file:<br>            documents.append(file.read())<br><br>all_chunks = []<br>for doc in documents:<br>    chunks = text_splitter.split_text(doc)<br>    all_chunks.extend(chunks)</pre><h3>Step 5: Embedding News Chunks Using OpenAI</h3><p>We generate embeddings for the news chunks using <strong>OpenAI embeddings</strong> and store them in a <strong>Chroma vector database</strong> for easy retrieval.</p><p>A <strong>vector database</strong> like Chroma stores data as embeddings (numerical representations of text or other content). These embeddings capture the meaning and context of the data, allowing for efficient similarity searches. In this project, Chroma helps retrieve the most relevant news articles by comparing the embeddings of user queries with stored article embeddings, ensuring that the closest matches are returned.</p><p>When the vector database compares embeddings, it uses <strong><em>cosine similarity</em></strong> to determine how closely two pieces of text are related. A higher cosine similarity score means the retrieved article is more relevant to the query.</p><p>Note: We can also use FAISS (Facebook AI Similarity Search) vector database instead of Chroma db.</p><p>Note: Remember to put your API_KEY</p><p>Note: We should use .env to store your API_KEYS.</p><pre>from langchain_openai import OpenAIEmbeddings<br>from langchain_chroma import Chroma<br><br>embeddings = OpenAIEmbeddings(model=&quot;text-embedding-3-small&quot;, api_key=&quot;YOUR_API_KEY&quot;)<br>db = Chroma(persist_directory=&quot;db/chroma_db&quot;, embedding_function=embeddings)<br><br>ids = [f&quot;doc_{i}&quot; for i in range(len(all_chunks))]<br>db.add_texts(all_chunks, ids=ids)</pre><p>While Chroma is effective for smaller datasets, FAISS may perform better for larger, distributed datasets due to its optimized search algorithms.</p><h3>Step 6: Retrieving Relevant News Articles</h3><p>We use the vector database to retrieve relevant articles based on the user’s query.</p><pre>retriever = db.as_retriever(search_type=&quot;similarity&quot;, search_kwargs={&quot;k&quot;: 3})<br><br>query = &quot;What is happening in Israel?&quot;<br>relevant_docs = retriever.invoke(query)<br><br>combined_input = (<br>    &quot;Here are some documents that might help answer the question: &quot;<br>    + &quot;\n\n&quot;.join([doc.page_content for doc in relevant_docs])<br>    + &quot;\n\nPlease summarize the content in no more than 4 lines.&quot;<br>)</pre><h3>Step 7: Summarizing the Retrieved Articles Using GPT-4</h3><p>Finally, we use <strong>GPT-4</strong> to generate a concise summary of the retrieved news articles.</p><pre>from langchain_openai import ChatOpenAI<br>from langchain_core.messages import HumanMessage, SystemMessage<br><br>llm = ChatOpenAI(model=&quot;gpt-4o&quot;, api_key=&quot;YOUR_API_KEY&quot;)<br><br>messages = [<br>    SystemMessage(content=&quot;You are a helpful assistant.&quot;),<br>    HumanMessage(content=combined_input),<br>]<br><br>result = llm.invoke(messages)<br><br>print(&quot;\n--- Generated Summary ---&quot;)<br>print(result.content)</pre><h3>Results and Key Takeaways</h3><p>When the model receives a query (e.g., “What is happening between Israel?”), it retrieves the most relevant news articles from the last 7 days and summarizes them into a concise, readable answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgcOoBJ0mCYC4TMxc6bdaA.png" /><figcaption>Model response</figcaption></figure><h3>Conclusion</h3><p>This project demonstrates the power of RAG models for real-time information retrieval and summarization. By combining Google News, LangChain, and OpenAI, I was able to build a useful tool to stay informed about current events in a concise manner.</p><p><strong>Future Work</strong></p><p>In Future, I will make a model which can chat and answer our questions regarding our news. It will be a simple Q&amp;A chatbot that helps users get answers related to the news they care about.</p><h3>Contact:</h3><ul><li><a href="https://www.linkedin.com/in/vivek-santosh-chaurasia-567b15197/">Linkedin</a></li><li>G<a href="https://github.com/vivekschaurasia">ithub</a></li><li>vc4654@rit.edu</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=301faefae7ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Case study on Natural Language Processing with Disaster Tweets]]></title>
            <link>https://medium.com/@vivekschaurasia/case-study-on-natural-language-processing-with-disaster-tweets-6ac4a45060db?source=rss-3bdb1be656cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ac4a45060db</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[kaggle-competition]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[applied-ai]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Vivekschaurasia]]></dc:creator>
            <pubDate>Fri, 28 Oct 2022 15:55:29 GMT</pubDate>
            <atom:updated>2022-10-28T15:55:29.611Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog is the case study of a competition held on Kaggle. The competition’s name is Natural Language Processing. Competition can be found <a href="https://www.kaggle.com/competitions/nlp-getting-started/overview">here</a>.</p><h3><strong>Introduction:</strong></h3><ol><li>Disasters can happen anywhere and sometimes it takes time for the agencies to know about the disaster. Nowadays as soon as something happens, people tweet about it and if the model can predict whether the given tweet is regarding the disaster or not then it can save time and agencies can help people who are stuck in the disaster’s region.</li><li>In times of emergency, twitter has become an important communication channel and with tweets many agencies can get the details about disasters in real time as soon as people start talking or tweeting about the disaster.</li><li>However, sometimes it is not clear whether the person tweeting is talking about a real disaster or just using slang.</li><li>In this competition model has to predict whether the given sentence is a real disaster or not. We have to predict 0 or 1. If 1 that means the disaster is real and 0 if the disaster is not real.</li><li>This problem is a binary class classification and the metric here we will use is F1 score.</li></ol><h3>Dataset:</h3><ol><li>The train file consists of 5 columns and they are Id, keyword, location, text and target and the test file consists of 4 columns and they are ID, keyword, location and text. While submitting, we have to submit in a format such that the csv file should contain Id and target value.</li><li>In the dataset, features like id, location are useless because Id is just the number of sequence and location column contains too many Null values. Therefore we will remove these columns/features.</li><li>The target feature contain 1 and 0 which means that the tweet is really a disaster tweet if target value is 1 and 0 means tweet is not a disaster tweet.</li><li>The dataset is not imbalanced dataset because the ratio of class 0 and 1 is 57 to 43. That means 57 percentage of points are 0 and 43 percentage of points are 1. So here we do not have to do process like Upsampling.</li></ol><h3>Metric:</h3><ol><li>The metric here we will use to evaluate our model is accuracy and Kaggle will evaluate our model using F1 score.</li><li><strong>Accuracy</strong> is the number of points model predicted correctly given the total number of points present in the dataset.</li><li><strong>F1 Score</strong> formula is 2*(precision*recall)/(precision + recall)</li><li>Since the data is balanced, it is safe to use accuracy as a metric.</li></ol><p><strong>Kaggle Data:</strong></p><p>To download the Kaggle data, visit <a href="https://www.kaggle.com/general/156610">here</a>.</p><h3>EDA:</h3><p>In the train.csv, we have 7613 rows and 5 columns. Since null values are present here, we will either do some EDA or remove those features.</p><p><strong>ID: </strong>The ID feature is useless because it is just a serial number with every row having a unique id. It won’t benefit in training the model, so we will remove ID column.</p><p><strong>Location:</strong> While doing EDA, we found out that in location feature, 56 percentage of values are Null. Since more than half of values are null, we will remove this feature.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26fd9a13ddcbe8ef76092446295bb2ec/href">https://medium.com/media/26fd9a13ddcbe8ef76092446295bb2ec/href</a></iframe><p><strong>Keyword:</strong> In keyword feature, we have total 61 Null values present in the feature.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21e2ca202cc849ffd901a381283df530/href">https://medium.com/media/21e2ca202cc849ffd901a381283df530/href</a></iframe><p>Since we have 61 rows where Null value is present in the keyword feature. So we will remove those rows. The total unique keywords we have are 221 keywords.</p><p><strong>Balanced Dataset:</strong> For training any classification model, we have to look if the dataset is balanced or imbalanced. Below is the code for knowing whether our data is balanced or imbalanced.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b61fce5c51e76e616a845da4e317de63/href">https://medium.com/media/b61fce5c51e76e616a845da4e317de63/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce576e26beec0050f4b77e8d9ab8cc52/href">https://medium.com/media/ce576e26beec0050f4b77e8d9ab8cc52/href</a></iframe><p>From the above code, we can see that positive and negative points are in the ratio of 57 to 42. So, we can say that the dataset is balanced.</p><p>Now with the below code, we will draw word cloud.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb4b7c83d83769b3962740692464f3a5/href">https://medium.com/media/eb4b7c83d83769b3962740692464f3a5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*-RBNWxlY2F1Cd5s9KNOybQ.png" /><figcaption>Word cloud of keyword feature.</figcaption></figure><h3>Feature Engineering:</h3><p>Feature Engineering is an important part of Machine and Deep learning. Here we will clean our data, for eg we will remove “https” from the sentence and instead of short forms like “he’ll”, we will write “he will”.</p><p>Below is the code to clean the data like removing punctuation, Html tags etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0586afe394a8ac5d7554a93bfd316bd/href">https://medium.com/media/f0586afe394a8ac5d7554a93bfd316bd/href</a></iframe><p>Stopwords in a given sentences are useless so it is important to remove them. nltk.download(‘stopwords’) contains every stopwords. However it also contains “not” so we will create a new list that will contain every stopword except “not”. Below is the function to remove every stopword from our sentence.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57f0cb1556002f32945b3a81330f86d3/href">https://medium.com/media/57f0cb1556002f32945b3a81330f86d3/href</a></iframe><p><strong>Stemming :</strong></p><p>At every sentence we can either use Stemming or Lemmatization. Usually we use stemming if our problem does not require real meaning of the word. If our problem is classification like our current problem then we use stemming and if our problem is like Chatbot or translation then we use Lemmatization. For more information refer <a href="https://www.analyticsvidhya.com/blog/2022/06/stemming-vs-lemmatization-in-nlp-must-know-differences/">here</a>.</p><p>For our problem we will use stemming. Below is the function for stemming.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ef3dd70b70e06bf7a7739f8c243b834/href">https://medium.com/media/4ef3dd70b70e06bf7a7739f8c243b834/href</a></iframe><h3><strong>Model:</strong></h3><p>In NLP, if we have 2 class classification then we use naive Bayes as a base model. So we will first train our model with Niave bayes and than train Deep learning models. If our Deep learning model performs better than Naive bayes than we will choose deep learning model.</p><p><strong>Naive Bayes:</strong> First we will split the data into features and target variable and then split the model in training and test set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a51557e942dc2991e751ca3a7d75b1f7/href">https://medium.com/media/a51557e942dc2991e751ca3a7d75b1f7/href</a></iframe><p>Now we have two columns for training and now in training we have keyword feature where keyword is categorical. So we will encode categorical features usong Label encoding.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89a4cbdd13f1938347d802bd02ef2005/href">https://medium.com/media/89a4cbdd13f1938347d802bd02ef2005/href</a></iframe><p>Now for text feature, we will use Count Vectorizer. For more information on count vectorizer, click <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d2e6aa82be7188d8f13dc50b2f991a7/href">https://medium.com/media/9d2e6aa82be7188d8f13dc50b2f991a7/href</a></iframe><p>After this we will fit our model, predict the test dataset and find the accuracy. Below is the code to do all of that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38300b0870f5cd043823f06e187ee98d/href">https://medium.com/media/38300b0870f5cd043823f06e187ee98d/href</a></iframe><p>With Naive Bayes we get 74% accuracy. So if our deep learning model give us accuracy of more than 74% than we will use our deep Learning model as final model.</p><p>In this section, we have used many Deep learning models like BERT, LSTM, Dense layer with Tokenization and we got better result in LSTM model. So, in this section I will only write about LSTM.</p><p><strong>LSTM Model:</strong> For training the model, we have two features (text and keyword). For text feature, we will convert it into numerical value using <a href="https://stackoverflow.com/questions/51956000/what-does-keras-tokenizer-method-exactly-do">Tokenizer</a>. Below is the code to tokenize train and test dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24fd327526f603bdb26969b424b81810/href">https://medium.com/media/24fd327526f603bdb26969b424b81810/href</a></iframe><p>Now for the keyword feature, we will convert them using Ordinal Encoder</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44ded07de978498c9daaa4521ce1eb23/href">https://medium.com/media/44ded07de978498c9daaa4521ce1eb23/href</a></iframe><p>Model architecture:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3e1e17d7531eb367fb1c25d580f0b2f/href">https://medium.com/media/f3e1e17d7531eb367fb1c25d580f0b2f/href</a></iframe><p>The whole code can be found on my <a href="https://github.com/vivekschaurasia/Natural-Language-Processing-with-Disaster-Tweets">Github</a>.</p><p>With LSTM, we got 80 accuracy on test dataset.</p><p><strong>Loss graph and accuracy:</strong> From Tensorboard, below is the graph of loss and accuracy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*r6lPLQogsDe6x3LokesOgA.jpeg" /></figure><p><strong>The final result:</strong></p><pre>+-------------------+--------------+--------|<br>|             Model             | Accuracy  |<br>+-------------------+--------------+--------|<br>|            LSTM               |   81%     |<br>|            BERT               |   79%     |<br>|      TF IDF + Dense layer     |   75%     |<br>|    Tokenization + Dense layer |   60%     | <br>+-------------------+--------------+--------|</pre><h3>Final Notebook:</h3><p>Here in the final notebook, we will import all the saved “pkl” files and create a pipeline that will make a final prediction. We will give raw data as input and then create a function which will take raw data and return the predicted value. The code can be found in my <a href="https://github.com/vivekschaurasia/Natural-Language-Processing-with-Disaster-Tweets">GitHub</a> account.</p><h3>Video Demo:</h3><p>Below is the video of model predicting the tweets.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEQ54WT23roQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEQ54WT23roQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FEQ54WT23roQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e990cb979045b25c9339ea0d1cc9dd06/href">https://medium.com/media/e990cb979045b25c9339ea0d1cc9dd06/href</a></iframe><h3>Future works:</h3><p>This problem can also be solved using Machine learning. Maybe Random forest will work better than LSTM cells. For getting more accuracy and less overfitting, we should collect more data and we should take care that the dataset should not contain Null values.</p><h3>Conclusion:</h3><p>With LSTM we got a good score however overfitting is very easy in deep learning.</p><h3>Reference:</h3><ol><li><a href="https://www.kaggle.com/competitions/nlp-getting-started">https://www.kaggle.com/competitions/nlp-getting-started</a></li><li><a href="https://towardsdatascience.com/cleaning-preprocessing-text-data-by-building-nlp-pipeline-853148add68a">https://towardsdatascience.com/cleaning-preprocessing-text-data-by-building-nlp-pipeline-853148add68a</a></li><li><a href="https://blog.bitext.com/what-is-the-difference-between-stemming-and-lemmatization/#:~:text=Stemming%20and%20lemmatization%20are%20methods,more%20detailed%20explanations%20and%20examples">https://blog.bitext.com/what-is-the-difference-between-stemming-and-lemmatization/#:~:text=Stemming%20and%20lemmatization%20are%20methods,more%20detailed%20explanations%20and%20examples</a>.</li><li><a href="https://www.kaggle.com/code/claudiofilho/nlp-disaster-tweets-naive-bayes">https://www.kaggle.com/code/claudiofilho/nlp-disaster-tweets-naive-bayes</a></li></ol><h3>Find me:</h3><ol><li><a href="https://github.com/vivekschaurasia?tab=repositories">GitHub</a></li><li><a href="http://www.linkedin.com/in/vivek-chaurasia-567b15197">LinkedIn</a></li><li>Mail : vivekschaurasia@gmail.com</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ac4a45060db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LANL earthquake case study]]></title>
            <link>https://medium.com/@vivekschaurasia/lanl-earthquake-case-study-a28c62fbe2a9?source=rss-3bdb1be656cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a28c62fbe2a9</guid>
            <category><![CDATA[case-study]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[eda]]></category>
            <dc:creator><![CDATA[Vivekschaurasia]]></dc:creator>
            <pubDate>Thu, 13 Oct 2022 10:24:19 GMT</pubDate>
            <atom:updated>2022-10-13T10:24:19.596Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*UlXFfpDyAhwI0KFdREGWbQ.jpeg" /><figcaption><a href="https://www.nbcnews.com/news/world/76-magnitude-earthquake-shakes-papua-new-guinea-rcna47186">https://www.nbcnews.com/news/world/76-magnitude-earthquake-shakes-papua-new-guinea-rcna47186</a></figcaption></figure><p>In this blog, we will do a case study about the LANL earthquake, which is a competition conducted on <a href="https://www.kaggle.com/competitions/LANL-Earthquake-Prediction">Kaggle.com</a>. In this case study, we will predict the time of the next earthquake to happen.</p><h3><strong>Dataset:</strong></h3><p>The dataset was created in a lab where with experiments they created the earthquake and recorded it. <a href="https://www.youtube.com/watch?v=m_dBwwDJ4uo&amp;t=1s">Here</a> is the video of the experiment.</p><ol><li>The data set can be found <a href="https://www.kaggle.com/competitions/LANL-Earthquake-Prediction/data">here</a>.</li><li>This dataset has 8.9GB of training csv file and a test folder with 2624 files, each file containing 150000 rows.</li><li>The training data has two columns (Acoustic data and time to failure).</li></ol><p><strong>a. acoustic_data :</strong> The Seismic Signals which is of datatype integer.</p><p><strong>b. time_to_failure:</strong> The time in seconds for the next laboratory earthquake to happen, this data type is in float.</p><p>4. We also have seg_id. For each seg_id in the test folder, we have to predict a single time_to_failure. The data within the test dataset is continuous, but all the test files do not make a continuous segment like in the training data.</p><h3>Metric:</h3><p>The metrics that can be used here are “<a href="https://en.wikipedia.org/wiki/Mean_squared_error">Mean squared error</a>”, “M<a href="https://en.wikipedia.org/wiki/Mean_absolute_error">ean absolute error</a>” or “<a href="https://en.wikipedia.org/wiki/Coefficient_of_determination">R-squared”</a>. But here we will use MAE (Mean absolute error) to evaluate as submission will be evaluated using MAE in Kaggle.</p><p>MAE is the average of the absolute value of each point of predicted value and actual value. Below is the formula for MAE, where Yi is actual value, Xi is the predicted value and n is total number of values present in the dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/0*dmRtwAO-ElhFM4ke.png" /><figcaption>Formula of MAE</figcaption></figure><h3><strong>Downloading the data from Kaggle:</strong></h3><p>Loading the data from Kaggle to colab is very easy and here I will tell you how you can download the LANL Earthquake Prediction dataset in 2–3 minutes in your colab notebook.</p><p>Step 1: Sign in to your Kaggle account or create a Kaggle account.</p><p>Step 2: Go to the dataset website (<a href="https://www.kaggle.com/competitions/LANL-Earthquake-Prediction/data">https://www.kaggle.com/competitions/LANL-Earthquake-Prediction/data</a>) and accept the competition rules.</p><p>Step 3: After accepting, go to your Kaggle account, Scroll to API section and Click Expire API Token to remove previous tokens if there and then Click on Create New API Token — It will download kaggle.json file on your machine.</p><p>Step 4: Now write the following code to upload the kaggle.json file from your machine to colab server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98797d21002aee6a28948dcef32acce0/href">https://medium.com/media/98797d21002aee6a28948dcef32acce0/href</a></iframe><p>Step 5: Now to download the dataset copy the api command and paste it in the colab’s cell. (kaggle competitions download -c LANL-Earthquake-Prediction). With in a minute “LANL-Earthquake-Prediction.zip” will be downloaded.</p><p>Step 6: Now for unzipping the file copy the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/680b5d4046f35f7f0d542055936c1d31/href">https://medium.com/media/680b5d4046f35f7f0d542055936c1d31/href</a></iframe><p>And now you have downloaded the train.csv file, sample_submission.csv file and test folder.</p><h3><strong>Loading the data and Doing EDA:</strong></h3><p>In the train.csv, we have 629145480 rows and 2 columns. So, instead of taking all the rows we can take 10M rows too. Usually we do this because of computational constraints.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59a0d7375870d9a72635c67cda45200a/href">https://medium.com/media/59a0d7375870d9a72635c67cda45200a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*fDzZMdM7RBDIGW-cSjSslA.jpeg" /><figcaption>output of df.head(2)</figcaption></figure><p>The shape of the data frame is (629145480, 2) and there are no null or Nan values present in the data frame.</p><h3>First Cut approach:</h3><p>This is the basic approach where we will predict with a model without any advance approach. We will add some statistical features and split the dataset into a train and test set. Now we will create a KNN and Random forest model. After creating the models we get train and test errors as 1.6 and 2.3 in KNN and 1.4 and 2.2 in Random forest. This is a good result but both the models are slightly overfitting. To reduce it, we will do some advance featurization like rolling window and create more models.</p><h3>EDA:</h3><p>Exploratory Data Analysis(EDA) plays an important role while creating a model. It is a necessary step to do while creating a model. It helps us to understand the dataset and its distribution. We can perform univariate analysis or multivariate analysis.</p><p>Here, initially since we have only two columns. We will perform univariate analysis on single feature i.e acoustic data and on time to failure column which is target column.</p><h4>EDA on Acoustic data:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*iZ3FNmYSmkPQ4SIqXkzQxA.png" /><figcaption>PDF of Acoustic Data</figcaption></figure><p>Above is the pdf of acoustic data. From the above diagram, it is difficult to know the range of values where most of the data are lying. Here histogram or pdf with some range can help us to know the distribution of the given feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*ZO3KTnwysuJgTEBcSoaBsw.png" /><figcaption>PDF of acoustic data from -50 to 50</figcaption></figure><p>From the above plot, we can clearly see that most of the points lie between -20 to 20. But still there are some points beyond -20 and 20. With help of percentiles we will see the outliers present in the dataset.</p><h4>EDA on Time to failure data:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*codcMWlpm0xlYx8EReVwzg.png" /><figcaption>PDF of Time to failure</figcaption></figure><p>The values range from 0 to 15. There is not much in the above plot.</p><h4>Box plot of acoustic data:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*y-hebe7LQPdMbgoxMnTyRA.png" /><figcaption>Box plot of acoustic data</figcaption></figure><p>From the box plot of acoustic data, we can’t determine much about the 25th, 50th or 75th percentile. So, we have to use percentiles here.</p><h3><strong>Outliers:</strong></h3><p>Outliers can be the problem and here we will find if the outliers are present in our dataset or not. We can detect outliers by the RANSAC method or by observing box plots or by using percentile values. Here we percentile values to detect the outliers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26820254d3c29e559859f3e9e675c192/href">https://medium.com/media/26820254d3c29e559859f3e9e675c192/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*vB7B1qy5tecbxGzefCfBtg.jpeg" /><figcaption>Percentile values from 5 to 100</figcaption></figure><p>Here we can clearly see that some values are very larger and some are very smaller. So, after observing the percentile from 95th to 100th and 0th to 5th, we can state that points smaller than -2 and bigger than 41 are outliers. So, now we create a new data frame which has values of acoustic data ranging from -2 to 41.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5dab4d7850bd422bbc59dc6a9494a31/href">https://medium.com/media/b5dab4d7850bd422bbc59dc6a9494a31/href</a></iframe><h3><strong>Feature Engineering:</strong></h3><p>We only have 1 feature and so we need to create more features like mean, variance etc. These features are statistical features. Here we will create the following features:</p><ol><li>Mean,</li><li>Standard Deviation,</li><li>Min and Max,</li><li>Kurtosis and Skewness</li><li>Absolute Max, Mean, Std,</li><li>Quantiles from 1 to 99</li><li>Rolling Windows</li></ol><p>Here we will create a function which will take a dataframe and return statistical features like Std, Kurtosis, etc and some features using rolling windows like 3_std300 , 3_max300 etc. For more information refer my <a href="https://github.com/vivekschaurasia/Earthquake-Prediction">GitHub code</a>. After this, we will have a total of 101 columns including time_to_failure column. However we have a feature min which has all the value same so that feature is useless. Therefore we will remove that feature. Now we have 100 features.</p><h3><strong>Correlation:</strong></h3><p>After adding the features we will look for correlated features and if we find a correlated feature we will delete that feature. If correlation between two features is greater than 0.5 than features are correlated and we will delete one of those feature. For correlation, we will use Pearson correlation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/175347160e1e1de3dddfc454c25e2205/href">https://medium.com/media/175347160e1e1de3dddfc454c25e2205/href</a></iframe><p>After removing the correlated features, we now only have 34 columns including time_to_failure. We have to find the top 10 features that are usefull for prediction.</p><h3>Top 10 features:</h3><p>For finding the top ten features, we will use an ensemble technique called <a href="https://scikit-learn.org/stable/auto_examples/ensemble/plot_gradient_boosting_regression.html">Gradient boosting regresion</a>. Now we have to separate the dataset in input variable (X) and target variable (y).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/892771062e22072e605d4d8bc8a01071/href">https://medium.com/media/892771062e22072e605d4d8bc8a01071/href</a></iframe><p>After this we will split our dataset into training and test set using the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/338384c8fb7455cc16c4480c0583bdf1/href">https://medium.com/media/338384c8fb7455cc16c4480c0583bdf1/href</a></iframe><p>With the below code, we will fit the train data and find the list of important features.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67f047bbf2d0f3cbf022a0fe9fb24e84/href">https://medium.com/media/67f047bbf2d0f3cbf022a0fe9fb24e84/href</a></iframe><p>Now we have sorted index of all the features. However, this features are in the ascending order, meaning least important features are kept first. So we need last 10 features from sorted_idx.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b83b9b279e5a5060c9e166d64ef0991/href">https://medium.com/media/9b83b9b279e5a5060c9e166d64ef0991/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*Mc8LatZXQZ9NrzT8adsLLA.jpeg" /><figcaption>Output of the above code</figcaption></figure><p>With the above code we will get the top 10 important features and they are:</p><pre>2_Std300, 3_skew80, 2_min80, 3_skew300, 1_skew10, 2_Std80, 3_Mean10, 2_skew10, 2_min300, 2_90th precentile10</pre><p>Now feature engineering is Done and we will save our daraframe into csv file and download it, so that we can import it whenever its needed. Next step is to create a model.</p><h3>Creating a model:</h3><p>First we will import the dataset that we downloaded and now we will split the dataset into separate the dataset in input variable (X) and target variable (y).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2a038440b0d2f974d2b1373a4f09556/href">https://medium.com/media/c2a038440b0d2f974d2b1373a4f09556/href</a></iframe><p>After this step, we have to split the dataset</p><h3>Splitting the dataset:</h3><p>We will split our data into x_train, x_test, y_train and y_test with 10% of data as test data and 90% as training data. It is necessary to do splitting here because our next step is standardizing the dataset and we don’t want to standardized the data when test set is present because this will lead to a problem called leakage. So, to prevent leakage we will first split the data and then standardized it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/338384c8fb7455cc16c4480c0583bdf1/href">https://medium.com/media/338384c8fb7455cc16c4480c0583bdf1/href</a></iframe><h3>Feature Scaling:</h3><p>Here we will transform our dataset using standardization technique. Standardization is a technique where all our values are centered around mean with a unit standard deviation and here mean is 0. I]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*KP9IJsqxrwN2VgkaYDps4Q.png" /><figcaption>Standardization formula</figcaption></figure><p>First we will fit our x_train data that is learn the data and then transform x_train and x_test to standardized x_train and x_test. We won’t use x_test data to fit the model because it will create a data leakage problem as discussed above section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/968fb055c2905e1dfaa6b498f2e728eb/href">https://medium.com/media/968fb055c2905e1dfaa6b498f2e728eb/href</a></iframe><p>Now we have done Standardization above and also we saved the pickel file of StandardScaler on x_tr because in future we will need this.</p><h3>Models:</h3><p>Here we will try different types of algorithms like KNN, Linear regression, random forest etc.</p><p><strong>Linear regression with L2 regularizer:</strong></p><p>For more information on L2 reg, refer <a href="https://towardsdatascience.com/intuitions-on-l1-and-l2-regularisation-235f2db4c261">this</a>.</p><p>Now we will use alpha as a parameter and chose the best alpha with the best score. After doing this, we got alpha = 0.25 as the best alpha. Below is the graph of all the alphas and their respective score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*pwm3-hhWM1eEJ0XEA5TdXA.jpeg" /><figcaption>Graph of all the alpha vs score</figcaption></figure><p>So after using 0.25 as the alpha, we get 2.785, 2.7002 and 2.727 as mean absolute error on train, cross validation and test data set respectively. We can improve our model by using some complex model. The good thing is our model is neither over fitting nor under fitting.</p><p><strong>Knn:</strong></p><p>Now we will use our second model and that is KNN. We will fir our training dataset with k as hyperparameter. Initially, k will range from 1 to 30 with a gap of 2 and we will store all the accuracies of K’s in the list.</p><p>From the below graph, we can see that after k = 15, the difference between train, cross and test accuracies are minimum and they are neither overfitting nor underfitting. So, we will choose k &gt; 10. To choose best K we will use GridSearchCV.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*I6exYrq3k7zCCEGOpkU9qw.jpeg" /><figcaption>KNN parameter tunning</figcaption></figure><p>Now we will use GridSearchCV and to plot the graph of every K with its score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*vqKN_92ZYkxgIJtdBDaDMA.jpeg" /><figcaption>K vs score</figcaption></figure><p>From the graph, the best K we get is k = 25 and after using k = 25, we get 2.414, 2.508 and 2.411 as mean absolute error on train, cross validation and test data set respectively. Knn performed better than Linear regression and it is also neither over fitting nor under fitting. Now we can save our model weights from the below code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc2e1739e60e7a3ad5fd433a2797a70d/href">https://medium.com/media/fc2e1739e60e7a3ad5fd433a2797a70d/href</a></iframe><p><strong>Random forest:</strong></p><p>Now we will use Random forest model with randomizedsearchcv. The hyperparameters here are: n_estimators = [5 , 10, 15, 20, 15, 30 , 40, 50], max_depth = [i for i in range(5 , 25 , 2)], bootstrap = [True , False], min_sample_split = [2, 5 , 10], max_features = [“auto”, “sqrt”] .</p><p>After fitting on training set with cv = 10, we got the best parameters as n_estimators: 50 , min_sample_split = 10, max_features = “sqrt”, max_depth = 9, and bootstrap = True. Below is the learning curve of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*xKv9puntyDeYeqwpGAFuLA.png" /><figcaption>Learning curve of Random forest.</figcaption></figure><p>After fitting our training set with best random forest parameters, we got 1.983 , 2.399 and 2.411 as mean absolute error on train, cross validation and test data set respectively. Till now Random forest has performed better than Knn and Linear regression and it is also neither over fitting nor under fitting. So, now we can save our model weights from the below code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58d1cd9ba54325b27babe749bcf4e9da/href">https://medium.com/media/58d1cd9ba54325b27babe749bcf4e9da/href</a></iframe><p><strong>XGBoost regressor:</strong></p><p>In XGBoost we will use gridsearch hyperparameter to find the best values for our hyperparamter. Here we will only use n_estimators and max_depth with similar values used in random forest. After training the model, we got the best parameter as max_depth = 5 and n_estimators = 50. Below is the learning curve of the model with best parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*Uun8cc26gNDNfnqSdK4TeA.png" /><figcaption>Learning curve of XGBoost Regressor</figcaption></figure><p>After training our train data with best XGBoost parameters, we got 1.95, 2.36 and 2.45 as mean absolute error on train, cross validation and test data set respectively. It is also neither over fitting nor under fitting. So, now we can save our model weights from the below code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6251d8c2367e7e5a7dab95918765c8e/href">https://medium.com/media/c6251d8c2367e7e5a7dab95918765c8e/href</a></iframe><p>Now since we have weights of three saved model, we can use them directly whenever we want instead of training them again and again.</p><p><strong>Final Step:</strong></p><p>In the final step we will take the three best models and they are Knn, Random forest and XGBoost and we will take the average of all the values predicted by these models. In the final result we can see that This gives the better result in test dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25414a0c36ee2c1b446a6277e0a3070e/href">https://medium.com/media/25414a0c36ee2c1b446a6277e0a3070e/href</a></iframe><p>The final result:</p><pre>+-------------------+--------------+-----------+-------------+<br>|       Model       | MAE on train | MAE on cv | MAE on Test |<br>+-------------------+--------------+-----------+-------------+<br>| Linear Regression |     2.78     |    2.70   |     2.72    |<br>|        KNN        |     2.41     |    2.50   |     2.48    |<br>|   Random Forest   |     1.98     |    2.39   |     2.41    |<br>|    XGBRegressor   |     1.95     |    2.36   |     2.42    |<br>| Averaging 3 model |     2.08     |    2.40   |     2.39    |<br>+-------------------+--------------+-----------+-------------+</pre><h3><strong>Final Notebook:</strong></h3><p>Here in the final notebook, we will import all the saved “pkl” files and create a pipeline that will make a final prediction. We will give raw data as input and then create a function which will take raw data and return the predicted value. The code can be found in my <a href="https://github.com/vivekschaurasia/Earthquake-Prediction">GitHub account</a>.</p><h3>Kaggle Competition:</h3><p>After submitting the result in Kaggle, my score is 2.23300 and private score is 2.430. Looking at the private scoreboard, my score stands in top 5 percent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXhgchbm7iACo-jZWaSUFA.jpeg" /><figcaption>Kaggle score.</figcaption></figure><h3>Future works:</h3><p>This problem can also be solved using Deep learning. RNN can be used here since our data is time series and maybe we can get better results in deep learning than Machine learning.</p><h3>Conclusion:</h3><p>With machine learning we got a good score and the statistical features helped us to get better results with it. We can conclude that feature engineering is an important aspect and plays an important role in machine learning.</p><h3><strong>Reference:</strong></h3><ol><li><a href="https://www.kaggle.com/competitions/LANL-Earthquake-Prediction">https://www.kaggle.com/competitions/LANL-Earthquake-Prediction</a></li><li><a href="https://medium.com/@ph_singer/1st-place-in-kaggle-lanl-earthquake-prediction-competition-15a1137c2457">https://medium.com/@ph_singer/1st-place-in-kaggle-lanl-earthquake-prediction-competition-15a1137c2457</a></li><li><a href="https://www.mdpi.com/1424-8220/20/15/4228">https://www.mdpi.com/1424-8220/20/15/4228</a></li><li><a href="https://www.kaggle.com/code/braindeadcoder/understanding-and-preparing-seismic-data/notebook">https://www.kaggle.com/code/braindeadcoder/understanding-and-preparing-seismic-data/notebook</a></li></ol><h3>Find me:</h3><ol><li><a href="https://github.com/vivekschaurasia?tab=repositories">GitHub</a></li><li><a href="http://www.linkedin.com/in/vivek-chaurasia-567b15197">LinkedIn</a></li><li>Mail : vivekschaurasia@gmail.com</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a28c62fbe2a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>