<?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 Abdullah Siddique on Medium]]></title>
        <description><![CDATA[Stories by Abdullah Siddique on Medium]]></description>
        <link>https://medium.com/@abdullah.siddique.010?source=rss-962684e95f6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gvZFJsp8ZOed80vR-4NcPg.png</url>
            <title>Stories by Abdullah Siddique on Medium</title>
            <link>https://medium.com/@abdullah.siddique.010?source=rss-962684e95f6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:06:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abdullah.siddique.010/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[Unlock Local AI Power with Ollama: A Quickstart Guide]]></title>
            <link>https://medium.com/@abdullah.siddique.010/unlock-local-ai-power-with-ollama-a-quickstart-guide-a05c1f66c559?source=rss-962684e95f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a05c1f66c559</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Abdullah Siddique]]></dc:creator>
            <pubDate>Wed, 07 Feb 2024 09:46:42 GMT</pubDate>
            <atom:updated>2024-02-07T09:46:42.344Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*lvvlWEP2DmOClxEy0sHk9g.png" /></figure><p><strong>Introduction</strong></p><p>In today’s rapidly evolving digital landscape, the demand for advanced AI capabilities, especially in language processing, has skyrocketed. Ollama emerges as a groundbreaking solution, offering enthusiasts, developers, and organizations the ability to harness the power of large language models (LLMs) directly on their local machines. This article delves into the core functionalities, installation processes, and the versatile applications of Ollama, guiding you through getting up and running with state-of-the-art language models across various platforms including macOS, Windows (via WSL2), Linux, and Docker.</p><p><strong>What Ollama Does</strong></p><p>Ollama is a lightweight, extensible framework designed to democratize access to large language models by facilitating their deployment on local environments. It simplifies the complexities involved in running and managing these models, providing a seamless experience for users across different operating systems. Here’s a snapshot of what Ollama brings to the table:</p><ul><li><strong>Ease of Installation:</strong> With straightforward commands for different operating systems, Ollama ensures a hassle-free setup process. For Linux and WSL2 users, it’s as simple as running a curl command.</li><li><strong>Diverse Model Support:</strong> Ollama hosts a library of open-source models, ranging from 2.7 billion to 70 billion parameters, catering to various needs and computational capabilities.</li><li><strong>Customization and Flexibility: </strong>Users can customize models to suit specific needs, from importing models in GGUF format to adjusting parameters and system messages for a tailored AI interaction.</li><li><strong>Comprehensive CLI and Docker Support:</strong> Whether you prefer a command-line interface or running models in isolated Docker containers, Ollama provides the flexibility to choose your preferred method.</li></ul><p><strong>Use Cases</strong></p><p>Ollama’s versatility shines through its wide range of applications. Here are just a few scenarios where Ollama can be a game-changer:</p><ul><li><strong>Educational Tools and Tutorials:</strong> By customizing prompts and models, educators can create interactive learning experiences in subjects like coding, languages, and science.</li><li><strong>Development and Testing Environments:</strong> Developers can leverage models like Code Llama for coding assistance, bug fixing, and even generating code snippets.</li><li><strong>Creative Writing and Content Generation:</strong> From generating story ideas to crafting detailed narratives, Ollama’s models can serve as a creative companion for writers and content creators.</li><li><strong>Personalized Chatbots: </strong>Whether for customer service, personal assistants, or thematic chatbots (like Mario from Super Mario Bros.), Ollama allows for the creation of specialized conversational agents.</li><li><strong>Research and Data Analysis:</strong> Researchers can use custom models to analyze large datasets, extract insights, or even summarize research papers and documents.</li></ul><p><strong>Getting Started with Ollama</strong></p><p>The journey to unleashing the potential of large language models locally begins with a few simple steps:</p><ol><li><strong>Installation: </strong>Follow the platform-specific instructions to install Ollama on macOS, Windows (via WSL2), Linux, or Docker.</li><li><strong>Model Selection: </strong>Choose from an array of open-source models based on your requirements, considering factors like parameters and size.</li><li><strong>Customization:</strong> Utilize the Modelfile to import models, customize prompts, and set parameters, tailoring the AI to your specific needs.</li><li><strong>Running and Managing Models: </strong>With commands to create, pull, run, and manage models, Ollama offers a comprehensive toolkit for interacting with your chosen LLMs.</li></ol><p><strong>Conclusion</strong></p><p>Ollama stands at the forefront of localized AI, bridging the gap between advanced language models and end-users. By offering a platform that is accessible, customizable, and versatile, Ollama empowers users to explore the full potential of AI without the need for extensive infrastructure or cloud dependencies. Whether you’re a developer, researcher, educator, or simply an AI enthusiast, Ollama provides the tools and resources to explore, innovate, and create with some of the most powerful language models available today. Start your journey with Ollama and unlock the world of possibilities that large language models offer, all from the comfort of your local machine.</p><p>That’s all folks</p><p>May the force be with you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a05c1f66c559" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating the New Frontier: A Guide to Thriving in the Generative AI Development Landscape]]></title>
            <link>https://medium.com/@abdullah.siddique.010/navigating-the-new-frontier-a-guide-to-thriving-in-the-generative-ai-development-landscape-1f1f6bfbfb7d?source=rss-962684e95f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f1f6bfbfb7d</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Abdullah Siddique]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 09:22:39 GMT</pubDate>
            <atom:updated>2024-01-25T09:22:39.266Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4NuVO8hSQyBVvvK8ATOEbw.png" /></figure><p>Are you poised to harness the transformative power of AI in development?</p><p>Set aside your notions of GitHub Co-Pilot and similar AI Code Assistants. We’re venturing into the deeper, more intricate realm of AI integration, akin to the seismic shift brought about by cloud development in recent years. As AI continues to evolve and refine its capabilities, a growing demand emerges for developers proficient in weaving AI innovations seamlessly into existing applications.</p><p>Fortunately, you have the golden opportunity to gear up for this shift by strategically honing the necessary skills.</p><p>Today, we embark on an enlightening journey to explore:</p><ul><li>A robust framework for advancing developer skills</li><li>The blueprint to evolve into a generative AI developer from ground zero</li><li>Essential insights every developer must grasp about AI integration in 2024</li><li>Key knowledge data analysts require for AI integration in 2024</li></ul><p>Dive in as we unravel these facets and prepare you to thrive in the AI-augmented landscape of development!</p><p><strong>A Blueprint for Elevating Developer Skills</strong></p><p>In the world of development, your skillset isn’t just growing — it’s ascending, layer by layer, like a meticulously crafted pyramid.</p><p>Imagine, if you will, each layer of this pyramid representing a pivotal aspect of your expertise. At the core lies the bedrock of all software engineering: the art of problem-solving. This foundational skill is universal, transcending beyond mere troubleshooting to become the heartbeat of every project you undertake.</p><p>Yet, the journey doesn’t pause at problem-solving. As a developer, you’re part of a dynamic ecosystem where diverse programming languages and frameworks interweave, each contributing to your unique tapestry of skills. Whether it’s crafting a sleek user interface or engineering complex data algorithms, you’re not just coding; you’re architecting solutions, one layer at a time.</p><p>Behold the pyramid of developer skills — a testament to your ever-evolving journey in the tech realm. Each tier, a milestone; each skill, a stepping stone to the apex of your potential.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OwYsEeDchA6eJBBJ_Eu8Sg.png" /></figure><p>This skill pyramid universally applies to software developers, showcasing that AI proficiency nestles among core competencies like API and Cloud knowledge. With a solid foundation in these fundamental skills, even novices can embark on a journey to become adept generative AI developers.</p><p>Up next, I’ll highlight key skills that pave the way for you to craft AI applications, setting you on a path to career readiness for 2024 and beyond.</p><p><strong>Embarking on the Journey to Becoming a Generative AI Developer</strong></p><p>In the intricate tapestry of software development, each skill intricately interlaces with the next, forming a robust foundation. For aspiring developers, this means embracing the basics before diving into the depths of AI. Yet, with the right arsenal of resources and a meticulously curated learning trajectory, transforming into a Generative AI (Gen AI) developer is not just a possibility — it’s an achievable milestone.</p><p>Here’s a streamlined roadmap to navigate from the realm of novice to the echelons of a seasoned AI developer:</p><ol><li><strong>Learn to Code</strong>: Initiate your journey with the essentials of problem-solving and Python.</li><li><strong>Python Projects</strong>: Apply your newfound knowledge in real-world scenarios through practical Python projects.</li><li><strong>Data Structures and Algorithms: </strong>Delve into the world of advanced computer science, a critical cornerstone for your development journey.</li><li><strong>Object-Oriented Programming (OOP):</strong> Grasp the principles of OOP, an indispensable skill for architecting modern, scalable applications.</li><li><strong>Cloud and API Design:</strong> Master the art of leveraging cloud infrastructure, a pivotal skill in today’s interconnected digital ecosystem.</li><li><strong>Data Science Basics:</strong> Understand that the realms of AI and machine learning are deeply rooted in data science fundamentals.</li><li><strong>Machine Learning and AI:</strong> Demystify the theories and fundamental principles of these cutting-edge technologies, complemented by hands-on practice.</li></ol><p>While this pathway might seem straightforward, each step is an expedition in itself, demanding time, dedication, and an unwavering commitment to learning. The realm of programming is ever-evolving, a continuous quest for knowledge, even for the most seasoned developers.</p><p>In summary, view your skillset as a living, breathing entity, consistently nurturing and expanding it. Embrace the journey, for every new skill acquired is a step closer to mastering the art of Generative AI development.</p><p><strong>Essential AI Skills for Developers in 2024</strong></p><p>In the realm of technological advancements, the current era mirrors the transformative cloud development wave of the early 2010s, but this time, it’s the dawn of the AI revolution. This seismic shift heralds AI integration as an essential competency for developers, reminiscent of the evolution that cloud development brought to web applications. The horizon is clear: AI development is poised to redefine the landscape of software engineering.</p><p>What does this evolution entail for developers on the ground? It signifies a paradigm shift towards crafting applications by harnessing the capabilities of existing AI tools. This transition, however, doesn’t necessitate a deep dive into the intricate mechanics of AI model construction, especially for those not directly involved with AI-centric organizations like OpenAI, Anthropic, or specialized teams within tech giants like Google and Facebook.</p><p>So, what’s the crux of AI knowledge that every developer must grasp to effectively employ these tools? Let’s unravel the essentials that will empower you to navigate and thrive in the AI-augmented landscape of 2024.</p><p><strong>Decoding Large Language Models for Developers</strong></p><p>Unveiling the Power of LLMs: Large Language Models (LLMs) like GPT-4 and Google Gemini are the driving forces behind AI marvels such as ChatGPT and Google Bard. For developers, understanding the mechanics of LLMs is not just beneficial — it’s crucial. These models are more than sophisticated auto-completes; they are intricate systems with vast potential for customization.</p><p><strong>Key LLM Insights for Developers:</strong></p><ul><li><strong>Optimization:</strong> How is the model refined for efficiency?</li><li><strong>Training Data:</strong> What kind of data feeds the model’s intelligence?</li><li><strong>Specialization and Limitations:</strong> Are there specific use-cases or known weak points?</li><li><strong>Privacy and Safety:</strong> What measures are in place to ensure data integrity and user safety?</li></ul><p><strong>Exploring LangChain</strong></p><p>LangChain stands as a robust framework for crafting applications powered by LLMs. It encompasses:</p><ul><li><strong>Libraries in Python &amp; JavaScript: </strong>Offering the core functionalities needed for development.</li><li><strong>LangChain Templates:</strong> Providing reference architectures for various tasks.</li><li><strong>LangServe:</strong> A tool for deploying LangChains through a REST API.</li><li><strong>LangSmith:</strong> A platform dedicated to monitoring, debugging, and evaluating LangChains and other LLM frameworks. LangChain exemplifies a vital tool in integrating LLMs into customized applications.</li></ul><p>Diving into Machine Learning &amp; Data Science Essentials: For developers, a grasp of the following is indispensable:</p><ul><li><strong>Machine Learning Algorithms: </strong>Understand the pillars of supervised, unsupervised, and reinforcement learning.</li><li><strong>Neural Networks and Deep Learning:</strong> Delve into the architecture integral to LLMs.</li><li><strong>Model Evaluation and Tuning:</strong> Learn how AI models are refined and benchmarked.</li></ul><p><strong>Foundational Data Science Concepts:</strong></p><ul><li><strong>Statistics and Probability:</strong> Master the basics of hypothesis testing and data distribution.</li><li><strong>Data Visualization:</strong> Skillfully use tools like Matplotlib, Seaborn, and Bokeh.</li><li><strong>Data Preprocessing:</strong> Learn the art of cleaning and organizing data.</li><li><strong>Linear Algebra:</strong> Refresh your knowledge on vectors and matrices, crucial for understanding AI frameworks.</li></ul><p>With these insights and tools at your disposal, you’re not just ready to face the AI-driven future — you’re ready to shape it.</p><p>That’s all Folks!!!</p><p>May the Force be with you!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f1f6bfbfb7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning in 2024 ; What would I do if I had to start over]]></title>
            <link>https://medium.com/@abdullah.siddique.010/machine-learning-in-2024-what-would-i-do-if-i-had-to-start-over-bea9d022c063?source=rss-962684e95f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bea9d022c063</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Abdullah Siddique]]></dc:creator>
            <pubDate>Mon, 01 Jan 2024 10:13:29 GMT</pubDate>
            <atom:updated>2024-01-01T10:13:29.055Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*8SjpeDtyKgnhGjnat3yezQ.png" /></figure><h3>Machine Learning in 2024 ; What would I do if I had to start over</h3><h3>7 step plan to follow to get started on your Machine Learning journey.</h3><p>I am a Machine Learning Engineer working as a freelancer. I have been in the field for 3 years now, I have worked with multi national companies and clients from all around the globe.</p><p>Today I am going to tell you how I would learn ML if I could start over, in 7 simple steps.</p><p>Let’s get started.</p><h3><strong>1. Python</strong></h3><p>Let’s begin with the first most important and basic step of all, learning Python.</p><p>Python is the corner stone, the first brick laid, for your ML journey. It’s the language used by pretty much everyone working on Machine Learning. You are going to build your marvelous ML monument atop Python.</p><p>For beginners I would recommend learning python basic such as what is a list, how to create dictionaries, how to deal with arrays, go over the basics of loops(for, while) and conditional statements(if-else). Learn how to create and call functions. I would even go as far as saying you also need to learn what list comprehensions and class inheritance are.</p><p>How to learn? Well honestly just hop onto YouTube and Search for “Python for beginners” you can find tons of resources there.</p><h3>2. Mathematics</h3><p>Programming is fun, but understanding the logic behind it is extremely crucial as well.</p><p>Now, you could argue that you don’t need math because so much is already automated and taken care of by cool Python libraries, which is true, but you will need to know the fundamentals of calculus, linear algebra, and probability theory to understand pretty much any ML approach.</p><p>But you don’t need complex math. High school or entry-level college math would be sufficient. You just need to understand what the derivative of a function is and how to compute it, what a matrix is and how the dot product works, what are integrals and how summation works.</p><p>Basic knowledge of statistics and probability such as how to calculate mean, mode, median, standard deviation and variance. How to take logs and reverse logs and how to calculate probabilities.</p><p>Now you don’t need to master it and memorize it, you can always revisit it later on or just simply google it.</p><p>Learn the basics, and then continue on to the next, fun step! Learning about the Basics of ML .</p><h3>3. Basic of ML</h3><p>So, now you know the basics of Python and math, we can start learning the basics of ML.</p><p>Master 3 libraries</p><p>i) Numpy</p><p>ii) Pandas</p><p>iii) Matplotlib</p><p>Numpy is a library for doing math with matrices or arrays. It’s a great starting point because you can now implement the math that you just learned about and see how simple it is to compute a dot product between two matrices.</p><p>Finally, pandas is a great tool for dealing with data that is in a tabular format. A lot of ML problems deal with tabular data and pandas let you again very easily manipulate and visualize those tables.</p><p>Matplotlib is a tool for visualizing data and graphs and just seeing what maths you are doing. And, in my opinion, at least, visualizing stuff is fun and just very useful!</p><p>These are the core libraries that you are going to always need. Even on Kaggle (a well know platform for ML, we’ll discuss later on) imports pandas and numpy by default. So my recommendation would be to have a strong grip over these libraries. Again you don’t need to know every function by memory but should know which to use where.</p><p>As you will see, by getting to know those frameworks, you will also automatically improve your overall practical Python and ML skills! But again, only focus on the basics by following a few tutorials. Later, when working on projects, you will really get to know the libraries.</p><h3>4. Diving deep in the realm of Machine Learning</h3><p>Once you have covered the basics, which should take 3 weeks at the most, now it’s time to delve deep into the realm of Machine Learning.</p><p>Now there are lots of courses out there, but one stands atop all. Taught by the God Father of Machine Learning himself, <a href="https://www.coursera.org/specializations/machine-learning-introduction#courses">Machine Learning Specialization by Andrew Nigel.</a></p><p>In this course you are going over the basics of pretty much every machine learining algorithm. You are going to get hands on practice for Tensorflow and Sicikit Learn. This course is absolutely gold! And it’s free!!!</p><p>Let’s go one step further and introduce yourself to the basics of neural networks. You have previously learned Tensorflow framework, but I would recommend switching over to Pytorch. I can give a detailed explanation on “Why Pytorch?” but I think you should find it out yourself.</p><p>I would recommend taking the course by <a href="https://www.youtube.com/@AndrejKarpathy">Andrej Karpathy</a>. It’s on YouTube and it’s totally free. <a href="https://www.youtube.com/watch?v=VMj-3S1tku0&amp;list=PLAqhIrjkxbuWI23v9cThsA9GvCAUhRvKZ&amp;ab_channel=AndrejKarpathy">From zero to hero</a>, it is as the name states.</p><p>Once we have covered the basic of Machine Learning algorithms and Neural Networks, let’s get a bit advanced and portal from Machine learning to the wonderous world of Deep Learning.</p><p>The questions arises where to start, well don’t worry about that. You are in the safe hands of the ML God Father, (drum roll please) <a href="https://www.coursera.org/specializations/deep-learning?irclickid=x-U2gpTSJxyLTxPwUx0Mo3EoUkDXeu01jUFXWo0&amp;irgwc=1#courses">The Deep Learning Specialization.</a> This course focuses more on implementing and training Neural Nets and the absolutely amazing thing here is that they also include Huggingface 🤗, which is a library that you pretty much can’t avoid. It’s really amazing.</p><p>So yeah, those are the 2 or perhaps even 3 courses I would take and recommend.</p><h3>5. Kaggle</h3><p>Time to meet your new best friend, Kaggle.</p><p>Need to create a notebook without creating a private environment, Kaggle.</p><p>Need a specific, particular dataset, Kaggle.</p><p>Need GPU for training your 2 GB Pytorch model, Kaggle.</p><p>Need to download and test the latest transformers model, Kaggle.</p><p>Can’t figure out what you did wrong in your code, need help from a supportive community, Kaggle.</p><p>Believe me when I say it, Kaggle is your bestfriend and always have your back. You can find every dataset on Kaggle, you can find different notebooks created by people that are a source of great learning. You can compare the work of 2 people and decide for yourself which model would you prefer. You can fork a notebook, make changes and see for yourself how the results turn out to be.</p><p>I can’t stress it anymore than this, get on Kaggle, start creating notebooks, read other people’s work, participate in discussions, learn from articles and general discussions, participate in competitions to see how far you have come. So get on <a href="https://www.kaggle.com/">Kaggle</a> and start Kaggling.</p><h3>6. Personal Projects and Open Source Contributions</h3><p>Now that you know what is Machine Learning , Deep learning, you have basic knowledge of tools and libraries, start working on personal projects.</p><p>I am not talking about creating EDA notebook on Kaggle for titanic dataset, be innovation. Create a project such as using machine learning to predict what animal does a cloud look like or using machine learning to tell what time it is on an analog clock, or generating new lyrics for already existing song and merge in the original one.</p><p>I am not saying these are your only options, be wild, be creative, be innovative, be an Machine Learning Engineer.</p><p>Start contributing to open source projects. You are not going to solve bugs on day one, start by writing documentation, fixing spelling mistakes, adding readme files, participate in the opened issued section. Start with baby steps.</p><p>For example, if there is a project that detects people entering and existing a building, you can add a feature that detects that person is wearing a mask or not.</p><p>Just start contributing, no matter how small, one day you are gonna make it to the top contributors.</p><h3>7. Learn, Grow, Evolve</h3><p>By now, you have learned the basic of ML and DL. Created some cool personal projects and became a Kaggler, but the journey doesn’t end here. You have to keep learning and you have to keep moving forward.</p><p>Here are some practices to keep you updated with the upcoming trends</p><ol><li>Read research papers, <a href="https://arxiv.org/">arXiv</a> is a good place to start.</li><li>Read some well known Newsletters.</li><li>Read medium articles.</li><li>Attend online AI conferences.</li><li>Network with ML experts on LinkedIn.</li></ol><p>You can connect with me on <a href="https://www.linkedin.com/in/abdullah1772/">LinekdIn</a> and let’s contribute and collaborate together.</p><p>I wish you Good Luck on your ML journey in 2024.</p><p>May the force be with you!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bea9d022c063" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Handwritten Digit Recognition Using K-Nearest Neighbors (KNN)]]></title>
            <link>https://blog.devgenius.io/understanding-handwritten-digit-recognition-using-k-nearest-neighbors-knn-da677e87c8ac?source=rss-962684e95f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/da677e87c8ac</guid>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[knn-classification]]></category>
            <category><![CDATA[digit-recognition]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Abdullah Siddique]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 13:31:53 GMT</pubDate>
            <atom:updated>2023-06-08T10:42:57.570Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*hpi5nNTBrjEnHz5EtOcqeQ.jpeg" /></figure><h3>Introduction</h3><p>Handwritten digit recognition is one of the foundational tasks in the field of machine learning, and it has several real-world applications, such as reading postal mail numbers, bank check digits, and form applications. In this article, we explore how the K-Nearest Neighbors (KNN) algorithm can be used to achieve this task using the MNIST dataset. KNN is a simple yet powerful non-parametric classification technique that works by finding a predefined number of training samples closest in distance to a new point and predicting the label from these.</p><h3>Motivation</h3><p>The choice of KNN for this task stems from its simplicity and effectiveness. Being a lazy learning algorithm, KNN makes no assumptions about the nature of the underlying data, making it useful for situations where the decision boundary is very irregular. Furthermore, its ability to adapt quickly to changes makes KNN an excellent choice for recognizing handwritten digits, where variation is the norm rather than the exception.</p><p>In this article we’ll be training KNN for MNIST, you can find the complete notebook <a href="https://www.kaggle.com/code/kane6543/classify-mnist-using-knn">here</a>. Now let’s discuss in detail what we are doing in this notebook.</p><h3>Loading the Dataset</h3><p>The MNIST (“Modified National Institute of Standards and Technology”) dataset is a large database of handwritten digits that is widely used for training and testing in the field of machine learning. It contains 60,000 training images and 10,000 testing images, each of which is a 28x28 grayscale image, associated with a label from 0 to 9.</p><pre>from sklearn.datasets import load_digits<br><br># Load data<br>digits = load_digits()<br>X = digits.images<br>y = digits.target<br></pre><h3>Performing Exploratory Data Analysis (EDA)</h3><p>First of all let’s display our dataset.</p><pre># Plot the first few images<br>fig, axes = plt.subplots(2, 5, figsize=(10, 5))<br>axes = axes.ravel()<br>for i in np.arange(0, 10):<br>    axes[i].imshow(X[i], cmap=&#39;gray&#39;)<br>    axes[i].set_title(&quot;Digit: %s&quot; % y[i])<br>    axes[i].axis(&#39;off&#39;)<br>plt.subplots_adjust(wspace=0.5)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*Buhl8omgPPN-D0D52jxiEQ.png" /></figure><p>Next plotting the distribution of classes in the MNIST dataset is a crucial step in Exploratory Data Analysis (EDA). The purpose of this analysis is to investigate whether the dataset is balanced, meaning each class (in this case, each digit from 0 to 9) has approximately an equal number of instances. An imbalanced dataset can lead to a bias in the machine learning model, causing it to perform well on the over-represented classes while performing poorly on the under-represented ones. By visualizing the class distribution, we can ensure that each class is adequately represented in our dataset. This informs our strategy for training the machine learning model and allows us to take corrective measures if necessary, such as data augmentation, resampling techniques or adjusting the class weights.</p><pre># Plot the distribution of classes<br>plt.figure(figsize=(10, 5))<br>plt.bar(unique, counts)<br>plt.xticks(unique)<br>plt.xlabel(&quot;Digit&quot;)<br>plt.ylabel(&quot;Frequency&quot;)<br>plt.title(&quot;Distribution of digits in MNIST&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*nXSNRU5uq3B8OvlmyVGwEg.png" /></figure><p>Now let’s visualize the average image for each digit (0 through 9) in the MNIST dataset. The reason for doing this is to gain a deeper understanding of the common patterns that underlie each digit class. By averaging all images belonging to a particular class, we obtain a representative image that encapsulates the common traits of that digit as it appears in our dataset. These ‘average images’ provide us with a general outline or a “prototypical” digit that our model is likely to encounter. Observing these images can shed light on the unique characteristics of each digit and give us a visual intuition about the features that the model might need to learn to differentiate between the different classes effectively.</p><pre># Compute average images for each digit<br>avg_images = np.array([np.mean(X[y == i], axis=0) for i in range(10)])<br><br># Plot average images<br>fig, axes = plt.subplots(2, 5, figsize=(10, 5))<br>axes = axes.ravel()<br>for i in np.arange(0, 10):<br>    axes[i].imshow(avg_images[i], cmap=&#39;gray&#39;)<br>    axes[i].set_title(&quot;Digit: %s&quot; % i)<br>    axes[i].axis(&#39;off&#39;)<br>plt.subplots_adjust(wspace=0.5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*DUfW3KcIygXTRMPLPQ-JDA.png" /></figure><p>Next up we perform this pixel intensity distribution analysis to better understand the distribution of pixel values across our MNIST dataset. By reshaping the 3D image data into a 2D array and subsequently flattening it to a 1D array, we can examine all pixel values collectively. The histogram then plots the frequency of these pixel values, ranging from 0 (black) to 255 (white). This provides insight into the general characteristics of our images. For example, if most pixel values are towards the lower end (near 0), it would indicate that our images are generally dark, with a few distinctive white areas representing the digits. This understanding can be useful for preprocessing steps, like normalization or standardization, and can also assist in refining our machine learning model by providing insight into the data it will learn from.</p><pre># Reshape X to 2D<br>X_2D = X.reshape(X.shape[0], -1)<br><br># Histogram of pixel intensities<br>plt.figure(figsize=(10, 5))<br>plt.hist(X_2D.ravel(), bins=30, color=&#39;gray&#39;, alpha=0.7)<br>plt.title(&quot;Distribution of pixel intensities&quot;)<br>plt.xlabel(&quot;Pixel intensity&quot;)<br>plt.ylabel(&quot;Frequency&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*bRpjZUj45NOKvqm7JsgHsw.png" /></figure><p>Next up we have t-SNE visualization. t-SNE (t-Distributed Stochastic Neighbor Embedding) is a machine learning algorithm particularly suited for the visualization of high-dimensional datasets, like the MNIST data, which consists of images of 8x8 pixels (a 64-dimensional dataset). When it becomes impractical to visualize such high-dimensional data, dimensionality reduction techniques, like t-SNE, help to represent this data in 2D or 3D, preserving significant structures at different scales. The t-SNE visualization plotted here translates these high-dimensional digit images into 2D while maintaining the relative distances between different data points. Each point in the plot corresponds to an MNIST digit, and the color corresponds to the actual digit label. Clusters of similar data points of the same color indicate that digits of the same type have similar pixel intensity patterns. In summary, we use t-SNE to better understand and gain insights from our high-dimensional data by visually identifying clusters or groups of similar instances, and potentially, outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*eCZ5pz99vCHnHPP_nHDEEQ.png" /></figure><h3>Preparing the Dataset for KNN</h3><p>The preparation of the dataset for the KNN model primarily involves normalizing the grayscale values and reshaping the data arrays. Normalization, which scales all grayscale values to between 0 and 1, helps the model train faster and reduces the chances of getting stuck in local optima. Reshaping the data arrays from 3 dimensions to 2 dimensions simplifies the input for the KNN model, which expects a 2D array.</p><pre># Load data<br>digits = load_digits()<br>X = digits.images.reshape((len(digits.images), -1))<br>y = digits.target</pre><h3>Splitting the Data</h3><p>The first crucial step is to divide our MNIST dataset into a training set and a testing set. This is done to evaluate our model’s performance on unseen data after training. The train_test_split function from sklearn&#39;s model_selection module is used for this purpose. The test_size parameter is set to 0.2, implying that 20% of the data is reserved for testing. The stratify=y parameter ensures that the distribution of labels remains the same in both the training and testing sets. The random_state parameter is used to reproduce the same training and testing sets across multiple runs.</p><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)</pre><h3>Defining Hyperparameters</h3><p>KNN’s performance is highly dependent on the choice of its hyperparameters. The three main hyperparameters that we consider are:</p><ol><li>n_neighbors: The number of neighbors to consider. We try values from 3 to 11.</li><li>weights: The weight function used in prediction. We consider two common choices: &#39;uniform&#39; (all points in each neighborhood are weighted equally) and &#39;distance&#39; (points are weighted by the inverse of their distance, so closer neighbors have a greater influence).</li><li>p: Power parameter for the Minkowski metric. When p=1, this is equivalent to using manhattan_distance, and euclidean_distance is used for p=2.</li></ol><pre>parameters = {<br>    &#39;n_neighbors&#39;: [3, 5, 7, 9, 11],<br>    &#39;weights&#39;: [&#39;uniform&#39;, &#39;distance&#39;],<br>    &#39;p&#39;: [1, 2]<br>}</pre><h3>Model Initialization and Grid Search</h3><p>We start by initializing the KNN model using KNeighborsClassifier(). Then, we perform a grid search to find the optimal combination of hyperparameters for our KNN model. Grid search is a process where you define a set of possible values for different hyperparameters, and you try every possible combination. In this case, the hyperparameters and their possible values are defined in the parameters dictionary.</p><p>The GridSearchCV function from sklearn&#39;s model_selection module is used to perform the grid search. This function trains a KNN model for each combination of hyperparameters and uses cross-validation to evaluate the performance of each model. The cv parameter specifies the number of folds for cross-validation, and the scoring parameter specifies the metric used for evaluation.</p><pre>knn = KNeighborsClassifier()<br>grid_search = GridSearchCV(knn, parameters, cv=5, scoring=&#39;accuracy&#39;)<br>grid_search.fit(X_train, y_train)</pre><h3>Evaluating the Results of Grid Search</h3><p>Once the grid search is completed, we can print the best combination of hyperparameters and the corresponding accuracy score. This is done using the best_params_ and best_score_ attributes of the grid_search object.</p><pre>print(grid_search.best_params_)<br>print(grid_search.best_score_)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*Mm2ryHb5HupBjgwVmp3Jdw.png" /></figure><h3>Training the Model with Optimal Hyperparameters</h3><p>Finally, we train a new KNN model using the best hyperparameters found by the grid search. The model is then fit using the training data.</p><pre>knn_best = KNeighborsClassifier(**grid_search.best_params_)<br>knn_best.fit(X_train, y_train)</pre><p>This process allows us to find the most suitable set of hyperparameters for our KNN model, allowing it to predict handwritten digits with a high degree of accuracy.</p><h3>Testing and Evaluating the Model</h3><p>After training our KNN model with the best set of hyperparameters, the next step is to evaluate its performance on the testing set. This is done by using the predict method of the knn_best model to predict the labels for the test data. To understand the model’s performance in a more detailed manner, we generate a classification report using sklearn’s classification_report function. The classification report provides key metrics such as precision, recall, and F1-score for each class, as well as the overall accuracy of the model.</p><pre>y_pred = knn_best.predict(X_test)<br>conf_mat = confusion_matrix(y_test, y_pred)<br>sns.heatmap(conf_mat, annot=True, fmt=&#39;d&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*olFYnwyx0jTIMcGZ8AcKQQ.png" /></figure><p>Based on the classification report, the K-nearest neighbors (KNN) model exhibits excellent performance on the MNIST dataset. The model accuracy is approximately 99%, indicating that the model predicts the correct class for 99% of the test images. Precision, recall, and F1-score values are all consistently high across different digits, demonstrating that the model’s performance is not biased towards specific classes. However, there’s a slight dip in performance for digit ‘8’ in terms of precision and for digit ‘9’ in terms of recall, suggesting minor misclassifications occurred within these categories. Overall, despite these minor discrepancies, the KNN model has proven to be very effective in recognizing handwritten digits in the MNIST dataset.</p><h3>Visualizing the Prediction of a Test Image</h3><p>In addition to overall performance metrics, it’s often useful to look at the model’s predictions for individual instances. Here, we select an image from the test set, use the model to predict its label, and then visualize the image along with the true and predicted labels.</p><pre># Send a testing image to the model, get prediction, and visualize it<br>test_image_index = 0<br>test_image = X_test[test_image_index]<br>test_image_label = y_test[test_image_index]<br>test_image_pred = knn_best.predict(test_image.reshape(1, -1))<br><br>plt.imshow(test_image.reshape(8, 8), cmap=&#39;gray&#39;)<br>plt.title(f&quot;True label: {test_image_label}, Predicted label: {test_image_pred[0]}&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*GStC3t6ad6DUwoTJ9eLC6Q.png" /></figure><h3>Conclusion</h3><p>In this article, we explored how the K-Nearest Neighbors (KNN) algorithm can be effectively applied for handwritten digit recognition using the MNIST dataset. The process involved loading and exploring the dataset, preparing it for the KNN model, and tuning the hyperparameters of the model using grid search. We then trained the model using the optimal hyperparameters and evaluated its performance through a classification report, confusion matrix, and visualization of individual predictions. The KNN model, despite its simplicity, was able to achieve a high degree of accuracy on this task, demonstrating its utility for image-based classification tasks. These findings reinforce the strength of machine learning techniques in automating and accurately performing complex tasks like digit recognition in diverse real-world applications.</p><p>That’s all folks. May the force be with you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da677e87c8ac" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/understanding-handwritten-digit-recognition-using-k-nearest-neighbors-knn-da677e87c8ac">Understanding Handwritten Digit Recognition Using K-Nearest Neighbors (KNN)</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the basics of Logistic Regression]]></title>
            <link>https://blog.devgenius.io/understanding-the-basics-of-logistic-regression-d27bbbfd285f?source=rss-962684e95f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d27bbbfd285f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[logistic-regression-model]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <dc:creator><![CDATA[Abdullah Siddique]]></dc:creator>
            <pubDate>Mon, 05 Jun 2023 19:57:41 GMT</pubDate>
            <atom:updated>2023-06-06T16:34:53.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c804Cwoux1cvwz9zf-oV_g.jpeg" /></figure><p>In this article, we delve into the implementation of a binary logistic regression model from scratch, using an email dataset for spam detection. We will build the model using Python and important libraries such as Numpy, Pandas, and Scikit-Learn.</p><h3>Introduction to Logistic Regression</h3><p>Logistic Regression is a fundamental machine learning technique that applies to situations where the output variable is categorical. In Binary Logistic Regression, the output variable has two categories, such as “spam” and “not spam” emails.</p><p>This algorithm uses the logistic function, also known as the sigmoid function, which maps any real-valued number into a range between 0 and 1, representing the probability of each class.</p><h3>Understanding the Dataset</h3><p>The <a href="https://www.kaggle.com/datasets/venky73/spam-mails-dataset">dataset</a> used here includes emails, each labeled either as spam (1) or not spam (0). The two primary columns used are ‘Email_text’ and ‘Labels’. The ‘Email_text’ column includes the content of the emails, and ‘Labels’ is the binary label indicating whether each email is spam or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*7PNPeh9rNnCwt-1R7L0I8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*569h7N5NV-NyJXwRRwbjdg.png" /></figure><p>For a more detailed EDA (Exploratory Data Analysis), you can find it here in this <a href="https://www.kaggle.com/code/kane6543/binary-logistic-regression-on-email-data">notebook</a>.</p><h3>Preprocessing the Text Data</h3><p>Before we proceed with the implementation of logistic regression, we need to preprocess our text data into a format that can be fed into the algorithm. We use CountVectorizer from Scikit-Learn, which converts a collection of text documents to a matrix of token counts. This implementation produces a sparse representation of the counts, which can significantly reduce memory usage for large datasets.</p><pre>from sklearn.model_selection import train_test_split<br>from sklearn.feature_extraction.text import CountVectorizer<br><br>Email_dataset = pd.read_csv(&quot;spam_ham_dataset.csv&quot;)<br><br>X = Email_dataset[&#39;Email_text&#39;]<br>y = Email_dataset[&#39;Labels&#39;].values<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># Fit the CountVectorizer on your training data<br>vectorizer = CountVectorizer()<br>X_train = vectorizer.fit_transform(X_train).toarray()<br><br># Transform your test data using the same vectorizer<br>X_test = vectorizer.transform(X_test).toarray()</pre><h3>Implementing Binary Logistic Regression</h3><p>We then initialize the weights and bias for our model and define the sigmoid function, which is used as the hypothesis function in logistic regression. The sigmoid function maps our function’s output to a range between 0 and 1, representing the probabilities.</p><pre>def sigmoid(x):<br>    return 1 / (1 + np.exp(-x))</pre><p>The cost function we use is the log loss function. This function measures the performance of a classification model where the prediction input is a probability value between 0 and 1. The goal of our machine learning models is to minimize this value.</p><pre>def cost_function(h, y):<br>    return (-y * np.log(h + 1e-10) - (1 - y) * np.log(1 - h + 1e-10)).mean()</pre><p>The cost function for logistic regression, sometimes called log loss, measures the performance of a classification model. Here are the key points:</p><ul><li>It calculates the error for a single training example.</li><li>The cost is calculated as the negative sum of the actual value times the natural log of the predicted value and the difference of the actual value from one times the natural log of the difference of the predicted value from one.</li><li>The formula for the cost function for a single training example is -y <em>log(h) — (1 — y) </em>log(1 — h).</li><li>If the actual class is 1 (y = 1) and the model correctly predicts 1 (h = 1), then the cost is 0.</li><li>If the actual class is 1 (y = 1) but the model predicts 0 (h = 0), then the cost is infinite.</li><li>The same applies when the actual class is 0 (y = 0).</li><li>When you calculate the cost function over the entire training set, it’s called the average cost function, and you take the average of all the individual costs.</li></ul><p>The cost function in logistic regression is a log loss function, also known as cross-entropy loss. When dealing with logistic regression, it’s more suitable than mean squared error as a loss function because it’s convex, which avoids problems with local minimums that are not global minimums. It’s defined as:</p><p><strong>J(w) = -1/n Σ [y <em>log(h(x)) + (1 — y) </em>log(1 — h(x))]</strong></p><p>This equation might look complex, but it’s essentially an average of loss values where the loss is calculated per individual prediction. Let’s break it down:</p><ul><li>h(x): this is the prediction your model makes for the input x. For logistic regression, it’s the output of the sigmoid function applied to the weighted sum of the input features.</li><li>y * log(h(x)): This part of the function calculates the loss for positive examples (where the actual value y is 1). If the actual value is 1 and the model predicts 1 (h(x) close to 1), the loss is 0 because log(1) = 0. But if the model predicts 0 (h(x) close to 0), the loss goes to infinity because log(0) approaches negative infinity, so we get a very large penalty for a false negative.</li><li>(1 — y) * log(1 — h(x)): This part of the function calculates the loss for negative examples (where the actual value y is 0). If the actual value is 0 and the model predicts 0 (h(x) close to 0), the loss is 0 because log(1) = 0. But if the model predicts 1 (h(x) close to 1), log(1 — h(x)) approaches negative infinity, so we get a large penalty for a false positive.</li><li>-1/n Σ: Finally, we sum up all these loss values for each example in our dataset and divide by the number of examples to compute the average loss, which is the value that the log loss function returns.</li><li>(1e-10) is a very small number that should prevent the values inside the log from becoming 0.</li></ul><p>By minimizing this cost function, we can optimize the parameters of our logistic regression model to make the best predictions possible. The cost function is ideal because it penalizes confidently wrong predictions more than it rewards confidently correct ones, and because it’s differentiable, allowing us to use efficient optimization algorithms like gradient descent.</p><p><strong>Implement Gradient Descent</strong></p><p>We then implement Gradient Descent, an optimization algorithm used to minimize the cost function. Gradient Descent is used while training a machine learning model. It’s an optimization algorithm, used to minimize some function by iteratively moving in the direction of steepest descent as defined by the negative of the gradient.</p><pre>def gradient_descent(X, h, y):<br>    return np.dot(X.T, (h - y)) / y.shape[0]</pre><p><strong>Training the Model</strong></p><p>After implementing these functions, we combine them into a training loop. We iterate over the data multiple times, each time updating the weights and bias using gradient descent, and calculating the cost function.</p><pre>def update_weight_loss(weight, learning_rate, gradient):<br>    return weight - learning_rate * gradient</pre><pre>num_iter = 1000<br>learning_rate = 0.1<br>weight = np.zeros(X_train.shape[1])<br><br>costs = []<br><br>for i in range(num_iter):<br>    z = np.dot(X_train, weight)<br>    h = sigmoid(z)<br>    gradient = gradient_descent(X_train, h, y_train)<br>    weight = update_weight_loss(weight, learning_rate, gradient)<br>    <br>    if(i % 100 == 0):<br>        z = np.dot(X_train, weight)<br>        h = sigmoid(z)<br>        cost = cost_function(h, y_train)<br>        costs.append(cost)<br>        print(f&#39;cost: {cost} \t&#39;)</pre><h3>Visualizing the Cost Function</h3><p>To visualize how our model is improving over time, we plot the value of the cost function at each epoch. This gives us a nice graph showing that the cost is indeed decreasing over time, confirming that our model is learning from the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*inCXQv3gcTRsKPmEK-hIlg.png" /></figure><h3>Predicting on New Data</h3><p>Once we have trained our model, we can use it to predict whether a new email is spam or not. To do this, we first need to transform the email text into a feature vector using the same CountVectorizer that we used for the training data. Then, we can simply pass this feature vector to our model to get a prediction.</p><pre>final_pred = sigmoid(np.dot(X_test, weight))<br>y_pred = final_pred.round()<br>print(&#39;Classification Report:&#39;)<br>print(classification_report(y_test, y_pred))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*N6LXfomCmRUe-St0TLUkWg.png" /></figure><h3>Conclusion</h3><p>In this article, we successfully implemented a binary logistic regression model from scratch to classify emails as spam or not. This not only provided us with a better understanding of how logistic regression works but also gave us a practical application of this fundamental machine learning technique. The principles we learned here can be applied to any binary classification task, making this a useful tool in our machine learning toolbox.</p><p>You can find the complete code <a href="https://www.kaggle.com/code/kane6543/binary-logistic-regression-on-email-data">here</a>.</p><p>That’s all folks. May the force be with you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d27bbbfd285f" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/understanding-the-basics-of-logistic-regression-d27bbbfd285f">Understanding the basics of Logistic Regression</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Your Python Unit Tests with GitHub Actions: A Step-by-Step Guide]]></title>
            <link>https://blog.devgenius.io/automating-your-python-unit-tests-with-github-actions-a-step-by-step-guide-26d1ed7c07a8?source=rss-962684e95f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/26d1ed7c07a8</guid>
            <category><![CDATA[github-workflow]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Abdullah Siddique]]></dc:creator>
            <pubDate>Sat, 13 May 2023 12:22:40 GMT</pubDate>
            <atom:updated>2023-06-06T16:35:01.790Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*ZAYeg0aUNrfqi1VPhzyekg.png" /></figure><p>Turbocharge your development workflow and catch bugs before they bite — all with the power of GitHub Actions and Python unit tests.</p><p>As the relentless advancement of technology continues, developers are constantly seeking ways to automate their workflow, improve efficiency, and maintain high-quality code. GitHub Actions, a powerful tool from the GitHub arsenal, offers all this and more. In this article, we’ll demystify GitHub Actions and explore how you can leverage its capabilities to supercharge your Python testing process.</p><p><strong>What are GitHub Actions and Why Use Them?</strong></p><p>GitHub Actions are automated tasks, or workflows, that you can set up in your repository to build, test, package, release, and deploy any project on GitHub. With GitHub Actions, you can orchestrate any workflow, based on nearly any event, while GitHub manages the execution, provides rich feedback, and secures every step along the way.</p><p>Why should you care? Well, imagine merging your code into the main branch, only to realize later that it broke your build. With GitHub Actions, you can automate your unit tests to run on every push or pull request, thereby catching bugs before they creep into your production code. This means less time debugging and more time developing!</p><p><strong>Setting up a GitHub Workflow</strong></p><p>Now that we understand the benefits of GitHub Actions, let’s walk through setting up a simple GitHub workflow to run Python unit tests whenever you push code to your repository. In this example, we’ll be using a simple Python script for managing a “Wallet” and its corresponding test suite.</p><p><strong>Step 1 : Prepare Your Python Scripts</strong></p><p>First, make sure you have two Python scripts in your repository: wallet.py (which contains a simple Wallet class for managing a balance) and test.py (which contains a test function to validate the functionality of the Wallet class).</p><p>In the root of your repository, create a Python file named wallet.py and another named test.py.</p><p>In wallet.py, define the Wallet class:</p><pre>class Wallet:<br>    def __init__(self, balance):<br>        self.balance = balance<br><br>    def set_balance(self, val):<br>        self.balance = self.balance + val<br><br>    def get_balance(self):<br>        return self.balance<br><br>    def remove_balance(self, val):<br>        self.balance = self.balance - val</pre><p>In test.py, we&#39;ll write tests for our Wallet class using pytest:</p><pre>from wallet import Wallet<br><br>def test_getbalance():<br>    obj = Wallet(0)<br>    obj.set_balance(20)<br>    assert obj.get_balance() == 20<br><br>def test_removebalance():<br>    obj = Wallet(50)<br>    obj.remove_balance(20)<br>    assert obj.get_balance() == 30<br><br>def test_setbalance():<br>    obj = Wallet(0)<br>    obj.set_balance(40)<br>    assert obj.get_balance() == 40</pre><p><strong>Step 2: Create the Workflow File</strong></p><p>In your repository, create a directory named .github at the root level, and within that, create another directory named workflows. Within workflows, create a new file named push_event_workflow.yml. GitHub Actions will automatically detect this file and run the actions defined in it whenever the conditions specified are met.</p><p>Our push_event_workflow.yml should look like this:</p><pre>name: Push Event Workflow<br><br>on: push <br><br>jobs:<br>  unit-testing:<br>    runs-on: ubuntu-latest <br>    <br>    steps:<br>    - name : Checkout code<br>      uses : actions/checkout@v2<br>      <br>    - name : Install Packages <br>      run : pip install pytest<br>      <br>    - name : Run tests <br>      run : pytest test.py</pre><p><strong>Step 3: Push to GitHub</strong></p><p>Push your code to GitHub. Once the push event is detected, GitHub Actions will initiate the workflow defined in push_event_workflow.yml.</p><p><strong>Step 4: Monitor the Workflow</strong></p><p>You can monitor the progress of the workflow by navigating to the “Actions” tab in your GitHub repository. Here you’ll see a list of all the workflows that have run, along with their status (whether they passed or failed). Click on a workflow run to see more detailed information. If a workflow fails, you can check the logs to determine what went wrong and fix it.</p><p>You can visit this <a href="https://github.com/abdullah1772/Creating-Github-Workflows">repo </a>to see an already set up workflow.</p><p><strong>Wrap Up: Embracing Automation with GitHub Actions</strong></p><p>GitHub Actions provides an easy-to-use, highly customizable tool for automating your development workflows. By handling repetitive tasks like building, testing, and deploying your code, GitHub Actions lets you focus on designing and writing your software.</p><p>Our simple Python “wallet” class example and corresponding tests showcase how you can set up GitHub Actions in your Python project. The possibilities, however, are endless. With GitHub Actions, you can automate almost any aspect of your development workflow, making your development process faster, more efficient, and less error-prone.</p><p>So why not give it a try? Start using GitHub Actions today and see how it can transform your development workflow for the better!</p><p>That’s all folks. May the force be with you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26d1ed7c07a8" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/automating-your-python-unit-tests-with-github-actions-a-step-by-step-guide-26d1ed7c07a8">Automating Your Python Unit Tests with GitHub Actions: A Step-by-Step Guide</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MLOps 101: Data Versioning Using DVC]]></title>
            <link>https://blog.devgenius.io/mlops-101-data-versioning-using-dvc-73242d87c572?source=rss-962684e95f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/73242d87c572</guid>
            <category><![CDATA[data-version-control]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[dvc]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <dc:creator><![CDATA[Abdullah Siddique]]></dc:creator>
            <pubDate>Fri, 12 May 2023 16:59:54 GMT</pubDate>
            <atom:updated>2023-06-06T16:35:10.405Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*_OLs1MIfbm2_JGA8V9dcRA.png" /></figure><p>DVC, which stands for Data Version Control, is an open-source tool that is used to version control data and machine learning models. It’s designed to handle large files, data sets, machine learning models, and metrics as well as code. It’s built to make ML models shareable and reproducible. DVC is designed to work with Git, but it overcomes some of the limitations of Git in handling large files.</p><p>Here are a few reasons why you would want to use DVC:</p><p>1. <strong>Data versioning:</strong> Git is not designed to handle large files or binary files effectively. DVC allows you to version control your data and models in a similar way as you do with your code in Git, but without straining your Git repository.</p><p>2. <strong>Data and model sharing:</strong> DVC integrates with remote storage (S3, GCS, Azure, SSH, HDFS, HTTP, and others) in a way that you can push and pull your data and models as easily as you would do with your code using Git.</p><p>3. <strong>Reproducibility:</strong> DVC tracks all the steps in your data processing and machine learning pipeline. This makes your projects reproducible. You can easily go back to any version of your project, with matching data, model, and code.</p><p>4. <strong>Collaboration and sharing:</strong> DVC makes it easier for data scientists to collaborate on projects. Different team members can work on their own experiments and then merge the changes in a controlled and systematic way.</p><p>5. <strong>Metrics tracking:</strong> DVC has built-in functions for visualizing and comparing metrics across different versions of a project. This is especially useful in machine learning projects where you want to track model performance.</p><p>In summary, DVC brings to data science and machine learning projects the same kind of versioning and collaboration features that Git brings to software development. It’s a tool that’s designed to handle the specific needs of data science and machine learning teams.</p><p>In this article we are going to learn how to pull and push your data on git using DVC. Before starting I am asuming you are familiar with Github and Git and already have Git setup on your device. Let’s Begin.</p><p><strong>Step 1: Installing DVC</strong></p><p>Before starting, make sure you have DVC installed. If not, you can install it by running the following command in your terminal:</p><pre>pip install dvc</pre><p><strong>Step 2: Setting up repositories</strong></p><p>Next go to your Github and create a repo “Data-Versioning-Using-DVC”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWt21EafmNWSqy46ZqjkiQ.png" /></figure><p>Afterwards create 2 Folders named “DVC_Push” and “DVC_Pull”. We are going DVC_Push to push our data file to the git repo and DVC_Pull to pull the file from git repo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rECTQlapVOmCvHgIm28MwQ.png" /></figure><p>Next go to your Google drive, Create an empty folder called “My_Data” and get the link to the folder and save it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NGcWAywW4keRYUzZ9_Tz9g.png" /></figure><p><strong>Step 3: Initialize DVC in your project</strong></p><p>Navigate to your project directory (DVC_Push ) via the command line and initialize git and DVC.</p><pre>cd C:\Users\path\to\repo\DVC\DVC_Push<br>git init<br>dvc init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V4y3I0PEziqF1wg7JZD-Mw.png" /></figure><p><strong>Step 4: Connect your local repository to your GitHub repository</strong></p><p>Add your GitHub repository as a remote:</p><pre>git remote add origin https://github.com/your-repo.git</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0SwmmZtfowh8h12fuFHeNw.png" /></figure><p><strong>Step 5: Configure DVC to use Google Drive as remote storage</strong></p><pre>dvc remote add -d myremote gdrive:your-drive-link</pre><p>This will set Google Drive as your default DVC remote. The -d flag sets it as the default remote. The gdrive:// URL is your Google Drive directory where you want to store your DVC-tracked files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dPJCt7Abae4Lm2EVOkQtpg.png" /></figure><p><strong>Step 6: Add your data file to DVC</strong></p><p>Put the data you want to add to DVC to your DVC_Push folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TIM2-pjxR6XWY4rVsXqsTA.png" /></figure><pre>dvc add data.csv</pre><p>This creates a new file named data.csv.dvc that tracks your data file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a7Y2hvUohIgZVT6nll-dCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pctXHaFZ6qHVPPPoaUeqYw.png" /></figure><p><strong>Step 7: Commit your changes to Git</strong></p><pre>git add data.csv.dvc .gitignore<br>git commit -m &quot;Add data file to DVC&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWYWUrhLQXlrHYSN6l4-iA.png" /></figure><p><strong>Step 8: Push your data to the DVC remote</strong></p><pre>dvc push</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Rk6S3UIxSr4UAL_6ezacw.png" /></figure><p>This will redirect you to google login and will ask you for permission. Grant DVC permission to access your Google drive and make changes to the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ft6-IE5bZz_1zrInqREucg.png" /></figure><p><strong>Step 8: Push your changes to the GitHub repository</strong></p><pre>git push -u origin master</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ZsNsTS2rf97-KLgyMKl0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2bXlXS7AHoiNDk4lLb1Sdg.png" /></figure><p>Now, your data file is stored in your Google Drive folder, and the DVC metadata is stored in your GitHub repository.</p><p><strong>Step 9: Pull the data to your DVC_Pull directory</strong></p><pre>git clone https://github.com/your-github-repo.git<br>cd Data-Versioning-Using-DVC</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hKBkbsPspj10y7D-1q0R4g.png" /></figure><p>Then, pull the data from the DVC remote:</p><pre>dvc pull</pre><p>In case you encounter the following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*Edl6Cpna4jhoQqJKXMhw3w.png" /></figure><p>One of the possible reasons is that your remote storage is not setup properly.</p><p>In the DVC_Pull directory write the following command in the terminal:</p><pre>dvc remote list</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*Y8QaZVwOfEozIgJMh8K06g.png" /></figure><p>And if this shows up empty, go to your DVC_Push repo and write the following commands in the terminal:</p><pre>git add .dvc/config<br>git commit -m &quot;Add DVC remote configuration&quot;<br>git push</pre><p>And now go back to your DVC_Pull directory and write the command:</p><pre>git pull</pre><p>You’ll now have the updated repository.</p><p>Write dvc remote list to check if there are any remote storages showing up, hopefully this’ll resolve your error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6xFiYlj1Xe3JpGevwto1pA.png" /></figure><p>Once a remote storage shows up, write the following command in the DVC_Pull directory terminal:</p><pre>dvc pull</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJZ65lnmZmigfYyrkQPkdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qk09_ccoSwPcuelJSb14VA.png" /></figure><p>As you can see in the directory above, the data file has been successfully pulled from the remote storage google drive.</p><p>Congratulations you have successfully used DVC to push and pull your data from remote storage setup on Google Storage.</p><p>That’s all Folks. May the force be with you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73242d87c572" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/mlops-101-data-versioning-using-dvc-73242d87c572">MLOps 101: Data Versioning Using DVC</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Linear Regression Pipeline with Airflow]]></title>
            <link>https://blog.devgenius.io/building-a-linear-regression-pipeline-with-airflow-ca55ee72ded?source=rss-962684e95f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca55ee72ded</guid>
            <category><![CDATA[apache-airflow]]></category>
            <category><![CDATA[machine-learning-pipeline]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Abdullah Siddique]]></dc:creator>
            <pubDate>Thu, 04 May 2023 08:36:41 GMT</pubDate>
            <atom:updated>2023-05-04T10:10:48.723Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ww5vY_r2oYjc_aN0dCjGtQ.png" /></figure><p>Introduction</p><p>In this article, we will demonstrate how to build an end-to-end pipeline to read CSV data, preprocess it, train a linear regression model, and test the model using Apache Airflow. If you don’t have apache airflow installed, you can follow this quick easy-to-setup guide <a href="https://medium.com/dev-genius/intro-to-airflow-setting-up-apache-airflow-11ea1e03965">here</a>. Airflow is an open-source workflow management system that allows you to easily build, schedule, and monitor complex data pipelines.</p><p>We will use a breast cancer dataset as an example, and our goal is to predict the diagnosis based on various features. The dataset consists of patient records, each containing 32 features. We will use linear regression as our prediction model. You can find the dataset <a href="https://www.kaggle.com/datasets/uciml/breast-cancer-wisconsin-data">here</a>.</p><p><strong>Step 1: Import required libraries and modules</strong></p><p>First, we will import the required libraries and modules, such as pandas, scikit-learn, and Airflow.</p><pre>import os<br>import joblib<br>import pandas as pd<br>import numpy as np<br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import mean_squared_error<br>from sklearn.preprocessing import LabelEncoder<br><br>from datetime import datetime, timedelta<br>from airflow import DAG<br>from airflow.operators.python import PythonOperator</pre><p><strong>Step 2: Define data processing functions</strong></p><p>Next, we will define four functions to read the CSV file, preprocess the data, train the linear regression model, and test the model.</p><pre>def read_csv(file_path):<br>    # ...<br><br>def preprocess_data(target_column, **kwargs):<br>    # ...<br><br>def train_linear_regression(**kwargs):<br>    # ...<br><br>def test_model(**kwargs):<br>    # ...</pre><p><strong>Reading Data</strong></p><pre>def read_csv(file_path):<br>    data = pd.read_csv(file_path)<br>    return data</pre><p><strong>Preprocess Data</strong></p><pre>def preprocess_data(target_column, **kwargs):<br>    <br>    task_instance = kwargs[&#39;ti&#39;]<br>    <br>    data = task_instance.xcom_pull(task_ids=&quot;read_csv&quot;)<br>    </pre><p>xcom_pull is a method in Apache Airflow that allows you to access and retrieve data (intermediate results or metadata) produced by one task and share it with another task in the same directed acyclic graph (DAG). The term &quot;XCom&quot; is short for &quot;cross-communication,&quot; which refers to the process of exchanging data between tasks in a workflow.</p><pre>    data = data.drop(&#39;id&#39;, axis = 1)<br>    data = data.drop(&#39;Unnamed: 32&#39;, axis = 1)<br>    <br>    le = LabelEncoder()<br><br>    data[&#39;diagnosis&#39;]= le.fit_transform(data[&#39;diagnosis&#39;])</pre><p>Next we are going to drop some unwanted columns, and use label encoder to convert text labels into numerical values for our target variable.</p><pre>    corr = data.corr()<br>    <br>    corr_threshold = 0.6<br>    selected_features = corr.index[np.abs(corr[&#39;diagnosis&#39;]) &gt;= corr_threshold]<br>    <br>    new_cancer_data = data[selected_features]</pre><p>The dataset has total 32 features. We are going to apply feature selection to select the most relevant features from the original dataset to use for model training. The primary goals of feature selection are to improve model performance, reduce computational complexity, and enhance interpretability.</p><pre>    X = new_cancer_data.drop(target_column, axis=1)<br>    y = data[target_column]<br>    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br>    <br>    return X_train.to_dict(), X_test.to_dict(), y_train.to_dict(), y_test.to_dict()</pre><p>Next we are going to split our dataset into train and test, and return the data converting it into dictionary because Xcom method only supports json format and not dataframes.</p><p>Here is the complete code for data processing:</p><pre>def preprocess_data(target_column, **kwargs):<br>    <br>    task_instance = kwargs[&#39;ti&#39;]<br>    <br>    data = task_instance.xcom_pull(task_ids=&quot;read_csv&quot;)<br>    data = data.drop(&#39;id&#39;, axis = 1)<br>    data = data.drop(&#39;Unnamed: 32&#39;, axis = 1)<br>    <br>    le = LabelEncoder()<br><br>    data[&#39;diagnosis&#39;]= le.fit_transform(data[&#39;diagnosis&#39;])<br>    <br>    corr = data.corr()<br>    <br>    corr_threshold = 0.6<br>    selected_features = corr.index[np.abs(corr[&#39;diagnosis&#39;]) &gt;= corr_threshold]<br>    <br>    new_cancer_data = data[selected_features]<br>    <br>    <br>    X = new_cancer_data.drop(target_column, axis=1)<br>    y = data[target_column]<br>    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br>    <br>    return X_train.to_dict(), X_test.to_dict(), y_train.to_dict(), y_test.to_dict()</pre><p><strong>Training the linear regression model</strong></p><pre>def train_linear_regression( **kwargs):<br>    <br>    task_instance = kwargs[&#39;ti&#39;]<br>    <br>    X_train_dict, _, y_train_dict, _ = task_instance.xcom_pull(task_ids=&quot;preprocess_data&quot;)<br>    <br>    X_train = pd.DataFrame.from_dict(X_train_dict)<br>    y_train = pd.Series(y_train_dict)</pre><p>The function then calls the task_instance.xcom_pull method with the task_ids=&quot;preprocess_data&quot; argument. This retrieves the data (X_train_dict, X_test_dict, y_train_dict, y_test_dict) that were output by the &quot;preprocess_data&quot; task. In this case, only the X_train_dict and y_train_dict are needed to train the model, so the X_test_dict and y_test_dict are discarded using the _ placeholder. The data are then converted from dictionaries to pandas DataFrame (X_train) and pandas Series (y_train) objects.</p><pre>    model = LinearRegression()<br>    model.fit(X_train, y_train)</pre><p>A linear regression model is instantiated using the LinearRegression() class from the sklearn.linear_model module. The model is fitted to the training data using the model.fit(X_train, y_train) method.</p><pre>    model_filepath = &quot;/mnt/c/Users/..../linear_regression_model.pkl&quot;<br>    joblib.dump(model, model_filepath)<br>    <br>    return model_filepath</pre><p>We are going to use joblib library to dump the trained model because Xcom only support json format and we can’t send the trained model to another task. So we are just going to train and dump the model, and send the file path of the training model to our next task. You can see the “/mnt/c/” before the actual filepath, that is necessary to add if you are running the apache airflow on WSL. The “mnt/c” mounts the C drive for making it accessible to the WSL.</p><p>Here is the complete training function:</p><pre>def train_linear_regression( **kwargs):<br>    <br>    task_instance = kwargs[&#39;ti&#39;]<br>    <br>    X_train_dict, _, y_train_dict, _ = task_instance.xcom_pull(task_ids=&quot;preprocess_data&quot;)<br>    <br>    X_train = pd.DataFrame.from_dict(X_train_dict)<br>    y_train = pd.Series(y_train_dict)<br>    <br>    model = LinearRegression()<br>    model.fit(X_train, y_train)<br>    <br>    model_filepath = &quot;/mnt/c/Users/Abdullah/Desktop/airflow_task/linear_regression_model.pkl&quot;<br>    joblib.dump(model, model_filepath)<br>    <br>    return model_filepath</pre><p><strong>Testing the model</strong></p><pre>def test_model(**kwargs):<br>    <br>    task_instance = kwargs[&#39;ti&#39;]<br>    <br>    model_filepath = task_instance.xcom_pull(task_ids=&quot;train_linear_regression&quot;)<br>    <br>    model = joblib.load(model_filepath)<br>    <br>    _, X_test_dict, _, y_test_dict = task_instance.xcom_pull(task_ids=&quot;preprocess_data&quot;)<br>    <br>    X_test = pd.DataFrame.from_dict(X_test_dict)<br>    y_test = pd.Series(y_test_dict)<br><br>    y_pred = model.predict(X_test)<br>    mse = mean_squared_error(y_test, y_pred)<br>    return mse<br></pre><p>Get the filepath of the trained model from the previous task using Xcom. Once the path is received load the model, and get the testing data from the task “preprocess_data”. Convert that dictionary data into pandas dataframe and get predictions on the testing data. Once we have the predictions we are going to calculate the MSE score to see how our model performed.</p><p><strong>Step 3: Define the Airflow DAG</strong></p><p>Now, we will define the Airflow DAG, which includes the default arguments and the schedule interval.</p><pre>default_args = {<br>    &quot;owner&quot;: &quot;airflow&quot;,<br>    &quot;depends_on_past&quot;: False,<br>    &quot;email_on_failure&quot;: False,<br>    &quot;email_on_retry&quot;: False,<br>    &quot;retries&quot;: 1,<br>    &quot;retry_delay&quot;: timedelta(minutes=5),<br>    &quot;start_date&quot;: datetime(2023, 5, 4),<br>} </pre><pre>dag = DAG(<br>    &quot;linear_regression_pipeline&quot;,<br>    default_args=default_args,<br>    description=&quot;A pipeline to read CSV, preprocess data, train and test a linear regression model&quot;,<br>    schedule_interval=timedelta(days=1),<br>    catchup=False,<br>)</pre><p>Once the arguments are set, we can create airflow tasks for each function that we wrote.</p><pre>file_path = &quot;/mnt/c/Users/.../data.csv&quot;<br>target_column = &quot;diagnosis&quot;</pre><p>First we define our filepath where our data is located and the target columns of our dataset.</p><p>Let’s define the tasks now.</p><pre>t1 = PythonOperator(<br>    task_id=&quot;read_csv&quot;,<br>    python_callable=read_csv,<br>    op_args=[file_path],<br>    dag=dag,<br>)<br><br>t2 = PythonOperator(<br>    task_id=&quot;preprocess_data&quot;,<br>    python_callable=preprocess_data,<br>    op_args=[target_column],<br>    provide_context=True,<br>    dag=dag,<br>)<br><br>t3 = PythonOperator(<br>    task_id=&quot;train_linear_regression&quot;,<br>    python_callable=train_linear_regression,<br>    provide_context=True,<br>    dag=dag,<br>)<br><br>t4 = PythonOperator(<br>    task_id=&quot;test_model&quot;,<br>    python_callable=test_model,<br>    provide_context=True,<br>    dag=dag,<br>)</pre><p>task_id: A unique identifier for the task.</p><p>python_callable: The function to be executed.</p><p>op_args: The arguments passed to the function e.g. in this case, the file_path of the CSV file to be read to the fuction read_csv</p><p>provide_context: A boolean flag indicating whether to pass the task&#39;s context (metadata) to the function. Set to True to allow the function to access the task_instance object.</p><p>dag: The DAG object to which this task belongs, dag.</p><p>In the end we define the order of the task to be executed.</p><pre>t1 &gt;&gt; t2 &gt;&gt; t3 &gt;&gt; t4</pre><p>You can find the complete code <a href="https://github.com/abdullah1772/Building-a-Linear-Regression-Pipeline-with-Airflow">here</a>.</p><p><strong>Step 4: Running the DAG</strong></p><p>Now that you have written the code it’s time to execute the DAG in apache airflow.</p><p>First make sure your file is placed in the dags folder inside the airflow directory. If you are using WSL, you can locate the directory here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*oHHt1Q8SXpNRE24Z8BWJYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUmAJTz_icaYETEToxKI9g.png" /></figure><p>Once your files are inplace, let’s head over to the webserver. Launch your airflow scheduler and webserver in separate WSL terminals.</p><p>airflow scheduler</p><p>airflow webserver --port 8080</p><p>Go to localhost:8080 and login. Scroll all the way down and you’ll find your linear regression pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZEYU5kySwbTuImHBGXXz6Q.png" /></figure><p>Click on the play button and your pipeline will start executing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bi4RFCiXRgm4te6_qId9Fw.png" /></figure><p>All your tasks are displayed in the red box. You can see the tasks executing and running. Incase if a task is unsucessful, you can go to the logs in the green ox, view logs as to where the error occured and fix it according to the nature of the error. If you haven’t installed any libraries, and it gives a missing module error, you can just go to your WSL terminal and install the libraries using pip .</p><p>You can further go into the graphs section and see how your pipeline executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uHZS_5LxCS-WUk3D44LhNw.png" /></figure><p>Let’s check the accuracy of our model. To do that click on the “test_model” task and go to it’s logs and we can see the accuracy of our model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wAuigcbxkvNSmjtO2ApFyA.png" /></figure><p>We got a MSE score of 0.06. The model fit accurately on our dataset.</p><p>Congratulations you have successfully implemented and executed your first ML pipeline on Apache Airflow.</p><p>That’s all folks. May the force be with you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca55ee72ded" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/building-a-linear-regression-pipeline-with-airflow-ca55ee72ded">Building a Linear Regression Pipeline with Airflow</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro To Airflow: Setting Up Apache Airflow]]></title>
            <link>https://blog.devgenius.io/intro-to-airflow-setting-up-apache-airflow-11ea1e03965?source=rss-962684e95f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/11ea1e03965</guid>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[wsl]]></category>
            <category><![CDATA[airflow-installation]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Abdullah Siddique]]></dc:creator>
            <pubDate>Thu, 04 May 2023 07:04:31 GMT</pubDate>
            <atom:updated>2023-05-04T10:11:03.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ww5vY_r2oYjc_aN0dCjGtQ.png" /></figure><p><strong>Introduction</strong></p><p>In this article, we will demonstrate how to install WSL, setup python in WSL, Install Apache Airflow, set-up Apache Airflow and run it. Airflow is an open-source workflow management system that allows you to easily build, schedule, and monitor complex data pipelines.</p><p><strong>What is Apache Airflow and why use it?</strong></p><p>Apache Airflow is an open-source platform used to programmatically create, schedule, and manage workflows. Airflow was developed by Airbnb and later became an Apache project. It is designed to provide a highly extensible and flexible framework for orchestrating complex data workflows, and it is implemented in Python.</p><p>Airflow enables users to define directed acyclic graphs (DAGs) to represent workflows, where each node represents a task and edges define the dependencies between tasks. Tasks in Airflow can be any Python callable, allowing you to leverage Python’s rich ecosystem of libraries and tools. Moreover, Airflow has a built-in scheduler that manages the execution of tasks based on the defined dependencies and schedules.</p><p>Here are some reasons why you should use Apache Airflow:</p><p>1. <strong>Scalability</strong>: Airflow is highly scalable, allowing you to manage and monitor hundreds or thousands of tasks simultaneously.</p><p>2. <strong>Extensibility</strong>: Airflow is highly extensible and provides a rich ecosystem of plugins and operators that can be used to integrate with various systems and services.</p><p>3. <strong>Flexibility</strong>: Airflow supports various workflow patterns, such as parallel execution, conditional branching, and dynamic pipeline generation.</p><p>4. <strong>Monitoring and Logging</strong>: Airflow provides a comprehensive web-based user interface for monitoring and managing tasks. It also integrates with various logging systems, making it easy to track and troubleshoot issues in your workflows.</p><p>5. <strong>Error handling and retries</strong>: Airflow has built-in support for error handling, retries, and alerting mechanisms, ensuring that your workflows are reliable and fault-tolerant.</p><p>6. <strong>Community and support</strong>: Apache Airflow has an active community of developers and users who contribute to the project and provide support through forums, mailing lists, and conferences.</p><p>Overall, Apache Airflow is a powerful and versatile platform for managing complex data workflows, offering robust functionality, scalability, and extensibility. By using Airflow, you can streamline your data pipeline development and maintenance process, making it easier to manage and monitor your data workflows.</p><p><strong>Setting up Apache Airflow</strong></p><p>There are two methods to set up apache airflow on your windows:</p><ol><li>Docker Image</li><li>Using Linux WSL</li></ol><p>In this article we’ll be utilizing the second method. So lets get started.</p><p><strong>Step 1: Setting up WSL</strong></p><p>Install the Windows Subsystem for Linux (WSL) following the instructions from the Microsoft website: <a href="https://docs.microsoft.com/en-us/windows/wsl/install">https://docs.microsoft.com/en-us/windows/wsl/install</a>.</p><p>Once you have followed all the steps properly, it should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*67Mq9TDV2sBZ8pdiTX0dXA.png" /></figure><p><strong>Step 2: Set up Python on WSL</strong></p><p>Once WSL is ready type in these commands to install python:</p><pre>sudo apt update<br>sudo apt install python3 python3-pip</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iV0cgvJgVz8ROLAzKAnCuw.png" /></figure><p>And Voila! You have successfully setup python3 in your WSL.</p><p><strong>Step3: Installing Apache Airflow</strong></p><pre>pip3 install apache-airflow</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HiXlzWaBcolvmlbXt_CGKA.png" /></figure><p>Try writing airflow in the WSL and if it returns with an error that means you need to add the path airflow to environment variables.</p><p>To do so simply write in your WSL terminal</p><pre>which airflow</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jFgCgU4O803eFHCIVGrALA.png" /></figure><p>Or if that doesn’t work, you can try this:</p><pre>find ~/.local -name airflow -type f -executable<br>export PATH=$PATH:&lt;directory_containing_airflow_executable&gt;</pre><p>This’ll give you the path where your airflow is installed.</p><p>Next simply type in the command below to add airflow to your environment variables:</p><pre>export PATH=$PATH:&lt;directory_containing_airflow_executable&gt;</pre><p>In my case it is:</p><pre>export PATH=$PATH:export PATH=$PATH:/home/abdullah/.local/bin/airflow</pre><p>Your airflow will finally be installed on your windows and we are ready to set it up and use it.</p><p><strong>Step 3: Setting up Apache Airflow</strong></p><p>Initialize the Airflow database:</p><pre>airflow db init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*grMBF8rlz8xDe_YWFIz1pw.png" /></figure><p>Start the Airflow web server:</p><pre>airflow webserver --port 8080</pre><p>Or you can choose any other port if 8080 is busy or according to your preferences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tu9Qv7yqn5Zl8_Vn4ihEsA.png" /></figure><p>Open another WSL terminal and start the Airflow scheduler:</p><pre>airflow scheduler</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZZjkZDDDIbJvqdS-qWc8A.png" /></figure><p>After following these steps, you should be able to access the Airflow web interface at <a href="http://localhost:8080/">http://localhost:8080</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5B6KDAI5FITCB41C7w_7dQ.png" /></figure><p><strong>Step 4: Creating a user</strong></p><p>To create a new user in airflow, open up a new WSL terminal and type in the following command:</p><pre>airflow create_user -r &lt;role&gt; -u &lt;username&gt; -e &lt;email&gt; -f &lt;first_name&gt; -l &lt;last_name&gt; -p &lt;password&gt;</pre><p>Replace the following placeholders with the appropriate information:</p><ul><li>&lt;role&gt;: The user role, such as Admin, Op, or User.</li><li>&lt;username&gt;: The desired username for the new Airflow user.</li><li>&lt;email&gt;: A valid email address for the new user.</li><li>&lt;first_name&gt;: The first name of the user (optional).</li><li>&lt;last_name&gt;: The last name of the user (optional).</li><li>&lt;password&gt;: The password for the new user.</li></ul><p><strong>For example:</strong></p><pre>airflow create_user -r Admin -u new_user -e new_user@example.com -f New -l User -p my_password</pre><p>This will add you as a user in the Apache Airflow and now you can access the Airflow Dashboard. Now go to <a href="http://localhost:8080/">http://localhost:8080</a> and enter your credentials and you’ll see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VtfR07XVUaTW9GkEyhPucg.png" /></figure><p>Congratulations!!! You have successfully Installed and setup Apache Airflow.</p><p>That’s all folks, May the Force be with you.</p><p>I’ll see you in the next article where we’ll build and deploy a machine learning pipeline using Apache Airflow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11ea1e03965" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/intro-to-airflow-setting-up-apache-airflow-11ea1e03965">Intro To Airflow: Setting Up Apache Airflow</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring KNN with Different Distance Metrics]]></title>
            <link>https://blog.devgenius.io/exploring-knn-with-different-distance-metrics-85aea1e8299?source=rss-962684e95f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/85aea1e8299</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[minkowski-distance]]></category>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[euclidean-distance]]></category>
            <category><![CDATA[manhattan-distance]]></category>
            <dc:creator><![CDATA[Abdullah Siddique]]></dc:creator>
            <pubDate>Wed, 03 May 2023 08:21:29 GMT</pubDate>
            <atom:updated>2023-05-03T09:18:30.477Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*LeFn0JlmRaeVwC4eBZHZrg.png" /></figure><p>Machine learning has become an essential tool for data scientists in solving a wide range of problems. One of the popular algorithms used is k-Nearest Neighbors (KNN). KNN is a simple, yet powerful algorithm that can be used for both classification and regression tasks. This article analyzes a Kaggle Notebook authored by me, which demonstrates the use of KNN with three different distance metrics: Euclidean, Minkowski, and Manhattan.</p><p>You can find the notebook <a href="https://www.kaggle.com/code/kane6543/knn-with-euclidean-minkowski-manhattan-distance?scriptVersionId=128083261">here</a>.</p><p><strong>Overview of KNN Algorithm</strong></p><p>KNN is a lazy learning, instance-based algorithm. It works by comparing the input features of a new sample with the features of existing samples in the dataset. The algorithm then selects the ‘k’ nearest samples, where ‘k’ is a user-defined parameter. The output for the new sample is determined based on the majority class (for classification) or the average value (for regression) of the ‘k’ nearest samples.</p><p><strong>Distance Metrics</strong></p><p>The notebook demonstrates the use of three different distance metrics to calculate the similarity between samples:</p><ol><li><strong>Euclidean Distance</strong></li></ol><pre>def euclidean_distance(x1, x2):<br>    return math.sqrt(np.sum((x1 - x2)**2))</pre><p>The euclidean_distance function calculates the Euclidean distance between two points (x1 and x2) in a multi-dimensional space. It takes two input arguments, x1 and x2, which are usually numpy arrays or lists representing the coordinates of the two points.</p><p>The function works as follows:</p><ol><li>Subtract x2 from x1 element-wise, resulting in the difference between corresponding coordinates.</li><li>Square the differences using the **2 operation.</li><li>Sum the squared differences using np.sum().</li><li>Take the square root of the sum using math.sqrt().</li></ol><p>The Euclidean distance is the straight-line distance between two points in a Euclidean space. By calculating the Euclidean distance, the algorithm can identify the nearest neighbors of a given sample and make predictions based on the majority class (for classification) or the average value (for regression) of the neighbors. Using Euclidean distance is helpful when working with continuous, real-valued features, as it provides an intuitive measure of similarity.</p><p>2. <strong>Minkowski Distance:</strong></p><p>A generalization of Euclidean and Manhattan distance, parameterized by ‘p’. When ‘p=2’, it becomes Euclidean distance, and when ‘p=1’, it becomes Manhattan distance.</p><pre>def minkowski_distance(x1, x2, p):<br>    return np.power(np.sum(np.power(np.abs(x1 - x2), p)), 1/p)</pre><p>The minkowski_distance function calculates the Minkowski distance between two points (x1 and x2) in a multi-dimensional space. It takes three input arguments: x1 and x2, which are usually numpy arrays or lists representing the coordinates of the two points, and p, which is a parameter that controls the behavior of the Minkowski distance.</p><p>The function works as follows:</p><ol><li>Calculate the absolute difference between the corresponding coordinates of x1 and x2 using np.abs(x1 - x2).</li><li>Raise the absolute differences to the power of p using np.power(np.abs(x1 - x2), p).</li><li>Sum the powered differences using np.sum().</li><li>Take the 1/p power of the sum using np.power(sum, 1/p).</li></ol><p>Using the Minkowski distance can be helpful in situations where you want to control the influence of individual features’ differences on the overall distance. By changing the p value, you can adjust the sensitivity of the distance metric to large or small differences in feature values, making it more suitable for specific problem domains or datasets.</p><p>The Minkowski distance can be used to measure the similarity or dissimilarity between samples based on their features. By calculating the Minkowski distance with an appropriate p value, the algorithm can identify the nearest neighbors of a given sample and make predictions based on the majority class (for classification) or the average value (for regression) of the neighbors.</p><p>3.<strong> Manhattan Distance</strong></p><p>The sum of the absolute differences between the coordinates of the two points.</p><pre>def manhattan_distance(x1, x2):<br>    return np.sum(np.abs(x1 - x2))</pre><p>The manhattan_distance function calculates the Manhattan distance between two points (x1 and x2) in a multi-dimensional space. It takes two input arguments, x1 and x2, which are usually numpy arrays or lists representing the coordinates of the two points.</p><p>The function works as follows:</p><ol><li>Calculate the absolute difference between the corresponding coordinates of x1 and x2 using np.abs(x1 - x2).</li><li>Sum the absolute differences using np.sum().</li></ol><p>The Manhattan distance, also known as the L1 distance or taxicab distance, is the sum of the absolute differences between the coordinates of the two points. It represents the shortest path between the points when movement is restricted to a grid-like structure, similar to a taxi navigating through city streets.</p><p>Using the Manhattan distance can be helpful in situations where the data features have different scales, or when the grid-like structure of the problem domain makes it a more appropriate measure of similarity. The Manhattan distance can be used to measure the similarity or dissimilarity between samples based on their features. By calculating the Manhattan distance, the algorithm can identify the nearest neighbors of a given sample and make predictions based on the majority class (for classification) or the average value (for regression) of the neighbors.</p><p>Compared to Euclidean distance, Manhattan distance is less sensitive to outliers, as it does not square the differences. This can make it more suitable for certain datasets or problems where the presence of outliers can have a significant impact on the performance of the model.</p><p><strong>KNN Algorithm</strong></p><p><strong>Using Euclidean Distance</strong></p><pre>def knn_euclidean_distance(X_train, y_train, X_test, k):<br>    # List to store the predicted labels for the test set<br>    y_pred = []<br>    <br>    # Iterate over each point in the test set<br>    for i in range(len(X_test)):<br>        distances = []<br>        # Iterate over each point in the training set<br>        for j in range(len(X_train)):<br>            # Calculate the distance between the two points using the Euclidean distance metric<br>            dist = euclidean_distance(X_test[i], X_train[j])<br>            distances.append((dist, y_train[j]))<br>        <br>        # Sort the distances list by distance (ascending order)<br>        distances.sort()<br>        <br>        # Get the k nearest neighbors<br>        neighbors = distances[:k]<br>        <br>        # Count the votes for each class<br>        counts = {}<br>        for neighbor in neighbors:<br>            label = neighbor[1]<br>            if label in counts:<br>                counts[label] += 1<br>            else:<br>                counts[label] = 1<br>        <br>        # Get the class with the most votes<br>        max_count = max(counts, key=counts.get)<br>        y_pred.append(max_count)<br>    <br>    return y_pred</pre><p>The `knn_euclidean_distance` function is an implementation of the k-Nearest Neighbors (KNN) algorithm using the Euclidean distance as a similarity measure between data points. It takes four input arguments: `X_train` (the training dataset features), `y_train` (the training dataset labels), `X_test` (the test dataset features), and `k` (the number of neighbors to consider when making predictions).</p><p>The function works as follows:</p><p>1. Initialize an empty list `y_pred` to store the predicted labels for the test set.<br>2. Iterate over each data point in the test set (`X_test`).<br>3. For each test data point, calculate the Euclidean distance to all the data points in the training set (`X_train`).<br>4. Store the calculated distances and their corresponding labels in a list called `distances`.<br>5. Sort the `distances` list in ascending order.<br>6. Select the `k` nearest neighbors from the sorted list.<br>7. Count the votes for each class (label) among the neighbors.<br>8. Determine the class with the most votes and append it to the `y_pred` list.<br>9. After iterating over all test data points, return the `y_pred` list containing the predicted labels for the test set.</p><p>The `knn_euclidean_distance` function is useful for solving classification problems, as it allows you to make predictions based on the majority class among the `k` nearest neighbors. By using the Euclidean distance as a similarity measure, the function can identify the nearest neighbors for each data point in the test set and predict their labels accordingly. This implementation is particularly helpful for understanding the inner workings of the KNN algorithm, as it provides an explicit way of calculating distances, selecting neighbors, and making predictions based on the neighbors’ votes.</p><p><strong>Using Minkowski Distance</strong></p><pre>def knn_minkowski_distance(X_train, y_train, X_test, k, p):<br>    # List to store the predicted labels for the test set<br>    y_pred = []<br>    <br>    # Iterate over each point in the test set<br>    for i in range(len(X_test)):<br>        distances = []<br>        # Iterate over each point in the training set<br>        for j in range(len(X_train)):<br>            # Calculate the distance between the two points using the Minkowski distance metric<br>            dist = minkowski_distance(X_test[i], X_train[j], p)<br>            distances.append((dist, y_train[j]))<br>        <br>        # Sort the distances list by distance (ascending order)<br>        distances.sort()<br>        <br>        # Get the k nearest neighbors<br>        neighbors = distances[:k]<br>        <br>        # Count the votes for each class<br>        counts = {}<br>        for neighbor in neighbors:<br>            label = neighbor[1]<br>            if label in counts:<br>                counts[label] += 1<br>            else:<br>                counts[label] = 1<br>        <br>        # Get the class with the most votes<br>        max_count = max(counts, key=counts.get)<br>        y_pred.append(max_count)<br>    <br>    return y_pred</pre><p>The `knn_minkowski_distance` function is an implementation of the k-Nearest Neighbors (KNN) algorithm using the Minkowski distance as a similarity measure between data points. It takes five input arguments: `X_train` (the training dataset features), `y_train` (the training dataset labels), `X_test` (the test dataset features), `k` (the number of neighbors to consider when making predictions), and `p` (the parameter controlling the behavior of the Minkowski distance).</p><p>The function works as follows:</p><p>1. Initialize an empty list `y_pred` to store the predicted labels for the test set.<br>2. Iterate over each data point in the test set (`X_test`).<br>3. For each test data point, calculate the Minkowski distance to all the data points in the training set (`X_train`) using the provided `p` parameter.<br>4. Store the calculated distances and their corresponding labels in a list called `distances`.<br>5. Sort the `distances` list in ascending order.<br>6. Select the `k` nearest neighbors from the sorted list.<br>7. Count the votes for each class (label) among the neighbors.<br>8. Determine the class with the most votes and append it to the `y_pred` list.<br>9. After iterating over all test data points, return the `y_pred` list containing the predicted labels for the test set.</p><p>The `knn_minkowski_distance` function is useful for solving classification problems, as it allows you to make predictions based on the majority class among the `k` nearest neighbors. By using the Minkowski distance as a similarity measure, the function provides flexibility in choosing an appropriate distance metric based on the characteristics of the data. For example, by setting `p=1`, the function calculates the Manhattan distance, and when `p=2`, it calculates the Euclidean distance.</p><p>This implementation is particularly helpful for understanding the inner workings of the KNN algorithm, as it provides an explicit way of calculating distances, selecting neighbors, and making predictions based on the neighbors’ votes. Moreover, it demonstrates the impact of different distance metrics on the performance of the KNN algorithm, allowing for easy experimentation with various values of `p` to find the best-suited distance metric for a given problem or dataset.</p><p><strong>Using Manhattan Distance</strong></p><p>When using manhattan distance the KNN algorithm remains the same as Euclidean distance but we change the distance function to manhattan distance function.</p><p><strong>Training the KNN algorithm</strong></p><p><strong>Dataset</strong></p><p>The dataset I am using is Breast Cancer Wisconsin dataset. You can find the dataset <a href="https://www.kaggle.com/datasets/uciml/breast-cancer-wisconsin-data">here</a>.</p><p>The Breast Cancer Wisconsin dataset is a widely-used benchmark dataset in machine learning and data mining for binary classification tasks. It was collected from the University of Wisconsin Hospitals, Madison, by Dr. William H. Wolberg and collaborators in the 1990s. The dataset is publicly available through the UCI Machine Learning Repository.</p><p>The Breast Cancer Wisconsin dataset contains 569 instances with 32 attributes each. These attributes are:</p><ol><li>ID number: Unique identifier for each sample.</li><li>Diagnosis: The target variable with two possible values — “M” (malignant) and “B” (benign).</li></ol><p>The following 30 features are computed from a digitized image of a fine needle aspirate (FNA) of a breast mass. They describe the characteristics of the cell nuclei present in the image. Each feature is calculated for each cell nucleus and then averaged, resulting in ten real-valued features:</p><ol><li>Radius: Mean distance from the center to points on the perimeter.</li><li>Texture: Standard deviation of gray-scale values.</li><li>Perimeter: Perimeter of the cell nucleus.</li><li>Area: Area of the cell nucleus.</li><li>Smoothness: Local variation in radius lengths.</li><li>Compactness: Perimeter² / area — 1.0.</li><li>Concavity: Severity of concave portions of the contour.</li><li>Concave points: Number of concave portions of the contour.</li><li>Symmetry: Symmetry of the cell nucleus.</li><li>Fractal dimension: “Coastline approximation” — 1.</li></ol><p>The mean, standard error, and the “worst” or largest (mean of the three largest values) of these ten features were computed for each image, resulting in 30 features in total. The dataset does not contain any missing attribute values.</p><p>Since the dataset contain 30 features, we perform feature selection on the dataset. The main purpose of this approach is to reduce the dimensionality of the dataset by selecting a smaller subset of features that have a strong linear relationship with the target variable. By choosing features with high correlation, the aim is to maintain the predictive power of the model while reducing the number of features used, thus potentially improving the model’s performance and interpretability. However, it’s important to note that this method only considers linear relationships between the features and the target variable, and it may not be effective if the underlying relationship is nonlinear or if important interactions between features are present.</p><pre>df = pd.read_csv(&#39;/kaggle/input/breast-cancer-wisconsin-data/data.csv&#39;)<br>corr = df.corr()<br>corr_threshold = 0.6<br>selected_features = corr.index[np.abs(corr[&#39;diagnosis&#39;]) &gt;= corr_threshold]<br>new_cancer_data = df[selected_features]</pre><p>This will provide us with a dataset only containing features with high correlation.</p><p><strong>Training the algorithm</strong></p><pre>X_train_np = np.array(X_train) <br>X_test_np = np.array(X_test)<br><br># Convert y_train and y_test to numpy arrays<br>y_train_np = np.array(y_train)<br>y_test_np = np.array(y_test)<br><br>k_values = list(range(1, 15))<br>accuracies = []<br><br>for k in k_values:<br>    y_pred = knn_euclidean_distance(X_train_np, y_train_np, X_test_np, k)<br>    accuracy = accuracy_score(y_test_np, y_pred)<br>    accuracies.append(accuracy)<br><br># Create a data frame to store k values and accuracies<br>results_df = pd.DataFrame({&#39;k&#39;: k_values, &#39;Accuracy&#39;: accuracies})<br><br># Create the interactive plot using Plotly<br>fig = px.line(results_df, x=&#39;k&#39;, y=&#39;Accuracy&#39;, title=&#39;KNN Accuracy for Different k Values&#39;, labels={&#39;k&#39;: &#39;k&#39;, &#39;Accuracy&#39;: &#39;Accuracy&#39;})<br>fig.show()<br><br># Get the best k value<br>best_k = k_values[accuracies.index(max(accuracies))]<br>best_accuracy = max(accuracies)<br>print(&quot;Best k value is:&quot;, best_k , &quot;where accuracy is:&quot; ,best_accuracy)</pre><p>This code snippet applies the k-Nearest Neighbors (KNN) algorithm using Euclidean distance to a classification problem, while varying the number of neighbors (k) to find the best k value that results in the highest accuracy. It uses the training set (X_train_np and y_train_np) to train the model and the test set (X_test_np and y_test_np) to make predictions and evaluate the model&#39;s performance.</p><p>This code snippet is useful for determining the optimal value of k, which is a hyperparameter of the KNN algorithm. Choosing the right k value is essential for achieving the best model performance, as a too-small k value might result in overfitting, while a too-large k value might lead to underfitting. By visualizing the relationship between k values and their corresponding accuracies, the user can gain insights into the model’s performance and choose the most suitable k value for their problem.</p><p>This approach is particularly useful for understanding the impact of the k parameter on the KNN algorithm’s performance and tuning it to achieve the best results on a given dataset.</p><p>we can modify the code for minkowski disatance as follow:</p><pre># Run the KNN algorithm on the test set for different k and p values<br>k_values = list(range(1, 15))<br>p_values = list(range(1, 6))<br>results = []<br><br>for k in k_values:<br>    for p in p_values:<br>        y_pred = knn_minkowski_distance(X_train_np, y_train_np, X_test_np, k, p)<br>        accuracy = accuracy_score(y_test_np, y_pred)<br>        results.append((k, p, accuracy))<br><br># Create a data frame to store k, p values, and accuracies<br>results_df = pd.DataFrame(results, columns=[&#39;k&#39;, &#39;p&#39;, &#39;Accuracy&#39;])<br><br># Create the 3D plot using Plotly<br>fig = go.Figure(data=[go.Scatter3d(<br>    x=results_df[&#39;k&#39;],<br>    y=results_df[&#39;p&#39;],<br>    z=results_df[&#39;Accuracy&#39;],<br>    mode=&#39;markers&#39;,<br>    marker=dict(<br>        size=4,<br>        color=results_df[&#39;Accuracy&#39;],<br>        colorscale=&#39;Viridis&#39;,<br>        showscale=True,<br>        opacity=0.8<br>    ),<br>    text=[f&quot;k={k}, p={p}, Acc={acc:.2f}&quot; for k, p, acc in results]<br>)])<br><br>fig.update_layout(scene=dict(<br>    xaxis_title=&#39;k&#39;,<br>    yaxis_title=&#39;p&#39;,<br>    zaxis_title=&#39;Accuracy&#39;<br>))<br><br>fig.show()</pre><p>To further improve our results we can apply scaling to our dataset.The primary purpose of applying feature scaling is to ensure that all features have the same scale, which can help improve the performance of distance-based algorithms like KNN. In the KNN algorithm, the distance between data points plays a crucial role in determining their similarity. If features have different scales, the algorithm may give more importance to features with larger scales, leading to suboptimal predictions. By scaling the features to have zero mean and unit variance, the algorithm can treat all features equally, resulting in better model performance.</p><p>We are going to use StandardScaler() and MinMaxScaler() to scale our dataset.StandardScaler and MinMaxScaler are two popular feature scaling techniques in machine learning. Both techniques are used to transform the features to a common scale, which helps improve the performance of many machine learning algorithms, especially those that rely on distances, like k-Nearest Neighbors (KNN) or support vector machines (SVM). Here&#39;s an overview of both methods:</p><p><strong>StandardScaler</strong>: The StandardScaler scales the features by transforming them to have zero mean and unit variance. It does this by subtracting the mean and dividing by the standard deviation for each feature.</p><pre>scaler = StandardScaler()<br>X_train_scaled = scaler.fit_transform(X_train)<br>X_test_scaled = scaler.transform(X_test)</pre><p><strong>MinMaxScaler</strong>: The MinMaxScaler scales the features by transforming them to a specified range, usually [0, 1]. It does this by subtracting the minimum value and dividing by the range (maximum — minimum) for each feature</p><pre>scaler = MinMaxScaler()<br>X_train_scaled = scaler.fit_transform(X_train)<br>X_test_scaled = scaler.transform(X_test)</pre><p>We use different scales and different distance functions to train KNN on our dataset so that we can make comparison and select the best technique suited for our dataset. We got the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*5Ojx69UflxePt20XenyDAQ.png" /></figure><p>We can use bar graph representation to better analyze and understand these results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlakZqzgfb55fKAy6xSs7g.png" /></figure><p>This DataFrame presents the results of applying the k-Nearest Neighbors (KNN) algorithm to a classification problem using different distance metrics and feature scaling techniques. The table contains the following columns:</p><ol><li>Index: The index number of the row.</li><li>Distance Metric: The distance metric used for the KNN algorithm, which can be either Euclidean distance, Minkowski distance, or Manhattan distance.</li><li>Feature Scaling: The feature scaling technique applied to the dataset. The options are None (no scaling), StandardScaler, or MinMaxScaler.</li><li>Best k value: The optimal number of neighbors (k) that resulted in the highest accuracy.</li><li>Best Accuracy: The highest accuracy achieved with the best k value.</li></ol><p>Based on the results, we can draw the following conclusions:</p><ol><li><strong>Distance Metrics:</strong> Both Euclidean distance and Minkowski distance have achieved the highest accuracy of 0.982456 when no feature scaling is applied. However, Manhattan distance has slightly lower accuracy in all cases, suggesting that Euclidean or Minkowski distance might be more suitable for this problem. Note that when the value of p in the Minkowski distance metric is 2, it is equivalent to the Euclidean distance. Hence, the results for these two metrics are the same in the current experiment.</li><li><strong>Feature Scaling:</strong> For Euclidean and Minkowski distance metrics, not applying any feature scaling resulted in the highest accuracy. However, for Manhattan distance, both StandardScaler and MinMaxScaler improved the model’s performance compared to the non-scaled data. This suggests that the impact of feature scaling depends on the distance metric being used.</li><li><strong>Best k value:</strong> The optimal k value varies depending on the distance metric and feature scaling technique. For instance, k=11 is the best value when no scaling is applied and using either Euclidean or Minkowski distance, while k=9 is the best when using Manhattan distance. When feature scaling is applied, the best k value is generally lower, ranging from 3 to 11.</li></ol><p>In conclusion, the best KNN model for this problem uses the Euclidean (or Minkowski with p=2) distance metric without any feature scaling, achieving an accuracy of 0.982456 with k=11 neighbors. However, it’s important to note that these results are specific to this dataset, and the optimal distance metric, feature scaling technique, and k value might differ for other problems.</p><p>That’s all folks. May the force be with you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85aea1e8299" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/exploring-knn-with-different-distance-metrics-85aea1e8299">Exploring KNN with Different Distance Metrics</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>