<?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 Praveen Raj on Medium]]></title>
        <description><![CDATA[Stories by Praveen Raj on Medium]]></description>
        <link>https://medium.com/@praveenraj.gowd?source=rss-171feb4841e8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QI7WiPKgr4yh0f-V</url>
            <title>Stories by Praveen Raj on Medium</title>
            <link>https://medium.com/@praveenraj.gowd?source=rss-171feb4841e8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 04:23:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@praveenraj.gowd/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[Claude Just Changed Everything: Claude Code, Co-work & Security]]></title>
            <link>https://medium.com/@praveenraj.gowd/claude-just-changed-everything-claude-code-co-work-security-817e273a6747?source=rss-171feb4841e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/817e273a6747</guid>
            <dc:creator><![CDATA[Praveen Raj]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 04:54:45 GMT</pubDate>
            <atom:updated>2026-02-26T04:54:45.536Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/990/0*aCwwzGgIgoaHNDPp.jpg" /></figure><blockquote>Anthropic’s bold new features aren’t just upgrades — they’re a full-scale transformation of how humans and AI collaborate at work.</blockquote><p>If you’ve been paying attention to the AI space lately, you already know that <strong>Anthropic’s Claude</strong> has been on an absolute tear. But the last few weeks have seen announcements so significant that even Wall Street couldn’t ignore them — and the stock market reactions have been nothing short of explosive.</p><p>From <strong>Claude Code</strong> revolutionizing software engineering to <strong>Claude Cowork</strong> redefining knowledge work, and the newly launched <strong>Claude Code Security</strong> sending cybersecurity stocks plummeting, Anthropic is sending a clear signal: the age of AI copilots is over. The age of <strong>AI collaborators</strong> has begun.</p><p>Let’s break it all down.</p><h3>⚡ Claude Code: The AI Coding Tool That Shook the Enterprise</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qlM_Zbe8BLdNor0L.jpeg" /></figure><p>When Anthropic launched <strong>Claude Code</strong>, it wasn’t just another code completion plugin. It was a <strong>terminal-native, agentic AI assistant</strong> that understands your <em>entire codebase</em> — not just the file you’re working in.</p><p>Here’s what sets Claude Code apart from every other AI coding tool on the market:</p><p><strong>🔧 It works where you work.</strong> Whether you’re in your terminal, VS Code, or a standalone desktop app, Claude Code integrates seamlessly. You can even hand off a session from your laptop to your phone and back again.</p><p><strong>🤖 True autonomy, not just suggestions.</strong> Claude Code doesn’t just autocomplete lines — it reads your repository, plans a multi-step approach, writes across multiple files, runs tests, and can even open pull requests automatically.</p><p><strong>📊 Real-world results that speak for themselves.</strong> Spotify integrated Claude Code into its engineering workflow and the results were staggering: a 90% reduction in engineering time, over 650 AI-generated code changes shipped per month, and roughly half of all Spotify updates now flowing through the system.</p><p><em>AI coding assistant, Claude Code agentic AI, AI for developers 2026, automated pull requests, AI pair programmer, Anthropic Claude Code</em></p><h3>🏢 Claude Cowork: “Claude Code for the Rest of Us”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gHd87TGf7OL57kRg.png" /></figure><p>If Claude Code is built for engineers, <strong>Claude Cowork</strong> is built for everyone else — and it might be the most consequential product Anthropic has ever shipped.</p><p>Launched in January 2026, Cowork is Anthropic’s answer to a question enterprises have been asking for years: <em>“How do we give our knowledge workers the same AI superpowers that developers have?”</em></p><h3>What Makes Cowork Different?</h3><p>Instead of using Claude as a separate chatbot, it can now live inside enterprise software tools, pulling context and data without users needing to leave the window they’re working in. Think about what that means in practice:</p><ul><li>A finance analyst can ask Claude to model private equity scenarios — without leaving their spreadsheet</li><li>An HR manager can generate job descriptions and offer letters from within their existing HR platform</li><li>A designer can produce a full creative brief while browsing their usual project management tools</li><li>An operations lead can summarize vendor proposals without switching apps</li></ul><p>The idea is to make it so that Claude could, for example, use spreadsheet data to create slide presentations the way a person would.</p><p>Anthropic’s Head of Americas, Kate Jensen, described it powerfully at the company’s recent enterprise event: “In 2025 Claude transformed how developers work, and in 2026 it will do the same for knowledge work. The magic behind Claude Code is simple. When you can delegate hard challenges, you can focus on the work that actually matters. Cowork brings that same power to knowledge workers.”</p><h3>The “Thinking Divide” — Are You on the Right Side?</h3><p>Anthropic coined a phrase that every business leader should internalize: <strong>“the thinking divide.”</strong> This is the growing gap between organizations that embed AI across employees, processes, and products simultaneously, and those that treat it as a point solution.</p><p>The companies ahead of this curve will compound their advantage. Those behind it will find it increasingly difficult to catch up.</p><p><em>Claude Cowork enterprise AI, AI knowledge worker tool, AI for office productivity 2026, enterprise AI agent, AI automation for business, Anthropic Cowork plugins</em></p><h3>🔐 Claude Code Security: The Feature That Rattled Cybersecurity Markets</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ESxoGM5pVWRvKQGm.jpg" /></figure><p>On February 20, 2026, Anthropic dropped a bombshell on the cybersecurity industry.</p><p><strong>Claude Code Security</strong> — a new capability embedded directly in Claude Code — uses advanced AI reasoning to scan codebases for vulnerabilities and suggest patches. The reaction was immediate: the Global X Cybersecurity ETF fell 4.9% to its lowest closing position since 2023. CrowdStrike dropped 8%, Cloudflare fell 8.1%, SailPoint declined 9.4%, and Okta fell 9.2%.</p><p>Why the panic? Because this isn’t your typical static analysis tool.</p><h3>What Claude Code Security Actually Does</h3><p>Traditional vulnerability scanners match code against known bad patterns. They’re useful, but limited. Claude Code Security is fundamentally different — it <em>reasons</em> about your code the way a senior security engineer would.</p><p>Claude Code Security focuses on high-severity vulnerabilities including memory corruption, injection flaws, authentication bypasses, and complex logic errors that pattern-matching tools typically miss. It’s particularly effective at finding context-dependent vulnerabilities that require understanding code across multiple files.</p><p>The proof is in the results: Anthropic pointed its most advanced AI model, Claude Opus 4.6, at production open-source codebases and found more than 500 high-severity vulnerabilities that had survived decades of expert review and millions of hours of fuzzing.</p><h3>What This Means for the Security Industry</h3><p>Let’s be clear about what Claude Code Security <em>is</em> and what it <em>isn’t</em>. As CrowdStrike CEO George Kurtz correctly noted, Claude Code Security is a code vulnerability scanner and patcher that competes more directly with static analysis tools like Snyk, Checkmarx, or Veracode than with endpoint detection platforms.</p><p>This is a tool for the <strong>development phase</strong> — finding bugs before they ship. It’s not a replacement for runtime security, threat detection, or incident response.</p><p>But here’s the important nuance: the implications for <strong>AppSec</strong> (application security) teams are massive. AI is now capable of finding vulnerabilities that took expert researchers years to discover. That changes the economics of software security forever.</p><p><em>Claude Code Security, AI vulnerability scanner, AppSec AI 2026, automated security patch, AI cybersecurity tool, Anthropic security feature, zero-day vulnerability detection AI</em></p><h3>🌊 The Bigger Picture: What All of This Means</h3><p>Anthropic isn’t shipping features — it’s building an entirely new category of enterprise software.</p><p>Anthropic’s boldest enterprise push yet includes rolling out private plug-in marketplaces, deep integrations, and AI agent tools that are reshaping corporate adoption. Companies like Salesforce, DocuSign, LegalZoom, Thomson Reuters, and FactSet are already integrated as partners.</p><p>The message is clear: Claude isn’t trying to be a better chatbot. It’s trying to be a <strong>virtual collaborator</strong> — one that understands your company’s data, fits into your existing workflows, and can autonomously execute complex, multi-step tasks.</p><h3>Are You Ready for the AI Collaboration Era?</h3><p>Here are the three things every professional and organization should take away from Anthropic’s recent announcements:</p><ol><li><strong>Developers should explore Claude Code now.</strong> The productivity gains are real and compounding. If you’re not using AI-native development tools in 2026, you’re already falling behind.</li><li><strong>Knowledge workers should watch Claude Cowork closely.</strong> The plugin ecosystem is still growing, but the trajectory is clear — AI is coming for knowledge work the same way it came for coding.</li><li><strong>Security teams need to adapt, not panic.</strong> Claude Code Security is a powerful addition to your arsenal, not a replacement for your entire stack. The organizations that will win are those that layer AI-native scanning with their existing security workflows.</li></ol><h3>💡 Final Thoughts</h3><p>The AI revolution isn’t coming — it’s here, and it’s moving faster than most organizations can track. <strong>Claude Code, Cowork, and Claude Code Security</strong> represent three distinct but interconnected fronts in Anthropic’s push to make AI genuinely useful across every layer of an enterprise.</p><p>Whether you’re a developer, a knowledge worker, a CISO, or a business leader, these tools have implications for your work <em>right now</em>.</p><p>The question isn’t whether to engage with this new era of AI collaboration. The question is whether you’ll be early enough to shape how it works in your organization — or late enough to have it shaped for you.</p><p><em>👋 Found this useful? Follow me for more deep-dives on AI tools, enterprise technology, and the future of work.</em></p><p><em>Drop a comment below with your thoughts on Anthropic’s latest moves — I’d love to hear how your team is thinking about AI adoption in 2026.</em></p><p><strong>#ArtificialIntelligence #ClaudeAI #Anthropic #ClaudeCode #Cowork #CyberSecurity #AISecurity #EnterpriseAI #AITools #FutureOfWork #MachineLearning #TechNews #SoftwareDevelopment #AIAgents #Productivity #DigitalTransformation #DevTools #AppSec #VulnerabilityManagement #AIInnovation #TechTrends2026 #GenerativeAI #LLM #AIForBusiness #WorkplaceAI #KnowledgeWork #ClaudeCowork #ClaudeCodeSecurity #Anthropic2026 #AIRevolution</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=817e273a6747" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Manus AI?: The First General AI Agent]]></title>
            <link>https://medium.com/@praveenraj.gowd/what-is-manus-ai-the-first-general-ai-agent-e034fb6a165b?source=rss-171feb4841e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e034fb6a165b</guid>
            <category><![CDATA[china]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Praveen Raj]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 04:04:04 GMT</pubDate>
            <atom:updated>2025-03-26T04:04:04.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jzBdEicOIyogZNiU.png" /></figure><p>China has been on a roll since the beginning of 2025. Earlier DeepSeek-R1, than Wan2.1 and now Manus AI</p><blockquote><em>Manus AI is claimed to be the best Agentic AI system so far</em></blockquote><p>Manus AI, developed by <strong>Monica.im</strong>, is a revolutionary general AI agent designed to autonomously execute complex tasks across multiple domains. Unlike traditional AI assistants, it doesn’t just assist — it <strong>plans, executes, and completes tasks independently</strong>.</p><h3>Key Features of Manus AI</h3><p><strong>Autonomous Task Execution</strong><br>Manus AI can independently handle complex tasks from start to finish. Whether it’s creating a <strong>detailed travel itinerary</strong>, generating <strong>in-depth analysis reports</strong>, or even <strong>developing a web game</strong>, it requires minimal human intervention.</p><p><strong>Multi-Modal Capabilities</strong><br>It processes and generates various types of data, including <strong>text, images, and code</strong>, making it a versatile tool for numerous applications.</p><p><strong>Advanced Tool Integration</strong><br>Manus seamlessly connects with external tools like <strong>web browsers, code editors, and databases</strong>, allowing it to automate workflows efficiently.</p><p><strong>Adaptive Learning &amp; Optimization</strong><br>The system continuously learns from interactions and optimizes its responses, ensuring <strong>personalized and efficient outputs</strong>.</p><p><strong>User-Friendly Interface</strong><br>No technical expertise is required — just provide simple instructions, and Manus takes care of the rest.</p><h3>Getting Started with Manus AI</h3><blockquote><a href="https://manus.im/?source=post_page-----0735473a5868---------------------------------------">manus.im</a></blockquote><p>Follow these steps to access Manus AI:</p><p><strong>Visit the Official Website</strong><br>Head to <a href="https://manus.im/">manus.im</a> and click <strong>“Get Started”</strong> in the top right corner.</p><p><strong>Log In with Google or Apple</strong><br>Use your Google or Apple account to sign in.</p><p><strong>Apply for Access</strong><br>Click <strong>“Apply for Access”</strong> to join the waitlist.</p><p><strong>Wait for Your Invitation</strong><br>Due to high demand, access is granted via invitation codes sent through email. Be patient while you wait for yours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xNzylmu3Af4JJTB3.png" /></figure><h3>Example Use Case: Personalized Travel Planning</h3><h3>Scenario</h3><p>You’re planning a trip to <strong>Japan in April</strong> and want a customized itinerary. Instead of researching for hours, you simply provide Manus AI with:</p><ul><li><strong>Your budget</strong></li><li><strong>Interests</strong> (e.g., historical sites, cultural experiences)</li><li><strong>Specific requirements</strong> (e.g., preferred pace, must-visit locations)</li></ul><h3>How Manus AI Helps</h3><p>Manus processes this information and generates a <strong>personalized 7-day Japan itinerary</strong>, including:<br>✔ <strong>Daily schedules</strong> with recommended activities<br>✔ <strong>Map navigation</strong> for seamless travel<br>✔ <strong>A Japanese phrasebook</strong> for easy communication<br>✔ <strong>An HTML travel guide</strong> for offline access</p><p>By integrating vast amounts of information, Manus ensures a hassle-free, well-organized trip — so you can <strong>focus on enjoying Japan, not planning it</strong>.</p><h3>Why Manus AI is a Game-Changer</h3><p>Manus AI sets itself apart from other AI tools in several ways:</p><h3>1. Full Autonomy</h3><p>Most AI systems require <strong>constant human input</strong> — Manus does not. It <strong>completes tasks end-to-end</strong> without manual intervention.</p><h3>2. State-of-the-Art Performance</h3><p>Manus has <strong>outperformed competitors</strong> on the <strong>GAIA benchmark test</strong>, proving its superiority in <strong>task planning and execution</strong>.</p><h3>3. Unmatched Versatility</h3><p>From <strong>travel planning</strong> and <strong>financial analysis</strong> to <strong>education and content creation</strong>, Manus adapts to various industries and use cases.</p><h3>4. Market Impact</h3><p>Since its announcement, <strong>China’s AI sector has seen a surge in investment</strong>, with increased confidence in the future of <strong>autonomous AI agents</strong>.</p><h3>5. Productivity Redefined</h3><p>By automating tedious tasks, Manus <strong>boosts efficiency</strong> and transforms the way people work, making it a <strong>powerful tool for businesses and individuals alike</strong>.</p><h3>Manus AI vs OpenAI’s Deep-Research</h3><ul><li><strong>Full Autonomy</strong> — Manus AI operates independently in the cloud, handling tasks like resume screening, real estate analysis, and financial evaluation without user input. In contrast, Deep Research requires more user interaction and guidance.</li><li><strong>Superior Benchmark Performance</strong> — Manus AI has outperformed Deep Research on the <strong>GAIA benchmark</strong>, excelling in task success rate, decision-making efficiency, and learning adaptability.</li><li><strong>Cost Efficiency</strong> — With a lower cost per task, Manus AI provides a more budget-friendly and scalable AI solution.</li><li><strong>Transparency &amp; Explainability</strong> — Designed for clear decision-making, Manus AI adheres to ethical and regulatory standards while maintaining effectiveness.</li><li><strong>Versatility &amp; Adaptability</strong> — Seamlessly integrates into various industries and workflows, handling complex, domain-specific tasks with ease.</li><li><strong>Open-Source Future</strong> — Plans to open-source key components, fostering global collaboration and expanding its capabilities.</li></ul><h3>Final Thoughts</h3><p>Manus AI is <strong>not just another AI assistant</strong> — it’s a fully autonomous system capable of <strong>executing real-world tasks with minimal supervision</strong>. As AI continues to evolve, Manus stands out as a <strong>true pioneer</strong> in the field of autonomous intelligence. Let’s see how it pans out when released in full throttle</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e034fb6a165b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Future of AI Agents in 2025]]></title>
            <link>https://medium.com/@praveenraj.gowd/the-future-of-ai-agents-in-2025-2d22041a650e?source=rss-171feb4841e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d22041a650e</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[aritificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Praveen Raj]]></dc:creator>
            <pubDate>Thu, 23 Jan 2025 07:12:06 GMT</pubDate>
            <atom:updated>2025-01-23T07:12:06.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/959/0*Hpfoqhzfg3Svlgvg" /></figure><h3>Introduction</h3><p>Artificial Intelligence (AI) agents have come a long way since their inception, evolving from simple rule-based systems to complex, autonomous entities capable of learning and decision-making. As we approach 2025, AI agents are poised to revolutionize various sectors, from healthcare to finance, by enhancing productivity, efficiency, and innovation. This blog explores the future of AI agents, focusing on three main themes: collaboration, regulation, and technological advancements. We will delve into how these intelligent systems are reshaping industries, the challenges they face, and the exciting possibilities they hold for the future.</p><h3>The Rise of Collaborative AI Agents</h3><h4>Definition and Explanation of Collaborative AI Systems</h4><p>Collaborative AI systems represent a paradigm shift in how AI agents operate, moving from isolated functionalities to interconnected networks of specialized agents working together. These systems are designed to leverage the strengths of multiple AI agents, each with distinct expertise, to tackle complex problems. For instance, a Virtual Lab might feature a professor AI agent leading a team of AI scientist agents, such as an AI chemist and an AI biologist, to conduct advanced research. This collaborative approach not only enhances the capabilities of individual agents but also fosters innovation by enabling them to work synergistically.</p><h4>Benefits of Collaborative AI in Research and Development</h4><p>The integration of collaborative AI systems in research and development offers numerous benefits. By combining the expertise of various AI agents, these systems can accelerate the pace of scientific discovery and innovation. For example, in scientific research, AI agents can analyze vast datasets, identify patterns, and generate hypotheses, significantly enhancing productivity. According to the <a href="https://hai.stanford.edu/news/predictions-ai-2025-collaborative-agents-ai-skepticism-and-new-risks">Stanford Institute for Human-Centered AI</a>, collaborative AI systems are expected to play a crucial role in advancing research methodologies and outcomes.</p><h4>Challenges and Solutions in Implementing Collaborative AI</h4><p>Despite their potential, implementing collaborative AI systems presents several challenges. These include technical issues such as interoperability between different AI agents and ethical concerns related to data privacy and security. To address these challenges, organizations must adopt strategies that integrate AI agents into existing workflows seamlessly. This involves developing standardized protocols for communication between agents and ensuring robust data governance frameworks to protect sensitive information.</p><h4>Future Outlook on Collaborative AI Agents</h4><p>Looking ahead, the future of collaborative AI agents appears promising. As technology continues to advance, we can expect increased human-AI collaboration in solving complex problems. This will likely lead to the development of more sophisticated AI systems capable of handling intricate tasks with minimal human intervention. The potential for collaborative AI to transform industries is immense, and its impact will be felt across various sectors, from healthcare to manufacturing.</p><h3>Technological Advancements and AI Agents</h3><h4>Overview of Technological Advancements Driving AI Agent Development</h4><p>Technological advancements are the driving force behind the evolution of AI agents. Innovations in machine learning, natural language processing, and computer vision have enabled the creation of self-learning systems that require less human intervention. These systems can adapt to new information and environments, making them more efficient and effective in performing tasks. An infographic on the evolution of AI technology can provide a visual representation of these advancements.</p><h4>Role of Smaller Language Models in Enhancing AI Agent Capabilities</h4><p>Smaller language models are playing a crucial role in enhancing the capabilities of AI agents. These models are designed to process and understand human language more efficiently, enabling AI agents to provide personalized experiences in customer service and other applications. According to <a href="https://www.forbes.com/sites/torconstantino/2024/12/31/top-5-ai-predictions-from-experts-in-2025/">Forbes</a>, the use of smaller language models is expected to grow, allowing AI agents to deliver more accurate and context-aware responses.</p><h4>Open-Source AI Models and Their Impact on AI Agent Accessibility</h4><p>The rise of open-source AI models has democratized access to advanced AI technologies, allowing businesses and developers to leverage these tools without significant financial investment. An example of this trend is the Deepseek model, which pushes the boundaries of performance and affordability. By utilizing open-source AI, businesses can enhance their operations and develop innovative solutions tailored to their specific needs.</p><h4>Future Trends in AI Agent Technology</h4><p>As we look to the future, several trends are expected to shape the development of AI agent technology. One such trend is the integration of video analysis capabilities, enabling AI agents to provide real-time assistance in various applications. This advancement will open new possibilities for AI agents in fields such as security, healthcare, and customer service, where real-time data processing is crucial.</p><h3>Regulatory and Ethical Considerations</h3><h4>Overview of Regulatory Challenges Facing AI Agents</h4><p>The rapid advancement of AI technology has raised significant regulatory challenges. Governments and regulatory bodies are grappling with how to manage the deployment of AI agents while ensuring public safety and privacy. Anticipated regulatory crackdowns may focus on issues such as data protection, algorithmic transparency, and accountability. A chart of the AI regulatory landscape can provide a visual overview of these challenges.</p><h4>Ethical Implications of AI Agent Deployment</h4><p>The deployment of AI agents also raises ethical concerns, particularly in sensitive areas such as healthcare. AI agents can process vast amounts of personal data, leading to potential privacy violations if not managed properly. According to <a href="https://techstartups.com/2025/01/01/top-15-ai-trends-for-2025-expert-predictions-you-need-to-know/">Tech Startups</a>, addressing these ethical implications is crucial to ensuring the responsible use of AI technology.</p><h4>Strategies for Ethical AI Agent Development</h4><p>To develop ethical AI agents, organizations must adopt best practices that prioritize transparency, fairness, and accountability. This includes implementing robust data governance frameworks, conducting regular audits of AI systems, and ensuring that AI agents are designed to operate within ethical boundaries. By adhering to these principles, businesses can build trust with their stakeholders and mitigate potential risks associated with AI deployment.</p><h3>Future Outlook on AI Regulation and Ethics</h3><p>The future of AI regulation and ethics will likely see increased focus on AI safety and national security. As AI agents become more integrated into critical infrastructure and decision-making processes, ensuring their reliability and security will be paramount. Policymakers and industry leaders must work together to establish comprehensive regulatory frameworks that balance innovation with public safety.</p><h3>Conclusion</h3><p>In conclusion, AI agents are set to play a transformative role in shaping the future of various industries by 2025. From collaborative AI systems enhancing research and development to technological advancements driving innovation, the potential of AI agents is immense. However, addressing regulatory and ethical challenges will be crucial to ensuring their responsible deployment. As businesses and individuals prepare for AI-driven changes, embracing these intelligent systems can unlock new opportunities and drive progress across sectors.</p><h4>References</h4><ul><li><a href="https://hai.stanford.edu/news/predictions-ai-2025-collaborative-agents-ai-skepticism-and-new-risks">Stanford Institute for Human-Centered AI</a></li><li><a href="https://www.forbes.com/sites/torconstantino/2024/12/31/top-5-ai-predictions-from-experts-in-2025/">Forbes</a></li><li><a href="https://techstartups.com/2025/01/01/top-15-ai-trends-for-2025-expert-predictions-you-need-to-know/">Tech Startups</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d22041a650e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphRAG — Full Guide]]></title>
            <link>https://medium.com/@praveenraj.gowd/graphrag-full-guide-b3d065aac3a2?source=rss-171feb4841e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3d065aac3a2</guid>
            <category><![CDATA[retrieval-augmented]]></category>
            <dc:creator><![CDATA[Praveen Raj]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 14:53:51 GMT</pubDate>
            <atom:updated>2024-09-18T14:53:51.702Z</atom:updated>
            <content:encoded><![CDATA[<h3>GraphRAG — Full Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*0GJrASvstep_hePz" /></figure><h3>What is RAG and KnowledgeGraph?</h3><p>One of the most exciting applications of Generative AI and LLMs is Retrieval-Augmented Generation (RAG), which lets you interact with external documents like PDFs, text files, and YouTube videos.</p><h4>1. How RAG works?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BkKNtYi6lzyIxxg-.png" /></figure><p>RAG takes a user’s query and:</p><blockquote><strong><em>- Searches</em></strong><em> a vector database (prepared using external documents) for relevant information using vector similarity.</em></blockquote><blockquote><strong><em>- Selects</em></strong><em> the top relevant documents.</em></blockquote><blockquote><strong><em>- Extracts</em></strong><em> useful content.</em></blockquote><blockquote><strong><em>- Combines</em></strong><em> this content with an LLM to generate an answer.</em></blockquote><h4>2. What is a Knowledge Graph?</h4><p>A knowledge graph is a <strong>structured representation of information</strong>, capturing entities, their attributes, and relationships. It models complex data and highlights connections within a domain Some key components of a Knowledge Graph are:</p><blockquote><strong><em>Entities</em></strong><em>: The fundamental units of a knowledge graph, representing real-world objects, concepts, or things (e.g., “Albert Einstein,” “Theory of Relativity,” “University”).</em></blockquote><blockquote><strong><em>Attributes</em></strong><em>: Properties or characteristics of entities (e.g., “Albert Einstein” has an attribute “birthdate” with the value “March 14, 1879”).</em></blockquote><blockquote><strong><em>Relationships</em></strong><em>: Connections between entities that describe how they are related to each other (e.g., “Albert Einstein” is related to “Theory of Relativity” by the relationship “developed”).</em></blockquote><blockquote><strong><em>Nodes and Edges</em></strong><em>: In a graphical representation, entities are nodes, and relationships are edges connecting these nodes.</em></blockquote><p>Consider a simple knowledge graph about scientific discoveries:</p><ol><li><strong>Entities</strong>: “Albert Einstein,” “Theory of Relativity,” “Speed of Light,” “Photoelectric Effect”</li><li><strong>Attributes</strong>: “Albert Einstein” (birthdate: “March 14, 1879”), “Theory of Relativity” (published: “1905”)</li><li><strong>Relationships</strong>:</li></ol><ul><li>“Albert Einstein” <strong>developed</strong> “Theory of Relativity”</li><li>“Theory of Relativity” <strong>relates to</strong> the “Speed of Light”</li><li>“Albert Einstein” <strong>proposed</strong> the “Photoelectric Effect”</li></ul><p>The basic RAG implementation has a serious issue. Consider this example:</p><blockquote><em>Suppose a company has a large collection of internal documents, including research papers, technical reports, emails, and meeting notes.</em></blockquote><blockquote><em>The goal is to answer the question: “What are the recent advancements in our AI research department?”</em></blockquote><p><strong>Retrieval</strong>:</p><blockquote><em>Searches the document collection for terms like </em><strong><em>“recent advancements”</em></strong><em> and </em><strong><em>“AI research department.”</em></strong></blockquote><blockquote><em>Retrieves the top documents based on vector similarity (e.g., documents containing similar phrases).</em></blockquote><p><strong>Response</strong>:</p><blockquote><em>Lists several documents or passages that mention</em><strong><em> advancements in AI research.</em></strong></blockquote><blockquote><em>Struggles to connect insights across different documents, often presenting isolated pieces of information without synthesis.</em></blockquote><p>The final output may retrieve these sentences:</p><ul><li><strong><em>Document 1:</em></strong><em> “Our team has recently developed a new AI model for natural language processing.”</em></li><li><strong><em>Document 2:</em></strong><em> “In the past quarter, we made significant progress in AI-based image recognition.”</em></li><li><strong><em>Document 3:</em></strong><em> “AI Advancements are at a rapid pace”</em></li></ul><p><strong>As you must have noticed, this approach misses on :</strong></p><ul><li><strong>Connecting the Dots</strong>: Might not link related advancements spread across the document but not directly mentioned. Also, it is very much driven by text similarity even if the sentence is a filler text (3rd output)</li><li><strong>Holistic Understanding</strong>: Might miss the overarching trends or themes because it focuses on similar phrases rather than understanding the context.</li></ul><h3>GraphRAG</h3><p>Graph RAG, as mentioned earlier, <strong>uses KnowledgeGraphs instead of Vector DBs for information retrieval</strong>, hence the output is more wholesome and meaningful compared to baseline RAG.</p><p><strong>How GraphRAG works?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6kA0nteDkBAXQ_Po.png" /></figure><ul><li><em>GraphRAG uses an LLM to automatically </em><strong><em>extract a rich knowledge graph</em></strong><em> from a collection of text documents.</em></li><li><em>The knowledge graph captures the </em><strong><em>semantic structure</em></strong><em> of the data, </em><strong><em>detecting “communities</em></strong><em>” of densely connected nodes at different levels of granularity.</em></li><li><em>These community summaries provide an overview of the dataset, allowing the system to </em><strong><em>answer global queries </em></strong><em>that would be difficult for naive RAG approaches.</em></li><li><em>When answering a user’s question, GraphRAG </em><strong><em>retrieves the most relevant information</em></strong><em> from the knowledge graph and uses it to condition the LLM’s response, improving accuracy and reducing hallucinations.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tdxjQbMcZvF-NxOA.png" /></figure><h3>Step 1: Knowledge Graph Creation</h3><h4>1. Data Collection:</h4><p>Gather a large corpus of text data containing the information needed for the knowledge graph. This could include articles, books, research papers, etc. This is plain text</p><h4>2. Entity and Relation Extraction:</h4><p><strong><em>Entity Extraction</em></strong><em>: Use LLMs and NER tools to identify and extract entities (e.g., people, places, events) from the text. For this, SOTA LLMs are a must else you may face quality issues in your results.</em></p><p><strong><em>Relation Extraction</em></strong><em>: Determine relationships between these entities using LLMs and rule-based systems to extract meaningful connections.</em></p><p>Now, as we have all the ingredients to build a graph database, let’s construct our Graph</p><h4>3. Graph Construction:</h4><p>Use the above extractions to create a graph object with the following details (Neo4j can be helpful):</p><blockquote><strong><em>Nodes</em></strong><em>: Represent extracted entities as nodes in the graph.</em></blockquote><blockquote><strong><em>Edges</em></strong><em>: Represent relationships between entities as edges connecting the nodes.</em></blockquote><blockquote><strong><em>Attributes</em></strong><em>: Add attributes to nodes and edges to store additional information, such as type of entity, type of relationship, and context. They are also extracted while extracting entities</em></blockquote><h4>4. Graph Storage:</h4><p>Store the constructed graph in a graph database (e.g., Neo4j), which supports efficient querying and manipulation of graph structures.</p><h4>Step 2: Community Summaries Generation</h4><h4>1. Community Detection:</h4><p>Use hierarchical community detection algorithms to identify clusters or communities within the graph.</p><blockquote><strong><em>Notes:</em></strong><em> Communities are groups of nodes (entities) that are densely connected with each other but sparsely connected with other nodes.</em></blockquote><h4>2. Summary Extraction:</h4><blockquote><em>Identify central nodes (entities with high connectivity or importance within the community).</em></blockquote><ul><li><em>Aggregate relevant information and relationships associated with these central nodes.</em></li><li><em>Summarize the extracted information to generate community summaries using LLMs.</em></li></ul><h3>Step 3: Retrieval in GraphRAG</h3><h4>1. Query Processing:</h4><p>Process the user query to identify key entities and relationships relevant to the query. Again LLMs will be used to identify entities and relationships of interest from user query</p><h4>2. Graph-Based Retrieval:</h4><blockquote><strong><em>Subgraph Extraction</em></strong><em>: Extract a subgraph from the knowledge graph that contains the entities and relationships relevant to the query. This subgraph includes nodes and edges directly connected to the key entities mentioned in the query.</em></blockquote><blockquote><strong><em>Context Expansion</em></strong><em>: Expand the context by including additional nodes and edges closely related to the subgraph, providing a richer context for retrieval.How?</em></blockquote><p>This can be done in multiple ways. Either extract all the nodes to which the subgraph entities have a path or Extract the entire community or Extract nodes at a distance &lt; X from the subgraph nodes where X is a distance threshold or using other Relationship/Link prediction Graph algorithms</p><h4>3. Information Aggregation:</h4><blockquote><em>Collect relevant facts and relationships from the nodes and edges in the subgraph using Graph Analytics</em></blockquote><blockquote><em>Summarize the collected information to address the query effectively using LLMs</em></blockquote><h4>4. Response Generation:</h4><p>Generate a natural language response based on the aggregated information. This response leverages the rich context provided by the subgraph to deliver a more accurate and comprehensive answer.</p><blockquote><em>Example Workflow</em></blockquote><ol><li><strong>Knowledge Graph Creation</strong>:</li></ol><blockquote><em>Process a large corpus of scientific literature to extract entities such as “protein”, “gene”, and “disease”, and relationships like “interacts with” and “causes”.</em></blockquote><blockquote><em>Build a knowledge graph where nodes represent proteins, genes, and diseases, and edges represent their interactions and causal relationships.</em></blockquote><p><strong>2. Community Summaries Generation</strong>:</p><blockquote><em>Analyze the graph using hierarchical community detection algorithms to identify clusters of closely related proteins, genes, and diseases.</em></blockquote><blockquote><em>For each cluster, identify central nodes (e.g., key proteins) and summarize their interactions and effects to provide an overview of the cluster.</em></blockquote><p><strong>3. Retrieval in GraphRAG</strong>:</p><blockquote><em>Process a user query about the relationship between a specific protein and a disease.</em></blockquote><blockquote><em>Extract a subgraph containing the queried protein, the disease, and related entities.</em></blockquote><blockquote><em>Include additional related entities and relationships to expand the context.</em></blockquote><blockquote><em>Aggregate information from the subgraph to generate a comprehensive response explaining the relationship between the protein and the disease.</em></blockquote><p>Before we wrap up, I need to touch upon the two types of search options GraphRAG provides, Global and Local search?</p><h3>Global Search vs. Local Search in GraphRAG</h3><p>Global Search involves<strong> querying the entire knowledge graph </strong>to find relevant entities and relationships. It searches across the entire graph to provide a comprehensive set of results. Global Search is used when the query requires a <strong>broad understanding</strong> and connections from various parts of the graph. It’s useful for queries that are <strong>not highly specific</strong> and benefit from a wider context.</p><p>Local Search focuses on a <strong>specific subgraph</strong> or a local neighborhood of nodes within the knowledge graph. It <strong>limits the search to a smaller</strong>, more defined area of the graph. Local Search is used when the <strong>query is highly specific</strong> and pertains to a particular part of the graph. It’s useful for queries that require detailed and focused information from a specific context.</p><p>Let’s understand with an example. Assume the below query for GraphRAG</p><h4><strong><em>Query: “Explain the relationship between Protein A and Disease X.”</em></strong></h4><h3>Global Search</h3><ul><li><strong>Process</strong>: The entire knowledge graph is searched to find all possible connections between Protein A and Disease X.</li><li><strong>Results</strong>: The search might reveal not only the direct interactions between Protein A and Disease X but also indirect connections through other proteins, genes, pathways, and related diseases.</li></ul><p><strong>Example Output</strong>:</p><blockquote><em>Protein A interacts with Protein B, which is known to influence Gene Y.</em></blockquote><blockquote><em>Gene Y has been implicated in Disease X.</em></blockquote><blockquote><em>Protein A is also part of a pathway that is often disrupted in Disease X.</em></blockquote><h3>Local Search</h3><ul><li><strong>Process</strong>: The search is limited to a subgraph around Protein A and Disease X, focusing on immediate connections.</li><li><strong>Results</strong>: The search might reveal direct interactions between Protein A and Disease X and immediate neighbors in the graph.</li></ul><p><strong>Example Output</strong>:</p><blockquote><em>Protein A directly interacts with Disease X.</em></blockquote><blockquote><em>Protein A and Disease X are both related to Gene Z within a specific biological pathway.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3d065aac3a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphRAG vs RAG]]></title>
            <link>https://medium.com/@praveenraj.gowd/graphrag-vs-rag-40c19f27537f?source=rss-171feb4841e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/40c19f27537f</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[graphrag]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Praveen Raj]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 14:28:28 GMT</pubDate>
            <atom:updated>2024-09-18T14:28:28.705Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zFmaNRC-qoP8F8fV.jpeg" /></figure><h3>Retrieval-Augmented Generation (RAG)</h3><p>Retrieval Augmented Generation (<em>or RAG for short</em>) was introduced as a technique to improve Large Language Models’ (<em>LLMs</em>) by incorporating information from external, reliable knowledge bases.</p><p>The principle behind RAG is straightforward; when an LLM is asked a question, it does not just rely on what it already knows.</p><p>Instead, it first looks up relevant information from a specified knowledge source.</p><p>This approach assures that the generated outputs references from a vast amount of contextually enriched data, augmented by the most current and relevant information available.</p><blockquote><strong><em>Three primary parts make up a standard RAG system:</em></strong></blockquote><ul><li><strong>Retriever Component:</strong> The retriever component can search a knowledge base or a sizable corpus of documents for pertinent information(<strong>closely connected with the subject/Query</strong>). The system identifies documents with content semantically related to the query and calculates relevance using a similarity measure, typically the <strong>cosine similarity </strong>between their vectors.</li><li><strong>Generator:</strong> Typically, this sizable language model creates a response by using the retrieved information and its initial question as input.</li><li><strong>Knowledge Base:</strong> A database the retriever uses to find documents or information.</li></ul><p>After collecting the information from external places in order to put it together, it appends this to the user’s prompt and sends it as an enriched input to the language model.</p><p>In the subsequent generative phase, the LLM combines this augmented prompt with its own training data representation to produce a response that is customized to the user’s query.</p><p>This response provides a mix of personalized and verifiable information, suitable for use through applications such as chatbots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/0*vc0fIjItFbbJXgtR.png" /><figcaption>Retrieval Augmented Generation</figcaption></figure><p>Establishing a knowledge base through document indexing and embedding is the first step in building a RAG system.</p><ul><li>Preparing a knowledge base by indexing documents and creating embeddings.</li><li>Training or fine-tuning a retriever model to search this knowledge base effectively.</li><li>Implementing a generator model, often a pre-trained language model.</li></ul><p>Integrating these components to work seamlessly together.</p><h3>What is Graph RAG?</h3><p>Graph RAG is an advanced version of the RAG approach that incorporates graph-structured data. Instead of treating the knowledge base as a flat collection of documents, it represents information as a network of interconnected entities and relationships.</p><p><strong>Graph RAG builds on the concept of RAG by leveraging on knowledge graphs (KGs).</strong></p><p>KGs are structured representations of real-world entities and their relationships.</p><p>They consist of two main components: <strong><em>nodes</em> and <em>edges</em>.</strong></p><blockquote><strong>Nodes represent individual entities such as <em>people</em>, <em>places</em>, <em>objects</em>, or <em>concepts</em>.</strong></blockquote><blockquote><strong>Edges, on the other hand, represent the relationships between these nodes which indicates how they are connected to each other.</strong></blockquote><p>Graph RAG is an advanced version of standard RAG that uses Knowledge Bases instead of vector similarity and vector DBs for retrieval from external documents, making the retrieval more comprehensive and wholesome<em>.</em></p><h3>Advantages of Graph RAG over Standard RAG</h3><p>Graph RAG offers several advantages:</p><ul><li><strong>Relational context:</strong> It captures and utilizes the relationships between different pieces of information, providing richer context.</li><li><strong>Multi-hop reasoning:</strong> Graph structures enable the system to follow chains of relationships, facilitating more complex reasoning.</li><li><strong>Structured knowledge representation:</strong> Graphs can more naturally represent hierarchical and non-hierarchical relationships than flat document structures.</li><li><strong>Efficiency: </strong>Graph structures can make certain types of queries more efficient, especially those involving relationship traversal.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/0*n0RvFRcdtMURa5KV" /><figcaption>knowledge graph</figcaption></figure><h3>How Graph RAG Works?</h3><blockquote><strong>Steps to follow:</strong></blockquote><ol><li><strong>Query Processing:</strong> The input query is analyzed and converted into a suitable format for graph querying.</li><li><strong>Graph Traversal: </strong>The system explores the graph structure, following relevant relationships to find connected information.</li><li><strong>Subgraph Retrieval:</strong> Instead of retrieving isolated pieces of information, it extracts relevant subgraphs that capture interconnected contexts.</li><li><strong>Information Integration:</strong> The retrieved subgraphs are combined and processed to form a coherent context.</li><li><strong>Response Generation:</strong> A language model uses the query and the integrated graph information to generate a response.</li></ol><h3>Flowchart of the Graph RAG Process</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/0*fu9Yo77q5UpA3vdL.png" /></figure><h3>Main Differences between Standard RAG and Graph RAG</h3><p>The key differences include:</p><ul><li><strong>Knowledge Representation:</strong> Standard RAG uses a flat document structure, while Graph RAG uses a graph structure.</li><li><strong>Retrieval Mechanism:</strong> Standard RAG often uses vector similarity search, whereas Graph RAG employs graph traversal algorithms.</li><li><strong>Context Comprehension:</strong> It can capture more complex, multi-step relationships that standard RAG might miss.</li><li><strong>Reasoning Capability:</strong> Graph RAG’s structure allows for more sophisticated reasoning over interconnected information.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F6njV57jN0_gH1zn.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40c19f27537f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Commands for Everyone]]></title>
            <link>https://medium.com/@praveenraj.gowd/git-commands-for-everyone-99548d8dd4a9?source=rss-171feb4841e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/99548d8dd4a9</guid>
            <category><![CDATA[repositories]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Praveen Raj]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 06:05:57 GMT</pubDate>
            <atom:updated>2024-09-18T06:05:57.384Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M5bkzDX5T78R25Mz" /></figure><h3>Basic Git Commands</h3><p><strong>1.Configure Git</strong></p><ul><li>Set global username and email (required for commits):</li></ul><pre>git config — global user.name “Your Name”<br>git config — global user.email “your_email@example.com”</pre><p><strong>2.Initialize a new repository</strong></p><ul><li>Initializes a new Git repository in your project:</li></ul><pre>git init</pre><p><strong>3.Clone an existing repository</strong></p><ul><li>Clone a remote repository to your local machine:</li></ul><pre>git clone &lt;repository_url&gt;</pre><p><strong>4.Check the status of the repository</strong></p><ul><li>Shows the status of your working directory (what’s changed, staged, or untracked):</li></ul><pre>git status</pre><p><strong>5.Stage changes (add files to the staging area)</strong></p><ul><li>Stage a specific file:</li></ul><pre>git add &lt;file_name&gt;</pre><ul><li>Stage all changes:</li></ul><pre>git add .</pre><p><strong>6.Commit changes</strong></p><ul><li>Commit staged changes with a descriptive message:</li></ul><pre>git commit -m &quot;Commit message describing the changes&quot;</pre><p><strong>7.View commit history</strong></p><ul><li>Show a log of commits:</li></ul><pre>git log</pre><ul><li>View a concise summary of commits (with one-liners):</li></ul><pre>git log --oneline</pre><p><strong>8.Push changes to remote repository</strong></p><ul><li>Push local changes to the remote repository (e.g., origin) and the specified branch (e.g., main):</li></ul><pre>git push origin main</pre><p><strong>9.Pull changes from the remote repository</strong></p><ul><li>Fetch and merge changes from the remote repository to your local branch:</li></ul><pre>git pull</pre><p><strong>10.Check differences</strong></p><ul><li>Compare changes in the working directory with the staging area:</li></ul><pre>git diff</pre><ul><li>Compare changes between commits:</li></ul><pre>git diff &lt;commit1&gt; &lt;commit2&gt;</pre><h3>Branching and Merging</h3><p><strong>1.Create a new branch</strong></p><ul><li>Create a new branch and switch to it:</li></ul><pre>git checkout -b &lt;new_branch_name&gt;</pre><p><strong>2.Switch between branches</strong></p><ul><li>Switch to an existing branch:</li></ul><pre>git checkout &lt;branch_name&gt;</pre><p><strong>3.List all branches</strong></p><ul><li>List local and remote branches:</li></ul><pre>git branch -a</pre><p><strong>4.Merge branches</strong></p><ul><li>Merge the specified branch into the current branch:</li></ul><pre>git merge &lt;branch_name&gt;</pre><h3>Remote Repository Commands</h3><p><strong>1.Add a remote repository</strong></p><ul><li>Add a remote repository (e.g., GitHub, GitLab):</li></ul><pre>git remote add origin &lt;repository_url&gt;</pre><p><strong>2.View remote URLs</strong></p><ul><li>View the URL of your remote repositories:</li></ul><pre>git remote -v</pre><p><strong>3.Rename a remote</strong></p><ul><li>Rename the remote repository (e.g., change origin to new_origin):</li></ul><pre>git remote rename origin new_origin</pre><p><strong>4.Remove a remote repository</strong></p><ul><li>Remove the specified remote:</li></ul><pre>git remote remove &lt;remote_name&gt;</pre><h3>Stashing</h3><p><strong>1.Stash changes</strong></p><ul><li>Temporarily save uncommitted changes without committing them:</li></ul><pre>git stash</pre><p><strong>2.Apply stashed changes</strong></p><ul><li>Apply the most recent stash:</li></ul><pre>git stash apply</pre><p>3.<strong>View stash list</strong></p><ul><li>Show a list of stashed changes:</li></ul><pre>git stash list</pre><h3>Undoing Changes</h3><p><strong>1.Undo unstaged changes</strong></p><ul><li>Revert changes in your working directory to the last commit (unstaged changes):</li></ul><pre>git checkout -- &lt;file_name&gt;</pre><p><strong>2.Reset staged changes</strong></p><ul><li>Unstage a file while retaining the changes in the working directory:</li></ul><pre>git reset &lt;file_name&gt;</pre><p><strong>3.Undo the last commit</strong></p><ul><li>Remove the last commit but keep the changes in the working directory:</li></ul><pre>git reset --soft HEAD~1</pre><p><strong>4.Remove commit and changes</strong></p><ul><li>Undo the last commit and discard the changes:</li></ul><pre>git reset --hard HEAD~1</pre><h3>Deleting Branches</h3><ol><li><strong>Delete a local branch</strong></li></ol><ul><li>Delete a local branch (must be merged or force delete using -D):</li></ul><pre>git branch -d &lt;branch_name&gt;</pre><p><strong>2.Delete a remote branch</strong></p><ul><li>Delete a branch on the remote repository:</li></ul><pre>git push origin --delete &lt;branch_name&gt;</pre><h3>summary:</h3><p>These commands cover most of the basic and intermediate Git functionality when working on the command line.</p><p>#gitcommands</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99548d8dd4a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gen-AI RoadMap(Intro)]]></title>
            <link>https://medium.com/@praveenraj.gowd/gen-ai-roadmap-intro-8e81a9f9c9e4?source=rss-171feb4841e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e81a9f9c9e4</guid>
            <dc:creator><![CDATA[Praveen Raj]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 05:35:55 GMT</pubDate>
            <atom:updated>2024-09-09T05:35:55.592Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qYsB7K1KsM4smwgG.jpg" /></figure><h3>What is Generative AI?</h3><p>Generative AI generates new data based on training samples. Generative models can generate Image, Text, Audio, Videos.</p><p>Generative AI is a very huge topic,</p><ul><li>Generative Image Model(GANs, Various Diffusions Models)</li><li>Generative Language Model(LLMs)</li></ul><p>When I refer to large language models, I mean natural language processing. Since NLP forms the foundation of massive language generated models(LLMs).</p><h3>Prerequisites:</h3><blockquote><strong>Programming Language:</strong></blockquote><p>Python is the most commonly used programming language for Data Science, Machine learning and AI domain.</p><p><em>Topics to cover:</em></p><ul><li>Variables, Numbers, Strings</li><li>Lists, Dictionaries, Sets, tuples</li><li>If condition, for loop</li><li>Functions, Lambda Functions</li><li>Modules (pip install)</li><li>Read, Write files</li><li>Exception handling</li><li>Classes, Objects</li></ul><blockquote><strong>NoSQL DataBase:</strong></blockquote><p>Need for a NoSQL database in a deep learning project depends on the nature of your data. Deep learning projects often involve working with large volumes of unstructured data, such as images, text, or audio. In many cases, NoSQL databases are used to store and manage such unstructured data efficiently.</p><p>Reason by you should Nosql Database:</p><ul><li>Scalability and Flexibility</li><li>Variety of Data Types</li><li>Real-time Data Ingestion</li><li>Distributed Computing</li><li>Schema-less Design</li></ul><p>Preference: <strong>MongoDB</strong></p><blockquote><strong>Math and Statistics for Data Science:</strong></blockquote><p>Topics to Learn in <strong>Statistics</strong></p><ul><li>Descriptive statistics</li><li>Inferential statistics</li><li>Basic plot in statistics</li><li>Measure of central tendency</li><li>Types of distributions</li><li>Central limit theorem</li><li>Correlation and covariance</li><li>Hypothesis testing</li></ul><p>Topics to Learn in <strong>Mathematics</strong></p><ul><li>Probability</li><li>Linear Algebra</li><li>Calculus</li></ul><blockquote><strong>Deep</strong> <strong>Learning:</strong></blockquote><ul><li>Artificial Neural Networks</li><li>Activation functions and Loss functions</li><li>Backpropagation, optimizers</li><li>Regularization, Normalization</li><li>Convolutional Neural Networks (CNNs)</li><li>Recurrent Neural Networks (RNNs)</li><li>Get hands-on experience with frameworks like TensorFlow or PyTorch</li></ul><blockquote><strong>Basics of Natural Language Processing</strong></blockquote><ul><li>Text Preprocessing: Regex,Lowercasing,Tokenization,Removing Punctuation,Removing Stop Words,Stemming,Lemmatization</li><li>Text Representation: Countvectorizer, TF-IDF, BOW,OHE</li><li>Text Classification: Naive Bayes</li><li>Fundamental library: Spacy &amp; NLTK</li></ul><blockquote><strong>Word Embedding Techniques</strong></blockquote><ul><li>Word2Vec</li><li>GloVe</li><li>ELMO</li><li>Fast Text</li></ul><blockquote><strong>Advance NLP Concepts</strong></blockquote><ul><li>Advance RNN like LSTM &amp; GRU</li><li>Encoder decoder &amp; Encoder decoder with Attention Mechanism</li><li>Transformer architecture: Self attention mechanism, key, query, value(KQV), Layer Normalization &amp; Positional Encoding</li><li>BERT: Contextual embedding and mask language modelling</li><li>GPT: Autoregressive Modelling</li></ul><h4><strong>An important concept needs to be learnt:</strong></h4><p><strong>Transfer Learning</strong>: learned from past work and applied it to the current challenge.</p><p><strong>Fine-Tuning of Model:</strong> Fine-tuning refers to the process of taking a pre-trained model and further training it on a domain specific task.</p><p>Different Sequence mapping: One to Many, Many to One, Many to Many</p><h3>Core Generative AI Models: LLMs</h3><ul><li><strong>BERT: </strong>Bidirectional Encoder Representations from Transformers (BERT) was developed by Google</li><li><strong>GPT:</strong> GPT stands for “Generative Pre-trained Transformer”.The model was developed by OpenAI</li><li><strong>XLM:</strong> Cross-lingual Language Model Pretraining by Guillaume Lample, Alexis Conneau.</li><li><strong>T5:</strong> The Text-to-Text Transfer Transformer It was created by Google AI</li><li><strong>Megatron:</strong> Megatron is a large, powerful transformer developed by the Applied Deep Learning Research team at NVIDIA</li><li><strong>M2M-100:</strong> multilingual encoder-decoder (seq-to-seq) model researchers at Facebook</li></ul><h3>OpenAI LLM Models</h3><ul><li><strong>GPT-4 and GPT-4 Turbo</strong>: A set of models that improve on GPT-3.5 and can understand as well as generate natural language or code</li><li><strong>GPT-3.5:</strong> A set of models that improve on GPT-3 and can understand as well as generate natural language or code</li><li><strong>DALL·E: </strong>A model that can generate and edit images given a natural language prompt</li><li><strong>TTS: </strong>A set of models that can convert text into natural sounding spoken audio</li><li><strong>Whisper: </strong>A model that can convert audio into text</li></ul><h3>Google AI LLM models</h3><ul><li>PaLM2</li><li>Gemini-pro</li><li>Gemini -pro-vision</li></ul><p><strong>Meta AI LLM Models</strong></p><ul><li>LlaMA &amp; LlaMA2</li></ul><p><strong>Open Source LLM Models</strong></p><ul><li>BLOOM</li><li>Llama 2</li><li>PaLM</li><li>Falcon</li><li>Claude</li><li>MPT-30B</li><li>Stablelm</li></ul><h3>Prompt Engineering</h3><p>Type of Prompting:</p><ul><li>Zero shot prompting(Direct Prompting)</li><li>Few shot prompting</li><li>Chain-of-thoughts prompting</li></ul><p><strong>Prompt Creation</strong>: Length,context structure and specific instruction</p><p><strong>Prompt Communities</strong>: Prompt Hero, FlowGPT, Snack Prompt</p><h4>Developed application powered by LLMs</h4><p>Explore Generative Model APIs</p><ul><li>OpenAI API</li><li>Hugging Face API</li><li>Gemini API</li></ul><h4>Framework for Developing LLM application</h4><ul><li>LangChain</li><li>Chainlit</li><li>Llama Index2</li></ul><h4>Vector Databases</h4><ul><li>ChromaDB</li><li>Waviet</li><li>Pinecone</li><li>OpenAI Faiss</li></ul><h4>Tools and Framework for Web-Application</h4><ul><li>Streamlit</li><li>Gradio</li><li>FastAPI</li><li>Flask</li></ul><h4>Deployment of LLM model</h4><ul><li>AWS</li><li>GCP</li><li>Azure</li><li>LangServe</li><li>Hugging Face Spaces</li></ul><h4>Some Advance topics</h4><ul><li>ChatGPT: Understanding of Chat Gpt Training and RLHF (Reinforcement learning through human feedback) Concept</li><li>RAG :Retrieval-Augmented Generation (RAG) Systems</li><li>PEFT :Parametric efficient fine tuning</li><li>Adaptive Ranking: low rank adaptation(LoRa) and Quantized Low Rank Adaptation(Qlora)</li><li>Evaluation of LLMs: Find evaluation metrics of results generated by LLM</li></ul><p>Finally,</p><p><strong>Work on small projects to apply what you’ve learned.</strong></p><p><strong>Experiment with different datasets and model architectures.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e81a9f9c9e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning Interview Questions (Part-1)]]></title>
            <link>https://medium.com/@praveenraj.gowd/machine-learning-interview-questions-part-1-a45a51db1b4d?source=rss-171feb4841e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a45a51db1b4d</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[preparation]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[questions]]></category>
            <dc:creator><![CDATA[Praveen Raj]]></dc:creator>
            <pubDate>Wed, 17 Jul 2024 06:55:13 GMT</pubDate>
            <atom:updated>2024-07-17T06:55:13.829Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*lF9YQlqW2844qVNN.png" /></figure><h3><strong>1. Types of Learning in ML?</strong></h3><ul><li><strong>Supervised</strong> Machine Learning</li><li><strong>Unsupervised</strong> Machine Learning</li><li><strong>Reinforcement</strong> Learning</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*0nMCuTX_sxAgbF_mR3e0jA.png" /><figcaption>Types of ML</figcaption></figure><p><strong>Supervised machine learning</strong> is based on supervision. It means in this learning technique, we train the machines using the “<strong><em>labelled</em></strong>” dataset, and based on the training, the machine predicts the output.</p><p>Let’s understand supervised learning with an example. Suppose we have an input dataset of cats and dog images. So, first, we will provide the training to the machine to understand the images, such as the <strong>shape &amp; size of the tail of cat and dog, Shape of eyes, color, height (dogs are taller, cats are smaller), etc.</strong> After completion of training, we input the picture of a cat and ask the machine to identify the object and predict the output. Now, the machine is well trained, so it will check all the features of the object, such as height, shape, color, eyes, ears, tail, etc., and find that it’s a cat. So, it will put it in the Cat category. This is the process of how the machine identifies the objects in Supervised Learning.</p><p>It depends on the Target variable in Output data.</p><ul><li>The target variable is <strong>continuous</strong>: Regression</li><li>The target variable is <strong>categorical</strong>: Classification</li></ul><p>Unsupervised machine learning, The machine is trained using the unlabeled dataset, and the machine predicts the output without any target variable.</p><p><strong>The main aim of the unsupervised learning algorithm is to group or categories the unsorted dataset according to the similarities, patterns, and differences.</strong> Machines are instructed to find the hidden patterns from the input dataset.</p><p>Let’s take an example to understand it more preciously. Suppose there is a basket of fruit images, and we input it into the machine learning model. The images are totally unknown to the model, and the task of the machine is to find the patterns and categories of the objects.</p><h4>Clustering</h4><p><strong>Centroid-based Methods</strong></p><ul><li>K-Means clustering</li><li>K-Means++ clustering</li></ul><p><strong>Distribution-based Methods</strong></p><ul><li>Gaussian mixture models (GMMs)</li><li>Expectation-Maximization Algorithms</li></ul><p><strong>Connectivity based methods</strong></p><ul><li>Hierarchical clustering</li></ul><p><strong>Density Based methods</strong></p><ul><li>DBSCAN (Density-Based Spatial Clustering of Applications with Noise)</li></ul><p><strong>Dimensionality Reduction Technique:</strong></p><ul><li>Principal Component Analysis (PCA)</li><li>t-distributed Stochastic Neighbor Embedding (t-SNE)</li></ul><p><strong>Reinforcement Learning</strong> is a type of machine learning algorithms where an agent learns to make successive decisions by interacting with its surroundings. The agent receives the feedback in the form of incentives or punishments based on its actions. The agent’s purpose is to discover optimal tactics that maximize cumulative rewards over time through trial and error. Reinforcement learning is frequently employed in scenarios in which the agent must learn how to navigate an environment, play games, manage robots, or make judgments in uncertain situations.</p><h3><strong>2. </strong>Regression<strong> and </strong>Classification<strong>?</strong></h3><h3>Regression</h3><p>Regression is a supervised learning technique used to predict continuous numerical values based on input features. It aims to establish a functional relationship between independent variables and a dependent variable, such as predicting house prices based on features like size, bedrooms, and location.<br>The goal is to minimize the difference between predicted and actual values using algorithms like Linear Regression, Decision Trees, or Neural Networks, ensuring the model captures underlying patterns in the data.</p><h3>Classification</h3><p>Classification is a type of supervised learning that categorizes input data into predefined labels. It involves training a model on labeled examples to learn patterns between input features and output classes. In classification, the target variable is a categorical value. For example, classifying emails as spam or not.<br>The model’s goal is to generalize this learning to make accurate predictions on new, unseen data. Algorithms like Decision Trees, Support Vector Machines, and Neural Networks are commonly used for classification tasks.</p><p><strong>NOTE:</strong> There are common Supervised Machine Learning Algorithm that can be used for both regression and classification task.</p><p><strong>1.Linear Regression</strong>: Linear regression is a type of regression algorithm that is used to predict a continuous output value. It is one of the simplest and most widely used algorithms in supervised learning. In linear regression, the algorithm tries to find a linear relationship between the input features and the output value. The output value is predicted based on the weighted sum of the input features.</p><p><strong>2.Logistic Regression</strong>: Logistic regression is a type of classification algorithm that is used to predict a binary output variable. It is commonly used in machine learning applications where the output variable is either true or false, such as in fraud detection or spam filtering. In logistic regression, the algorithm tries to find a linear relationship between the input features and the output variable. The output variable is then transformed using a logistic function to produce a probability value between 0 and 1.</p><p><strong>3.Decision Trees</strong>: Decision tree is a tree-like structure that is used to model decisions and their possible consequences. Each internal node in the tree represents a decision, while each leaf node represents a possible outcome. Decision trees can be used to model complex relationships between input features and output variables.<br>A decision tree is a type of algorithm that is used for both classification and regression tasks.</p><ul><li><strong>Decision Trees Regression: </strong>Decision Trees can be utilized for regression tasks by predicting the value linked with a leaf node.</li><li><strong>Decision Trees Classification: </strong>Random Forest is a machine learning algorithm that uses multiple decision trees to improve classification and prevent overfitting.</li></ul><p><strong>4.Random Forests</strong>: Random forests are made up of multiple decision trees that work together to make predictions. Each tree in the forest is trained on a different subset of the input features and data. The final prediction is made by aggregating the predictions of all the trees in the forest.<br>Random forests are an ensemble learning technique that is used for both classification and regression tasks.</p><p><strong>Bagging</strong> is a simple and a very powerful ensemble method. It is a general procedure that can be used to reduce our model’s variance.</p><ul><li><strong>Random Forest Regression</strong>: It combines multiple decision trees to reduce overfitting and improve prediction accuracy.</li><li><strong>Random Forest Classifier:</strong> Combines several decision trees to improve the accuracy of classification while minimizing overfitting.</li></ul><p><strong>5.Support Vector Machine(SVM)</strong>: The SVM algorithm creates a hyperplane to segregate n-dimensional space into classes and identify the correct category of new data points. The extreme cases that help create the hyperplane are called support vectors, hence the name Support Vector Machine.<br>A Support Vector Machine is a type of algorithm that is used for both classification and regression tasks.</p><ul><li><strong>Support Vector Regression: </strong>It is a extension of Support Vector Machines (SVM) used for predicting continuous values.</li><li><strong>Support Vector Classifier: </strong>It aims to find the best hyperplane that maximizes the margin between data points of different classes.</li></ul><p><strong>6.K-Nearest Neighbors (KNN)</strong>: KNN works by finding k training examples closest to a given input and then predicts the class or value based on the majority class or average value of these neighbors. The performance of KNN can be influenced by the choice of k and the distance metric used to measure proximity. However, it is intuitive but can be sensitive to noisy data and requires careful selection of k for optimal results.<br>A K-Nearest Neighbors (KNN) is a type of algorithm that is used for both classification and regression tasks.</p><ul><li><strong>K-Nearest Neighbors Regressio</strong>n: It predicts continuous values by averaging the outputs of the k closest neighbors.</li><li><strong>K-Nearest Neighbors Classification: </strong>Data points are classified based on the majority class of their k closest neighbors.</li></ul><p><strong>7.Gradient Boosting</strong>: Gradient Boosting combines weak learners, like decision trees, to create a strong model. It iteratively builds new models that correct errors made by previous ones. Each new model is trained to minimize residual errors, resulting in a powerful predictor capable of handling complex data relationships.<br>A Gradient Boosting is a type of algorithm that is used for both classification and regression tasks.</p><blockquote>Adaptive Boosting, Gradient Boosting Decision Tree, Xtreme Gradient Boosting</blockquote><ul><li><strong>Gradient Boosting Regression:</strong> It builds an ensemble of weak learners to improve prediction accuracy through iterative training.</li><li><strong>Gradient Boosting Classification: </strong>Creates a group of classifiers to continually enhance the accuracy of predictions through iterations.</li></ul><h3>Ensemble methods: bagging, boosting and stacking</h3><ul><li><strong>Bagging</strong>, that often considers homogeneous weak learners, learns them independently from each other in parallel and combines them following some kind of deterministic averaging process</li><li><strong>Boosting</strong>, that often considers homogeneous weak learners, learns them sequentially in a very adaptative way (a base model depends on the previous ones) and combines them following a deterministic strategy</li><li><strong>Stacking</strong>, that often considers heterogeneous weak learners, learns them in parallel and combines them by training a meta-model to output a prediction based on the different weak models predictions</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*_fJdn6T4HhBdTZbA" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*azhAOpNLTcag4ZDk" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/0*7t8Ddju1H9lBmKPm" /></figure><h3>3.One Hot Encoding and Label Encoding?</h3><p>How should we handle categorical target variables?</p><h4>Label Encoding — Squeezing Categories into Numbers:</h4><p>Imagine you have data of the customer feedback form. You might have Poor, Fair, Good, Very Good, and Excellent. Now, you want to use a computer to work with this list. Computers prefer numbers over words, so how can we represent these feedback categories using numbers? This is where Label Encoding comes in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/0*QRfP5sfEF1vbqE-I.png" /></figure><p>Label Encoding assigns a unique number to each category. In our example, we could assign the number 1 to Poor, 2 to Fair, and so on. So, your list of customer feedback would become [1, 2, 3,4,5].</p><p>However, it has a drawback when used for nominal categories, such as colors, because it can imply an unintended order.</p><h4>One-Hot Encoding: Every Category Gets Its Own Place:</h4><p>One-Hot Encoding is another technique to convert categorical data into a numerical form. Instead of giving each category a single number, it creates a new binary column (1 or 0) for each category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0pKKjqLT_wE7A0sa.png" /></figure><p>One-Hot Encoding is suitable for nominal data, like colors or car brands, where there is no inherent order. It ensures that the machine understands that each category is unique.</p><p>However, it has a drawback of creating feature vector for each unique category that causes <strong>Curse of dimensionality</strong> and If unseen data contains categories which was never seen in historical data its encoding becomes zero.</p><h3>4.How do you select important variables while working on a data set?</h3><p>There are several methods to select important variables from a data set, including:</p><ol><li><strong>Variance Thresholding</strong></li></ol><ul><li>Features which are having <strong>Zero variance</strong> or less information we can drop them.</li><li><strong>Forward Selection:</strong> in this method, any selected algorithm starts modelling data with an empty set of features and iteratively adds one feature at a time, evaluating the performance of the predictive model at each step. This process continues until the algorithm uses a desired number of features or until it not gains an optimal performance.</li><li><strong>Backward Elimination: </strong>We can think of this method as the opposite of the forward selection method, where it starts with a whole set of features and removes one feature in every iteration. This process continues until the algorithm uses a desired number of features or until it not gains an optimal performance.</li></ul><p><strong>2. Recursive feature elimination</strong></p><ul><li>RFE is a feature selection strategy that recursively eliminates the least important features until the required amount of features is attained. The procedure begins with training a model on the complete feature set and ranking the features in order of significance based on the model’s coefficients or feature importance. The feature with the least importance is then deleted, and the procedure is continued until the required number of characteristics is obtained.</li><li>RFE is founded on the idea that a decent model may be created with a reduced collection of features that are more relevant to the target variable. It may be used to any model that contains a feature significance concept, such as linear regression or decision trees. RFE may assist to decrease model complexity and increase interpretability while preserving or even enhancing performance. It can, however, be computationally expensive, particularly for big datasets or complicated models.</li></ul><p>3.<strong>Regularization methods</strong></p><ul><li>Regularization methods are used to prevent overfitting in machine learning models by adding a penalty term to the cost function of a model. The penalty term encourages the model to have smaller coefficients for less important features. There are different types of regularization methods, including Ridge regression, Lasso regression, and Elastic Net.</li><li><strong>Ridge regression</strong> adds a penalty term equivalent to the square of the magnitude of coefficients. The regularization parameter controls the strength of the penalty and helps to shrink the coefficients toward zero.</li><li><strong>Lasso regression</strong> adds a penalty term equivalent to the absolute value of coefficients. This penalty term forces the coefficients of less important features to zero, resulting in a sparse model.</li><li><strong>Elastic Net</strong> is a Ridge and Lasso regression method that employs a linear combination of the Ridge and Lasso penalty terms. The regularization parameter governs the severity of the Ridge and Lasso penalties.</li><li>These regularization strategies are effective for selecting significant variables from data collection and can improve the performance and interpretability of machine learning models.</li></ul><p><strong>4.Principal component analysis (PCA)</strong></p><ul><li>Principal component analysis (PCA) is a dimensionality reduction technique that transforms the original features of a dataset into a new set of uncorrelated features, known as principal components. The principal components are ranked in order of the amount of variance they explain in the data. PCA finds the direction in which the data has the most variation and projects the data in that direction. The next direction is found as the one that explains the most variance while being orthogonal to the previous direction, and so on until all directions are found.</li><li>PCA can simplify the analysis of high−dimensional data and enhance model performance by reducing the number of features to a smaller collection of primary components. The number of maintained primary components may be decided by the amount of variation explained, and the other components can be removed.</li><li>PCA may also be used as a preprocessing step before using other feature selection methods, such as regularized regression or univariate feature selection, to minimize the dimensionality of data.</li></ul><p><strong>5.Feature importance using tree−based models</strong></p><ul><li>Random Forest and Gradient Boosting are two tree−based models that may quantify the importance of each feature in predicting the target variable. These models are built by recursively splitting the feature space based on the target variable. Throughout the partitioning operation, the most informative feature is chosen to separate the data. The significance of a feature may be determined by calculating how much each characteristic decreases an impurity measure, such as Gini impurity or entropy.</li><li>We may compute the crucial scores for each feature after building the tree-based model by averaging the scores across all of the trees in the model. Higher significance ratings indicate that qualities have a larger role in predicting the target variable. These crucial properties can be selected for further investigation or utilized to train a simpler model. Tree−based models are frequently used for feature selection due to their stability and ability to handle both continuous and categorical data.</li></ul><h3>5.Varince inflation Factor(VIF)</h3><p>Multicollinearity exists when there is a linear relationship, or correlation, between one or more of the independent variables or inputs.</p><p>Multicollinearity creates a problem in the multiple regression model because the inputs are all influencing each other. Therefore, they are not actually independent, and it is difficult to test how much the combination of the independent variables affects the dependent variable, or outcome, within the regression model.</p><p>In VIF method, we pick each feature and regress it against all of the other features. For each regression, the factor is calculated as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*JLTZqWc_8r7m4wdB" /></figure><p>Where, R-squared is the coefficient of determination in linear regression. Its value lies between 0 and 1.</p><p><strong>Interpreting VIF Values:</strong></p><ul><li>VIF &lt; 5: The variable has low multicollinearity (no significant issue).</li><li>VIF between 5 and 10: The variable has moderate multicollinearity (requires further investigation).</li><li>VIF &gt; 10: The variable has high multicollinearity (serious issue, consider mitigation techniques).</li></ul><pre>Gender  Height  Weight  Index<br>0    Male     174      96      4<br>1    Male     189      87      2<br>2  Female     185     110      4<br>3  Female     195     104      3<br>4    Male     149      61      3</pre><pre>feature        VIF<br>0  Gender   2.028864<br>1  Height  11.623103<br>2  Weight  10.688377</pre><p>As we can see, height and weight have very high values of VIF, indicating that these two variables are highly correlated. This is expected as the height of a person does influence their weight. Hence, considering these two features together leads to a model with high multicollinearity.</p><h3>6.Confusion Matrix</h3><p>It is a Evaluation metric for machine learning classification problem where output can be two or more classes. It is a table with 4 different combinations of predicted and actual values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/0*V9bzdn9bL27w_K5B.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/0*tkUUeALl4Jd3FHbn" /></figure><ol><li>True Positive : Model Predicted that the Person have Cancer and in Reality Person have Cancer.</li><li>False Positive (Type 1 Error) : Model Predicted Person have cancer but in Reality Person don’t have Cancer.</li><li>False Negative (Type 2 Error) : Machine Learning Model Predicted Person Don’t have cancer but in Reality the Patient have Cancer .</li><li>True Negative : Model Predicted Person Don’t have cancer &amp; In Reality Person Don’t have Cancer.</li></ol><p>Just Remember, We describe predicted values as Positive and Negative and actual values as True and False.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/0*i1hj5bwdcwm9A2AE.png" /></figure><p>🔹Understand one Thing Guys, In the Above Example, <strong>True Positives</strong> and <strong>True Negatives </strong>are giving Correct Output as the Reality So these is No Risk in these Two.</p><p>🔹 When we Talk about <strong>Type I error</strong>, here The Model is predicting that the person have Cancer According to the Symptoms/Features &amp; In Reality the Person Doesn’t Have Cancer. So There needs to be some Cleaning of Data to Fix the Output.</p><p>🔹 Similarly When it comes to <strong>Type II error</strong> Being More Serious Because, Model is predicting that the person Don’t have Cancer According to the Symptoms/Features but In Reality Person Have Cancer. Another Example for This is a Thermometer, When we will check the Body Temperature it will Not Show the Correct or will Show less Temperature but in Reality the Patient may have very high Temperature fever.</p><p>✅ Some More Examples on <strong>Type I &amp; Type II Error</strong> :</p><p>🔹<strong> Type I Error (False Positive): — Fire alarm rings when there is no fire.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*NmtsiewBZUJpDyll" /></figure><p>🔹 <strong>Type II Error (False Negative): — Fire alarm fails to ring when there is fire.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/0*SsiuLGAc2szZCCAW" /></figure><p>🔹 Type I Error (False Positive): — Man with Doctor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/0*n00dudlifv1KCXcV" /></figure><p>🔹 Type II Error (False Negative): — Pregnant Lady with Doctor</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/0*4S0s0SqVGykJedlv" /></figure><p><strong>True Positive:</strong></p><p>Interpretation: You predicted positive and it’s true.</p><p>You predicted that a woman is pregnant and she actually is.</p><p><strong>True Negative:</strong></p><p>Interpretation: You predicted negative and it’s true.</p><p>You predicted that a man is not pregnant and he actually is not.</p><p><strong>False Positive: (Type 1 Error)</strong></p><p>Interpretation: You predicted positive and it’s false.</p><p>You predicted that a man is pregnant but he actually is not.</p><p><strong>False Negative: (Type 2 Error)</strong></p><p>Interpretation: You predicted negative and it’s false.</p><p>You predicted that a woman is not pregnant but she actually is.</p><p>🔹 Guys I Hope we are Now Clear with What The Errors are and when we Evaluate These Errors :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/0*Wnu-Y4HkmotoRkOi" /></figure><h3>7. Is it better to have too many false positives or too many false negatives? Explain?</h3><p>It depends on the question as well as on the domain for which we are trying to solve the problem.</p><ul><li>If you’re using Machine Learning in the domain of medical testing, then a false negative is very risky, since the report will not show any health problem when a person is actually unwell.</li><li>Similarly, if Machine Learning is used in spam detection, then a false positive is very risky because the algorithm may classify an important email as spam.</li></ul><h3>8.Model Accuracy vs Model Performance</h3><p>When I had huge dataset it was literally a tough job to use Advanced Algorithms like Decision trees or ensembles as they take multiple hours to execute with small RAM boxes. On the other hand, most of the time they ensure good accuracy. That’s why I used to feed my appetite with Logistic Regression or Linear Support vector machines because they are super fast and works really well with large datasets.</p><p>Anyways, the first and foremost thing we should know is that it depends on the application and type of problem we are solving. Suppose we are processing medical images to detect cancer cells where accuracy metric plays a very vital role. There isn’t any time constraint. Here the cost of error is very high. So model accuracy, in this case, should be excellent and moreover it is expected to get near about 100% accuracy.</p><p>On the other hand, if we consider Google search or internet applications people hate to wait very long for the page loading. In that case, speed is a crucial factor. Hence model performance must be our priority. More such examples like in computer vision, real-time face detection has to be very fast. They don’t demand very high accuracy. So performance/speed should be considered in place of accuracy.</p><h3>9.Target Imbalance?</h3><p>While working as a data scientist, some of the most frequently occurring problem statements are related to binary classification. A common problem when solving these problem statements is that of class imbalance. When observation in one class is higher than in other classes, a class imbalance exists.</p><ul><li>Example: To detect fraudulent credit card transactions. As shown in the graph below, the fraudulent transaction is around 400 compared to the non-fraudulent transaction of around 90000.</li></ul><p><strong>Resampling Techniques to Solve Class Imbalance</strong></p><p>One of the widely adopted class imbalance techniques for dealing with highly unbalanced datasets is called resampling. It consists of removing samples from the majority class (under-sampling) and/or adding more examples from the minority class (over-sampling).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*Jwcvrge8Dw4VZepQ.png" /></figure><p>Despite the advantage of balancing classes, these techniques also have their weaknesses (there is no free lunch).</p><p>The simplest implementation of <strong>over-sampling</strong> is to duplicate random records from the minority class, which can cause overfishing.</p><p>In <strong>under-sampling</strong>, the simplest technique involves removing random records from the majority class, which can cause a loss of information.</p><h4>A. Random Under-Sampling</h4><p>Undersampling can be defined as <strong>removing some observations of the majority class</strong>. This is done until the majority and minority class is balanced out.</p><p>Under-sampling can be a good choice when you have a ton of data -think millions of rows. But a drawback to under-sampling is that we are removing information that may be valuable.</p><h4>B. Random Over-Sampling</h4><p>Oversampling can be defined as adding more copies to the minority class. Oversampling in machine learning can be a good choice when you don’t have a ton of data to work with.</p><p>A con to consider when undersampling is that it can cause overfitting and poor generalization to your test set.</p><h4>C. Synthetic Minority Oversampling Technique (SMOTE)</h4><p>This technique generates synthetic data for the minority class.</p><p>SMOTE (Synthetic Minority Oversampling Technique in machine learning) works by randomly picking a point from the minority class and computing the k-nearest neighbors for this point. The <strong>synthetic points are added</strong> between the chosen point and its neighbors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*hqCVP7LEEIQZ3wfD.png" /></figure><p><strong>SMOTE algorithm</strong> works in 4 simple steps:</p><ol><li>Choose a minority class as the input vector.</li><li>Find its k nearest neighbors (<strong><em>k_neighbors</em></strong> is specified as an argument in the <strong><em>SMOTE()</em></strong> function).</li><li>Choose one of these neighbors and place a synthetic point anywhere on the line joining the point under consideration and its chosen neighbor.</li><li>Repeat the steps until the data is balanced.</li></ol><h4>D. Change the Performance Metric</h4><p>Accuracy is not the best metric to use when evaluating imbalanced datasets, as it can be misleading.</p><p>Metrics that can provide better insight are:</p><ul><li><strong>Confusion Matrix:</strong> a table showing correct predictions and types of incorrect predictions.</li><li><strong>Precision: </strong>the number of true positives divided by all positive predictions. Precision is also called Positive Predictive Value. It is a measure of a classifier’s exactness. Low precision indicates a high number of false positives.</li><li><strong>Recall:</strong> the number of true positives divided by the number of positive values in the test data. The recall is also called Sensitivity or the True Positive Rate. It is a measure of a classifier’s completeness. Low recall indicates a high number of false negatives.</li><li><strong>F1: Score:</strong> the weighted average of precision and recall.</li><li><strong>Area Under ROC Curve</strong> (AUROC): AUROC represents the likelihood of your model distinguishing observations from two classes.<br>In other words, if you randomly select one observation from each class, what’s the probability that your model will be able to “rank” them correctly?</li></ul><h3>10.Cross Validation</h3><p>Cross-validation is a technique for evaluating a machine learning model and testing its performance. Cross-validation is a technique used to evaluate the performance of a machine learning model by training it on different subsets of the data and testing it on the remaining subset. This is something different from the general train-test split</p><blockquote><strong><em>Introduction:</em></strong></blockquote><p>Simply put, in the process of cross-validation, the original data sample is randomly divided into several subsets. The machine learning model trains on all subsets, except one. After training, the model is tested by making predictions on the remaining subset. The goal is to estimate the model’s performance on unseen data, similar to how cross-validation works.</p><blockquote><strong><em>Why to use Cross Validation?</em></strong></blockquote><p>Suppose you build a machine learning model to solve a problem, and you have trained the model on a given dataset. When you check the accuracy of the model on the training data, it is close to 95%. Does this mean that your model has trained very well, and it is the best model because of the high accuracy?</p><p>No, it’s not! Because your model is trained on the given data, it knows the data well, captured even the minute variations(noise), and has generalized very well over the given data. If you expose the model to completely new, unseen data, it might not predict with the same accuracy and it might fail to generalize over the new data. This problem is called over-fitting.</p><p>Sometimes the model doesn’t train well on the training set as it’s not able to find patterns. In this case, it wouldn’t perform well on the test set as well. This problem is called Under-fitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*4XRlHbVjNmbkptKQ.png" /></figure><p>Cross validation is a way to check if a machine learning model is overfitting or underfitting on a given dataset.</p><h4><strong><em>Methods used for Cross-Validation:</em></strong></h4><p>There are several methods used for cross-validation, each with its own advantages and disadvantages. Some of the most common methods are:</p><blockquote><strong><em>Holdout Validation:</em></strong></blockquote><p>The hold-out method, also known as train-test split, is the simplest type of cross-validation. It involves randomly dividing the dataset into two subsets: a training set and a holdout set (or test set). The model is trained on the training set, and its performance is evaluated on the holdout set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/0*K11tsPOedDqmF6gQ.png" /></figure><p>A common rule of thumb is to use about 70% of the dataset as a training set and 30% as a validation set.</p><p>This method is straightforward and easy to implement but can be less accurate than other cross-validation techniques primarily because it does not account for the variability of the data split.</p><p>1. The performance of the model evaluated through holdout cross-validation can vary significantly based on the specific split of the data. This variability arises because the data used for training and testing is not guaranteed to be representative of the entire dataset. This can lead to an overly optimistic or pessimistic evaluation of the model’s performance.</p><p>2. Holdout cross-validation does not allow for a comprehensive assessment of model performance across different hyperparameters. Since the model is trained and tested only once, it’s challenging to determine the optimal hyperparameters for the model.</p><p>Thus, Holdout cross-validation is a good starting point for model evaluation, but for more reliable performance estimates, other cross-validation techniques like k-fold cross-validation are recommended. However, it’s worth noting that for datasets with a large number of observations, holdout cross-validation can be computationally efficient and may still provide a reasonable estimate of model performance.</p><blockquote><strong><em>1.</em></strong><em> </em><strong><em>K-fold cross validation:</em></strong></blockquote><p>K-fold cross validation is a method of evaluating the performance of a machine learning model by splitting the data into k subsets or “folds” of roughly equal size. The model is trained on k-1 of the folds and tested on the remaining fold. This process is repeated k times, with each fold being used as the test set once. The performance of the model is then averaged across all k iterations. This gives an estimate of how well the model is likely to perform on new, unseen data.</p><p>Here’s an example to explain it:</p><p>Suppose we have a dataset of 100 samples, and we want to train a model to predict if a person has diabetes based on their age and BMI. We can use k-fold cross validation to evaluate the performance of the model. We can split the data into 10 folds, meaning that each fold will have 10 samples.</p><p>In the first iteration, we will use the first 9 folds (90 samples) to train the model and the remaining fold (10 samples) to test the model. We will record the performance of the model (e.g. accuracy, precision, recall, etc.) In the second iteration, we will use the second fold as the test set, and the rest of the 9 folds as the training set. We will again record the performance of the model.</p><p>This process will repeat until all the 10 folds have been used as the test set once. After all the iterations, we will average the performance of the model across all 10 iterations. This will give us an estimate of how well the model is likely to perform on new, unseen data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*JtrjVJyYjYPdmMra.png" /></figure><blockquote><strong><em>2.</em></strong><em> </em><strong><em>Stratified k-fold cross validation</em></strong></blockquote><p>Stratified k-fold cross validation is a method of cross-validation that ensures that the proportion of samples for each class is roughly the same in each fold. This is useful when the class distribution is imbalanced, meaning that there are different number of samples for each class. let’s take an example to illustrate how Stratified k-fold cross validation works.</p><p>Suppose we have a dataset of 1000 samples, and we want to train a model to classify the samples as either “A” or “B” class. The dataset has 600 samples of class “A” and 400 samples of class “B”. We want to use k-fold cross validation to evaluate the performance of the model, where k = 5.</p><p>In regular k-fold cross validation, the data is randomly split into 5 subsets or “folds” of roughly equal size (200 samples per fold). However, this could lead to a situation where all samples of class “A” end up in one fold and all samples of class “B” end up in another fold. This would not be an accurate representation of the model’s performance on unseen data.</p><p>With stratified k-fold cross validation, we first divide the data into 5 folds based on the class distribution. This means that each fold will have roughly 120 samples of class “A” and 80 samples of class “B”. This way, the proportion of samples for each class is roughly the same in each fold.</p><p>The model is then trained on 4 folds and tested on the remaining fold, this process is repeated 5 times with each fold being used as the test set once. The performance of the model is then averaged across all 5 iterations. This gives an estimate of how well the model is likely to perform on new, unseen data.</p><p>Note: The main difference between Stratified k-fold cross validation and regular k-fold cross-validation is how the data is split into folds.</p><p>In regular k-fold cross-validation, the data is randomly split into k subsets or “folds” of roughly equal size. This means that each fold will have roughly the same number of samples, regardless of their class labels.</p><p>In contrast, in stratified k-fold cross-validation, the data is first divided into k folds based on the class distribution. This means that each fold will have roughly the same proportion of samples for each class. This is useful when the class distribution is imbalanced, meaning that there are different number of samples for each class.</p><p>The main advantage of stratified k-fold cross-validation is that it helps to prevent bias in the evaluation process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*QRZN_4t4gQwq9CP5.png" /></figure><blockquote><strong><em>how to choose K in K fold cross validation:</em></strong></blockquote><p>Choosing the value of k in k-fold cross-validation is a trade-off between bias and variance. In general, a larger value of k will result in a lower bias and a higher variance, while a smaller value of k will result in a higher bias and a lower variance.</p><p>Here are a few examples to illustrate how the choice of k can affect the performance of k-fold cross-validation:</p><p>· If k is set to be very small, say k = 2 or 3, the model will have a higher bias and a lower variance. In this case, the model is trained on a small portion of the data and the test set is also small, so the model may not generalize well to new, unseen data.</p><p>· If k is set to be very large, say k = n-1 where n is the number of samples, the model will have a lower bias and a higher variance. In this case, the model is trained on almost all the data and the test set is very small, so the model may fit the training data very well but may not generalize well to new, unseen data.</p><p>· A common choice for k is 10, which is widely used in practice. This value tends to work well in most cases and provides a good balance between bias and variance.</p><p>It is important to experiment with different values of k and evaluate the performance of the model using different evaluation metrics. Also, the choice of k is highly dependent on the dataset and the model, so it’s good to try multiple values of k and choose the one that gives the best performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a45a51db1b4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google’s BERT in NLP]]></title>
            <link>https://medium.com/@praveenraj.gowd/googles-bert-in-nlp-674114a571e8?source=rss-171feb4841e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/674114a571e8</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[innomatics-research-labs]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Praveen Raj]]></dc:creator>
            <pubDate>Tue, 19 Mar 2024 08:42:07 GMT</pubDate>
            <atom:updated>2024-06-05T11:02:55.321Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G1fF9F7QTf-YXmAu.jpg" /></figure><h3>What is BERT?</h3><p>BERT stands for <strong><em>B</em></strong><em>idirectional </em><strong><em>E</em></strong><em>ncoder </em><strong><em>R</em></strong><em>epresentations from </em><strong><em>T</em></strong><em>ransformers</em> and is a language representation model by Google. It uses two steps, <strong>pre-training </strong>and<strong> fine-tuning</strong>, that means that the same pre-trained model can be fine-tuned for a variety of final tasks that might not be similar to the task model was trained on and give close to state-of-the-art results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HU3S9kksGROZZ8EJ.png" /><figcaption>BERT: Two Steps</figcaption></figure><h3>Why is BERT Important?</h3><p>Imagine a sentence: “She plays the <strong>violin</strong> beautifully.” Traditional language models would process this sentence from left to right, missing the crucial fact that the identity of the instrument (“<strong>violin</strong>”) impacts the interpretation of the entire sentence. <strong><em>BERT</em></strong>, however, understands that the context-driven relationship between words plays a pivotal role in deriving meaning. It captures the essence of bidirectionality, allowing it to consider the complete context surrounding each word, revolutionizing the accuracy and depth of language understanding.</p><h3>How does BERT work?</h3><p>At its core, BERT is powered by a powerful neural network architecture known as <strong>Transformers</strong>. This architecture incorporates a mechanism called <strong>self</strong>-<strong>attention</strong>, allowing BERT to weigh the significance of each word based on its context, both preceding and succeeding. This context-awareness imbues BERT with the ability to generate contextualized word embeddings, which are representations of words considering their meanings within sentences.</p><p>It’s similar to BERT reading and re-reading the sentence to gain a deep understanding of every word’s role.</p><p>Consider the sentence: <strong><em>“The ‘lead’ singer will ‘lead’ the band.”</em></strong></p><p>Traditional models might struggle with the ambiguity of the word “<strong>lead</strong>.” BERT, however, effortlessly distinguishes that the first “<em>lead</em>” is a <strong>noun</strong>, while the second is a <strong>verb.</strong></p><p>BERT, a language model which is bidirectionally trained (this is also its key technical innovation). This means we can now have a deeper sense of language context and flow compared to the single-direction language models.</p><p>So how does BERT manage to pre-train bi-directionally? It does so by using a procedure called <strong>Masked Language Model.</strong></p><h3>BERT Architecture</h3><p>Simply put, it is <strong><em>a stack of Transformer’s Encoder.</em></strong></p><p><strong>BERT-Base</strong>: L = 12-layer, H 768-hidden-nodes, A = 12-attention-heads, 110M parameters<strong><br></strong><strong>BERT-Large</strong>: L= 24-layer, H = 1024-hidden-nodes, A = 16-attention-heads, 340M parameters</p><p><strong>L </strong>= Number of layers (i.e., Transformer encoder blocks in the stack).<br><strong>H</strong> = Hidden size (i.e. the size of <em>q, k </em>and<em> v </em>vectors).<br><strong>A </strong>= Number of attention heads.</p><p><strong><em>Fun fact</em></strong>: BERT-Base was trained on 4 cloud TPUs for 4 days and BERT-Large was trained on 16 TPUs for 4 days!</p><h3>A. Pre-training BERT</h3><p>The BERT model is trained on the following two unsupervised tasks.</p><h4>1. Masked Language Model (MLM)</h4><ul><li>It randomly masks words in the sentence and then it tries to predict them. Masking means that the model looks in both directions and it uses the full context of the sentence, both left and right surroundings, in order to predict the masked word.</li><li>Unlike the previous language models, it takes both the previous and next tokens into account at the <strong>same time.</strong>(It might be more accurate to say that BERT is non-directional though.)</li></ul><p><strong>But why is this non-directional approach so powerful?</strong></p><blockquote>Pre-trained language representations can either be <strong><em>context-free</em></strong> or <strong><em>context-based</em></strong>.</blockquote><p><em>Context-based </em>representations can then be <strong><em>unidirectional</em></strong> or <strong><em>bidirectional</em></strong>. Context-free models like word2vec generate a single <a href="https://towardsml.com/2018/06/12/understanding-word-embeddings/">word embedding</a> representation (a vector of numbers) for each word in the vocabulary.</p><ul><li>For example, the word “<em>bank</em>” would have the same <strong>context-free</strong> representation in “<em>bank account</em>” and “<em>bank of the river.</em>” On the other hand, context-based models generate a representation of each word that is based on the other words in the sentence.</li><li>For example, in the sentence “<em>I accessed the bank account</em>,” a unidirectional contextual model would represent “<em>bank</em>” based on “<em>I accessed the</em>” but not “<em>account</em>.” However, BERT represents “<em>bank</em>” using both its previous and next context — “<em>I accessed the</em> … <em>account</em>” — starting from the very bottom of a deep neural network, making it deeply bidirectional.</li></ul><h4>Masked Language Model (MLM) Objective: Teaching BERT Context</h4><p>This task enables the deep bi-directional learning aspect of the model. In this task, some percentage of the input tokens are masked (Replaced with [<em>MASK</em>] token) at random and the model tries to predict these masked tokens — not the entire input sequence. The predicted tokens from the model are then fed into an output softmax over the vocabulary to get the final output words.</p><p>This, however creates a mismatch between the pre-training and fine-tuning tasks because the latter does not involve predicting masked words in most of the downstream tasks. This is mitigated by a subtle twist in how we mask the input tokens.</p><p>Approximately 15% of the words are masked while training, but all of the masked words are not replaced by the [<em>MASK</em>] token.</p><ul><li>80% of the time with [<em>MASK</em>] tokens.</li><li>10% of the time with a random tokens.</li><li>10% of the time with the unchanged input tokens that were being masked.</li></ul><h4>2. Next Sentence Prediction (NSP)</h4><p>The Language Model doesn’t directly capture the relationship between two sentences which is relevant in many downstream tasks such as <a href="https://towardsdatascience.com/evaluation-of-an-nlp-model-latest-benchmarks-90fd8ce6fae5">Question Answering (QA) and Natural Language Inference (NLI)</a>.</p><p>In order to understand <em>relationship</em> between two sentences, BERT training process also uses next sentence prediction. A pre-trained model with this kind of understanding is relevant for tasks like question answering. During training the model gets as input pairs of sentences and it learns to predict if the second sentence is the next sentence in the original text as well.</p><p>BERT separates sentences with a special [SEP] token. During training the model is fed with two input sentences at a time such that:</p><p>In this task, two sentences — A and B — are chosen for pre-training.</p><ul><li>50% of the time B is the actual next sentence that follows A.</li><li>50% of the time B is a random sentence from the corpus.</li></ul><h3>B. Training — Inputs and Outputs.</h3><p>The model is trained on both above mentioned tasks simultaneously. This is made possible by clever usage of inputs and outputs.</p><blockquote>BERT is based on the <a href="https://ai.googleblog.com/2017/08/transformer-novel-neural-network.html"><strong>Transformer model architecture</strong></a>, instead of LSTMs.</blockquote><p>BERT relies on a Transformer (the attention mechanism that learns contextual relationships between words in a text). A basic Transformer consists of an encoder to read the text input and a decoder to produce a prediction for the task. Since <strong>BERT’s goal is to generate a language representation model, it only needs the ENCODER part</strong>. The input to the encoder for BERT is a sequence of tokens, which are first converted into vectors and then processed in the neural network. But before processing can start, BERT needs the input to be massaged and decorated with some extra metadata:</p><h4>Tokenization: Breaking Text into Meaningful Chunks</h4><p>Imagine you’re teaching BERT to read a book. You wouldn’t hand in the entire book at once; you’d break it into sentences and paragraphs. Similarly, BERT needs text to be broken down into smaller units called tokens. But here’s the twist: BERT uses WordPiece tokenization. It splits words into smaller pieces, like turning “running” into “run” and “ning.” This helps handle tricky words and ensures that BERT doesn’t get lost in unfamiliar words.</p><p>Example: Original Text: “ChatGPT is fascinating.”</p><p>WordPiece Tokens: [“Chat”, “##G”, “##PT”, “is”, “fascinating”, “.”]</p><h4>Input Formatting: Giving BERT the Context</h4><p>BERT loves context, and we need to serve it to him on a platter. To do that, we format the tokens in a way that BERT understands. We add special tokens like [CLS] (stands for classification) at the beginning and [SEP] (stands for separation) between sentences. As Shown in the Figure (Machine Language Model). We also assign segment embeddings to tell BERT which tokens belong to which sentence.</p><p>Example: Original Text: “ChatGPT is fascinating.”</p><p>Formatted Tokens: [“[CLS]”, “Chat”, “##G”, “##PT”, “is”, “fascinating”, “.”, “[SEP]”]</p><h4>Inputs</h4><p>The model needs to take input for both a single sentence or two sentences packed together unambiguously in one token sequence. Authors note that a “sentence” can be an arbitrary span of contiguous text, rather than an actual linguistic sentence. A [SEP] token is used to separate two sentences as well as a using a learnt segment embedding indicating a token as a part of segment A or B.</p><p><strong><em>Problem #1:</em></strong> All the inputs are fed in one step — as opposed to RNNs in which inputs are fed sequentially, the model is <strong><em>not able to preserve the ordering</em></strong> of the input tokens. The order of words in every language is significant, both semantically and syntactically.</p><p><strong><em>Problem #2:</em></strong> In order to perform Next Sentence Prediction task properly we need to be able to <strong><em>distinguish between sentences A and B</em></strong>. Fixing the lengths of sentences can be too restrictive and a potential bottleneck for various downstream tasks.</p><p>Both of these problems are solved by adding embeddings containing the required information to our original tokens and using the result as the input to our BERT model. The following embeddings are added to token embeddings:</p><ol><li><strong>Token embeddings</strong>: A [CLS] token is added to the input word tokens at the beginning of the first sentence and a [SEP] token is inserted at the end of each sentence.</li><li><strong>Segment embeddings</strong>: A marker indicating Sentence A or Sentence B is added to each token. This allows the encoder to distinguish between sentences. They provide information about the sentence a particular token is a part of.</li><li><strong>Positional embeddings</strong>: A positional embedding is added to each token to indicate its position in the sentence. They provide information about the order of words in the input.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/0*-OzmQUUUwS8joJz8" /></figure><p>Essentially, the Transformer stacks a layer that maps sequences to sequences, so the output is also a sequence of vectors with a 1:1 correspondence between input and output tokens at the same index.</p><h4>Outputs</h4><p>How does one predict output for two different tasks simultaneously? The answer is by using different <strong>Feed Forward Neural Network + SoftMax layer</strong> built on top of output(s) from the last encoder, corresponding to desired input tokens. We will refer to the outputs from last encoder as final states.</p><p>The first input token is always a special classification <em>[CLS] </em>token. The final state corresponding to this token is used as the aggregate sequence representation for classification tasks and used for the Next Sentence Prediction where it is fed into a FFNN + SoftMax layer that predicts probabilities for the labels “<em>IsNext</em>” or “<em>NotNext</em>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/0*7SEVrpInPB3nM990" /></figure><p>To predict if the second sentence is connected to the first one or not, basically the complete input sequence goes through the Transformer based model, the output of the [CLS] token is transformed into a 2×1 shaped vector using a simple classification layer, and the IsNext-Label is assigned using softmax.</p><p>The final states corresponding to [<em>MASK</em>] tokens is fed into FFNN+SoftMax to predict the next word from our vocabulary.</p><h4>Masked Language Model (MLM) Objective: The Fill-in-the-Blanks Game</h4><p>During pretraining, BERT is given sentences with some words masked (hidden). It then tries to predict those masked words based on the surrounding context. This is like a language version of the fill-in-the-blanks game. By guessing the missing words, BERT learns how words relate to each other, achieving its contextual brilliance.</p><h4>Next Sentence Prediction (NSP) Objective: Grasping Sentence Flow</h4><p>BERT doesn’t just understand words; it grasps the flow of sentences. In the NSP objective, BERT is trained to predict if one sentence follows another in a text pair. This helps BERT comprehend the logical connections between sentences, making it a master at understanding paragraphs and longer texts.</p><blockquote>The model is trained with both <strong>MLM</strong> and <strong>NSP</strong> together. This is to minimize the combined loss function of the two strategies — <em>“</em><strong><em>together is better</em></strong><em>”</em>.</blockquote><h3>C. When can we use it and how to fine-tune it?</h3><p>How can we fine-tune it for a specific task? BERT can be used for a wide variety of language tasks.</p><p>Fine-tuning BERT requires careful consideration. You can fine-tune not only the final classification layer but also intermediate layers. This enables BERT to adapt more effectively to your specific task. Experiment with different layers and learning rates to find the best combination.</p><p>The tasks we fine-tune BERT for are called “downstream tasks.” Examples include sentiment analysis, named entity recognition, and more. Fine-tuning involves updating BERT’s weights using task-specific data. This helps BERT specialize in these tasks without starting from scratch.</p><p>Fine-tuning on various downstream tasks is done by swapping out the appropriate inputs or outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D1rN6vVd-sJmxms1.png" /><figcaption>Fine-tuning BERT on various downstream tasks</figcaption></figure><p>In <strong>Sentence Pair Classification</strong> and <strong>Single Sentence Classification</strong>, the final state corresponding to [<em>CLS</em>] token is used as input for the additional layers that makes the prediction.</p><p>For example, say we are creating <strong>a question answering application</strong>. In essence question answering is just a prediction task — on receiving a question as input, the goal of the application is to identify the right answer from some corpus. So, given a question and a context paragraph, the model predicts a start and an end token from the paragraph that most likely answers the question. This means that using BERT a model for our application can be trained by learning two extra vectors that mark the beginning and the end of the answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/0*BihaMzfBZKwPhECI" /></figure><p>In QA tasks, a start (S) and an end (E) vector are introduced during fine tuning. There are two new parameters learned during fine-tuning: a <strong>start vector</strong> and an <strong>end vector. </strong>The question is fed as sentence A and the answer as sentence B.</p><p>In the fine-tuning training, most hyper-parameters stay the same as in BERT training.</p><h3>GPT — The distant cousin</h3><p>Is BERT the only model that is producing these ground breaking results? No. Another model by Open AI, called GPT has been making quite the buzz on internet.</p><p>But what many people don’t realize that these two models have something in common, that is both these model reuse a Transformer component. As stated earlier <strong>BERT stacks the encoder part</strong> of the Transformer as its building block. Meanwhile, <strong>GPT uses the decoder part</strong> of the Transformer as its building block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/0*XM5cGy_hHHRVdzcm.png" /></figure><p>Note that the bidirectional connections in BERT due to encoder’s bidirectional self-attention. Meanwhile, the connections in GPT are only in a single direction, from left-to-right, due to decoder design to prevent looking at future predictions.</p><h3>Conclusion</h3><ol><li>BERT is a stacked Transformer’s Encoder model.</li><li>It has two phases — pre-training and fine-tuning.</li><li>Pre-training is computationally and time intensive.</li><li>It is, however, independent of the task it finally does, so same pre-trained model can be used for a lot of tasks.</li><li>GPT is not that different from BERT and is a stacked Transformer’s decoder model.</li><li>There are many variants of BERT out there.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=674114a571e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Recurrent Neural Networks (RNN) — NLP]]></title>
            <link>https://medium.com/@praveenraj.gowd/understanding-recurrent-neural-networks-rnn-nlp-e2f4cae03a4f?source=rss-171feb4841e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2f4cae03a4f</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[recurrent-neural-network]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Praveen Raj]]></dc:creator>
            <pubDate>Thu, 07 Dec 2023 06:49:25 GMT</pubDate>
            <atom:updated>2023-12-08T07:56:36.910Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Recurrent Neural Networks (RNN) — NLP</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0KCGUmyzGQPgn-BX.png" /></figure><h3>What is RNN ?</h3><p>Recurrent Neural Network(RNN) is a type of Neural Network where the output from the previous step is fed as input to the current step.</p><ul><li>In some cases when it is required to <strong>predict the next word of a sentence, the previous words are required and hence there is a need to remember the previous words</strong>. Thus RNN came into existence, which solved this issue with the help of a Hidden Layer.</li><li>The main and most important feature of RNN is its <strong>Hidden state</strong>, which remembers some information about a sequence. The state is also referred to as <strong><em>Memory State </em></strong>since it remembers the previous input to the network.</li><li>RNN uses the same weights for each element of the sequence.</li></ul><p>RNN are a class of neural networks that is powerful for modeling sequence data such as time series or natural language. Basically, main idea behind this architecture is to use sequential information.</p><p><strong>Do you know how Google’s autocomplete function works???</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TksjwVdMivo2i8gB.jpg" /></figure><p>Basically, collection of large volumes of most frequently occurring consecutive words fed into <strong><em>RNN network.</em> </strong>It analyze the data by finding the sequence of words occurring frequently and builds a model to predict the next word in the sentence.</p><p>So, do you see the importance of the RNN in our daily life.</p><p><strong>Why to make it more complex by introducing a new network (RNN), hen we already have feed forward neural network(ANN)?</strong></p><p>In ANN, information flows only in forward direction from the input nodes, through the hidden layers and to the output nodes. There are no cycles or loops in the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LHPPBd_Di7TGlJO1.png" /><figcaption>ANN architecutre</figcaption></figure><p><strong><em>Issues in the feed forward neural network : -</em></strong></p><ol><li>Can’t handle sequential data.</li><li>Consider only current input.</li><li>Can’t memorize the previous input.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t54z2fof4jwFZhVT.png" /><figcaption>RNN architecture</figcaption></figure><h3>Table of contents</h3><ul><li>What are RNNs used for?</li><li>What are RNNs and how do they work?</li><li>A trivial example — forward propagation, backpropagation through time</li><li>One major problem: vanishing gradients</li></ul><h3>What are RNNs used for?</h3><p>Recurrent Neural Networks (RNNs) are widely used for data with some kind of sequential structure. For instance, time series data has an intrinsic ordering based on time. Sentences are also sequential, “I love dogs” has a different meaning than “Dogs I love.” Simply put, if the <em>semantics</em> of your data is altered by random permutation, you have a sequential dataset and RNNs may be used for your problem! To help solidify the types of problems RNNs can solve, here is a <strong>list of common applications¹ </strong>:</p><ul><li>Speech Recognition</li><li>Sentiment Classification</li><li>Machine Translation (i.e. Chinese to English)</li><li>Video Activity Recognition</li><li>Name Entity Recognition — (i.e. Identifying names in a sentence)</li></ul><p>Great! We know the types of problems that we can apply RNNs to, now…</p><h3>What are RNNs and how do they work?</h3><p>RNNs are different than the classical multi-layer perceptron (MLP) networks because of two main reasons: 1) They take into account what happened <em>previously</em> and 2) they <em>share </em>parameters/weights.</p><h3><strong>The architecture of an RNN</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FShHbrj52tVkxlqf.png" /></figure><blockquote><strong>Left</strong>: Shorthand notation often used for RNNs</blockquote><blockquote><strong>Right</strong>: Unfolded notation for RNNs</blockquote><p><em>Don’t worry if this doesn’t make sense, we’re going to break down all the variables and go through a forward propagation and backpropagation in a little bit! Just focus on the flow of variables at first glance.</em></p><h3><strong>A breakdown of the architecture</strong></h3><p>The green blocks are called <strong><em>hidden states</em></strong>. The blue circles, defined by the <strong>vector</strong> <strong><em>a</em></strong><em> </em>within each block, are called <strong><em>hidden nodes </em></strong><em>or</em><strong><em> hidden units</em></strong><em> </em>where the number of nodes is decided by the hyper-parameter <strong><em>d</em></strong><em>. </em>Similar to activations in MLPs, think of each green block as an activation function that acts on each blue node. <strong>We’ll talk about the calculations within the hidden states in the forward propagation section of this article.</strong></p><p><strong>Vector <em>h</em></strong><em> — </em>is the output of the hidden state after the activation function has been applied to the hidden nodes. As you can see at time <em>t,</em> the architecture takes into account what happened at <em>t-1</em> by including the <em>h </em>from the <em>previous</em> hidden state as well as the input <em>x</em> at time <em>t</em>. This allows the network to account for information from previous inputs that are sequentially behind the current input. It’s important to note that the zeroth <em>h </em>vector will always start as a vector of 0’s because the algorithm has no information preceding the first element in the sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/0*T9IvN4tJ3rDOSvME.png" /></figure><p>The hidden state at t=2, takes as input the output from t-1 and x at t.</p><p><strong>Matrices <em>Wx, Wy, Wh</em></strong> — are the weights of the RNN architecture which are <em>shared</em> throughout the entire network. The model weights of <em>Wx</em> at <em>t=1</em> are the exact same as the weights of <em>Wx</em> at <em>t=2</em> and every other time step.</p><p><strong>Vector <em>xᵢ</em></strong><em> — </em>is the input to each hidden state where i=1, 2,…, n for each element in the input sequence. Recall that text must be encoded into numerical values. For example, every letter in the word “dogs” would be a one-hot encoded vector with dimension <em>(4x1). </em>Similarly, x can also be word embedding or other numerical representations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tpT01Ahe6JILZX29.png" /></figure><p>One-Hot Encoding of the word “dogs”</p><p><strong>RNN Equations</strong></p><p>Now that we know what all the variables are, here are all the equations that we’re going to need in order to go through an RNN calculation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*QGuUhXdJcFYBLnOh.png" /></figure><p>These are the only three equations that we need, pretty sweet! The<strong> hidden nodes </strong>are a concatenation of the previous state’s output weighted by the weight matrix <em>Wh</em> and the input <em>x</em> weighted by the weight matrix <em>Wx. </em>The <em>tanh</em> function is the <strong>activation function</strong> that we mentioned earlier, symbolized by the green block. The <strong>output of the hidden state</strong> is the activation function applied to the hidden nodes.<strong> </strong>To make a <strong>prediction</strong>, we take the output from the current hidden state and weight it by the weight matrix <em>Wy </em>with a soft max activation.</p><p>It’s also important to understand the dimensions of all the variables floating around. In general for predicting a sequence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*u4clPWDcZUU8XwW9.png" /></figure><p>Where</p><ul><li><strong>k</strong> is the dimension of the input vector <em>xᵢ</em></li><li><strong>d</strong> is the number of hidden nodes</li></ul><p>Now we’re ready to walk through an example!</p><h3>A trivial example</h3><p>Take the word <strong>“dogs,” </strong>where we want to train an RNN to predict the letter <strong>“s” </strong>given the letters <strong>“d”-“o”-“g”</strong>. The architecture above would look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VTpQZapRbl3Eo5-R.png" /></figure><p>RNN architecture predicting the letter “s” in “dogs”</p><p>To keep this example simple, we’ll use 3 hidden nodes in our RNN <em>(d=3)</em>. The dimensions for each of our variables are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*K-Gab2mZINc0HHII.png" /></figure><p>where k = 4, because our input <em>x </em>is a 4-dimensional one-hot vector for the letters in “dogs.<em>”</em></p><h3>Forward Propagation</h3><p>Let’s see how a forward propagation would work at time <em>t=1. </em>First, we have to calculate the hidden nodes <strong><em>a</em></strong>, then apply the activation function to get <strong><em>h</em></strong>, and finally calculate the <strong>prediction</strong>. Easy!</p><p>At <strong>t=1</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eyrYJMrNBKg5t88N.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bWgmnCiiFBIWdilm.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VNIzllS_BhOtL-XG.png" /></figure><p>To make the example concrete, I’ve initialized random weights for the matrices <strong><em>Wx, Wy, </em></strong>and<em> </em><strong>Wh </strong>to provide an example with numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*joBNih5SZA209Vi3.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HyFrQTytHFdIObu4.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lA9v5xHdtbO3ofcV.png" /></figure><p>At t=1, our RNN would predict the letter “d” given the input “d”. This doesn’t make sense, but that’s ok because we’ve used untrained random weights. This was just to show the workflow of a forward pass in an RNN.</p><p>At t=2 and t=3, the workflow would be analogous except that the <em>vector h </em>from <em>t-1</em> would no longer be a vector of 0’s, but a vector of non-zeros based on the inputs before time <em>t. (As a reminder, the weight matrices Wx, Wh, and Wy remain the same for t=1,2, and 3.</em> )</p><p>It’s important to note that while the RNN <em>can</em> output a prediction at every single time step, it isn’t necessary. If we were just interested in the letter after the input “dog” we could just take the output at t=3 and ignore the others.</p><p>Now that we understand how to make predictions with RNNs, let’s explore how RNNs learn to make <em>correct predictions</em>.</p><h3>Backpropagation through time (BPTT)</h3><p>Like their classical counterparts (MLPs), RNNs use the backpropagation methodology to learn from sequential training data. Backpropagation with RNNs is a little more challenging due to the <strong><em>recursive nature of the weights and their effect on the loss which spans over time.</em></strong> We’ll see what that means in a bit.</p><p>To get a concrete understanding of how backpropagation works, let’s lay out the general workflow:</p><ol><li>Initialize weight matrices <strong><em>Wx, Wy, Wh</em></strong><em> </em>randomly</li><li>Forward propagation to compute predictions</li><li>Compute the loss</li><li>Backpropagation to compute gradients</li><li>Update weights based on gradients</li><li>Repeat steps 2–5</li></ol><p><strong><em>Note:</em></strong><em> that the output h from the hidden unit is not learned, it is merely the information gained by concatenating the learned weights to previous output h and current input x.</em></p><p>Because this example is a classification problem where we’re trying to predict four possible letters (“d-o-g-s”), it makes sense to use the <strong>multi-class cross entropy loss function</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qSQzJieJs4TSjMrZ.png" /></figure><p>Taking into account all time steps, the <strong>overall loss is</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9Lowl-rl_ZFyWARZ.png" /></figure><p>Visually, this can be seen as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KxWTXt09v5k-K9A8.png" /></figure><p>Given our loss function, we need to calculate the gradients for our three weight matrices <em>Wx, Wy, Wh, </em>and update them<em> </em>with a learning rate η. Similar to normal backpropagation, the gradient gives us a sense of how the loss is changing with respect to each weight parameter. We update the weights to minimize loss with the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iaPOy7XlcxFExZ1z.png" /></figure><p>where i = x, y, and h as a shorthand for the 3 weight matrices</p><p>Now here comes the tricky part, calculating the gradient for <em>Wx, Wy, and Wh. </em>We’ll start by calculating the gradient for <em>Wy</em> because it’s the easiest. As stated before, the effect of the weights on loss spans over time. The weight gradient for <em>Wy </em>is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z49nYMVLc6S-e8oA.png" /></figure><p>That’s the gradient calculation for <em>Wy</em>. Hopefully, pretty straight forward, <strong>the main idea is chain rule and to account for the loss at each time step.</strong></p><p>The weight matrices <em>Wx</em> and W<em>h </em>are analogous to each other, so we’ll just look at the gradient for <em>Wx</em> and leave <em>Wh</em> to you. One of the trickiest parts about calculating <em>Wx </em>is the recursive dependency on the previous state, as stated in line (2) in the image below. We need to account for the derivatives of the current error with respect to each of the previous states, which is done in (3). Finally, we again need to account for the loss at each time step (4).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FlIqRrHYy1RsiFzh.png" /></figure><p>And that’s backpropagation! Once we have the gradients for <em>Wx, Wh, and Wy</em>, we update them as usual and continue on with the backpropagation workflow. Now that you know how RNNs learn and make predictions.</p><h3>One major problem: vanishing gradients</h3><p>A problem that RNNs face, which is also common in other deep neural nets, is the <strong>vanishing gradient problem</strong>. Vanishing gradients make it difficult for the model to learn long-term dependencies. For example, if an RNN was given this sentence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bc0LmYU8ntPPGxyH.png" /></figure><p>and had to predict the last two words “german” and “shepherd,” the RNN would need to take into account the inputs “brown”, “black”, and “dog,” which are the nouns and adjectives that describe a german shepherd. However, the word “brown” is quite far from the word “shepherd.” From the gradient calculation of <em>Wx</em> that we saw earlier, we can break down the backpropagation error of the word “shepherd” back to “brown” and see what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-K83ubu9KTBoTknO.png" /></figure><p>The partial derivative of the state corresponding to the input “shepherd” respective to the state “brown” is actually a chain rule in itself, resulting in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0vm99g_TT0oSEub-.png" /></figure><p>That’s a lot of chain rule! These chains of gradients are troublesome because if less than 1 they can cause the loss from the word shepherd with respect to the word brown to approach 0, thereby <em>vanishing</em>. This makes it difficult for the weights to take into account words that occur at the start of a long sequence. So the word “brown” when doing a forward propagation, may not have any effect in the prediction of “shepherd” because the weights weren’t updated due to the vanishing gradient. This is one of the major disadvantages of RNNs.</p><p>However, there have been advancements in RNNs such as gated recurrent units (GRUs) and long short term memory (LSTMs) that have been able to deal with the problem of vanishing gradients.</p><h3>Types of RNN architectures:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cnS6jRCi55Q9Lbj2.png" /></figure><h4>One to One</h4><p>This type of RNN behaves the same as any simple Neural network it is also known as Vanilla Neural Network. In this Neural network, there is only one input and one output.</p><h4>One To Many</h4><p>In this type of RNN, there is one input and many outputs associated with it. One of the most used examples of this network is Image captioning where given an image we predict a sentence having Multiple words.</p><h4>Many to One</h4><p>In this type of network, Many inputs are fed to the network at several states of the network generating only one output. This type of network is used in the problems like sentimental analysis. Where we give multiple words as input and predict only the sentiment of the sentence as output.</p><h4>Many to Many</h4><p>In this type of neural network, there are multiple inputs and multiple outputs corresponding to a problem. One Example of this Problem will be language translation. In language translation, we provide multiple words from one language as input and predict multiple words from the second language as output.</p><h3>Advantages and Disadvantages of Recurrent Neural Network</h3><blockquote><strong>Advantages</strong></blockquote><ol><li>An RNN remembers each and every piece of information through time. It is useful in time series prediction only because of the feature to remember previous inputs as well. This is called Long short term memory.</li><li>Recurrent neural networks are even used with convolutional layers to extend the effective pixel neighborhood.</li></ol><blockquote><strong>Disadvantages</strong></blockquote><ol><li>Vanishing and exploding gradient problems.</li><li>Training an RNN is a very difficult task.</li><li>It cannot process very long sequences if using Tanh or Relu as an activation function.</li></ol><h3>Applications of Recurrent Neural Network</h3><ol><li>Language Modelling and Generating Text</li><li>Speech Recognition</li><li>Machine Translation</li><li>Image Recognition, Face detection</li><li>Time series Forecasting</li></ol><h3>Variation Of Recurrent Neural Network (RNN)</h3><p>To overcome the problems like vanishing gradient and exploding gradient descent several new advanced versions of RNNs are formed some of these are as;</p><ol><li>Bidirectional Neural Network (BiNN)</li><li>Long Short-Term Memory (LSTM)</li></ol><blockquote><strong><em>Bidirectional Neural Network (BiNN)</em></strong></blockquote><p>A BiNN is a variation of a Recurrent Neural Network in which the input information flows in both direction and then the output of both direction are combined to produce the input. BiNN is useful in situations when the context of the input is more important such as NLP tasks and Time-series analysis problems.</p><blockquote><strong><em>Long Short-Term Memory (LSTM)</em></strong></blockquote><p>Long Short-Term Memory works on the read-write-and-forget principle where given the input information network reads and writes the most useful information from the data and it forgets about the information which is not important in predicting the output. For doing this three new gates are introduced in the RNN. In this way, only the selected information is passed through the network.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2f4cae03a4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>