<?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 Oluseye Jeremiah on Medium]]></title>
        <description><![CDATA[Stories by Oluseye Jeremiah on Medium]]></description>
        <link>https://medium.com/@oluseyejeremiah?source=rss-5830e69cd0a1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ICf1VdHaG6MGGg-TTguxBw.jpeg</url>
            <title>Stories by Oluseye Jeremiah on Medium</title>
            <link>https://medium.com/@oluseyejeremiah?source=rss-5830e69cd0a1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 23:31:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oluseyejeremiah/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[Why GraphQL Adoption Keeps Growing: Benefits and Limitations]]></title>
            <link>https://medium.com/@oluseyejeremiah/why-graphql-adoption-keeps-growing-benefits-and-limitations-9c5408c902ff?source=rss-5830e69cd0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c5408c902ff</guid>
            <dc:creator><![CDATA[Oluseye Jeremiah]]></dc:creator>
            <pubDate>Fri, 03 Oct 2025 12:21:17 GMT</pubDate>
            <atom:updated>2025-10-03T12:21:17.341Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYtAeSpAq01yJta4JRmZrQ.png" /></figure><p>REST has been the default method for designing APIs for years. It’s predictable, resource-oriented, and simple enough that nearly every engineering team has used it. However, as applications grew more complex, their shortcomings became increasingly difficult to overlook. Mobile clients wanted lighter payloads. Single-page apps needed flexible queries. Teams found themselves battling over-fetching, under-fetching, and endless endpoint versions to keep features moving.</p><p>GraphQL emerged as a direct response. Instead of hard-coded endpoints, it lets clients declare exactly what data they need. That shift may sound small, but it changes the relationship between frontend and backend teams, reduces wasted network calls, and makes APIs easier to evolve.</p><p>This isn’t theoretical. Companies like<a href="https://docs.github.com/en/graphql"> GitHub</a>,<a href="https://shopify.dev/docs/api/graphql"> Shopify</a>, and<a href="https://netflixtechblog.com/our-learnings-from-adopting-graphql-f099de39ae5f"> Netflix</a> rely on GraphQL in production to simplify API use and scale effectively. Adoption continues to grow because GraphQL addresses recurring problems in distributed systems.</p><p>In this post, we’ll explore the challenges that REST left unsolved, compare GraphQL with REST, explain how GraphQL works, and examine the benefits and limitations that drive its adoption.</p><h3>The API Landscape Before GraphQL</h3><p>Before GraphQL, REST was the dominant API design approach. Its resource-based model was simple: define endpoints, return JSON, and let clients assemble the data. This worked when applications were smaller and client needs were predictable.</p><p>As systems scaled, cracks appeared:</p><ul><li><strong>Over-fetching:</strong> Endpoints returned more data than required. A mobile app that requires only a user’s name and avatar might receive the entire user object.</li><li><strong>Under-fetching:</strong> Clients made multiple round-trips to gather related data. A dashboard fetching customers, orders, and invoices often requires three or four requests.</li><li><strong>Versioning headaches:</strong> New features led to /v2 and /v3 endpoints, leaving teams juggling multiple versions in production.</li><li><strong>One-size-fits-all models:</strong> REST assumed the same data served every client. Mobile, web, and IoT clients often require different shapes, which resulted in bloated responses or fragile workarounds.</li></ul><p>These problems weren’t abstract. They appeared in every production system at scale. REST remains useful for many APIs, but teams need a more flexible model that addresses over-fetching, under-fetching, and version churn without requiring the rewriting of every client. This set the stage for GraphQL.</p><h3>What GraphQL Brings to the Table</h3><p>GraphQL, introduced by Facebook in 2015, directly addresses the weaknesses of REST. Instead of rigid endpoints, the client specifies the shape of the data it wants, and the server responds with that shape.</p><p>Key features include:</p><ul><li><strong>Strongly typed schema:</strong> Defines objects, fields, and relationships. It acts as a contract between frontend and backend, reducing guesswork and enabling evolution without breaking clients.</li><li><strong>Single endpoint:</strong> Consolidates APIs into one entry point. Instead of /users, /orders, and /products, a single endpoint accepts declarative queries.</li><li><strong>Declarative data fetching:</strong> Eliminates over-fetching and under-fetching. A mobile app can request only an ID, name, and avatar, while a web dashboard can query orders and invoices in a single call.</li><li><strong>Introspection and tooling:</strong> The schema can be queried for documentation. Tools like GraphiQL and Apollo Studio make APIs self-discoverable, easing onboarding and debugging.</li><li><strong>Frontend alignment:</strong> Frameworks like Apollo Client and Relay integrate queries into component lifecycles, fitting naturally with how teams build SPAs and mobile apps.</li></ul><p>These qualities make GraphQL particularly effective for <strong>modern API design</strong>, where speed, flexibility, and cross-team collaboration are most crucial.</p><h3>GraphQL vs REST: Why Developers Prefer It</h3><p>The benefits of GraphQL adoption are practical and immediate:</p><ul><li><strong>Fewer requests, faster apps:</strong> By returning exactly the requested data, GraphQL reduces bandwidth use and round trips, especially valuable for mobile clients.</li><li><strong>Faster iteration cycles:</strong> Frontend teams don’t need to wait on new endpoints. If a field exists in the schema, they can query it directly.</li><li><strong>Better developer experience:</strong> Introspection, type safety, and ecosystem support make APIs easier to explore and debug. GraphiQL offers interactive queries, while Apollo Client integrates seamlessly with React for enhanced data handling.</li><li><strong>Strong typing for safety:</strong> IDEs offer better autocomplete, reducing runtime surprises and simplifying refactors.</li></ul><p>Adoption by leading platforms validates these advantages. GitHub migrated large parts of its API to GraphQL to simplify complex queries. Shopify utilizes it to power storefront APIs, enabling partners to build more sophisticated apps. Netflix has written about consolidating multiple data sources under a single GraphQL schema. These examples demonstrate GraphQL in production at scale.</p><p>For developers, the appeal is clear: GraphQL reduces friction, speeds up development, and provides a more reliable contract between client and server.</p><h3>GraphQL Benefits and Limitations</h3><p>No technology is without tradeoffs. While GraphQL adoption grows, it brings challenges:</p><ul><li><strong>Complexity on the server: </strong>Resolvers must handle dynamic queries, nested relationships, and performance tuning. Poor design can lead to slow queries or denial-of-service risks.</li><li><strong>Caching difficulties: </strong>REST benefits from simple HTTP caching by URL. GraphQL queries are unique, which complicates cache invalidation. Teams often rely on Apollo or Relay, or build custom caching layers.</li><li><strong>Learning curve: </strong>Teams must learn schemas, resolvers, and query planning. Backends need monitoring and query cost analysis. Adoption slows if cultural and technical shifts aren’t managed.</li><li><strong>Not always necessary:</strong>For small internal APIs with a handful of endpoints, REST is still simpler and easier to maintain. Using GraphQL where it isn’t needed adds overhead without clear benefits.</li></ul><p>The key takeaway is that GraphQL shifts complexity. It solves recurring client-side problems but introduces new concerns on the server side. Successful adoption requires investment in schema design, performance safeguards, and developer education.</p><h3>Why GraphQL Adoption Continues to Grow</h3><p>Despite its trade-offs, GraphQL adoption continues to rise because it aligns with modern engineering practices.</p><ul><li><strong>Mature ecosystem:</strong> Servers like Apollo, Hasura, and GraphQL Helix make advanced features, such as schema stitching, subscriptions, and federation, more accessible.</li><li><strong>Frontend-first model:</strong> With React, Vue, and Next.js, GraphQL lets teams colocate queries with UI components, improving maintainability.</li><li><strong>Standardization:</strong> As more companies adopt GraphQL internally, developers recognize familiar patterns across organizations. This shared experience boosts confidence for new adopters.</li></ul><p>In short, GraphQL isn’t perfect, but it consistently addresses over-fetching, under-fetching, and version churn while aligning with today’s API needs.</p><h3>Conclusion</h3><p>GraphQL’s growth isn’t about replacing REST but filling its gaps. Over-fetching, under-fetching, and rigid versioning made it difficult to deliver efficient experiences across clients. GraphQL solves those challenges by letting clients declare exactly what they need.</p><p>The tradeoffs — server complexity, caching, and the learning curve — are real, but so are the benefits. With strong tooling, an active ecosystem, and years of production use, GraphQL has proven it can handle the needs of large-scale systems.</p><p>For senior engineers and architects, the conclusion is straightforward: GraphQL isn’t a silver bullet, but when applied to the right problems, it enables APIs that are easier to evolve, more efficient for clients, and better suited to modern application development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c5408c902ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring The Titanic Dataset Using YOLOPandas And Comet]]></title>
            <link>https://medium.com/@oluseyejeremiah/exploring-the-titanic-dataset-using-yolopandas-and-comet-173c0df9bde?source=rss-5830e69cd0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/173c0df9bde</guid>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Oluseye Jeremiah]]></dc:creator>
            <pubDate>Fri, 29 Mar 2024 15:35:23 GMT</pubDate>
            <atom:updated>2024-03-29T15:35:23.545Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AnKMhoan6C5nRvpn.jpg" /><figcaption>Image Credit: <a href="https://i2.wp.com/">https://i2.wp.com/</a></figcaption></figure><p>In the realm of data science and machine learning, the Titanic dataset has long been a rite of passage for aspiring data explorers and model builders. It offers a captivating glimpse into the historical tragedy of the RMS Titanic while providing a rich playground for data analysis and predictive modeling. But what happens when we infuse this classic dataset with cutting-edge tools like YOLOPANDAS and Comet? The result is a data expedition that transcends traditional exploration, unlocking hidden insights and redefining the way we engage with data.</p><p>In this journey, we delve into the fusion of YOLOPANDAS, a powerful data manipulation library, and Comet, a state-of-the-art machine learning operations platform. Together, they form a dynamic duo that empowers data scientists to navigate the Titanic dataset with precision and sophistication. This exploration will uncover not only the historical narratives buried within the data but also the modern techniques and tools that enhance our ability to extract meaningful knowledge from it. Join us as we embark on a voyage into the world of data science, where history meets innovation in the exploration of the Titanic dataset.</p><h4>About YOLOPandas</h4><p>YOLOPandas is a Python library that makes it easy to work with data in a variety of formats, including CSV, JSON, and Excel files. It also allows you to interact with your data using natural language, making it a powerful tool for data exploration and analysis.</p><p>YOLOPANDAs is built on top of the LangChain library, which allows it to use large language models (LLMs) to generate and execute code. This means that you can use YOLOPANDAS to write complex data transformation and analysis pipelines without having to write any Python code yourself.</p><p>To use YOLOPandas, you first need to install the library using pip.</p><pre>pip install yolopandas</pre><p>Once you have installed YOLOPandas, you can start using it to interact with your data.</p><h4>About Comet</h4><p>Comet is a machine learning platform made to assist you in efficiently managing and overseeing your machine learning experiments. A collection of tools users can use through its platform to track and evaluate model performance is one of Comet’s standout features. You can look through the supplementary information accessible here to gain a more thorough understanding of Comet and its capabilities.</p><h4>Overview Of LLMs</h4><p>A large language model (LLM) is a form of AI algorithm that analyzes, synthesizes, generates, and predicts new material using deep learning methods and extraordinarily enormous data sets. Neural networks (NNs), which are computer architectures influenced by the human brain, are another name for LLMs. These neural networks operate by layering a network of nodes, much like neurons.</p><p>Large-scale text and code datasets are used to train LLMs. Books, articles, code repositories, and other types of content can all be used as training materials. In order to create new text and code that are comparable to the training material, the LLM learns to recognize patterns in the data.</p><h4>Getting Started</h4><p>Step 1: Import all necessary libraries</p><pre>from yolopandas import pd<br><br>import matplotlib.pyplot as plt</pre><p>Step 2: Load The Dataset</p><pre>Titanic_dataset= pd.read_csv(&#39;/content/tested.csv&#39;)</pre><p>Step 3: Create an environment for your project on Comet’s workspace</p><pre>`os.environ[&#39;COMET_API_KEY&#39;]= &#39;XOwzVd3UjckDWT9HLWXKqMTTG&#39;<br>os.environ[&#39;COMET_PROJECT_NAME&#39;] = &quot;Titanic_dataset&quot;</pre><p>After creating the environment on the workspace, we move on to create the first prompt</p><pre>comet_llm.log_prompt(<br>    prompt = &quot;What is this prompt about?&quot;,<br>    output = &quot;I want to know about Titanic.&quot;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHnyAOiphXcW-tRHY2NG4A.png" /></figure><p>We can initiate our dataset exploration using the LLM accessor. By default, the ‘yolo’ parameter is configured as ‘false,’ granting us the advantage of reviewing the code before actual execution and allowing us to make an informed decision to either accept or reject it. Conversely, when we set ‘yolo’ to ‘True,’ the code is executed without any prior preview, instantly running directly from the LLM.</p><p>The ‘yolo’ parameter operates as a binary flag, enabling or disabling the execution of code directly from the LLM. This ‘yolo’ parameter can be seamlessly integrated into any of the YOLOPandas query functions, offering flexibility and control in managing code execution within our exploration process.</p><pre>Titanic_dataset.llm.query(&quot;Show the first three names in the dataset&quot;, yolo=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hkAME6SepM9X30uqXN2PZg.png" /></figure><pre>Titanic_dataset.llm.query(&quot;What columns are missing values?&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RU0BbRkGCdUqhvYBSarPwQ.png" /></figure><pre>Titanic_dataset.llm.query(&quot;Now show me how many males survived.&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CMDQokjxUfn72HnBqIM60g.png" /></figure><pre>Titanic_dataset.llm.query(&quot;Now show me how many females survived.&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GGRhTzaFTWUlvquPz-5QNg.png" /></figure><pre>Titanic_dataset.llm.query(&quot;Now tell me about Kelly, Mr. James&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*40VhLal2itbMHw6zY37seQ.png" /></figure><pre>Titanic_dataset.llm.query(&quot;Now show me a chart of males who survived and the females who survived&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VK8-zFLJiczL4Urlaw_aNg.png" /></figure><p>There’s no limit to the questions that can be asked, so you can explore the dataset further once you’re done. The next step is to log our data in the Comet workspace.</p><pre>from comet_ml import Artifact, Experiment<br><br><br>Titanic_dataset= pd.read_csv(&quot;/content/tested.csv&quot;)<br><br>artifact_one = Artifact(name=&quot;Titanic_Dataset&quot;, artifact_type=&quot;dataset&quot;)<br>artifact_one.add(&quot;/content/tested.csv&quot;)<br><br>#log the two datasets as artifacts to Comet<br>experiment.log_artifact(artifact_one)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mgowhWZDX7SwCW8JOKHhcA.png" /></figure><p>We then have to end the experiment.</p><pre>experiment.end()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*20aEVjid93U842MLwN52Tw.png" /></figure><h4>Conclusion</h4><p>In conclusion, the Titanic dataset may be explored using YOLOPANDAs and Comet, two potent tools that can be used to create machine-learning models that forecast passenger survivability.</p><p>A strong and effective workflow for exploring and analyzing the Titanic dataset may be made by combining YOLOPANDAS with Comet. YOLOPANDAS can be used to undertake exploratory data analysis as well as clean and prepare the data. Then, Comet can be used to monitor and control machine learning studies to forecast passenger survival.</p><p>You can rapidly and efficiently gather insights from the Titanic dataset using YOLOPANDAS and Comet and create machine-learning models that can be used to forecast passenger survival.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=173c0df9bde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Effective and User-Friendly Medical Chatbot with OpenAI and CometLLM: A Step-by-Step…]]></title>
            <link>https://medium.com/@oluseyejeremiah/building-an-effective-and-user-friendly-medical-chatbot-with-openai-and-cometllm-a-step-by-step-0c822f9bf47b?source=rss-5830e69cd0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c822f9bf47b</guid>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Oluseye Jeremiah]]></dc:creator>
            <pubDate>Fri, 29 Mar 2024 15:33:41 GMT</pubDate>
            <atom:updated>2024-03-29T15:33:41.272Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an Effective and User-Friendly Medical Chatbot with OpenAI and CometLLM: A Step-by-Step Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/0*0M2IMOd2GgZcDqZD.jpg" /><figcaption>Photo credit:<a href="https://www.mobihealthnews.com/content/bot-md-gets-700k-global-doctor-facing-ai-chatbot-app">mobihealthnews.com</a></figcaption></figure><p>The application of artificial intelligence (AI) is transforming patient involvement and information sharing in the quickly changing field of healthcare technology. This article walks you through building a cutting-edge Doctor Chatbot as it explores the fascinating field of conversational AI. We will explore step-by-step directions to create an intelligent yet friendly chatbot designed for medical interactions, utilizing the potent powers of OpenAI and CometLLM.</p><p>Learn how CometLLM, a dynamic platform for machine learning experimentation, and OpenAI, a trailblazing force in AI research, are collaborating to transform the healthcare experience. This post offers a thorough road map for developers and healthcare professionals alike, covering everything from comprehending the nuances of OpenAI’s cutting-edge models to building a seamless chatbot architecture.</p><h4>About CometLLM</h4><p>Comet’s LLMOps toolbox provides customers with access to state-of-the-art prompt management innovations, including quicker iterations, better performance bottleneck diagnosis, and a visual tour of Comet’s ecosystem’s internal prompt chain operations.</p><p>Comet excels in accelerating progress in the following critical areas with its LLMOps tools:</p><p>1. Prompt History Mastery: Keeping accurate records of prompts, responses, and chains is critical in the world of machine learning products powered by big language models. Comet’s LLMOps tool offers a very user-friendly interface for thorough, fast history tracking, and analysis. Users can learn a great deal about how their prompts and answers have changed over time.</p><p>2. Prompt Playground Adventure: One of the most creative features in the LLMOps toolbox is the Prompt Playground, a dynamic environment where Prompt Engineers can conduct quick explorations. This allows them to quickly test out different prompt templates and see how they affect different scenarios. During the iterative process, users are empowered to make well-informed decisions thanks to their increased experimentation agility.</p><p>3. Prompt Usage Surveillance: Using paid APIs may be necessary to navigate the world of huge language models. Precise usage tracking is available at the project and experiment levels using Comet’s LLMOps tool. Users may better understand API use with the help of this meticulously thorough tracking system, which makes resource allocation and optimization easier.</p><p>In summary, Comet’s LLMOps toolset is an essential tool for engineers, developers, and academics who are delving into the intricacies of huge language models. Their approach is not only streamlined, but it also provides increased transparency and efficiency, which makes it easier to design and refine ML-driven apps.</p><h3>Building a Doc-Bot OpenAI and CometLLM</h3><p>Before delving into the intricacies of code, it’s crucial to grasp the foundational components and key features of the chatbot we’re about to build—DocBot. Tasked with the role of a virtual health assistant, DocBot is designed to cater to a spectrum of user needs within the realm of healthcare.</p><h4>Main Components and Features:</h4><p>1. General Health Inquiries:<br>DocBot serves as a reliable source for users seeking information on general health and wellness. Users can ask about maintaining a healthy lifestyle, dietary recommendations, and other holistic health practices.</p><p>2. Advice on Common Ailments<br>With DocBot, users can seek guidance on common health issues such as colds, headaches, and stress management. The chatbot provides practical advice, suggesting remedies and lifestyle adjustments to alleviate common ailments.</p><p>3. Specialized Health Tips:<br>DocBot extends its capabilities to offer specialized advice for users with chronic conditions, mental health concerns, and those navigating the various facets of healthy aging. This personalized guidance ensures a tailored approach to individual health needs.</p><p>4. Emergency Situations Guidance:<br>In critical situations, DocBot steps up as a virtual first responder, providing users with essential first aid information for emergencies. From burns to CPR guidelines, the chatbot imparts crucial knowledge to users in times of urgency.</p><h4>Guiding Principles:</h4><p>Empathy: DocBot is designed to engage with users empathetically, understanding the importance of a human touch even in virtual interactions. The chatbot responds with compassion, acknowledging the sensitivity of health-related queries.</p><p>Informativeness: In each interaction, DocBot aims to be informative and educational. Whether offering advice on healthy living or guiding users through emergency procedures, the chatbot prioritizes the dissemination of accurate and valuable information.</p><p>User-Centric Approach: DocBot places users at the center of its functionality. By addressing a spectrum of health-related inquiries, the chatbot ensures a user-centric experience, tailoring responses to meet individual needs.</p><p>Safety and Responsibility: Recognizing the critical nature of health advice, DocBot operates with a commitment to safety and responsibility. The chatbot encourages users to consult healthcare professionals for personalized guidance in specific situations.</p><p>Step 1: Install all dependencies</p><pre>%pip install &quot;comet_llm&gt;=1.4.1&quot; &quot;openai&gt;1.0.0&quot;<br>import os<br>from openai import OpenAI<br>import comet_llm<br>from IPython.display import display<br>import ipywidgets as widgets<br>import time</pre><pre>import comet_llm<br><br>comet_llm.init(project=&quot;Doc_bot_openai&quot;)<br>from openai import OpenAI<br><br>client = OpenAI()</pre><p>Step 2: Defining The Role For The Bot</p><p>Developing a user-friendly chatbot experience with a focus on empathy and informativeness in DoctorBot’s responses is the main goal, encouraging interaction and engagement. The code below attempts to improve user comprehension by classifying health information, making it a useful and trustworthy resource for health-related questions. The final objective is to encourage users to seek expert medical counsel when needed and to make informed health decisions.</p><pre># Customize your medical advice list if necessary.<br>advice_list = &#39;&#39;&#39;<br># Medical Advice List<br><br>## General Health:<br><br>- Healthy Diet  <br>  - Tips: Include a variety of fruits and vegetables in your diet. Limit processed foods.<br>  <br>- Regular Exercise  <br>  - Tips: Aim for at least 30 minutes of moderate exercise most days of the week.<br><br>- Adequate Sleep  <br>  - Tips: Ensure you get 7-9 hours of sleep per night for overall well-being.<br><br>## Common Ailments:<br>- Cold and Flu Remedies  <br>  - Tips: Stay hydrated, get plenty of rest, and consider over-the-counter cold remedies.<br><br>- Headache Relief  <br>  - Tips: Drink water, rest in a quiet room, and consider over-the-counter pain relievers.<br><br>- Stress Management  <br>  - Tips: Practice deep breathing, meditation, or engage in activities you enjoy.<br><br>## Common Symptoms and Solutions:<br>- Fever  <br>  - Tips: Stay hydrated, rest, and consider over-the-counter fever reducers.<br><br>- Cough  <br>  - Tips: Stay hydrated, use cough drops, and consider over-the-counter cough medicine.<br><br>- Sore Throat  <br>  - Tips: Gargle with warm saltwater, stay hydrated, and rest your voice.<br><br>- Fatigue  <br>  - Tips: Ensure you get enough sleep, maintain a balanced diet, and consider stress-reducing activities.<br><br>## Specialized Advice:<br>- Chronic Conditions  <br>  - Tips: Follow your prescribed treatment plan and attend regular check-ups.<br><br>- Mental Health Support  <br>  - Tips: Reach out to a mental health professional if you&#39;re struggling emotionally.<br><br>- Healthy Aging  <br>  - Tips: Stay socially active, exercise regularly, and attend routine health check-ups.<br><br>## Emergency Situations:<br>- First Aid for Burns  <br>  - Tips: Run cold water over the burn, cover with a clean cloth, and seek medical attention.<br><br>- CPR Guidelines  <br>  - Tips: Call for help, start chest compressions, and follow emergency protocols.<br><br>&#39;&#39;&#39;<br><br>context_doctor = [{&#39;role&#39;: &#39;system&#39;,<br>                   &#39;content&#39;: f&quot;&quot;&quot;<br>You are DoctorBot, an AI assistant providing medical advice and information.<br><br>Your role is to assist users with general health inquiries, provide advice on common ailments, offer specialized health tips, and guide users in emergency situations.<br><br>Be empathetic and informative in your interactions.<br><br>We offer a variety of medical advice across categories such as General Health, Common Ailments, Common Symptoms and Solutions, Specialized Advice, and Emergency Situations.<br><br>The Current Medical Advice List is as follows:<br><br>```{advice_list}```<br><br>Encourage users to ask questions about their health, provide relevant advice, and remind them to consult with a healthcare professional for personalized guidance.<br>&quot;&quot;&quot;}]</pre><p>Step 3: Creating the Chatbot</p><p>After you configure your environment and define your <em>advise_list</em>, you can create your DocBot chatbot. The get_completion_from_messages function sends messages to the OpenAI GPT-3.5 Turbo model and retrieves responses from the model.</p><pre># Create a Chatbot<br>def get_completion_from_messages(messages, model=&quot;gpt-3.5-turbo&quot;):<br>    client = OpenAI(<br>        api_key=&quot;OPEN_AI_KEY&quot;,<br>    )<br><br>    chat_completion = client.chat.completions.create(<br>        messages=messages,<br>        model=model,<br>    )<br>    return chat_completion.choices[0].message.content</pre><p>Step 4: Interacting with Patients</p><p>To interact with patients, use a simple user interface with text entry for Patients messages and a button to start a conversation. Thecollect_messages function processes user input, updates conversation context, and displays chat history.</p><pre>def collect_messages(_):<br>    user_input = inp.value<br>    inp.value = &#39;&#39;<br>    <br>    context_doctor.append({&#39;role&#39;:&#39;user&#39;, &#39;content&#39;:f&quot;{user_input}&quot;})<br><br>    # Record the start time<br>    start_time = time.time()  <br><br>    response = get_completion_from_messages(context_doctor) <br><br>    # Record the end time<br>    end_time = time.time()  <br><br>    # Calculate the duration<br>    duration = end_time - start_time</pre><p>Step 5: Log records into Comet</p><p>The next step involves using comet_llm to keep track of what patients ask, how the bot responds, and how long each interaction takes. The information is logged on the Comet website. This helps in improving the model for future training. You can learn more about experiment tracking with <a href="https://github.com/comet-ml/comet-llm">Comet LLM</a>.</p><pre>  # Log to comet_llm<br>    comet_llm.log_prompt(<br>        prompt=user_input,<br>        output=response,<br>        duration=duration,<br>        metadata={<br>            &quot;role&quot;: context_doctor[-1][&#39;role&#39;],<br>            &quot;content&quot;: context_doctor[-1][&#39;content&#39;],<br>            &quot;context&quot;: context_doctor,<br>            &quot;advice_list&quot;: advice_list<br>        },<br>    )<br><br>    context_doctor.append({&#39;role&#39;: &#39;assistant&#39;, &#39;content&#39;: f&quot;{response}&quot;})<br><br>    user_pane = widgets.Output()<br>    with user_pane:<br>        display(widgets.HTML(f&quot;&lt;b&gt;User:&lt;/b&gt; {user_input}&quot;))<br><br>    assistant_pane = widgets.Output()<br>    with assistant_pane:<br>        display(widgets.HTML(f&quot;&lt;b&gt;Assistant:&lt;/b&gt; {response}&quot;))<br><br>    display(widgets.VBox([user_pane, assistant_pane]))<br><br>inp = widgets.Text(value=&quot;Hi&quot;, placeholder=&#39;Enter text here…&#39;)<br>button_conversation = widgets.Button(description=&quot;Chat!&quot;)<br>button_conversation.on_click(collect_messages)<br><br>dashboard = widgets.VBox([inp, button_conversation])<br><br>display(dashboard)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i1mB8ASUFX8HNMyp4bN2IA.png" /></figure><p>The prompts have been logged on the Comet website. By analyzing these logs, you can use various strategies to make responses quicker, improve accuracy, enhance customer satisfaction, and eliminate unnecessary steps in your medical operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9thT6Mp_VcItl3xX_h7qsw.gif" /></figure><p>More training is required for a DocBot chatbot that is more sophisticated. Comet LLM is a useful tool for logging and viewing messages and threads, which streamlines the process of developing chatbot language models and enhances workflow. It offers insights for effective model building and optimization, simplifies problem-solving, assures workflow reproducibility, and aids in identifying successful methods.</p><h3>Conclusion</h3><p>In conclusion, this comprehensive article explains how to utilize OpenAI and CometLLM to build a strong and approachable medical chatbot. Through the utilization of CometLLM’s machine learning experimentation capabilities and OpenAI’s complex language models, developers and medical professionals can acquire valuable insights into developing a conversational AI that is specifically designed for medical interactions.In order to ensure that the chatbot, DocBot, competently helps users with general health inquiries, common ailments, specialist guidance, and emergency circumstances, the guide highlights the significance of user-centric design. The resulting chatbot, which is dedicated to empathy and informativeness, encourages users to seek expert help when necessary in addition to offering useful health information. This guide offers a preview of the future of intuitive and efficient digital health aides and demonstrates how cutting-edge technologies can revolutionize healthcare communication.</p><p>You can check the <a href="https://colab.research.google.com/drive/1-a2vCeu-RpFMfLOqNdnTfgQoc1SvBkSE#scrollTo=94ZADw1Zn5hH">full code here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c822f9bf47b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building A HealthBot Using Chainlit And OpenAI]]></title>
            <link>https://medium.com/@oluseyejeremiah/building-a-healthbot-using-chainlit-and-openai-6f131f5e4b66?source=rss-5830e69cd0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f131f5e4b66</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Oluseye Jeremiah]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 18:34:52 GMT</pubDate>
            <atom:updated>2024-01-22T18:34:52.015Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*69vLXZCjrJwdXytj0CTSiQ.jpeg" /></figure><p>In this tutorial, we’ll delve into the world of Chainlit, an open-source Python package designed to expedite the development of Chat GPT-like applications by seamlessly integrating your unique business logic and data. We’ll explore how to harness the power of Chainlit to build intelligent and customized HealthBot applications, leveraging its capabilities to create a responsive and context-aware conversational experience. Combined with OpenAI, this tutorial will guide you through the process of constructing a HealthBot that not only understands health-related queries but also incorporates your specific business requirements. Let’s embark on the journey of building an innovative HealthBot using Chainlit and OpenAI.</p><p>Before we get started take a look at the end product</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_9nx4BGoN10L68Ah0bZ7w.png" /></figure><h4>Prerequisites</h4><p>To assure the project’s effective execution, developing an application that resembles ChatGPT utilizing Chainlit and OpenAI demands a particular level of technical expertise.</p><p>These are the primary fields of competence that are required:</p><p>1.Python Programming</p><p>2. Principles of Artificial Intelligence and Machine Learning</p><p>3. API Integration and OpenAI API Key Access</p><h4>Understanding Chainlit</h4><p><a href="https://docs.chainlit.io/get-started/overview">Chainlit </a>is an open-source Python module that has been painstakingly designed to facilitate the rapid building of Chat-like applications by allowing you to easily integrate your unique business logic and data. Specifically designed to build ChatGPT-like apps, it offers a quick and efficient way to integrate into existing code bases or start projects from scratch. With features like data permanence, quick iteration tools, and quick build times, Chainlit is a versatile tool that works with all Python applications and modules. It finds great use in a wide range of AI and machine learning endeavors, particularly those based around conversational AI, thanks to integrations for prominent frameworks and libraries. It provides a ChatGPT-like frontend for instant use, but it also gives customers the ability to customize their frontend using Chainlit as a reliable backend.</p><h4>Key Features</h4><ul><li>Fast and Easy Development: Chainlit provides a step-based approach to building LLM applications, making it quick and efficient to get your bot up and running.</li><li>Customizable UI: You can create a custom user interface for your Chainlit application, ensuring it seamlessly integrates with your brand and user experience.</li><li>Integrations: Chainlit integrates with various tools and libraries, including OpenAI, Haystack, and Llama Index, allowing you to leverage their functionalities within your application.</li><li>Robust Features: Chainlit offers features like authentication, monitoring, data streaming, and multi-user support, making your application secure, scalable, and reliable.</li></ul><p>Overall, Chainlit is a powerful and versatile tool for building chatbot applications.</p><h4>Building The HealthBot</h4><p>After setting up the python environment the next step will be to install all necessary dependencies.</p><pre>pip install chainlit<br>pip install --upgrade openai<br></pre><p>Step 2: Create the main application using Chainlit</p><pre>import chainlit as cl<br>from src.llm import ask_doctor, messages<br><br><br>@cl.on_message<br>async def main(message: cl.Message):<br>    # Your custom logic goes here...<br>    messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message.content})<br>    response = ask_doctor(messages)<br>    messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: response})<br><br>    # Send a response back to the user<br>    await cl.Message(<br>        content =response,<br>    ).send()<br><br></pre><p>The above code is the app.py version of the entire application. This code segment, utilizing Chainlit, serves as a key part of a chatbot implementation. It intercepts and processes user messages, appending them to a message list. Subsequently, it calls the `ask_doctor` function, incorporating the accumulated messages to generate a response from a doctor-like entity. The assistant’s reply is then appended to the message list. Finally, the response is sent back to the user, maintaining a conversational flow. The `messages` list retains the entire conversation, offering a record of interactions for future analysis or reference.</p><p>Step 3: Build the llm.py section`</p><pre>from openai import OpenAI<br>from src.prompt import health_prompts<br><br><br>client = OpenAI()<br><br>messages = [<br>    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: health_prompts}<br>]<br><br><br>def ask_doctor(messages, model=&quot;gpt-3.5-turbo&quot;,temperature=0):<br>    response = client.chat.completions.create(<br>        model= model,<br>        messages=  messages,<br>        temperature= temperature <br>    )<br><br>    return response.choices[0].message.content<br><br></pre><p>This Python code uses the OpenAI library to create a health chatbot powered by the GPT-3.5-turbo model. The chatbot receives user messages, appends them to a list of messages, and utilizes the `ask_doctor` function to obtain responses from the language model. The code includes predefined health prompts for the chatbot to start the conversation. It sets up a communication loop where the user’s messages trigger model responses, and the assistant’s replies are sent back to the user. The temperature parameter in the ask_doctor function controls the randomness of the model’s responses, offering a dynamic interaction experience.</p><p>Step 4:The next step will be to build the prompt which the application runs on</p><pre># Customize your health-related prompts and information if necessary.<br>health_prompts = &#39;&#39;&#39;<br># Health Bot Information<br><br>## General Health:<br><br>- What are the benefits of regular exercise?<br>  - Exercise helps improve cardiovascular health, boost mood, and maintain a healthy weight.<br><br>- How many hours of sleep are recommended for adults?<br>  - Adults should aim for 7-9 hours of sleep per night for optimal health.<br><br>- What are some healthy eating tips?<br>  - Include a variety of fruits, vegetables, whole grains, and lean proteins in your diet.<br><br>## Mental Health:<br><br>- How to manage stress effectively?<br>  - Practice relaxation techniques, exercise, and prioritize self-care.<br><br>- Tips for better mental well-being?<br>  - Connect with others, practice gratitude, and seek professional help if needed.<br><br>## Nutrition:<br><br>- What are some superfoods for a balanced diet?<br>  - Include foods like berries, leafy greens, nuts, and fatty fish in your diet.<br><br>- How to stay hydrated throughout the day?<br>  - Drink at least 8 glasses of water daily and consume hydrating foods.<br><br>## Fitness:<br><br>- Recommended daily physical activity for adults?<br>  - Aim for at least 150 minutes of moderate-intensity exercise per week.<br><br>- Effective home workouts for beginners?<br>  - Try bodyweight exercises, yoga, or brisk walking.<br><br>&#39;&#39;&#39;<br><br>context_health = [{&#39;role&#39;: &#39;system&#39;,<br>                  &#39;content&#39;: f&quot;&quot;&quot;<br>You are HealthBot, an AI assistant for health-related inquiries.<br><br>Your role is to provide information on general health, mental well-being, nutrition, and fitness.<br><br>Feel free to answer health-related questions, share tips, and encourage users to adopt a healthy lifestyle.<br><br>Below are some health-related prompts:<br><br>```{health_prompts}```<br><br>Make the health-related interactions informative and encourage users to ask about any health concerns or seek advice.<br>&quot;&quot;&quot;}]</pre><p>This code defines a set of health-related prompts and information for a chatbot called HealthBot. The prompts cover topics such as general health, mental well-being, nutrition, and fitness. Each prompt includes a question and a brief, informative answer. The code sets up the context for the HealthBot, describing its role as an AI assistant for health-related inquiries. The assistant is encouraged to provide information, answer questions, and promote a healthy lifestyle. The system context includes the predefined health prompts, ready for the HealthBot to interact with users, offering valuable health-related advice and tips.</p><p>So before we run the application let’s add a welcome note to the front page that tells users what the bot is all about</p><pre># Doctor Klaus - Your Health Companion<br><br>Greetings! I&#39;m Doctor Klaus, your dedicated health companion on this wellness journey. 🌟<br><br>In my virtual clinic, I&#39;m here to provide you with valuable health insights, answer your health-related queries, and offer guidance on leading a healthier lifestyle. Let me tell you a bit about myself:<br><br>👨‍⚕️ About Doctor Klaus:<br>- I&#39;m an AI-powered health assistant designed to assist you with a wide range of health inquiries.<br>- My knowledge spans various health topics, including exercise, nutrition, mental well-being, and general health guidelines.<br>- Your well-being is my priority, and I&#39;m here to make your health journey more accessible, informative, and tailored to your needs.<br><br>💡 How I Can Assist You:<br>- Answering your general health questions.<br>- Providing tips for mental well-being and stress management.<br>- Sharing information on nutrition and healthy eating habits.<br>- Recommending personalized fitness routines and exercises.<br><br>🌐 How to Interact with Me:<br>- Simply ask me your health-related questions, and I&#39;ll provide you with accurate and relevant information.<br>- Whether you&#39;re curious about specific health topics or seeking advice on wellness practices, I&#39;m here for you.<br><br>Embark on this wellness adventure with me, Doctor Klaus! Together, we&#39;ll explore the path to a healthier, happier you. For any health-related queries, type your questions below, and let&#39;s kickstart your journey to well-being. 🚀💚</pre><h3>Run the Application</h3><p>To start your Chainlit app, open a terminal and navigate to the directory containing app.py. Then run the following command:</p><pre>chainlit run app.py -w</pre><p>The -w flag tells Chainlit to enable auto-reloading, so you don’t need to restart the server every time you make changes to your application. Your chatbot UI should now be accessible at <a href="http://localhost:8000/">http://localhost:8000</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_9nx4BGoN10L68Ah0bZ7w.png" /></figure><p>We can see that the app is working you can then go ahead and ask any health related questions.</p><h4>Conclusion</h4><p>Building a health bot is more than just code and AI. It’s about empowering users with reliable information and promoting informed choices about their well-being. This journey, while ambitious, becomes surprisingly accessible thanks to the incredible capabilities of Chainlit.</p><p>Chainlit acts as your user-friendly architect, crafting a seamless interface where your health bot shines. You don’t need to be a coding wizard — Chainlit’s features and intuitive structure let you build a beautiful and interactive platform for your bot to engage with users.</p><p>But Chainlit’s magic extends beyond aesthetics. It acts as the communication bridge, translating complex AI responses into clear and user-friendly language. Think of it as your health bot’s personal translator, ensuring every interaction is informative and engaging.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f131f5e4b66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building A Heart Disease Prediction Model Using Machine Learning]]></title>
            <link>https://medium.com/@oluseyejeremiah/building-a-heart-disease-prediction-model-using-machine-learning-4c690243a93e?source=rss-5830e69cd0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c690243a93e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Oluseye Jeremiah]]></dc:creator>
            <pubDate>Sat, 13 Jan 2024 23:32:26 GMT</pubDate>
            <atom:updated>2024-01-13T23:32:26.838Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*9ifX7PtUfKsgRTdO" /><figcaption>Photo credit: bu.edu</figcaption></figure><p>In the dynamic world of healthcare, we’re witnessing a groundbreaking shift towards using technology to better understand and tackle life-threatening conditions. One such leap forward is the integration of machine learning (ML) in predicting heart disease, a pervasive threat that claims lives globally. In this article, we embark on a journey to explore the development of an innovative ML model, aiming to redefine how we approach and safeguard cardiovascular health.</p><p>Heart disease, with its various complexities affecting the heart and blood vessels, calls for a proactive approach to healthcare. While traditional risk assessments have been helpful, the rise of ML holds the promise of heightened precision and accuracy. This article dives into the process of creating a predictive model that can identify potential heart issues before symptoms emerge, leveraging algorithms and vast datasets.</p><p>Come along as we unravel the intricate steps involved in building a machine-learning model for heart disease prediction. We’ll explore the pivotal roles of data collection, feature engineering, model selection, and validation strategies. This article not only sheds light on the technical side of ML but also emphasizes the profound impact these innovations can have on reshaping the landscape of preventive healthcare.</p><p>Picture a future where data-driven insights empower healthcare professionals to intervene early, potentially saving lives and fostering a healthier society. As we delve into the world of predictive analytics for heart disease, let’s envision a human-centric approach that prioritizes well-being and brings us one step closer to a healthier tomorrow.</p><p>For our text editor, we’ll be using DeepNote</p><p><a href="https://deepnote.com/docs">Deepnote</a> is a cloud-based collaborative workspace for data science and analytics teams. Think of it as a supercharged Jupyter notebook with built-in features for:</p><ul><li>Seamless collaboration: Multiple users can work on notebooks together in real time, see each other’s changes, and even chat within the platform.</li><li>Powerful data analysis: It combines code blocks, SQL queries, and visualization tools, enabling teams to explore and analyze data efficiently.</li><li>Easy sharing and documentation: Notebooks can be easily shared with colleagues and stakeholders, and version control ensures everyone’s on the same page.</li><li>Beautiful dashboards and reports: Create interactive dashboards and reports to present findings clearly and compellingly.</li><li>Integrated tools and extensions: Connect to popular data sources, libraries, and cloud platforms directly within Deepnote.</li></ul><p>Overall, Deepnote streamlines data science workflows, fosters collaboration, and empowers teams to turn data into actionable insights. It’s a popular choice for organizations looking to boost their data science productivity and impact.</p><h4>Getting Started</h4><p>The first step involves installing all dependencies</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F91902bd3573547c2af8466ec18d1c07f%3Fheight%3D188&amp;display_name=Deepnote&amp;url=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F91902bd3573547c2af8466ec18d1c07f%3Fheight%3D188&amp;image=https%3A%2F%2Fdeepnote.com%2Fstatic%2Fthumbnails%2Fmain.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=deepnote" width="700" height="188" frameborder="0" scrolling="no"><a href="https://medium.com/media/2361aaf96f24b25cc190c42462fc1bbe/href">https://medium.com/media/2361aaf96f24b25cc190c42462fc1bbe/href</a></iframe><p>Step 2: This involves loading the dataset to begin data preprocessing</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F29697d90ab23492fae2c776873a95f0c%3Fheight%3D116&amp;display_name=Deepnote&amp;url=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F29697d90ab23492fae2c776873a95f0c%3Fheight%3D116&amp;image=https%3A%2F%2Fdeepnote.com%2Fstatic%2Fthumbnails%2Fmain.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=deepnote" width="700" height="116" frameborder="0" scrolling="no"><a href="https://medium.com/media/82e19a6672fea8767b58cafd5960ffeb/href">https://medium.com/media/82e19a6672fea8767b58cafd5960ffeb/href</a></iframe><p>Step 3: To better understand the dataset we view the first 10 rows of the dataset</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F411dbb5a8c1f4b72854390da85aa6623%3Fheight%3D320&amp;display_name=Deepnote&amp;url=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F411dbb5a8c1f4b72854390da85aa6623%3Fheight%3D320&amp;image=https%3A%2F%2Fdeepnote.com%2Fstatic%2Fthumbnails%2Fmain.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=deepnote" width="700" height="320" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a2fcfa267cde65c7da32d9adf761300/href">https://medium.com/media/9a2fcfa267cde65c7da32d9adf761300/href</a></iframe><p>we also use the .describe() feature to get insights from the dataset</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2Ff4438940f44d4059a585c0cc0665454f%3Fheight%3D398&amp;display_name=Deepnote&amp;url=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2Ff4438940f44d4059a585c0cc0665454f%3Fheight%3D398&amp;image=https%3A%2F%2Fdeepnote.com%2Fstatic%2Fthumbnails%2Fmain.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=deepnote" width="700" height="398" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b73eb1806880885b969142eca8e54c8/href">https://medium.com/media/1b73eb1806880885b969142eca8e54c8/href</a></iframe><p>Step 4: This code groups the diabetes dataset by the ‘Outcome’ column and then calculates the mean of each group. The ‘Outcome’ column usually represents the categories or classes, in this case, it could be ‘0’ for non-diabetic and ‘1’ for diabetic. By using the mean() function, it computes the average values for each feature or column for each outcome. Therefore, the resulting output would include the average of all the columns of the dataset for each outcome (0 and 1).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F8be79601db5349948b2e7b27c457ec14%3Fheight%3D224&amp;display_name=Deepnote&amp;url=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F8be79601db5349948b2e7b27c457ec14%3Fheight%3D224&amp;image=https%3A%2F%2Fdeepnote.com%2Fstatic%2Fthumbnails%2Fmain.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=deepnote" width="700" height="224" frameborder="0" scrolling="no"><a href="https://medium.com/media/255c920ac6d621b19aeb2bc4e1838ca2/href">https://medium.com/media/255c920ac6d621b19aeb2bc4e1838ca2/href</a></iframe><p>Step 5: This code is used to separate the features and target from the ‘diabetes_dataset’ data frame. The `drop()` function is used to remove the ‘Outcome’ column from the data frame. The resultant data frame, which contains all columns other than &#39;Outcome&#39;, is assigned to ‘X’, which will serve as a feature matrix for the machine learning model. ‘Y’ is assigned the ‘Outcome’ column from the &#39;diabetes_dataset&#39;, which acts as a target variable. This will be used to train the machine-learning model. The ‘Outcome’ column typically contains the label or result that the model will attempt to predict.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F2b17f119ce254d9893b54a7346fa811e%3Fheight%3D134&amp;display_name=Deepnote&amp;url=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F2b17f119ce254d9893b54a7346fa811e%3Fheight%3D134&amp;image=https%3A%2F%2Fdeepnote.com%2Fstatic%2Fthumbnails%2Fmain.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=deepnote" width="700" height="134" frameborder="0" scrolling="no"><a href="https://medium.com/media/48ffdf57dbf8e880ef0e23340a19f282/href">https://medium.com/media/48ffdf57dbf8e880ef0e23340a19f282/href</a></iframe><p>Step 6: This line of code splits the dataset into a training set and a testing set using the function ‘train_test_split()’ from the sklearn library. The ‘test_size’ parameter is set to 0.2 which means 20% of the data will be used for testing and the rest 80% will be used for training the model. The ‘stratify’ parameter is set to Y which means the train-test split will be made in such a way that the proportion of values in the sample produced will be the same as the proportion of values provided in the ‘Outcome’ column. The ‘random_state’ parameter is set to 2, which ensures that the splits you generate are reproducible and it affects the randomness of the training and testing indices produced.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2Fdaeb18ba15e54e0e8c4ba9ac253d3670%3Fheight%3D98&amp;display_name=Deepnote&amp;url=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2Fdaeb18ba15e54e0e8c4ba9ac253d3670%3Fheight%3D98&amp;image=https%3A%2F%2Fdeepnote.com%2Fstatic%2Fthumbnails%2Fmain.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=deepnote" width="700" height="98" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b745359e15609ad0bb7a03e134209cd/href">https://medium.com/media/1b745359e15609ad0bb7a03e134209cd/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F78157e865a454590bff678cc524679cc%3Fheight%3D507&amp;display_name=Deepnote&amp;url=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F78157e865a454590bff678cc524679cc%3Fheight%3D507&amp;image=https%3A%2F%2Fdeepnote.com%2Fstatic%2Fthumbnails%2Fmain.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=deepnote" width="700" height="507" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b003fc7c37d5651a9eb81195dae9bca/href">https://medium.com/media/3b003fc7c37d5651a9eb81195dae9bca/href</a></iframe><p>From the above table, we can see the pregnacies by age and the effect it has on heart disease.</p><p>Step 7: This line of code is printing the shape of three different data frames: ‘X’, ‘X_train’, and ‘X_test’. The shape of a data frame is a tuple that contains the number of rows and columns in the data frame. ‘X’ is the data frame that contains the entire feature set, ‘X_train’ contains the features for the training set, and ‘X_test’ contains the features for the test set. The output would be three tuples, each representing the number of rows and columns for the respective data frame.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F5a7769b4c7fa41cabb7e00cfc84fb14d%3Fheight%3D128.53125&amp;display_name=Deepnote&amp;url=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F5a7769b4c7fa41cabb7e00cfc84fb14d%3Fheight%3D128.53125&amp;image=https%3A%2F%2Fdeepnote.com%2Fstatic%2Fthumbnails%2Fmain.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=deepnote" width="700" height="128" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bf1b085c2c58cca7f0287d52ee37cc5/href">https://medium.com/media/3bf1b085c2c58cca7f0287d52ee37cc5/href</a></iframe><p>Step 8: The next step involves initiating a Support Vector Machine (SVM) classifier from the ‘svm’ function found in the ‘sklearn’ Python library. The SVM classifier’s kernel is set to ‘linear’. In essence, this piece of code creates a linear SVM model that can be trained using the ‘fit’ function on a labeled dataset to be able to classify new, previously unseen data into pre-defined categories. The performance of the trained classifier can be evaluated using different metrics applicable to classification problems.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F91c962305f034112a0b57433e4be06e9%3Fheight%3D98&amp;display_name=Deepnote&amp;url=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F91c962305f034112a0b57433e4be06e9%3Fheight%3D98&amp;image=https%3A%2F%2Fdeepnote.com%2Fstatic%2Fthumbnails%2Fmain.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=deepnote" width="700" height="98" frameborder="0" scrolling="no"><a href="https://medium.com/media/b20f47331c4241a46fcd5597e30332f6/href">https://medium.com/media/b20f47331c4241a46fcd5597e30332f6/href</a></iframe><p>Moving on the piece of code below is responsible for training the Support Vector Machine (SVM) classifier on the training data. The &#39;classifier.fit(X_train, Y_train)&#39; method is called, where ‘X_train’ is the set of input features for the training data and ‘Y_train’ is the output label for those input features. The model learns from this data and this learned model can further be used to make predictions on unseen data.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F07a7f00152b6441ea56799f5620b96a0%3Fheight%3D190.36458587646484&amp;display_name=Deepnote&amp;url=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F07a7f00152b6441ea56799f5620b96a0%3Fheight%3D190.36458587646484&amp;image=https%3A%2F%2Fdeepnote.com%2Fstatic%2Fthumbnails%2Fmain.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=deepnote" width="700" height="190" frameborder="0" scrolling="no"><a href="https://medium.com/media/d22c1bea32b6156b076937ed96375530/href">https://medium.com/media/d22c1bea32b6156b076937ed96375530/href</a></iframe><p>Step 9: We then calculate the accuracy of the predictive model on the training data. The ‘classifier.predict(X_train)’ function generates predictions for the training data based on the trained model, and the results are stored in ‘X_train_prediction’. The ‘accuracy_score()’ function from the sklearn library is then utilized to compare these predictions with the actual labels (‘Y_train’) to compute the accuracy of the model. The calculated accuracy score is stored in ‘training_data_accuracy’.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2Fc1f7bd05f24b4ea8abf19890bcd44e06%3Fheight%3D134&amp;display_name=Deepnote&amp;url=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2Fc1f7bd05f24b4ea8abf19890bcd44e06%3Fheight%3D134&amp;image=https%3A%2F%2Fdeepnote.com%2Fstatic%2Fthumbnails%2Fmain.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=deepnote" width="700" height="134" frameborder="0" scrolling="no"><a href="https://medium.com/media/fef49dff4b03a0f6056277b1fb415706/href">https://medium.com/media/fef49dff4b03a0f6056277b1fb415706/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F38fa54a0c5b943888bec7cb8d3348ddd%3Fheight%3D128.53125&amp;display_name=Deepnote&amp;url=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F38fa54a0c5b943888bec7cb8d3348ddd%3Fheight%3D128.53125&amp;image=https%3A%2F%2Fdeepnote.com%2Fstatic%2Fthumbnails%2Fmain.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=deepnote" width="700" height="128" frameborder="0" scrolling="no"><a href="https://medium.com/media/459fbf834b104617f79571d2de88014a/href">https://medium.com/media/459fbf834b104617f79571d2de88014a/href</a></iframe><p>We can see the accuracy of our training data is manageable , we can then go on to build the prediction model</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F7ae80580819448db966ee7b8f641708c%3Fheight%3D444.7916717529297&amp;display_name=Deepnote&amp;url=https%3A%2F%2Fembed.deepnote.com%2Fa332e4ea-38f7-49ea-a07c-d378c800e8c6%2Fe168b982556545c59a23f8787bb5fbc5%2F7ae80580819448db966ee7b8f641708c%3Fheight%3D444.7916717529297&amp;image=https%3A%2F%2Fdeepnote.com%2Fstatic%2Fthumbnails%2Fmain.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=deepnote" width="700" height="444" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc54a5ff69d5815983f55b035411e92e/href">https://medium.com/media/bc54a5ff69d5815983f55b035411e92e/href</a></iframe><p>We can see that our prediction model works and the patient here is Diabetic.</p><h4>Conclusion</h4><p>In our pursuit to predict heart disease through machine learning, the constructed model stands as a beacon of hope, promising a transformative approach to preventive healthcare. The model’s accuracy, validated through meticulous calibration and training, reflects its efficacy in discerning subtle patterns for early detection. Precision, recall, and F1 scores affirm its reliability in identifying potential cardiovascular issues. However, acknowledging the dynamic nature of healthcare data, ongoing refinement is crucial for the model’s adaptability. Beyond numerical accuracy, the model symbolizes our collective commitment to a future where predictive analytics becomes a transformative force, guiding us toward early intervention and shaping a healthier tomorrow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c690243a93e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Step-by-Step Guide: Efficiently Managing TensorFlow/Keras Model Development with Comet]]></title>
            <link>https://heartbeat.comet.ml/a-step-by-step-guide-efficiently-managing-tensorflow-keras-model-development-with-comet-c44476a8e3c3?source=rss-5830e69cd0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c44476a8e3c3</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Oluseye Jeremiah]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 15:34:18 GMT</pubDate>
            <atom:updated>2023-11-28T15:34:18.115Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>Welcome to the step-by-step guide on efficiently managing TensorFlow/Keras model development with Comet. TensorFlow and Keras have emerged as powerful frameworks for building and training deep learning models. However, as your model development process becomes more complex and involves numerous experiments and iterations, keeping track of your progress, managing experiments, and collaborating effectively with team members becomes increasingly challenging.</p><p>This is where Comet comes to the rescue. Comet is a comprehensive experiment tracking and collaboration platform for machine learning projects. It empowers data scientists and machine learning practitioners to streamline their model development workflow, maintain a structured record of experiments, and foster seamless collaboration among team members.</p><p>In this guide, we will walk you through the process of efficiently managing TensorFlow/Keras model development using Comet. We will explore the essential features of Comet that enable you to track experiments, log hyperparameters and metrics, visualize model performance, optimize hyperparameter configurations, and facilitate collaboration within your team. Following our step-by-step instructions and incorporating Comet into your workflow can enhance productivity, maintain experiment reproducibility, and derive valuable insights from your model development process.</p><p>Whether you are an experienced machine learning practitioner or just starting your journey in deep learning, this article will provide practical strategies and tips to leverage Comet effectively. Let&#39;s dive in and discover how you can take control of your TensorFlow/Keras model development with Comet.</p><h4>Introducing MLOps</h4><p>Machine learning (ML) is an essential tool for businesses of all sizes. However, deploying ML models in production can be complex and challenging. This is where MLOps comes in.</p><p>MLOps is a set of principles and practices that combine software engineering, data science, and DevOps to ensure that ML models are deployed and managed effectively in production. MLOps encompasses the entire ML lifecycle, from data preparation to model deployment and monitoring.</p><h4>Why Is MLOps Important?</h4><p>There are several reasons why MLOps is essential. First, ML models are becoming increasingly complex and require a lot of data to train. This means it is necessary to have a scalable and efficient way to deploy and manage ML models in production.</p><p>Second, ML models are constantly evolving. This means that it is vital to have a way to monitor and update ML models as new data becomes available. MLOps provides a framework for doing this.</p><p>Finally, ML models need to be secure. They can make important decisions, such as approving loans or predicting customer behavior. MLOps provides a framework for securing ML models.</p><h4>How Does MLOps Work?</h4><p>MLOps typically involves the following steps:</p><ol><li>Data Preparation: The first step is preparing the data that will be used to train the ML model. This includes cleaning the data, removing outliers, and transforming the data into a format that the ML model can use.</li><li>Model Training: The next step is training the ML model. This involves using the prepared data to train the model. The training process can be iterative, and trying different models and hyperparameters may be necessary to find the best model.</li><li>Model Deployment: Once the ML model is trained, it must be deployed in production. This means making the model available to users so they can use it to make predictions.</li><li>Model Monitoring: Once the ML model is deployed, it must be monitored to ensure it performs as expected. This involves tracking the model&#39;s accuracy, latency, and other metrics.</li><li>Model Maintenance: As new data becomes available, the ML model may need to be updated. This is known as model maintenance. Model maintenance involves retraining the model with the latest data and deploying the updated model in production.</li></ol><h3>Keeping Track of Your ML Experiments</h3><p>Accurate experiment tracking simplifies comparing metrics and parameters across different data versions, evaluating experiment results, and identifying the best or worst predictions on test or validation sets. Additionally, it allows for in-depth analysis of hardware consumption during model training.</p><p>The following explanations will guide you in efficiently tracking your experiments and generating insightful charts. By implementing these strategies, you can enhance your experiment management and visualization capabilities, allowing you to derive valuable insights from your data.</p><h4>Project Requirements</h4><p>To ensure adequate tracking and management of your TensorFlow model development, it is crucial to establish a performance metric as a project goal. For instance, you may set the F1-score as the metric to optimize your model&#39;s performance.</p><p>The initial deployment phase should focus on building a simple model while prioritizing the development of a robust machine-learning pipeline for prediction. This approach allows for the swift delivery of value and prevents excessive time spent pursuing the elusive perfect model.</p><p>As your organization embarks on new machine learning projects, the number of experiment runs can quickly multiply, ranging from tens to hundreds or even thousands. Without proper tracking, your workflow can become convoluted and challenging to navigate.</p><p>That&#39;s why tracking tools like Comet have become standard in machine learning projects. Comet enables you to log essential information such as data, model architecture, hyperparameters, confusion matrices, graphs, etc. Integrating a tool like Comet into your workflow or code is relatively simple compared to the complications that arise when you neglect proper tracking.</p><p>To illustrate the tracking approach, let&#39;s consider an example where we train a text classification model using TensorFlow and Long Short-Term Memory (LSTM) networks. Following the steps in this guide will provide insights into effectively utilizing tracking tools and seamlessly managing your TensorFlow model development process.</p><h4>Achieve a Well-Organized Model Development Process with Comet</h4><h4>Install Dependencies For This Project</h4><p>We&#39;ll be using Comet in Google Colab, so we need to install Comet on our machine. Follow the commands below to do this.</p><pre>`%pip install comet_ml tensorflow numpy<br>  !pip3 install comet_ml<br>   import comet_ml<br>   from comet_ml import Experiment<br>   import logging<br><br>logging.basicConfig(level=logging.INFO)<br>LOGGER = logging.getLogger(&quot;comet_ml&quot;)</pre><p>Now that we&#39;ve installed the necessary dependencies let&#39;s import them.</p><pre>import comet_ml<br>from comet_ml import Experiment<br>import logging<br>import pandas as pd<br>import tensorflow as tfl<br>import numpy as np<br>import csv<br>from tensorflow.keras.preprocessing.text import Tokenizer<br>from tensorflow.keras.preprocessing.sequence import pad_sequences<br>from tensorflow import keras<br>from tensorflow.keras import layers<br>import re<br>import nltk<br><br>nltk.download(&#39;stopwords&#39;)<br>from nltk.corpus import stopwords</pre><p>Connect your project to the Comet platform. If you&#39;re new to the platform, read the <a href="https://www.comet.com/docs/v2/">guide</a>.</p><pre>`# Create an experiment<br>experiment = comet_ml.Experiment(<br>    project_name=&quot;Tensorflow_Classification&quot;,<br>    workspace=&quot;olujerry&quot;,<br>      api_key=&quot;YOUR API-KEYS&quot;,<br>    log_code=True,<br><br>   auto_metric_logging=True,<br>    auto_param_logging=True,<br>    auto_histogram_weight_logging=True,<br>    auto_histogram_gradient_logging=True,<br>    auto_histogram_activation_logging=True,</pre><p>It&#39;s important to connect your project to the Comet platform at the beginning of your project so every single parameter and metric can be logged.</p><h4>Save the Hyperparameters (For Each Iteration)</h4><pre>params={<br>                    &#39;embed_dims&#39;: 64,<br>                    &#39;vocab_size&#39;: 5200,<br>                    &#39;max_len&#39;: 200,<br>                    &#39;padding_type&#39;: &#39;post&#39;,<br>                    &#39;trunc_type&#39;: &#39;post&#39;,<br>                    &#39;oov_tok&#39;: &#39;&lt;OOV&gt;&#39;,<br>                    &#39;training_portion&#39;: 0.75<br>    }<br><br>experiment.log_parameters(params)</pre><h3>About The Dataset</h3><p>The dataset we&#39;re using is BBC news article data for classification. It consists of 2225 documents from the <a href="http://news.bbc.co.uk/">BBC</a> News website corresponding to stories in five topical areas from 2004–2005.</p><ul><li>Class Labels: 5 (business, entertainment, politics, sport, tech)</li><li>Download the data <a href="http://mlg.ucd.ie/datasets/bbc.html">here</a>.</li></ul><p>In the below section, I&#39;ve created a list called labels and text, which will help us store the labels of the news article and the actual text associated with it. We&#39;re also removing the stopwords using <a href="https://www.nltk.org/">nltk</a>.</p><pre>labels = []<br>texts = []<br><br>with open(&#39;dataset.csv&#39;, &#39;r&#39;) as file:<br>    data = csv.reader(file, delimiter=&#39;,&#39;)<br>    next(data)<br>    for row in data:<br>        labels.append(row[0])<br>        text = row[1]<br>        for word in stopwords_list:  # Iterate over the stop words list<br>            token = &#39; &#39; + word + &#39; &#39;<br>            text = text.replace(token, &#39; &#39;)<br>            text = text.replace(&#39; &#39;, &#39; &#39;)<br>        texts.append(text)<br><br>print(len(labels))<br>print(len(texts))</pre><p>Let&#39;s split the data into training and validation sets. If you look at the above parameters, we&#39;re using 80% for training and 20% for validating the model we&#39;ve built for this use case.</p><pre>`training_portion = 0.8  # Assigning a value of 0.8 for an 80% training portion<br>train_size = int(len(texts) * training_portion)<br><br>train_text = texts[0:train_size]<br>train_labels = labels[0:train_size]<br><br>validation_text = texts[train_size:]<br>validation_labels = labels[train_size:]</pre><p>To tokenize the sentences into subword tokens, we will consider the top five thousand most common words. We will use the &quot;oov_token&quot; placeholder when encountering unseen special values. For words not found in the &quot;word_index,&quot; we will use &quot;&lt;00V&gt;&quot;. The &quot;fit_on_texts&quot; method will update the internal vocabulary utilizing a list of texts. This approach allows us to create a vocabulary index based on word frequency.</p><pre>`vocab_size = 10000  # Assigning a value for the vocabulary size<br> oov_tok = &#39;&lt;OOV&gt;&#39;  # Assigning a value for the out-of-vocabulary token<br>tokenizer = Tokenizer(num_words = vocab_size, oov_token=oov_tok)<br>tokenizer.fit_on_texts(train_text)<br>word_index = tokenizer.word_index<br>dict(list(word_index.items())[0:8])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*2aig0e37Uadypu0R70eOcA.png" /></figure><p>Observing the provided output, we notice that &quot;&lt;oov&gt;&quot; is the most frequently occurring token in the corpus, followed by other words.</p><p>With the vocabulary index constructed based on frequency, our next step is converting these tokens into sequence lists. The &quot;text_to_sequence&quot; function accomplishes this task by transforming the text into a sequence of integers. It maps the words in the text to their corresponding integer values according to the word_index dictionary.</p><pre>`train_sequences = tokenizer.texts_to_sequences(train_text)<br> print(train_sequences[16])<br>max_length = 100  # Assigning a value for the maximum sequence length<br><br>train_sequences = tokenizer.texts_to_sequences(train_text)<br>train_padded = pad_sequences(train_sequences, maxlen=max_length, truncating=&#39;post&#39;, padding=&#39;post&#39;)<br></pre><p>When training neural networks for downstream natural language processing (NLP) tasks, ensuring that the input sequences are the same size is important. We can use the max_len parameter to add padding to the sequences to achieve this. In our case, we initially set max_len to 200, and we applied padding using padding_sequences.</p><p>For sequences with lengths smaller or greater than max_len, we truncate or pad them to the specified length of 200. For example, if a sequence has a length of 186, we add 14 zeros at the end to pad it to 200. Typically, we fit the data once but perform sequence conversion multiple times, so we have separate training and validation sets instead of combining them.</p><pre>`padding_type = &#39;post&#39;  # Assigning a value for the padding type (&#39;post&#39; or &#39;pre&#39;)<br><br><br>trunc_type = &#39;post&#39;  # Assigning a value for the truncation type (&#39;post&#39; or &#39;pre&#39;)<br><br><br>valdn_padded = pad_sequences(valdn_sequences, maxlen=max_len, padding=padding_type, truncating=trunc_type)<br><br><br>vmax_len = 100  # Assigning a value for the maximum sequence length<br><br>valdn_sequences = tokenizer.texts_to_sequences(validation_text)<br>valdn_padded = pad_sequences(valdn_sequences, maxlen=max_len, padding=padding_type, truncating=trunc_type)<br><br>print(len(valdn_sequences))<br>print(valdn_padded.shape)</pre><p>Next, let&#39;s examine the labels for our dataset. To work with the labels effectively, we need to tokenize them. Additionally, all training labels are expected to be in the form of a NumPy array. We can use the following code snippet to convert our labels into a NumPy array.</p><pre>`label_tokenizer = Tokenizer()<br>label_tokenizer.fit_on_texts(labels)</pre><p>Before we proceed with the modeling task, let&#39;s examine how the texts appear after padding and tokenization. It is important to note that some words may be represented as &quot;&lt;oov&gt;&quot; (out of vocabulary) because they are not included in the vocabulary size specified at the beginning of our code. This is a common occurrence when dealing with limited vocabulary sizes.</p><pre>`word_index_reverse = {index: word for word, index in word_index.items()}<br><br># %% In [41]:<br>def decode_article(text):<br>    return &#39; &#39;.join([word_index_reverse.get(i, &#39;?&#39;) for i in text])<br>print(decode_article(train_padded[24]))<br>print(&#39;**********&#39;)<br>print(train_text[24])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xHGumjD_ySf2gTUjKdihdg.png" /></figure><p>To train our TensorFlow model, we will use the tfl.keras.Sequential class that allows us to group a linear stack of layers into a TensorFlow Keras model. The first layer in our model is the embedding layer, which stores a vector representation for each word. It converts sequences of words into sequences of vectors. Word embeddings are commonly used in NLP to ensure that words with similar meanings have similar vector representations.</p><p>We then use the tfl.keras.layers.Bidirectional wrapper to create a bidirectional LSTM layer. This layer helps propagate inputs forward and backward through the LSTM layers, enabling the network to learn long-term dependencies more effectively. After that, we form it into a dense neural network for classification.</p><p>Our model uses the &#39;relu&#39; activation function, which returns the input value for positive values and 0 for negative values. The embed_dims variable represents the dimensionality of the embedding vectors and can be adjusted based on your specific needs.</p><p>The final layer in our model is a dense layer with six units, followed by the &#39;softmax&#39; activation function. The &#39;softmax&#39; function normalizes the network&#39;s output, producing a probability distribution over the predicted output classes.</p><p>Here&#39;s the code for the model:</p><pre>`embed_dims = 100  # Placeholder value, adjust it based on your needs<br><br>model = tfl.keras.Sequential([<br>    tfl.keras.layers.Embedding(vocab_size, embed_dims),<br>    tfl.keras.layers.Bidirectional(tfl.keras.layers.LSTM(embed_dims)),<br>    tfl.keras.layers.Dense(embed_dims, activation=&#39;relu&#39;),<br>    tfl.keras.layers.Dense(6, activation=&#39;softmax&#39;)<br>])<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*B4NrIbto5Gce_vmddI7xYw.png" /></figure><p>From the model summary above, we can observe that our model consists of an embedding layer and a bidirectional LSTM layer. The output size from the bidirectional layer is twice the size we specified for the LSTM layer, as it considers both forward and backward information.</p><p>We used the &#39;categorical_crossentropy&#39; loss function for this multi-class classification task. This loss function is commonly used in tasks where we have multiple classes and want to quantify the difference between the predicted probability distribution and the true distribution.</p><p>The optimizer we have chosen is &#39;adam,&#39; a variant of gradient descent. &#39;Adam&#39; is known for its adaptive learning rate and performs well in many scenarios.</p><p>Our model is designed to learn word embeddings through the embedding layer, capture long-term dependencies with the bidirectional LSTM layer, and produce predictions using the softmax activation function in the final dense layer.</p><pre>`model.compile(loss=&#39;sparse_categorical_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])</pre><h4>ML Model Development Organized Using Comet</h4><pre>`epochs_count = 10<br><br>history = model.fit(train_padded, training_label_seq,<br>                    epochs=epochs_count,<br>                    validation_data=(valdn_padded, validation_labels_seq),<br>                    verbose=2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RRCkIiTi-KZnjeswWWmhiA.png" /></figure><p>The accuracy of the experiment was logged:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XhjBLkf330wEvj6YeLo_Eg.png" /></figure><p>We can also see the loss of the experiment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4eFY__BFS0Ed3BKDZx9EZg.png" /></figure><p>We can also monitor RAM and CPU usage as part of model training. The information can be found in the System Metrics section of the experiments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7iVV0yRQgxyAvmJnJit9tA.png" /></figure><h4>Viewing Your Experiment On The Comet Platform</h4><p>To view all your logged experiments, you need to end the experiment using the code below:</p><pre>experiment.end()</pre><p>After running the code, you will get a link to the Comet platform and a summary of everything logged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3ERb-tQdXCyoUdMoGZMKg.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fe_JnMaGFfGQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3De_JnMaGFfGQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fe_JnMaGFfGQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/dafb109aac63e7df104925a1ea0c962f/href">https://medium.com/media/dafb109aac63e7df104925a1ea0c962f/href</a></iframe><h3>Conclusion</h3><p>If the above model shows signs of overfitting after 6 epochs, it is recommended to adjust the number of epochs and retrain the model. By experimenting with different numbers of epochs, you can find the optimal point where the model achieves good performance without overfitting.</p><p>Debugging and analyzing the model&#39;s performance during development iteratively is crucial. Error analysis helps identify areas where the model may be failing and provides insights for improvement. Tracking how the model&#39;s performance scales as training data increases is also essential. This can help determine if collecting more data will lead to better results.</p><p>Model-specific optimization techniques can be applied when addressing underfitting, characterized by high bias and low variance. This includes performing error analysis, increasing model capacity, tuning hyperparameters, and adding new features to capture more patterns in the data.</p><p>On the other hand, when dealing with overfitting, which is characterized by low bias and high variance, it is recommended to consider the following approaches:</p><ol><li>Adding more training data: Increasing the training data can help the model generalize better and reduce overfitting.</li><li>Regularization: Techniques like L1 or L2 regularization, dropout, or early stopping can prevent the model from over-relying on specific features or reducing complex interactions between neurons.</li><li>Error Analysis: Analyzing the model&#39;s errors in training and validation data can provide insights into specific patterns or classes that the model struggles with. This information can guide further improvements.</li><li>Hyperparameter Tuning: Adjusting hyperparameters like learning rate, batch size, or optimizer settings can help find a better balance between underfitting and overfitting.</li><li>Reducing Model Size: If the model is too complex, it may have a higher tendency to overfit. Consider reducing the model&#39;s size by decreasing the number of layers or reducing the number of units in each layer.</li></ol><p>It is also valuable to consult existing literature and seek guidance from domain experts or colleagues who have experience with similar problems. Their insights can provide helpful directions for addressing overfitting effectively.</p><p>Remember that model development is an iterative process that may require multiple iterations of adjustments and experimentation to achieve the best performance for your specific problem.</p><p>Here is a link to <a href="https://colab.research.google.com/drive/1yTDP5NO5RNSDAAVEhZ_fCMgkuT_fYBIz">my notebook on Google Colab</a>, as well as the <a href="https://app.neptune.ai/aravindcr/Tensorflow-Text-Classification/n/code-walk-through-942a1459-ea07-426a-9703-033614bb52cf/4d3cdd39-eea5-441c-872e-23302882a95d">original notebook by Aravind CR</a>.</p><p><em>Editor&#39;s Note: </em><a href="https://heartbeat.comet.ml/"><em>Heartbeat</em></a><em> is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We&#39;re committed to supporting and inspiring developers and engineers from all walks of life.</em></p><p><em>Editorially independent, Heartbeat is sponsored and published by </em><a href="http://comet.com/?utm_source=heartbeat&amp;utm_medium=referral&amp;utm_campaign=AMS_US_EN_AWA_heartbeat_EN"><em>Comet,</em></a><em> an MLOps platform that enables data scientists &amp; ML teams to track, compare, explain, &amp; optimize their experiments. We pay our contributors, and we don&#39;t sell ads.</em></p><p><em>If you&#39;d like to contribute, head on over to our</em><a href="https://heartbeat.comet.ml/call-for-contributors-fee7f5b80f3e"><em> call for contributors</em></a><em>. You can also sign up to receive our weekly newsletter (</em><a href="https://www.deeplearningweekly.com/"><em>Deep Learning Weekly</em></a><em>), check out the </em><a href="https://www.comet.com/site/blog/"><em>Comet blog</em></a><em>, join us on</em><a href="https://join.slack.com/t/fritz-ai-community/shared_invite/enQtNTY5NDM2MTQwMTgwLWU4ZDEwNTAxYWE2YjIxZDllMTcxMWE4MGFhNDk5Y2QwNTcxYzEyNWZmZWEwMzE4NTFkOWY2NTM0OGQwYjM5Y2U"><em> </em></a><a href="https://join.slack.com/t/cometml/shared_invite/zt-49v4zxxz-qHcTeyrMEzqZc5lQb9hgvw"><em>Slack</em></a><em>, and follow Comet on </em><a href="https://twitter.com/Cometml"><em>Twitter</em></a><em> and </em><a href="https://www.linkedin.com/company/comet-ml/"><em>LinkedIn</em></a><em> for resources, events, and much more that will help you build better ML models, faster.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c44476a8e3c3" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/a-step-by-step-guide-efficiently-managing-tensorflow-keras-model-development-with-comet-c44476a8e3c3">A Step-by-Step Guide: Efficiently Managing TensorFlow/Keras Model Development with Comet</a> was originally published in <a href="https://heartbeat.comet.ml/">Heartbeat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started With Comet’s LLMOps]]></title>
            <link>https://heartbeat.comet.ml/getting-started-with-comets-llmops-40ce27bddb42?source=rss-5830e69cd0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/40ce27bddb42</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llmops]]></category>
            <dc:creator><![CDATA[Oluseye Jeremiah]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 20:09:20 GMT</pubDate>
            <atom:updated>2023-10-19T20:09:20.303Z</atom:updated>
            <content:encoded><![CDATA[<h4>An Introduction to Large Language Models (LLMs)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*11nxiG9i9LJPC6ST.jpg" /><figcaption>Image credit: <a href="https://www.shaip.com/">shaip.com</a></figcaption></figure><p>In the rapidly evolving landscape of artificial intelligence and natural language processing, large language models (LLMs) have emerged as powerful tools capable of understanding, generating, and manipulating human language with unprecedented proficiency. These remarkable AI systems have found applications in a wide array of fields, revolutionizing the way we interact with technology and enabling new possibilities in communication, automation, and problem-solving. In this article, we will delve into the world of LLMs, exploring what they are, how they work, their impact on various domains, and finally Comet’s LLMOps</p><h3>What Are Large Language Models (LLMs)?</h3><p>Large language models are a class of artificial intelligence models that excel at processing and generating human language. These models are often neural networks, mainly variants of the Transformer architecture, which have proven highly effective for natural language understanding and generation tasks. LLMs are characterized by their enormous size, with billions of parameters, and their ability to generalize and adapt to a wide range of language-related tasks.</p><h3>How Do LLMs Work?</h3><p>At their core, LLMs employ deep learning techniques to understand and generate text. They are trained on massive datasets comprising diverse text sources, such as books, articles, websites, and more. During training, the models learn to recognize patterns, relationships, and semantics within the text data. This enables them to grasp grammar, syntax, context, and even nuanced aspects of language like sentiment and tone.</p><p>The key to the success of LLMs is their attention mechanism, which allows them to focus on different parts of the input text when making predictions or generating text. This attention mechanism, combined with the massive scale of their parameters, enables LLMs to capture complex dependencies and generate coherent and contextually relevant text.</p><h3>Applications of LLMs</h3><p>The versatility of LLMs has led to their adoption across a wide range of applications.</p><p>1. Natural Language Understanding: LLMs can extract meaning from text, making them invaluable for tasks like sentiment analysis, text classification, and named entity recognition.</p><p>2. Text Generation: LLMs can generate human-like text, which has applications in content creation, chatbots, and even creative writing.</p><p>3. Machine Translation: They excel at language translation tasks, breaking down language barriers and facilitating global communication.</p><p>4. Question Answering: LLMs can provide answers to questions by extracting relevant information from vast amounts of text.</p><p>5. Chatbots and Virtual Assistants: LLMs can be used to power chatbots and virtual assistants, providing human-like interactions and personalized responses to users</p><p>6. Content Recommendation: LLMs are behind personalized content recommendation systems, improving user experiences on websites and streaming platforms.</p><p>7. Content Generation: LLMs can be used to generate different creative text formats of text content, such as poems, code, scripts, musical pieces, emails, letters, etc., which can be used for a variety of purposes, such as marketing, education, and entertainment.</p><h3>Ethical and Social Considerations</h3><p>While LLMs offer tremendous potential, they also raise important ethical and societal questions. Concerns include biases present in training data, the potential for misinformation generation, and the concentration of AI power in the hands of a few organizations. Addressing these issues is crucial to ensuring that LLMs are used responsibly and for the benefit of society.</p><h3>About Comet</h3><p>Comet is a powerful machine learning platform designed to help you effectively manage and monitor your machine learning experiments. Among its notable features, Comet provides users with a suite of tools to track and assess model performance. For a more comprehensive understanding of Comet and its capabilities, you can explore additional information <a href="https://www.comet.com/docs/v2/guides/getting-started/what-is-comet/">available here.</a></p><h3>Getting Started With Comet LLMOps</h3><p>Comet’s LLMOps toolkit opens the door to cutting-edge advancements in prompt management, offering users a gateway to expedited iterations, improved identification of performance bottlenecks, and a visual journey through the inner workings of prompt chains within Comet’s ecosystem.</p><p>Comet’s LLMOps tools shine in their ability to accelerate progress in the following key areas:</p><p>1. Prompt History Mastery: In the realm of ML products driven by large language models, maintaining meticulous records of prompts, responses, and chains is paramount. Comet’s LLMOps tool provides an effortlessly intuitive interface for the comprehensive tracking and analysis of prompt history. Users can gain deep insights into the evolution of their prompts and responses.</p><p>2. Prompt Playground Adventure: Within the LLMOps toolkit lies the innovative Prompt Playground, a dynamic space where Prompt Engineers can embark on expedited explorations. Here, they can swiftly experiment with various prompt templates and observe how these templates impact diverse contexts. This newfound agility in experimentation empowers users to make informed decisions during the iterative process.</p><p>3. Prompt Usage Surveillance: Navigating the world of large language models may involve tapping into paid APIs. Comet’s LLMOps tool offers meticulous usage tracking at both project and experiment levels. This finely detailed tracking system allows users to gain a nuanced understanding of API consumption, facilitating resource allocation and optimization.</p><p>In summary, Comet’s LLMOps toolkit stands as an indispensable resource for researchers, engineers, and developers immersed in the complexities of large language models. It not only streamlines their workflow but also offers enhanced transparency and efficiency, paving the way for the seamless development and fine-tuning of ML-driven applications.</p><h4>Step 1:</h4><p>Login to the Comet website. If you&#39;ve yet to use the platform, you can <a href="https://www.comet.com/signup">sign up here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aHmdnRu_rLr9VaOhuJJHDQ.png" /></figure><h4>Step 2:</h4><p>Click on the icon in the right-hand corner that has the ‘NEW PROJECT’ tag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNYx3iBwDjvPawkzVfvmiQ.png" /></figure><h4>Step 3:</h4><p>Fill in the boxes and SELECT large language models as project type then, click on CREATE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJrpSluaKcyuKTw-uAUmjw.png" /></figure><h4>Step 4:</h4><p>The next step is to install the open-source LLM SDK, which offers a comprehensive set of features for LLMOps. It can be installed using pip in a terminal or command line.</p><pre>pip install comet-llm</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVconrqp_0OZEijwgTm-pA.png" /></figure><p>The next step is to log prompts and responses to the LLM using the LLM SDK. The LLM SDK allows you to log prompts with their corresponding responses and any other relevant metadata, such as token usage. This can be done using the log_prompt() function.</p><p>Note:To avoid including your API key and workspace for every single prompt, using the comet_llm.init() function will save you stress</p><pre>import comet_llm<br><br>comet_llm.init(project=&quot;Alexa-cometllm-prompts&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6dZhaXDcnTbXxnSWnPK6g.png" /></figure><p>After which we then proceed to log our first prompt.</p><pre><br><br><br>comet_llm.log_prompt(<br>    prompt=&quot;Hey,What&#39;s your name?&quot;,<br>    output=&quot; My name is Alexa, and i&#39;m your new best friend<br>    project=&quot;Alexa-chatbot&quot;,<br>    <br>)</pre><p>The prompt and response get logged into our Comet dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FoBBTyKOFJktMnIeRt2Eiw.png" /></figure><p>Now let&#39;s create more complex prompts:</p><pre>comet_llm.log_prompt(<br>    prompt=&quot;Answer the question and if the question can&#39;t be answered, say \&quot;I don&#39;t know\&quot;\n\n---\n\nQuestion: What is your name?\nAnswer:&quot;,<br>    prompt_template=&quot;Answer the question and if the question can&#39;t be answered, say \&quot;I don&#39;t know\&quot;\n\n---\n\nQuestion: {{question}}?\nAnswer:&quot;,<br>    prompt_template_variables={&quot;question&quot;: &quot;What is your name?&quot;},<br>    project=&quot;Alexa Chatbot&quot;,<br>   <br><br>     metadata= {<br>        &quot;usage.prompt_tokens&quot;: 7,<br>        &quot;usage.completion_tokens&quot;: 5,<br>        &quot;usage.total_tokens&quot;: 12,<br>    },<br>    output=&quot; My name is Alexa.&quot;,<br>    duration=16.598,<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pn5vOv9i9JuClps2JNl3fA.png" /></figure><p>Once the code is loaded, it becomes accessible within the Comet workspace, where it is meticulously recorded. This workspace serves as an archive for all prompts and responses. Within this workspace, a table sidebar offers a comprehensive view of the logged data, including details such as prompts, responses, metadata, duration, and more. Simply click on a specific row to access this valuable information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yfQWw-iZCo5zZ_X0ynOUOw.gif" /></figure><h4>Conclusion</h4><p>In conclusion, embarking on the journey to explore Comet’s LLMOps is a promising step for anyone venturing into the world of large language models (LLMs). This suite of tools provides an invaluable toolkit for researchers, engineers, and data scientists, enabling them to harness the full potential of LLMs while ensuring efficient experimentation, prompt tracking, and model performance monitoring.</p><p>As we’ve discovered throughout this guide, LLMOps offers a range of features, from tracking prompt histories and facilitating rapid iterations with the Prompt Playground to monitoring usage and resource allocation. These tools not only streamline the development process but also enhance transparency and accountability, addressing the ethical and operational challenges that accompany LLM research and deployment.</p><p>By taking advantage of Comet’s LLMOps, users can unlock the true power of large language models, pushing the boundaries of what is possible in natural language understanding, generation, and beyond. Whether you are a seasoned AI practitioner or just beginning to explore this fascinating field, Comet’s LLMOps offers a welcoming gateway into a realm where language and technology converge, promising exciting innovations and discoveries on the horizon.</p><p><em>Editor’s Note: </em><a href="https://heartbeat.comet.ml/"><em>Heartbeat</em></a><em> is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.</em></p><p><em>Editorially independent, Heartbeat is sponsored and published by </em><a href="http://comet.com/?utm_source=heartbeat&amp;utm_medium=referral&amp;utm_campaign=AMS_US_EN_AWA_heartbeat_EN"><em>Comet,</em></a><em> an MLOps platform that enables data scientists &amp; ML teams to track, compare, explain, &amp; optimize their experiments. We pay our contributors, and we don’t sell ads.</em></p><p><em>If you’d like to contribute, head on over to our</em><a href="https://heartbeat.comet.ml/call-for-contributors-fee7f5b80f3e"><em> call for contributors</em></a><em>. You can also sign up to receive our weekly newsletter (</em><a href="https://www.deeplearningweekly.com/"><em>Deep Learning Weekly</em></a><em>), check out the </em><a href="https://www.comet.com/site/blog/"><em>Comet blog</em></a><em>, join us on</em><a href="https://join.slack.com/t/fritz-ai-community/shared_invite/enQtNTY5NDM2MTQwMTgwLWU4ZDEwNTAxYWE2YjIxZDllMTcxMWE4MGFhNDk5Y2QwNTcxYzEyNWZmZWEwMzE4NTFkOWY2NTM0OGQwYjM5Y2U"><em> </em></a><a href="https://join.slack.com/t/cometml/shared_invite/zt-49v4zxxz-qHcTeyrMEzqZc5lQb9hgvw"><em>Slack</em></a><em>, and follow Comet on </em><a href="https://twitter.com/Cometml"><em>Twitter</em></a><em> and </em><a href="https://www.linkedin.com/company/comet-ml/"><em>LinkedIn</em></a><em> for resources, events, and much more that will help you build better ML models, faster.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40ce27bddb42" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/getting-started-with-comets-llmops-40ce27bddb42">Getting Started With Comet’s LLMOps</a> was originally published in <a href="https://heartbeat.comet.ml/">Heartbeat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Segmentation Techniques in Computer Vision]]></title>
            <link>https://heartbeat.comet.ml/image-segmentation-techniques-in-computer-vision-68eb3c2c20d3?source=rss-5830e69cd0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/68eb3c2c20d3</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Oluseye Jeremiah]]></dc:creator>
            <pubDate>Mon, 14 Aug 2023 11:49:50 GMT</pubDate>
            <atom:updated>2023-08-14T11:49:50.150Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*U7gtUrpCzij0zTviAPmQgA.jpeg" /></figure><p>Have you ever played Tetris? Remember how you had to fit different shapes together to form complete lines and score points?</p><p>Well, image segmentation in computer vision is a bit like playing a high-tech version of Tetris! Instead of fitting shapes together, we’re trying to segment an image into different regions or shapes based on color, texture, edges, and other visual features. It’s a challenging but exciting task, with many applications in fields such as autonomous driving, medical imaging, and augmented reality.</p><p>So get ready to flex your Tetris skills and dive into the fascinating world of image segmentation in computer vision!</p><p>Before we dive into the techniques, let’s talk briefly about image segmentation.</p><h4>Image Segmentation</h4><p>Image segmentation is a fundamental task in computer vision that involves dividing an image into distinct regions or segments based on certain criteria, such as color, texture, or edges.</p><p>Image segmentation is essential in many computer vision applications, including object recognition, scene understanding, and image manipulation. Expertise in image segmentation requires knowledge of various techniques, ranging from traditional methods, such as thresholding and edge-based segmentation, to more advanced techniques, like deep learning-based segmentation.</p><p>Understanding the strengths and limitations of different segmentation techniques is critical to selecting the most appropriate approach for a specific application.</p><p>With the rapid advancement of computer vision technology and the growing demand for high-quality image analysis, expertise in image segmentation has become increasingly important for researchers, engineers, and practitioners in the field.</p><h4>Image Segmentation Techniques</h4><ol><li><strong>Thresholding:</strong> Thresholding is one of the simplest and most popular image segmentation techniques. It involves setting a threshold value and dividing the image into two segments: one containing pixels with values above the threshold and the other containing pixels with values below the threshold. Thresholding is often used for binary image segmentation, where the goal is to separate foreground objects from the background.</li><li><strong>Edge-based Segmentation: </strong>Edge-based segmentation is another popular technique that involves detecting edges in the image and using them to separate different regions. Edges are the boundaries between different regions in the image, and they can be detected using various edge detection algorithms, such as the Canny edge detector. Once the edges are detected, they can be used to segment the image by grouping the pixels on either side of the edges into separate regions.</li><li><strong>Region-based Segmentation:</strong> Region-based segmentation is a technique that involves grouping pixels in the image based on their similarity in color, texture, or other visual features. Region-based segmentation can be performed using clustering algorithms, such as k-means clustering or mean-shift clustering, which group similar pixels into clusters. The resulting clusters can then be used to segment the image into different regions.</li><li><strong>Watershed Segmentation:</strong> Watershed segmentation is a particularly useful technique for segmenting images with multiple objects or regions that touch or overlap. Watershed segmentation treats the image as a topographic map, where the pixel values represent the height of the terrain. The algorithm starts by flooding the image from the highest points and gradually filling the basins between the objects. The resulting basins correspond to the different objects in the image and can be used to segment the image.</li><li><strong>Deep Learning-based Segmentation: </strong>Deep learning-based segmentation is a more recent technique that has gained popularity in recent years, particularly with the advent of convolutional neural networks (CNNs). CNNs can learn to segment images by training on large datasets of labeled images. The network is trained to predict a segmentation mask for each input image, where each pixel is assigned a label corresponding to its region. Deep learning-based segmentation can achieve state-of-the-art performance on many image segmentation tasks.</li></ol><h4>Conclusion</h4><p>In conclusion, image segmentation is an important problem in computer vision that has many applications in various fields. Several different image segmentation techniques are available, each with its strengths and weaknesses. The best technique depends on the application and the characteristics of the images being segmented. By understanding the different image segmentation techniques, computer vision practitioners can choose the best approach for their specific task and achieve better results.</p><p><em>Editor’s Note: </em><a href="https://heartbeat.comet.ml/"><em>Heartbeat</em></a><em> is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.</em></p><p><em>Editorially independent, Heartbeat is sponsored and published by </em><a href="http://comet.com/?utm_source=heartbeat&amp;utm_medium=referral&amp;utm_campaign=AMS_US_EN_AWA_heartbeat_EN"><em>Comet,</em></a><em> an MLOps platform that enables data scientists &amp; ML teams to track, compare, explain, &amp; optimize their experiments. We pay our contributors, and we don’t sell ads.</em></p><p><em>If you’d like to contribute, head on over to our</em><a href="https://heartbeat.comet.ml/call-for-contributors-fee7f5b80f3e"><em> call for contributors</em></a><em>. You can also sign up to receive our weekly newsletter (</em><a href="https://www.deeplearningweekly.com/"><em>Deep Learning Weekly</em></a><em>), check out the </em><a href="https://www.comet.com/site/blog/"><em>Comet blog</em></a><em>, join us on</em><a href="https://join.slack.com/t/fritz-ai-community/shared_invite/enQtNTY5NDM2MTQwMTgwLWU4ZDEwNTAxYWE2YjIxZDllMTcxMWE4MGFhNDk5Y2QwNTcxYzEyNWZmZWEwMzE4NTFkOWY2NTM0OGQwYjM5Y2U"><em> </em></a><a href="https://join.slack.com/t/cometml/shared_invite/zt-49v4zxxz-qHcTeyrMEzqZc5lQb9hgvw"><em>Slack</em></a><em>, and follow Comet on </em><a href="https://twitter.com/Cometml"><em>Twitter</em></a><em> and </em><a href="https://www.linkedin.com/company/comet-ml/"><em>LinkedIn</em></a><em> for resources, events, and much more that will help you build better ML models, faster.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68eb3c2c20d3" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/image-segmentation-techniques-in-computer-vision-68eb3c2c20d3">Image Segmentation Techniques in Computer Vision</a> was originally published in <a href="https://heartbeat.comet.ml/">Heartbeat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring Your CV Model: A Beginner’s Guide Using Kangas and Comet]]></title>
            <link>https://heartbeat.comet.ml/monitoring-your-cv-model-a-beginners-guide-using-kangas-and-comet-4d70af55c1ef?source=rss-5830e69cd0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d70af55c1ef</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[kanga]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[cometml]]></category>
            <category><![CDATA[heartbeat]]></category>
            <dc:creator><![CDATA[Oluseye Jeremiah]]></dc:creator>
            <pubDate>Mon, 08 May 2023 12:10:50 GMT</pubDate>
            <atom:updated>2023-05-08T12:10:50.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LvCz2FaojU7W9-fPfXfUkA.png" /></figure><p>Computer Vision (CV) is a rapidly growing field that is transforming the way we interact with technology. As more and more companies adopt computer vision models for various applications, it has become increasingly important to monitor the performance of these models over time to ensure they continue to deliver accurate results.</p><p>In this article, we’ll introduce you to the basics of monitoring your CV models using Kangas and Comet, two powerful tools that make it easy to track and analyze the performance of your models. Whether you’re new to computer vision or have some experience under your belt, this beginner’s guide will help you gain a better understanding of the importance of monitoring your models and how to get started with these powerful monitoring tools.</p><p>We’ll cover everything from setting up your environment to tracking key metrics and analyzing the results. By the end of this article, you’ll have a solid understanding of how to monitor your CV models using Kangas and Comet, and be well on your way to delivering more accurate and reliable results.</p><h4><strong>About Comet</strong></h4><p>Comet is a powerful tool for monitoring and analyzing machine learning experiments. It allows users to track their experiments in real time, visualize the results, and share their findings with others. With Comet, users can quickly identify issues with their models, optimize performance, and collaborate with team members. It’s particularly useful for CV models, where accuracy and performance are critical to success.</p><h4><strong>About Kangas</strong></h4><p>Kangas is a robust platform for monitoring and analyzing structured and unstructured data. By using Kangas and Comet together, users can get a complete picture of their models’ performance, identify issues quickly, and collaborate with team members to optimize results.</p><h3>How to Use Kangas and Comet Together</h3><p>Using Kangas and Comet together provides users with a complete picture of their models’ performance. By tracking key metrics and visualizing the results, users can quickly identify issues that may impact accuracy and optimize performance over time.</p><p>To get started, you’ll need to set up your environment. Then, you can start tracking metrics and visualizing the results using the intuitive user interfaces of both tools. This makes it easy to identify trends and patterns that may impact performance, and collaborate with team members to optimize results.</p><blockquote>The most important thing to keep in mind when building and deploying your model? Understanding your end-goal. <a href="https://www.comet.com/site/blog/industry-qa-where-most-machine-learning-projects-fail/?utm_source=heartbeat&amp;utm_medium=referral&amp;utm_campaign=AMS_US_EN_AWA_heartbeat_CTA">Read our interview with ML experts from Stanford, Google, and HuggingFace to learn more</a>.</blockquote><h4><strong>About The Dataset</strong></h4><p>Today, we’re using the bean dataset, which is a collection of pictures of beans that were captured outdoors with smartphones. It has three classes: two for diseases and one for healthy bean plants. In this blog, we’ll attempt to differentiate between healthy and unhealthy bean leaves. You can get the data <a href="http://huggingface.co/datasets/nateraw/beans">here</a>.</p><h4><strong>Getting Started</strong></h4><p>The first step is to install all the needed libraries.</p><pre>!pip3 install comet_ml --q<br>from comet_ml import Experiment<br><br>comet_ml.init(api_key= &quot;YOUR-COMET-API-KEY&quot;,<br>              project_name= &quot;my-project&quot;)<br>experiment = comet_ml.Experiment()<br><br>!pip install kangas torch datasets transformers scikit-learn --q<br>import kangas as kg<br>import tensorflow as tf<br>import matplotlib.pyplot as plt <br>import numpy as np<br>from tqdm import tqdm<br>from tensorflow import keras<br>from tensorflow.keras import datasets, layers, models<br>from datasets import load_dataset</pre><p>Next we load the dataset:</p><pre>dataset = load_dataset(&quot;beans&quot;, split=&quot;train&quot;)</pre><p>We then instantiate a Kangas DataGrid using our dataset:</p><pre>dg = kg.DataGrid(dataset)</pre><p>To show what’s in our DataGrid, we use the .show() method:</p><pre>dg.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rpbzT85t3jiyqIYbILoVww.jpeg" /></figure><p>Once the dataset is loaded, we begin to investigate its filtering and group-by capabilities. In particular, we examine the bean leaf images to identify any discernible differences. We observe that the leaves labeled 0 and 1 exhibit signs of disease, while the leaves labeled 2 appear to be healthy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Yv3U95DjKtPH6am5JjUZA.jpeg" /></figure><p>The photographs are then organized into each label using the “group-by” feature of the Kangas UI.</p><p>We then go to building the ML model so we can track using Comet.</p><pre>df = pd.DataFrame(dataset)<br>selected_columns = df.columns[:100] # Select the first 100 columns<br>df = df[selected_columns] # Subset the dataframe to include only the selected columns<br>y_train = y_train.reshape(-1)<br>y_train[:5]</pre><p>In the above code block, y_train = y_train.reshape(-1) reshapes the array y_train to a one-dimensional array.</p><p>The second line of code y_train[:5] selects the first five elements of the newly reshaped y_train array and returns them.</p><p>We then divide the beans dataset into classes.</p><pre>classes = [ &#39;angular leaf spot&#39;, &#39;bean rust&#39;, &#39;healthy&#39;]</pre><p>The code below defines a function called plot_sample that takes three arguments: a numpy array containing image data samples X, a numpy array containing labels for each sample in y, and an integer index index indicating which sample to plot. The function converts the index to an integer, rounds it, and creates a new figure with dimensions 15x2. It then displays the image corresponding to the selected sample and sets the x-axis label to the class label of the selected sample. The class labels are obtained from a dictionary called classes.</p><pre>def plot_sample(X, y, index):<br>    index = np.round(index).astype(int)<br>    plt.figure(figsize = (15,2))<br>    plt.imshow(X[index])<br>    plt.xlabel(classes[y[index]])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*iwEIEp5vlAqfhImEIQXMpA.png" /><figcaption>Fig 1</figcaption></figure><p>After viewing the various categories of leaves we then start building our ML model.</p><pre>from tensorflow import keras<br>from tensorflow.keras import layers<br><br>model = keras.Sequential([<br>    layers.Conv2D(filters=32, kernel_size=(3, 3), activation=&#39;relu&#39;, input_shape=(500, 500, 3)),<br>    layers.MaxPooling2D((2, 2)),<br>    <br>    layers.Conv2D(filters=64, kernel_size=(3, 3), activation=&#39;relu&#39;),<br>    layers.MaxPooling2D((2, 2)),<br>    <br>    layers.Conv2D(filters=128, kernel_size=(3, 3), activation=&#39;relu&#39;),<br>    layers.MaxPooling2D((2, 2)),<br>    <br>    layers.Flatten(),<br>    layers.Dense(256, activation=&#39;relu&#39;),<br>    layers.Dense(3, activation=&#39;softmax&#39;)<br>])from tensorflow import keras<br>from tensorflow.keras import layers<br><br>model = keras.Sequential([<br>    layers.Conv2D(filters=32, kernel_size=(3, 3), activation=&#39;relu&#39;, input_shape=(500, 500, 3)),<br>    layers.MaxPooling2D((2, 2)),<br>    <br>    layers.Conv2D(filters=64, kernel_size=(3, 3), activation=&#39;relu&#39;),<br>    layers.MaxPooling2D((2, 2)),<br>    <br>    layers.Conv2D(filters=128, kernel_size=(3, 3), activation=&#39;relu&#39;),<br>    layers.MaxPooling2D((2, 2)),<br>    <br>    layers.Flatten(),<br>    layers.Dense(256, activation=&#39;relu&#39;),<br>    layers.Dense(3, activation=&#39;softmax&#39;)<br>])</pre><p>To extract important features from input images, the model starts with a convolutional layer that uses 32 filters of size 3x3. ReLU activation function is used to deal with non-linearity. The input shape is set to (500, 500, 3), which indicates that the input image is 500x500 pixels with 3 color channels.</p><p>To reduce the input image size, a max pooling layer with a pool size of 2x2 is added to the model.</p><p>This process is then repeated two more times, with 64 and 128 filters in each convolutional layer. A max pooling layer with a pool size of 2x2 is added after each convolutional layer.</p><p>The output from the convolutional layers is then converted into a 1D feature vector using a flatten layer. Then, two fully connected layers (Dense) are added to the model, with the first layer having 256 nodes and the second layer having 3 nodes. ReLU activation function is used for the first dense layer, and softmax activation function is used for the last layer.</p><p>In multi-class classification problems, the softmax function helps normalize the output and gives a probability distribution across all classes.</p><p>The next step involves compiling the model. This is where the network architecture is configured, and the learning process is initialized with parameters such as the loss function, optimizer, and performance metrics.</p><pre>model.compile(loss=&#39;categorical_crossentropy&#39;,<br>              optimizer=&#39;adam&#39;,<br>              metrics=[&#39;accuracy&#39;])</pre><p>The above code is a crucial step in configuring a neural network model for training and evaluation. It specifies the loss function, optimizer, and performance metrics that will be used during the learning process, and helps to ensure that the model is optimized for the specific problem at hand.</p><pre>from datasets import load_dataset<br>from tensorflow.keras.utils import to_categorical<br><br># Load the &quot;beans&quot; dataset<br>dataset = load_dataset(&quot;beans&quot;, split=&quot;train[:80%]&quot;)<br>val_dataset = load_dataset(&quot;beans&quot;, split=&quot;train[80%:]&quot;)<br><br># Convert the input images to NumPy arrays<br>X_train = np.array([np.array(image) for image in dataset[&#39;image&#39;]])<br>X_val = np.array([np.array(image) for image in val_dataset[&#39;image&#39;]])<br><br># Convert the target labels to NumPy arrays and one-hot encode them<br>y_train = to_categorical(np.array(dataset[&#39;labels&#39;]))<br>y_val = to_categorical(np.array(val_dataset[&#39;labels&#39;]))<br><br># Compile the model<br>model.compile(loss=&#39;categorical_crossentropy&#39;,<br>              optimizer=&#39;adam&#39;,<br>              metrics=[&#39;accuracy&#39;])<br><br># Train the model<br>history = model.fit(X_train, y_train, batch_size=32, epochs=10, validation_data=(X_val, y_val))</pre><p>The above code loads the dataset, splits it into training and validation data, converts the input images and target labels to NumPy arrays, compiles the model with the chosen optimizer, loss function, and metrics, and finally trains the model using the training data and validates it on the validation data. The training process is saved to the ‘history’ variable. This code demonstrates how to train a machine learning model on the “beans” dataset using the Keras library. It loads the dataset, splits it into training and validation data, converts the input images and target labels to NumPy arrays, compiles the model with the chosen optimizer, loss function, and metrics, and finally trains the model using the training data and validates it on the validation data. The training process is saved to the ‘history’ variable.</p><p>The next step involves evaluating the performance of a machine learning model on a validation dataset and logging the evaluation metrics</p><pre>loss, accuracy = model.evaluate(X_val,y_val)<br>print(&quot;Loss: &quot;, loss)<br>print(&quot;Accuracy: &quot;, accuracy)<br><br>experiment.log_metric(&quot;Loss&quot;, loss, step=None, include_context=True)<br>experiment.log_metric(&quot;Accuracy&quot;, accuracy, step=None, include_context=True)</pre><p>The above code logs the evaluation metrics using a library called Comet for experiment tracking. The model.evaluate() function calculates the loss and accuracy of the model on the validation dataset. The calculated loss and accuracy values are then logged using the experiment.log_metric() function of the Comet library. This function logs the metric name, value, and context of the current experiment if required. Overall, the code evaluates the model&#39;s performance, prints the results, and logs them using a library for experiment tracking.</p><p>We then save our model and log it to Comet.</p><pre>model.save(&#39;model&#39;)<br>experiment.log_model(model, &#39;model&#39;)</pre><p>Finally, we view our logged model in comet.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPtMjE69vYdc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPtMjE69vYdc&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/87ced3c80bc71225b59dde307f7aac72/href">https://medium.com/media/87ced3c80bc71225b59dde307f7aac72/href</a></iframe><h3>Conclusion</h3><p>In conclusion, monitoring the performance of machine learning models is crucial for ensuring accuracy and reliability. Kangas and Comet are two popular tools that can be used to monitor and visualize the performance of your models. These tools allow developers and data scientists to track various performance metrics, analyze model predictions, and identify potential issues or errors. With Kangas and Comet, even beginners can easily monitor their models and make informed decisions to improve their performance. By adopting these tools, developers can ensure that their models perform optimally and provide accurate and reliable results for various tasks.</p><p><em>Editor’s Note: </em><a href="https://heartbeat.comet.ml/"><em>Heartbeat</em></a><em> is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.</em></p><p><em>Editorially independent, Heartbeat is sponsored and published by </em><a href="http://comet.com/?utm_source=heartbeat&amp;utm_medium=referral&amp;utm_campaign=AMS_US_EN_AWA_heartbeat_EN"><em>Comet,</em></a><em> an MLOps platform that enables data scientists &amp; ML teams to track, compare, explain, &amp; optimize their experiments. We pay our contributors, and we don’t sell ads.</em></p><p><em>If you’d like to contribute, head on over to our </em><a href="https://heartbeat.comet.ml/call-for-contributors-fee7f5b80f3e"><em>call for contributors</em></a><em>. You can also sign up to receive our weekly newsletter (</em><a href="https://www.deeplearningweekly.com/"><em>Deep Learning Weekly</em></a><em>), check out the </em><a href="https://www.comet.com/site/blog/"><em>Comet blog</em></a><em>, join us on </em><a href="https://join.slack.com/t/cometml/shared_invite/zt-49v4zxxz-qHcTeyrMEzqZc5lQb9hgvw"><em>Slack</em></a><em>, and follow Comet on </em><a href="https://twitter.com/Cometml"><em>Twitter</em></a><em> and </em><a href="https://www.linkedin.com/company/comet-ml/"><em>LinkedIn</em></a><em> for resources, events, and much more that will help you build better ML models, faster.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d70af55c1ef" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/monitoring-your-cv-model-a-beginners-guide-using-kangas-and-comet-4d70af55c1ef">Monitoring Your CV Model: A Beginner’s Guide Using Kangas and Comet</a> was originally published in <a href="https://heartbeat.comet.ml/">Heartbeat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring A Convolutional Neural Network (CNN) in Comet]]></title>
            <link>https://heartbeat.comet.ml/monitoring-a-convolutional-neural-network-cnn-in-comet-702c2d51c839?source=rss-5830e69cd0a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/702c2d51c839</guid>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[cnn-model]]></category>
            <category><![CDATA[heartbeat]]></category>
            <category><![CDATA[ann]]></category>
            <category><![CDATA[cometml]]></category>
            <dc:creator><![CDATA[Oluseye Jeremiah]]></dc:creator>
            <pubDate>Wed, 01 Mar 2023 14:22:36 GMT</pubDate>
            <atom:updated>2023-03-01T14:22:36.080Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tracking your image classification experiments with Comet ML</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*4ik_OeQvo2rjBCltjsjojQ.jpeg" /><figcaption>Photo from nmedia on Shutterstock.com</figcaption></figure><h4>Introduction</h4><p>Image classification is a task that involves training a neural network to recognize and classify items in images. A dataset of labeled images is used to train the network, with each image given a particular class or label. Thousands or even millions of photos make up the normal size of the dataset needed to train the model. Before being fed into the network, the photos are pre-processed and shrunk to the same size.</p><p>A convolutional neural network (CNN) is primarily used for image classification. Convolutional, pooling, and fully linked layers are some of the layers that make up a CNN. The pooling layers are used to shrink the spatial dimensions of the image while preserving the key features, whereas the convolutional layers are in charge of identifying patterns and features in the image. The image is subsequently classified using the convolutional and pooling layers’ retrieved features by the fully connected layers.</p><p>Once trained, the model can be used to categorize new, unseen photos. The network processes the image, and the result is a probability distribution across all potential classifications. The anticipated label for the image is the class with the highest likelihood.</p><p>Numerous applications, including object identification, image search, and image annotation, can benefit from image categorization. For instance, picture classification can be used in self-driving automobiles to recognize and classify items like vehicles, people, and traffic signs so that the vehicle can travel safely. Image classification can be used in search engines to index and retrieve photos based on their content. Additionally, picture categorization can be used in photo management software to automatically identify photographs with pertinent labels, making it simpler to find and organize them.</p><h3>Comet</h3><p>Comet is a machine-learning experimentation tool that assists you in keeping track of your machine-learning experiments. Another important feature of Comet is that it allows users to track or monitor the performance of a model by utilizing the various tools accessible on the Comet platform. You can learn more about Comet <a href="https://www.comet.com/signup?utm_source=Heartbeat&amp;utm_medium=referral&amp;utm_campaign=AMS_US_EN_SNUP_Heartbeat_Comet_Content">here</a>.</p><p>In this tutorial, we will learn how to keep track of our image classification model in Comet. After building our model, we will log it onto the Comet experimentation website or platform to follow and track the progress of our experiment. So let’s get started with it.</p><h3>Prerequisites</h3><p>In order to focus on the model monitoring function in Comet, we will be using a code tutorial from <a href="https://codebasics.io/">CodeBasics</a> to build, train, and test our models. You can find the original code in <a href="https://github.com/codebasics/deep-learning-keras-tf-tutorial/blob/master/16_cnn_cifar10_small_image_classification/cnn_cifar10_dataset.ipynb">this repo here</a>, or follow along with <a href="https://colab.research.google.com/github/olujerry/olujerry/blob/main/Image_Classification_Model.ipynb#scrollTo=R9gvj3dP74U6">my modified version here</a>.</p><p>Using one of the following lines at the command prompt, you can install the Comet library on your machine if it isn’t already present. Be aware that pip is probably what you should use if you’re installing packages directly into a Colab notebook or another environment that makes use of virtual machines.</p><pre>pip install comet_ml</pre><p>— or —</p><pre>conda install -c comet_ml</pre><h4>About The Dataset.</h4><p>The CIFAR-10 dataset consists of 6,000 images per class in 10 classes totaling 60,000 32x32 color images. 10,000 test photos and 50,000 training images are available.</p><p>Five training batches and one test batch, each with 10,000 photos, are created from the dataset. Exactly 1,000 randomly chosen photos from each class make up the test batch. The remaining images are distributed across the training batches in random order, but certain training batches can have a disproportionate number of images from a particular class. The training batches are made up of 5,000 photographs from each class together. You can get the <a href="https://www.cs.toronto.edu/~kriz/cifar.html.">dataset here</a>.</p><blockquote>Want to see the evolution of AI-generated art projects? <a href="https://www.comet.ml/team-comet-ml/clipdraw/view/Y4aT3gy6IrPQKBi5wncFXCYLR?utm_campaign=clipdraw-gradio&amp;utm_source=blog&amp;utm_medium=summary">Visit our public project to see time-lapses, experiment evolutions, and more</a>!</blockquote><h4><strong>Understanding the goal</strong></h4><ol><li>Build a neural network to recognize different types of images assigned to it.</li><li>Use both the CNN and ANN and see the network with the most accuracy.</li><li>Detect layers and patterns in the dataset.</li><li>Monitor ML model performance after training in the Comet dashboard, including its accuracy and loss.</li><li>Monitor hardware performance.</li></ol><h4>Exploring the model:</h4><p>Let’s import and Install the needed libraries</p><pre>import tensorflow as tf<br>from tensorflow.keras import datasets,layers,models<br>import matplotlib as plt<br>import pandas as pd<br>import numpy as np</pre><p>The dataset is subsequently loaded, and the test and training datasets are loaded simultaneously.</p><pre>(X_train,y_train),(X_test,y_test)= datasets.cifar10.load_data()</pre><p>Next, we examine the training dataset’s form. The dataset’s form also reveals that we have 50,000 training samples, a 32 by 32 image, and that the third digit stands for the RGB channel.</p><pre>X_train.shape</pre><p>We check the test samples after examining the train sample shapes.</p><pre>X_test.shape </pre><p>We also define our classes:</p><pre>classes = [&quot;airplane&quot;,&quot;automobile&quot;,&quot;bird&quot;,&quot;cat&quot;,&quot;deer&quot;,&quot;dog&quot;,&quot;frog&quot;,&quot;horse&quot;,&quot;ship&quot;,&quot;truck&quot;]</pre><p>Then, we create the following function:</p><pre>def plot_sample(X, y, index):<br>    plt.figure(figsize = (15,2))<br>    plt.imshow(X[index])<br>    plt.xlabel(classes[y[index]])</pre><p>We can test the function as follows:</p><pre>plot_sample(X_train, y_train, 0)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*-OyurbmgGdwft9SlgFm07Q.jpeg" /></figure><p>We can try another sample image:</p><pre>plot_sample(X_train, y_train, 0)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*gO-GarRFIp-oSNAThWUkvg.jpeg" /></figure><p>Normalize the pictures to a value between 0 and 1. The image has three channels (R, G, and B), each of which can have a value between 0 and 255. So we must divide it by 255 to normalize it in the 0–1 range.</p><pre>X_train = X_train / 255.0<br>X_test = X_test / 255.0</pre><h4>Model Building</h4><p>We then construct an artificial neural network first, followed by a convolutional neural network, and we can test the effectiveness of both models as well as compare their benefits and drawbacks.</p><pre>ann = models.Sequential([<br>        layers.Flatten(input_shape=(32,32,3)),<br>        layers.Dense(3000, activation=&#39;relu&#39;),<br>        layers.Dense(1000, activation=&#39;relu&#39;),<br>        layers.Dense(10, activation=&#39;softmax&#39;)    <br>    ])<br><br>ann.compile(optimizer=&#39;SGD&#39;,<br>              loss=&#39;sparse_categorical_crossentropy&#39;,<br>              metrics=[&#39;accuracy&#39;])<br><br>ann.fit(X_train, y_train, epochs=5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*50HqD322TejiaRp27cc37Q.jpeg" /></figure><p>We can therefore see from the code above that there are four layers. The first layer accepts images with a 32 by 32 pixel dimension, while the second and third levels are deep layers with 3000 and 1000 neurons, respectively. The fourth layer then includes 10 categories to reflect the 10 sample images that are included in our dataset. After executing the code, we can see that the ANN’s accuracy on training samples is quite low—about 10%.</p><p>We then try it on test samples to see if the results get better.</p><pre>ann.evaluate(X_test,y_test)</pre><p>We can see from the review above that ANN continues to perform poorly. The last step is to print a classification report that displays the recall and precision for each sample image.</p><pre>from sklearn.metrics import confusion_matrix , classification_report<br>import numpy as np<br>y_pred = ann.predict(X_test)<br>y_pred_classes = [np.argmax(element) for element in y_pred]<br><br>print(&quot;Classification Report: \n&quot;, classification_report(y_test, y_pred_classes))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*QvHgweNvSRx49uG4SeToyA.jpeg" /></figure><p>The precision and recall scores for each of the sample photos can then be examined (0–9). A sample image with index 1 has, for instance, the highest precision scores when compared to the others, as can be seen by looking at it.</p><p>The next step is to utilize build and train a CNN:</p><pre>model = models.Sequential([<br>    layers.Conv2D(filters=32, kernel_size=(3, 3), activation=&#39;relu&#39;, input_shape=(32, 32, 3)),<br>    layers.MaxPooling2D((2, 2)),<br>    <br>    layers.Conv2D(filters=64, kernel_size=(3, 3), activation=&#39;relu&#39;),<br>    layers.MaxPooling2D((2, 2)),<br>    <br>    layers.Flatten(),<br>    layers.Dense(64, activation=&#39;relu&#39;),<br>    layers.Dense(10, activation=&#39;softmax&#39;)<br>])<br><br>model.compile(optimizer=&#39;adam&#39;,<br>              loss=&#39;sparse_categorical_crossentropy&#39;,<br>              metrics=[&#39;accuracy&#39;])</pre><p>We then run our loss and metrics tests using the Adam optimizer, which is known for its versatility.</p><pre>model.fit(X_train, y_train, epochs=10, verbose=1,batch_size=128)</pre><p>We train the model for 10 epochs and get 70% accuracy, which is significantly higher than ANN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*pz69yhZCwNdeXsqqzig8Rw.jpeg" /></figure><p>To further our model building, we also try to evaluate the test dataset to see if we can get a high accuracy score.</p><pre>model.evaluate(X_test,y_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*F7MBss541w32pIfy3_oPyw.jpeg" /></figure><p>The accuracy we have is 65%, which is above average, as we can then see.<br>So now that our CNN model is prepared, all that is left to do is plot a sample image and wait for the model to identify it.</p><pre>plot_sample(X_test, y_test,6)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*BhvkAZ2k4x8fFyt61aPGCA.jpeg" /></figure><p>We can see that this is obviously an automobile; let’s see if our model can identify it as such.</p><pre>classes[y_classes[6]]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*yYG_fNR2NQt5PSm6UZJr2w.jpeg" /></figure><h4>Monitoring In Comet</h4><p>In this section, I’ll be revealing the step-by-step process of logging our experiments in Comet.</p><p>The first step involves Installing comet which we have done at the beginning</p><pre>!pip3 install comet_ml</pre><p>The next step is to import experiments from Comet to enable us to log on to the Comet platform.</p><pre>from comet_ml import experiment</pre><p>We then move forward by creating an experiment and also setting the auto-logging features and other important features to true.</p><pre># Create an experiment<br>experiment = comet_ml.Experiment(<br>    project_name=&quot;image classification&quot;,<br>    workspace=&quot;&lt;olujerry&gt;&quot;,<br>     api_key=&quot;API_KEY&quot;,<br>    auto_metric_logging=True,<br>    auto_param_logging=True,<br>    auto_histogram_weight_logging=True,<br>    auto_histogram_gradient_logging=True,<br>    auto_histogram_activation_logging=True,<br>    log_code=True<br>)</pre><p>The next step involves logging important features that we want to monitor on the Comet platform.</p><p>Using the experiment, we record some parameters using log_parameters(params):</p><pre>batch_size = 128<br>epochs = 10<br>EMBEDDING_SIZE = 50<br>learning_rate = 0.001<br><br>params={<br>    &quot;batch_size&quot;:batch_size,<br>    &quot;epochs&quot;:epochs,<br>    &quot;embed_size&quot;:EMBEDDING_SIZE,<br>    &quot;optimizer&quot;:&quot;Adam&quot;,<br>    &quot;learning_rate&quot;:learning_rate,<br>    &quot;loss&quot;:&quot;sparse_categorical_crossentropy&quot;,<br>    }<br><br>experiment.log_parameters(params)</pre><p>We then log the accuracy and loss of our model using the experiment.log_metric method:</p><pre>loss, accuracy = model.evaluate(X_test,y_test)<br>print(&quot;Loss: &quot;, loss)<br>print(&quot;Accuracy: &quot;, accuracy)<br><br>experiment.log_metric(&quot;Loss&quot;, loss, step=None, include_context=True)<br>experiment.log_metric(&quot;Accuracy&quot;, accuracy, step=None, include_context=True)</pre><p>Finally, before viewing our logged model on the Comet platform we log the saved model and then end the experiment afterward, as we are using an interactive notebook.</p><pre>experiment.log_model(model, &#39;model&#39;)<br>experiment.end()</pre><p>The next step involves checking out the performance of our model on the Comet platform.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FseVLbLznvOo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DseVLbLznvOo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FseVLbLznvOo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f5601369a5b28c5e6455b971dda12ea/href">https://medium.com/media/5f5601369a5b28c5e6455b971dda12ea/href</a></iframe><h4>Conclusion</h4><p>We have successfully built a CNN model that helps classify images, and we also tested the ANN, and we were able to evaluate the efficiency of both models. Here is a <a href="https://colab.research.google.com/github/olujerry/olujerry/blob/main/Image_Classification_Model.ipynb#scrollTo=R9gvj3dP74U6">link to my notebook</a>, as well as the<a href="https://github.com/codebasics/deep-learning-keras-tf-tutorial/blob/master/16_cnn_cifar10_small_image_classification/cnn_cifar10_dataset.ipynb"> original notebook by Codebasics</a>.</p><p><em>Editor’s Note: </em><a href="https://heartbeat.comet.ml/"><em>Heartbeat</em></a><em> is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.</em></p><p><em>Editorially independent, Heartbeat is sponsored and published by </em><a href="http://comet.com/?utm_source=heartbeat&amp;utm_medium=referral&amp;utm_campaign=AMS_US_EN_AWA_heartbeat_EN"><em>Comet,</em></a><em> an MLOps platform that enables data scientists &amp; ML teams to track, compare, explain, &amp; optimize their experiments. We pay our contributors, and we don’t sell ads.</em></p><p><em>If you’d like to contribute, head on over to our</em><a href="https://heartbeat.comet.ml/call-for-contributors-fee7f5b80f3e"><em> call for contributors</em></a><em>. You can also sign up to receive our weekly newsletter (</em><a href="https://www.deeplearningweekly.com/"><em>Deep Learning Weekly</em></a><em>), check out the </em><a href="https://www.comet.com/site/blog/"><em>Comet blog</em></a><em>, join us on</em><a href="https://join.slack.com/t/fritz-ai-community/shared_invite/enQtNTY5NDM2MTQwMTgwLWU4ZDEwNTAxYWE2YjIxZDllMTcxMWE4MGFhNDk5Y2QwNTcxYzEyNWZmZWEwMzE4NTFkOWY2NTM0OGQwYjM5Y2U"><em> </em></a><a href="https://join.slack.com/t/cometml/shared_invite/zt-49v4zxxz-qHcTeyrMEzqZc5lQb9hgvw"><em>Slack</em></a><em>, and follow Comet on </em><a href="https://twitter.com/Cometml"><em>Twitter</em></a><em> and </em><a href="https://www.linkedin.com/company/comet-ml/"><em>LinkedIn</em></a><em> for resources, events, and much more that will help you build better ML models, faster.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=702c2d51c839" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/monitoring-a-convolutional-neural-network-cnn-in-comet-702c2d51c839">Monitoring A Convolutional Neural Network (CNN) in Comet</a> was originally published in <a href="https://heartbeat.comet.ml/">Heartbeat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>