<?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 Sandy M. on Medium]]></title>
        <description><![CDATA[Stories by Sandy M. on Medium]]></description>
        <link>https://medium.com/@sandy_m?source=rss-bd97610a8ec5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Sandy M. on Medium</title>
            <link>https://medium.com/@sandy_m?source=rss-bd97610a8ec5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:44:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sandy_m/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[Transformative AI: From the horse’s mouth — the ELI5 way]]></title>
            <link>https://medium.com/@sandy_m/transformative-ai-from-the-horses-mouth-explained-like-i-m-5-1a2ab7b7e3e2?source=rss-bd97610a8ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a2ab7b7e3e2</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-safety]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Sandy M.]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 00:21:39 GMT</pubDate>
            <atom:updated>2025-04-05T00:07:51.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AZTPtOv2lRZk8TAeyi6JdA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@steve_j?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Steve Johnson</a> on <a href="https://unsplash.com/photos/a-blue-and-a-white-mannequin-face-to-face-wj_LPlw2Rns?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Understanding the implications of artificial intelligence (AI) is very crucial, as it is the next revolution and it will enable us to do so much more than we can do now. In this article, I will demystify the concepts of AI, current AI systems, their purpose, and informed opinions on the future risks and rewards by the heads of institutions leading the research and development of AI.</p><h3>What is artificial intelligence, and how does it work?</h3><p>AI is simply designing computers to think and learn like humans instead of following a strict set of rules; they can recognize patterns, make decisions, and improve their knowledge over time. AI systems simply predict output based on a given input. To build these systems, we need three things, which are:</p><ul><li>Compute</li><li>Data</li><li>Algorithms</li></ul><p>Compute refers to a powerful computer that can process information very fast and is optimized for AI; data is real information used to learn more about something (pictures of dogs and cats if you are trying to build an AI that can differentiate between pictures of dogs and cats); and algorithms are simply mathematical functions. To build a <a href="https://aws.amazon.com/what-is/large-language-model/">Large Language Model</a> (LLM) like ChatGPT or Gemini, they got a lot of data from all over the internet and fit the data into different algorithms like <a href="https://blogs.nvidia.com/blog/what-is-a-transformer-model/">transformers</a>, <a href="https://www.analyticsvidhya.com/blog/2022/07/gradient-descent-and-its-types/">gradient decent</a>, etc., and then the algorithms ran the calculations on the powerful computers. Over the past years, we have seen improvements in data, computing, and algorithms, and each improvement has led to significant achievements in AI systems.</p><h3>Where are we currently in building these systems?</h3><p>Improvements in computing, data, and algorithms have led to and will lead to AI having more capabilities to meet and exceed human intelligence (like <a href="https://en.wikipedia.org/wiki/AlphaGo">AlphaGo</a>). Some people call it artificial general intelligence (AGI), but for the sake of this article, we will call it transformative AI. Ross Gruetzemacher and Jess Whittlestone, in their paper <a href="https://www.sciencedirect.com/science/article/pii/S0016328721001932#sec0030">The transformative potential of artificial Intelligence</a>, define transformative AI as advanced AI systems with much greater potential for societal impact (for example, AGI) because it captures the idea that a broad spectrum of advanced AI systems is worthy of concern and proposes 3 different levels of transformativeness.</p><p>Narrowly transformative AI: Any AI technology or application with the potential to lead to practically irreversible change focused primarily on a specific domain or sector of society, such as warfare or education. Eg., Facial Recognition</p><p>Transformative AI: Any AI technology or application with the potential to lead to practically irreversible change that is broad enough to impact the most important aspects of life and society. For example Transformer language model</p><p>Radically Transformative AI: Any AI technology or application that meets the criteria for TAI and has potential impacts that are extreme enough to result in radical changes to the metrics used to measure human progress and well-being, or to result in the reversal of societal trends previously thought of as practically irreversible—for example, human-level artificial intelligence.</p><h3>Why are we building this technology?</h3><p>Modern AI researchers and developers hope to build superintelligence AI, one big, powerful system that can solve any task easier and faster than what is possible in the current human economy. We will be able to do research faster, develop cures for illnesses, slow aging, and solve other human problems more efficiently, but at the same time, there are concerns that we have about this system.</p><p>First, we don’t know why they make the decisions they do; there is <a href="https://www.sap.com/resources/what-is-ai-bias#:~:text=Artificial%20intelligence%20bias%2C%20or%20AI,AI">bias</a> in human data, which will extend to the system, and over time, what if the interest of the AI no longer aligns with ours, leaving us at their mercy? These are just some of the issues. It is important to note that some people may be building this technology with economic gains in mind, while others are altruistic because building these systems costs a lot of money.</p><h3>What does this mean for the future?</h3><p>Some people downplay the impacts AI can have on us; I’ll highlight the opinions of CEOs of top AI research institutions on what they think the future of artificial intelligence will look like. Let’s bear in mind that they might be exaggerating this for gains (raising funds, company stock growth), but they will have the most educated guess.</p><p>Sam Altman, the CEO of <a href="https://openai.com/">OpenAI</a> (the company that owns ChatGPT), believes that when we achieve AGI, it will be able to perform the task that humans currently do, thereby reducing the cost of production, making things more affordable, offering taxing policies for capital and land, and providing individuals financial freedom to chase their interest in the changing workspace.</p><p>The CEO of <a href="https://www.anthropic.com/">Anthropic</a> (the company that owns Claude) Dario Amodei believes AI will be a force of good that will improve various aspects of human life (Biology and Physical Health, Economic Development and Poverty Alleviation, Peace and Governance, Work &amp; Meaning) from accelerated drug discovery, personalized medication, etc. and also acknowledges the risks and asks we develop the technology ethically and safely.</p><p>Demis Hassabis, CEO of <a href="https://deepmind.google/">Google DeepMind</a>, believes that AGI is possible by 2030 and said they will have human-like reasoning, could be the most revolutionary technology, and will change various sectors and increase human capabilities. He also believes these systems can be deceptive, and we have to build them to be transparent and trustworthy.</p><h3>Conclusion</h3><p>Accurately predicting technological progress is impossible, but we can all agree that they are right to a good extent. This article aims to guide you to any epiphany about AI safety and raise questions like: Are we taking adequate caution and building these systems safely seeing how much it can change the world as we know it today? We should focus more on AI safety, AI Policy, and AI alignment. If you are interested in learning more you should check out the <a href="https://aisafetyfundamentals.com/intro-to-tai/">Intro to Transformative</a> AI by BlueDot Impact.</p><p>Resources &amp; Further Reading</p><p><a href="https://aisafetyfundamentals.com/blog/ai-risks/">https://aisafetyfundamentals.com/blog/ai-risks/</a></p><p><a href="https://homosabiens.substack.com/p/deadly-by-default">https://homosabiens.substack.com/p/deadly-by-default</a></p><p><a href="https://moores.samaltman.com/">https://moores.samaltman.com/</a></p><p><a href="https://www.youtube.com/watch?v=yr0GiSgUvPU">https://www.youtube.com/watch?v=yr0GiSgUvPU</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a2ab7b7e3e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Role of Reinforcement Learning in Improving the Capabilities of Large Language Models]]></title>
            <link>https://medium.com/@sandy_m/the-role-of-reinforcement-learning-in-improving-the-capabilities-of-large-language-models-ac9b5f40ba45?source=rss-bd97610a8ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac9b5f40ba45</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Sandy M.]]></dc:creator>
            <pubDate>Fri, 17 May 2024 08:49:00 GMT</pubDate>
            <atom:updated>2024-05-17T08:49:00.945Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XSCmjkUswBC0I1PfZQQgXA.jpeg" /><figcaption>image by Marcus Spiske</figcaption></figure><h4><strong>Introduction</strong></h4><p>Large language models are currently revolutionizing natural language processing tasks like text generation, translation, and question-answering. The models are based on what we call transformer architectures, which are trained on vast amounts of data and then fine-tuned to carry out specific tasks. The performances of these LLMs are awe-inspiring, but there is also room for improvement to get them to perform better. Reinforcement learning (RL) is a powerful technique to improve the capabilities of large language models further, and in this article, we will explore the role that reinforcement learning plays in expanding and extending the capabilities of these models.</p><p><strong>Understanding Reinforcement Learning</strong></p><p>Reinforcement learning is an area of machine learning that focuses on learning through interaction with an environment. An agent learns to make an order of actions that maximizes a cumulative reward. Here’s how reinforcement learning can be applied to LLMs:</p><ol><li>Exploration vs. Exploitation: RL models balance exploration (trying out new generation strategies) and exploitation (relying on known strategies). This balance is important for language models to avoid getting stuck in suboptimal or repetitive patterns of text generation.</li><li>Reward-Based Fine-Tuning: After the pretraining of a large language model, RL can be used to fine-tune the model. In RL, the model interacts with an environment, and the actions are guided by a reward signal. When we talk about language models, this reward can be based on the quality and relevance of the generated text.</li><li>Policy Optimization: RL algorithms can optimize the policy (the strategy the model uses to generate text) by trying out various actions and learning from them based on the feedback provided by the reward signal. This helps the model process its text generation abilities over time, which results in more contextually accurate and coherent responses.</li></ol><p><strong>Applications of RL in Language Models</strong></p><p>Let’s explore some use cases for how RL enhances the abilities of large language models:</p><p>1. Conversational AI: RL is used to fine-tune models in chatbots and virtual assistants so that they can create more contextually appropriate responses. RL makes these applications more helpful and entertaining by rewarding models for sustaining fair discussions and offering replies.</p><p>Consider a virtual assistant that utilizes RL to improve its replies to user questions. When a user asks a question, the RL agent provides many answers, each with a unique method. These replies are then graded based on user input, with bigger awards going to the most relevant and useful responses. The virtual assistant learns to provide replies that are not only accurate but also adapted to the user’s tastes and needs over time</p><p>2. Content Generation: RL may be used to guarantee that created material adheres to certain criteria or objectives while performing content production activities such as article authoring or code generation. It has the potential to reward models for producing language that is informative, accurate, and well-structured.</p><p>Consider an AI content generator that uses RL to increase the quality of articles created. To develop articles, the RL agent experiments with various writing styles, tones, and structures. To measure the efficacy of each article, user input is gathered. Based on the input, the model then modifies its writing style and structure, eventually enhancing the quality of the created material.</p><p>3. Language Translation: For content production activities such as article writing or code generation, RL may be used to guarantee that the created material adheres to certain criteria or objectives. It may reward models for producing language that is informative, accurate, and well-structured.</p><p>Consider an AI content generator that uses RL to increase the quality of created articles. To develop articles, the RL agent experiments with different writing styles, tones, and structures. User input is gathered to assess the efficacy of each article. The model then modifies its writing style and structure depending on the input, eventually enhancing the quality of the created material.</p><p>4. Summarization: By encouraging models to write brief yet useful summaries, RL aids in summarizing tasks. The relevance of the summary to the source material can be used to determine the reward signal.</p><p>Consider a text summarizing model that uses RL to create news article summaries. The RL agent develops and analyzes numerous candidate summaries depending on user choices. Summaries that are regarded as more relevant and informative are rewarded more heavily, causing the model to create better summaries that encapsulate the main ideas of the original articles.</p><p><strong>Challenges and Future Directions</strong></p><p>RL assists in task summarization by encouraging models to create succinct but useful summaries. The reward signal can be determined by the summary’s relation to the original content.</p><p>Consider a text-summarizing model that generates news article summaries using RL. Depending on the user’s selections, the RL agent generates and assesses a large number of candidate summaries. Summaries that are deemed more relevant and informative are significantly rewarded, leading the model to produce better summaries that embody the major concepts of the original articles.</p><p>Another issue that has to be addressed is the scalability of RL training for large language models. To train RL agents at scale, large computing resources are required, and efficient distributed RL algorithms are required to make this possible. Researchers are attempting to improve RL training pipelines and algorithms to minimize resource needs and make RL more accessible to a larger range of applications.</p><p>Concerns have been raised about the use of RL in language models from an ethical standpoint. RL agents may create biased or destructive outputs if they learn from biased or harmful feedback. It is critical to ensure that RL training is carried out responsibly and ethically in order to avoid unforeseen outcomes.</p><p>We can anticipate breakthroughs in RL algorithms geared particularly toward language models in the future. Models may improve their ability to think, draw reasonable conclusions, and comprehend complex contexts. This advancement will result in even more outstanding language-generating capabilities across a wide range of applications.</p><h4><strong>Conclusion</strong></h4><p>Reinforcement learning is critical for improving the capabilities of big language models. We may obtain more contextually accurate, coherent, and meaningful text production in applications ranging from conversational AI to content creation and translation by fine-tuning these models with RL approaches. As RL research progresses, we should expect even more spectacular accomplishments from huge language models in the next few years, significantly narrowing the gap between AI and human-level language interpretation and generation. RL will continue to be a driving force in pushing the frontiers of what language models can do with careful consideration of ethical and practical constraints.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac9b5f40ba45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Version Controlling Deep Learning Projects with DVC]]></title>
            <link>https://medium.com/@sandy_m/version-controlling-deep-learning-projects-with-dvc-eacb9e5f39e4?source=rss-bd97610a8ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/eacb9e5f39e4</guid>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[dvc]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Sandy M.]]></dc:creator>
            <pubDate>Fri, 17 May 2024 08:48:36 GMT</pubDate>
            <atom:updated>2024-05-17T08:48:36.562Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3IAY_6xx6WdwK-DdroOpOg.jpeg" /><figcaption>credit: unsplash</figcaption></figure><p>While working on projects as a deep learning engineer it can get pretty messed up, especially if you’re trying out various experiments and working with a team. So how do you keep track of the data and models during these experiments?</p><p>Version control is the act of recording changes made to files by tracking all modifications done to the file, it also helps in collaboration within a team of developers in various locations. You can use Gitlab, Github, etc for version control but they all have file size restrictions, and most times the files used to work on machine learning and data science projects are large therefore sharing data among the team will involve transferring different versions for all changes.</p><p>Just like normal software development, we can perform version control properly for our machine learning projects using DVC and Git, DVC is an open-source version control system used to manage machine learning projects and is specifically designed to take care of large datasets, and models.</p><p>How DVC works is that it monitors the various versions of the data or the model using a text file that refers to a particular version of the data or the model and then uses the same file to search for any stored version of the data or model, in this tutorial we will use DVC to carry out data and model version control.</p><p>First, to get started you have to install DVC using the command below:</p><pre>pip install dvc</pre><p>After that, you clone the repository you want to version control:</p><pre>git clone https://github.com/your/first-repo.git (this should be the link to your repo)<br>cd first-repo</pre><p>Then create a branch called testing:</p><pre>git checkout -b “testing”</pre><p>The next step will be to initialize DVC in the folder you just cloned using the code below:</p><pre>dvc init</pre><p>After running the command below a folder .dvc will be created and you can see it by running:</p><pre>git status</pre><p>Now we’re done with the setup the next step will be adding data and then training the model:</p><pre>dvc get https://www.kaggle.com/datasets/andrewmvd/dog-and-cat-detection/download?datasetVersionNumber=1<br>unzip -q dog-and-cat-detection.zip<br>rm -f dog-and-cat-detection.zip</pre><p>Next, you add the data to the repo using DVC add:</p><pre>dvc add dog-and-cat-detection</pre><p>Now to get the model we have to train the model and get an output of the model.h5 and the metrics.csv and then capture the state of the model using DVC add:</p><pre>python train.py<br>dvc add model.h5</pre><p>Commit all changes done so far:</p><pre>git add data.dvc model.h5.dvc metrics.csv .gitignore<br>git commit -m &quot;initial model trained with first data&quot;<br>git tag -a &quot;v0.1&quot; -m &quot;model v0.1, first data&quot;</pre><p>Let’s assume you have more data or have made changes to the data and now have to train your model on the new data and want to create a new version of the model:</p><pre>dvc get https://www.kaggle.com/datasets/andrewmvd/dog-and-cat-detection/download?datasetVersionNumber=1<br>unzip -q dog-and-cat-detection.zip<br>rm -f dog-and-cat-detection.zip</pre><p>Using the new data we have let’s train the model again:</p><pre>​​dvc add data<br>$ python train.py<br>$ dvc add model.h5</pre><p>Now we commit this second version:</p><pre>git add data.dvc model.h5.dvc metrics.csv<br>$ git commit -m &quot;new model, trained with more data&quot;<br>$ git tag -a &quot;v0.2&quot; -m &quot;model v0.2, more data&quot;</pre><p>At this point, you have two versions of your data, model, and metrics saved up, if you need any of them you can use DVC checkout to get them:</p><pre>git checkout v0.1<br>$ dvc checkout</pre><p>You also have the option of selecting either the data, model, or metrics of a version if you don&#39;t want to get all of them:</p><pre>git checkout v0.1 data.dvc<br>$ dvc checkout data.dvc</pre><p>This tutorial covered the basics of how you can quickly get started with maintaining various versions of your data and model with DVC, There are so many other exciting use cases that can help you manage your deep learning projects better. You can go through the documentation at <a href="https://dvc.org/doc/use-cases">https://dvc.org/doc/use-cases</a> and get your hands dirty.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eacb9e5f39e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Segmentation with PyTorch and Comet]]></title>
            <link>https://heartbeat.comet.ml/image-segmentation-with-pytorch-and-comet-1798d3bb005d?source=rss-bd97610a8ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1798d3bb005d</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cometml]]></category>
            <category><![CDATA[image-segmentation]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Sandy M.]]></dc:creator>
            <pubDate>Thu, 03 Aug 2023 14:50:50 GMT</pubDate>
            <atom:updated>2023-08-03T14:50:50.398Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>Image segmentation is a crucial component of computer vision, and involves dividing a picture into various parts. Popular deep learning framework PyTorch offers strong tools and packages to successfully complete image segmentation tasks. In this article, we’ll look at how to segment images using PyTorch, covering all the key procedures and methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8CZsbDtZdRiJ0PWhVB1zuw.jpeg" /><figcaption>Photo by George Milton: <a href="https://www.pexels.com/photo/woman-working-retouching-photo-on-laptop-at-convenient-workplace-7014337/">https://www.pexels.com/photo/woman-working-retouching-photo-on-laptop-at-convenient-workplace-7014337/</a></figcaption></figure><p><strong>Prerequisites</strong></p><p>You should be familiar with Python and PyTorch and have a basic knowledge of deep learning in order to follow this lesson. Make sure PyTorch and Torchvision are installed in your Python environment as well.</p><p><strong>Step 1: Dataset Preparation</strong></p><p>Getting a dataset that can be used for image segmentation is the first step. There are several datasets available, including custom datasets, COCO, and PASCAL VOC. Make sure your dataset includes annotated photos with labels for each pixel identifying the relevant section or class.</p><p><strong>Step 2: Setting up Comet account</strong></p><p>We’ll be using the Comet GUI to track our experiments and to do this you’ll have to create an account at <a href="http://www.comet.com/site">http://www.comet.com/site</a> and then create a workspace and get your API key because we’ll need to add it to our code.</p><p><strong>Step 3: Loading and Preprocessing the Data</strong></p><p>In this step, we’ll load and preprocess the dataset for training our segmentation model. We’ll use the Torchvision library, which provides pre-built datasets and data transformation functions. We will also be using Comet to track the experiment so if you don’t have it installed already you can install it on your terminal using the command below and then import it.</p><pre>pip install comet_ml</pre><p>1. Import the required libraries:</p><pre>import torch<br>from torch.utils.data import Dataset, DataLoader<br>import torchvision.transforms as transforms<br>from torchvision.datasets import YourDatasetClass<br>import comet_ml<br>from comet_ml import Experiment<br><br>import numpy as np<br>from PIL import Image</pre><p>2. Add your API key and set a project name</p><pre>experiment = comet_ml.Experiment(&quot;YOUR-API-KEY&quot;)<br>comet_ml.init(project_name=&#39;image-segmentation&#39;)</pre><p>3. Create a custom dataset class by inheriting from `torch.utils.data.Dataset` and override the `__len__` and `__getitem__` methods:</p><pre>class CustomDataset(Dataset):<br>    def __init__(self, transform=None):<br>        self.transform = transform<br>        # Load and initialize your dataset here<br>    <br>    def __len__(self):<br>        # Return the total number of images in the dataset<br>        pass<br><br>    def __getitem__(self, index):<br>        # Retrieve and preprocess the image and its corresponding segmentation mask<br>        pass</pre><p>4. Implement the `__len__` method to return the dataset size.</p><p>5. Implement the `__getitem__` method to load and preprocess the image and all its segmentation masks. Apply any required transformations using the `transform` parameter.</p><p>6. Next, create an instance of your custom dataset, highlighting any desired transformations:</p><pre>transform = transforms.Compose([<br>    transforms.ToTensor(),<br>    # Add any additional transformations here<br>])<br><br>dataset = CustomDataset(transform=transform)</pre><p>7. Let’s log the image data to Comet</p><pre>for data in Dataset:<br>    # Extract image data<br>    image_data = data[0][3]  <br><br>    # Create PIL Image object<br>    image = Image.fromarray(image_data)<br><br>    # Generate image name<br>    image_id = data[0][0]  <br>    image_name = f&quot;Image ID: {image_id}&quot;<br>     <br>    <br>    # Log image and annotations to Comet<br>    experiment.log_image(image, name=image_name)</pre><p>8. Now we’ll split the dataset into training and validation sets (e.g., using `torch.utils.data.random_split`).</p><p>9. create data loaders that will efficiently load the data during training:</p><pre>train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)<br>val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)</pre><p><strong>Step 4: Building the Segmentation Model</strong></p><p>To build the segmentation model we’ll define the architecture. There are various architectures available, such as U-Net, FCN, or DeepLab.</p><p>1. Import the required PyTorch modules:</p><pre>import torch.nn as nn<br>import torch.nn.functional as F</pre><p>2. Define the segmentation model by creating a class that will inherit from `torch.nn.Module`:</p><pre>class SegmentationModel(nn.Module):<br>    def __init__(self):<br>        super(SegmentationModel, self).__init__()<br>        # Define your model architecture here<br>    <br>    def forward(self, x):<br>        # Implement the forward pass of your model<br>        pass</pre><p>3. Implement the `__init__` method that will define the layers and modules of your model.</p><p>4. Implement the `forward` method to define the forward pass of your model.</p><p><strong>Step 5: Training the Model</strong></p><p>Now, let’s train the segmentation model using the prepared dataset and the architecture we defined earlier.</p><p>1. Set the device to either GPU or CPU, depending on availability:</p><pre>device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)</pre><p>2. Instantiate your segmentation model and move it to the device you have available:</p><pre>model = SegmentationModel().to(device)</pre><p>3. Define the loss function and optimizer:</p><pre>criterion = nn.CrossEntropyLoss()<br>optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate, momentum=momentum)</pre><p>4. Start the training loop:</p><pre>for epoch in range(num_epochs):<br>    model.train()<br>    for images, masks in train_loader:<br>        images = images.to(device)<br>        masks = masks.to(device)<br>        <br>        optimizer.zero_grad()<br>        <br>        outputs = model(images)<br>        loss = criterion(outputs, masks)<br>        <br>        loss.backward()<br>        optimizer.step()</pre><p>5. Implement the loop for validation:</p><pre>model.eval()<br>with torch.no_grad():<br>    for images, masks in val_loader:<br>        images = images.to(device)<br>        masks = masks.to(device)<br>        <br>        outputs = model(images)<br>        # Evaluate and store the performance metrics (e.g., accuracy, IoU, etc.)</pre><p><strong>Step 6: Model Evaluation</strong></p><p>After training, we need to evaluate the performance of our model on unseen data.</p><p>1. Implement the evaluation loop:</p><pre>model.eval()<br>with torch.no_grad():<br>    for images, masks in test_loader:<br>        images = images.to(device)<br>        masks = masks.to(device)<br>        <br>        outputs = model(images)<br>        # Evaluate and store the performance metrics (e.g., accuracy, IoU, etc.)</pre><p>2. Analyze and visualize the results using your desired visualization techniques and metrics.</p><p>3. End the experiment so you can visualize the result in the comet UI</p><pre>experiment.end()</pre><p>Now you can go over to your Comet dashboard and check the image panel to visualize the image dataset that was logged in and see the model output, and metrics, tune the hyperparameters and do other amazing things.</p><p><strong>Conclusion</strong></p><p>We have covered the necessary steps for doing image segmentation with PyTorch in this tutorial. The dataset preparation, data loading, model design, training, and assessing the model were all covered. Keep in mind that this lesson just gives a basic foundation; to further increase the segmentation accuracy, you may explore different methodologies and sophisticated architectures.</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=1798d3bb005d" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/image-segmentation-with-pytorch-and-comet-1798d3bb005d">Image Segmentation with PyTorch 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[Image generation using Neural Style Transfer and Kangas]]></title>
            <link>https://heartbeat.comet.ml/image-generation-using-neural-style-transfer-and-kangas-2d6c91e13eb2?source=rss-bd97610a8ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d6c91e13eb2</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[image-generation]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[neural-style-transfer]]></category>
            <dc:creator><![CDATA[Sandy M.]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 17:41:42 GMT</pubDate>
            <atom:updated>2023-07-25T19:48:48.255Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ktwur4RmoL1FdBllKK4cnA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@davidclode?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">David Clode</a> on <a href="https://unsplash.com/photos/yLxQRYpuwqg?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Algorithms for deep learning have been used to create art, enabling us to create original images by fusing the style and content of other embodiments. In this lesson, we will examine the idea of neural style transfer and discover how to use deep learning frameworks to execute it. By the conclusion of this tutorial, you will be able to produce your own artistic images that combine the style and substance of several photos.</p><p><strong>Overview of Neural Style Transfer</strong></p><p>Neural style transfer is a technology that blends two images’ content and style to produce a new image incorporating both features. In order to extract the content and stylistic features from the input photos, a pre-trained convolutional neural network (CNN) is used in the process. We will also be using kangas for visualizing images because it&#39;s a great tool for exploring and visualizing large-scale multimedia data.</p><p>The steps covered in the lesson are as follows:</p><ul><li>Install Kangas</li><li>Preparing and loading the content and style pictures</li><li>Being familiar with the VGG19 model architecture</li><li>Taking the pre-trained model’s content and style attributes</li><li>defining the loss function to balance the weights of the content and the style</li><li>Reducing the loss by optimizing the resulting picture</li></ul><p><strong>Kangas Installation</strong></p><pre>pip install kangas</pre><p><strong>Neural style transfer implementation</strong></p><p>Using Python and a deep learning framework called TensorFlow, we will go into the code implementation of neural style transfer in this section.</p><p>First, let’s import all the libraries that will be needed for this tutorial</p><pre>import tensorflow as tf<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import kangas as kg<br>from kangas import DataGrid, Image</pre><p>Now let’s load the pre-trained VGG19 model that will be used for training the model</p><pre>vgg_model = tf.keras.applications.VGG19(include_top=False, weights=&#39;imagenet&#39;)</pre><p>After that, we’ll preprocess the images that will be used to build the model. We’ll be using two images, the first image is the content image is the image whose content or subject we want to retain in the final generated image and the second is the style image which is the image that possesses a distinct artistic style.</p><pre>content_image_path = &#39;content_image.jpg&#39;<br>style_image_path = &#39;style_image.jpg&#39;<br><br># Load and preprocess content and style images<br>def load_and_preprocess_image(image_path):<br>    img = tf.io.read_file(image_path)<br>    img = tf.image.decode_image(img, channels=3)<br>    img = tf.image.convert_image_dtype(img, tf.float32)<br>    img = tf.image.resize(img, (256, 256))<br>    img = img[tf.newaxis, :]<br>    return img<br><br>content_image = load_and_preprocess_image(content_image_path)<br>style_image = load_and_preprocess_image(style_image_path)<br><br><br></pre><p>After processing the image let’s load them with kangas and set up a data grid so we can have a good view of the images</p><pre>content_image = kg.Image(content_image, name=&#39;content.jpeg&#39;) <br>dg = kg.DataGrid(name=&#39;Art Images&#39;) <br>dg.extend([{&#39;Image&#39;: content_image}])<br><br>style_image = kg.Image(style_image, name=&#39;style.jpeg&#39;)<br>dg.append([{&#39;Image&#39;: style_image}])<br><br># kickstart the UI<br>dg.show()</pre><p>After preprocessing the images the next step will be to define the styles and content layer that will be used to carry out feature extraction.</p><pre>content_layers = [&#39;block5_conv2&#39;]<br>style_layers = [&#39;block1_conv1&#39;, &#39;block2_conv1&#39;, &#39;block3_conv1&#39;, &#39;block4_conv1&#39;, &#39;block5_conv1&#39;]</pre><p>Now it’s time to build the style transfer model</p><pre>def style_transfer_model(vgg_model, style_layers, content_layers):<br>    vgg_model.trainable = False<br>    style_outputs = [vgg_model.get_layer(name).output for name in style_layers]<br>    content_outputs = [vgg_model.get_layer(name).output for name in content_layers]<br>    model_outputs = style_outputs + content_outputs<br>    return tf.keras.models.Model(vgg_model.input, model_outputs)<br><br>style_transfer = style_transfer_model(vgg_model, style_layers, content_layers)</pre><p>And now define the content and style weights</p><pre>content_weight = 1e3<br>style_weight = 1e-2</pre><p>The next step will be for us to define the loss function</p><pre>def style_content_loss(outputs, style_targets, content_targets, style_weight, content_weight):<br>    style_outputs = outputs[:len(style_layers)]<br>    content_outputs = outputs[len(style_layers):]<br><br>    style_loss = tf.add_n([tf.reduce_mean(tf.square(style_outputs[i] - style_targets[i])) for i in range(len(style_outputs))])<br>    style_loss *= style_weight / len(style_outputs)<br><br>    content_loss = tf.add_n([tf.reduce_mean(tf.square(content_outputs[i] - content_targets[i])) for i in range(len(content_outputs))])<br>    content_loss *= content_weight / len(content_outputs)<br><br>    total_loss = style_loss + content_loss<br>    return total_loss</pre><p>Now let’s extract the content and style features from the pre-trained model</p><pre>def get_feature_representations(model, content_image, style_image):<br>    content_features = model(content_image)[&#39;block5_conv2&#39;]<br>    style_features = [model(layer)[name] for layer, name in zip(style_image, style_layers)]<br>    return content_features, style_features<br><br>content_features, style_features = get_feature_representations(style_transfer, content_image, style_image)</pre><p>Next, we’ll create the initial generated image as a random noise and define the learning rate.</p><pre>generated_image = tf.Variable(content_image + tf.random.normal(content_image.shape) * 0.01)<br>optimizer = tf.optimizers.Adam(learning_rate=0.02, beta_1=0.99, epsilon=1e-1)</pre><p>It’s time to perform neural style transfer and define the number of training interactions</p><pre>@tf.function()<br>def train_step(image):<br>    with tf.GradientTape() as tape:<br>        outputs = style_transfer(image)<br>        loss = style_content_loss(outputs, style_features, content_features, style_weight, content_weight)<br>    gradient = tape.gradient(loss, image)<br>    optimizer.apply_gradients([(gradient, image)])<br>    image.assign(tf.clip_by_value(image, clip_value_min=0.0, clip_value_max=1.0))<br><br># Number of training iterations<br>num_iterations = 1000</pre><p>And then perform style transfer for each of the iterations</p><pre>for i in range(num_iterations):<br>    train_step(generated_image)<br>    if i % 100 == 0:<br>        print(&quot;Iteration:&quot;, i)</pre><p>Now let’s use kangas again to visualize the generated image</p><pre>image = kg.Image(generated_image[0]).to_pil()<br>image</pre><p><strong>Conclusion</strong></p><p>In this lesson, we looked at the fascinating field of neural style transfer in deep learning for the arts. We discussed the main ideas underlying the method and gave detailed directions for implementing it with Python and a deep learning framework. We may create appealing and beautiful images via neural style transfer by fusing the content of one image with the style of another. You can carry on experimenting, changing the settings, and investigating variants of the approach to make it better.<br>Keep in mind that neural style transfer is just the start of the amazing possibilities that deep learning presents for the creation of art and images.</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=2d6c91e13eb2" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/image-generation-using-neural-style-transfer-and-kangas-2d6c91e13eb2">Image generation using Neural Style Transfer and Kangas</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[Building a Text Summarization Model]]></title>
            <link>https://heartbeat.comet.ml/building-a-text-summarization-model-532f4446efc3?source=rss-bd97610a8ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/532f4446efc3</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[heartbeat]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[text-summarization]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Sandy M.]]></dc:creator>
            <pubDate>Wed, 03 May 2023 17:41:23 GMT</pubDate>
            <atom:updated>2023-05-06T22:28:42.156Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DoJ6pfD6Kqy0jrTxANVRUQ.jpeg" /><figcaption>image by <a href="https://www.freepik.com/author/fabrikasimf">fabrikasimf</a></figcaption></figure><p>The process of condensing a longer text document while keeping the main concept and crucial details is known as text summarization. A large document’s content can be rapidly understood using this tool and can also be used to summarize news stories or academic papers.</p><p>In this tutorial, we’ll look at how to use Python to create a text summarizer. We’ll use a well-liked toolkit called NLTK (Natural Language Toolkit), which offers a variety of tools for text processing and analysis.</p><p><strong>Install NLTK</strong></p><p>NLTK must be installed before we can begin. Run the following program in your terminal to execute this:</p><pre>pip install nltk</pre><p><strong>Import Libraries and Load Data</strong></p><p>After NLTK has been loaded, we can start by importing the required libraries and loading the data for the summary. We’ll use the NLTK news articles dataset in this exercise.</p><pre>import nltk<br>from nltk.corpus import reuters<br><br>nltk.download(&#39;reuters&#39;)<br><br>articles = reuters.fileids()</pre><p>The Reuters dataset is downloaded using the code above, and the file ids are then loaded into the variable ‘articles’. The reuters.raw() method can then be used to obtain the content of each article.</p><p><strong>Tokenize Sentences</strong></p><p>Tokenizing the text into individual sentences is the next stage. The sent_tokenize() function from NLTK can be used to complete this job.</p><pre>from nltk.tokenize import sent_tokenize<br><br>sentences = []<br><br>for article in articles:<br>    sentences.extend(sent_tokenize(reuters.raw(article)))</pre><p>The code mentioned above separates each article into a sentence and adds it to the list of ‘sentences’.</p><p><strong>Preprocess Text</strong></p><p>The content must first be preprocessed to get rid of any extraneous information like stop words, punctuation, and special characters before we can summarize it. For this job, we can use the built-in functions of NLTK.</p><pre>from nltk.corpus import stopwords<br>from nltk.tokenize import word_tokenize<br>from string import punctuation<br><br>stop_words = set(stopwords.words(&#39;english&#39;) + list(punctuation))<br><br>def preprocess(text):<br>    tokens = word_tokenize(text.lower())<br>    tokens = [token for token in tokens if token not in stop_words]<br>    return &quot; &quot;.join(tokens)<br>    <br>processed_sentences = [preprocess(sentence) for sentence in sentences]</pre><p>The stop words and marks in NLTK are loaded first in the code above. The text is then tokenized, stop words and punctuation are removed, and a function called preprocess() gives the processed text as a string. The processed sentences are then stored in the processed sentences list after each sentence in the sentences list has been subjected to the preprocess() function.</p><blockquote>Curious to see how Comet works? <a href="https://www.comet.com/site/blog/debugging-your-machine-learning-models-with-comet-artifacts/?utm_source=heartbeat&amp;utm_medium=referral&amp;utm_campaign=AMS_US_EN_AWA_heartbeat_CTA">Check out our PetCam scenario to see MLOps in action</a>.</blockquote><p><strong>Create Word Frequencies</strong></p><p>The second stage is to create a dictionary of each sentence’s word frequencies. For this, we can make use of NLTK’s FreqDist() method.</p><pre>from nltk.probability import FreqDist<br><br>word_frequencies = {}<br><br>for sentence in processed_sentences:<br>    for word in word_tokenize(sentence):<br>        if word not in word_frequencies:<br>            word_frequencies[word] = 1<br>        else:<br>            word_frequencies[word] += 1<br>            <br>maximum_frequency = max(word_frequencies.values())<br><br>for word in word_frequencies.keys():<br>    word_frequencies[word] = (word_frequencies[word]/maximum_frequency)</pre><p>With the help of the above code, a dictionary named word_frequencies is created, storing the frequency of each word used in the processed sentences. Prior to updating the frequency count in the word frequencies dictionary, we loop through each phrase and each word within it. The next step is to determine the word’s highest frequency in the document. To normalize the values, we then divide each frequency count by this maximum frequency.</p><p><strong>Calculate Sentence Scores</strong></p><p>We can now determine a score for each sentence based on the sum of the word frequencies for that sentence since we have generated word frequencies for each sentence.</p><pre>sentence_scores = {}<br><br>for sentence in processed_sentences:<br>    for word in word_tokenize(sentence):<br>        if sentence not in sentence_scores:<br>            sentence_scores[sentence] = word_frequencies[word]<br>        else:<br>            sentence_scores[sentence] += word_frequencies[word]</pre><p>The above code generates a dictionary called sentence scores that stores each sentence’s value. We update the number for each sentence in the sentence_scores dictionary by looping through each sentence and each word within each sentence_scores.</p><p><strong>Pick the Best Sentences</strong></p><p>To make a summary of the text, we can choose the top n sentences with the highest scores. We will pick the best five sentences for this example.</p><pre>import heapq<br><br>summary_sentences = heapq.nlargest(5, sentence_scores, key=sentence_scores.get)<br><br>summary = &quot; &quot;.join(summary_sentences)<br>print(summary)</pre><p>The best 5 sentences with the highest scores are chosen using the heapq.nlargest() function in the code above. The ultimate summary is made by combining these sentences.</p><p><strong>Checking the Text Summarizer</strong></p><p>Let’s use an example article to try our summarizer:</p><pre>text = &quot;&quot;&quot;<br>World number one Novak Djokovic said he will compete at the Miami Open after skipping the tournament last year due to the COVID-19 pandemic.<br>The 33-year-old Serbian has been in top form this year, winning the Australian Open for the ninth time and reaching the final of the ATP Cup.<br>&quot;I&#39;m very excited to confirm my participation at Miami Open this year,&quot; Djokovic, who has won the Miami tournament six times, said on Twitter.<br>&quot;It&#39;s been a while since I played in Miami and I can&#39;t wait to be back in front of the fans,&quot; he added.<br>The tournament, which features both men&#39;s and women&#39;s events, runs from March 22 to April 4.<br>&quot;&quot;&quot;<br><br>processed_text = preprocess(text)<br><br>sentences = sent_tokenize(text)<br>processed_sentences = [preprocess(sentence) for sentence in sentences]<br><br>word_frequencies = {}<br>for sentence in processed_sentences:<br>    for word in word_tokenize(sentence):<br>        if word not in word_frequencies:<br>            word_frequencies[word] = 1<br>        else:<br>            word_frequencies[word] += 1<br>            <br>maximum_frequency = max(word_frequencies.values())<br><br>for word in word_frequencies.keys():<br>    word_frequencies[word] = (word_frequencies[word]/maximum_frequency)<br>    <br>sentence_scores = {}<br>for sentence in processed_sentences:<br>    for word in word_tokenize(sentence):<br>        if sentence not in sentence_scores:<br>            sentence_scores[sentence] = word_frequencies[word]<br>        else:<br>            sentence_scores[sentence] += word_frequencies[word]<br>            <br>summary_sentences = heapq.nlargest(2, sentence_scores, key=sentence_scores.get)<br>summary = &quot; &quot;.join(summary_sentences)<br><br>print(summary)</pre><p>Output:</p><pre>&quot;I&#39;m very excited to confirm my participation at Miami Open this year,&quot; Djokovic, who has won the Miami tournament six times, said on Twitter. The tournament, which features both men&#39;s and women&#39;s events, runs from March 22 to April 4.</pre><p>By picking the most crucial phrases from the news article, our summarizer has effectively produced a summary. By altering the amount passed to heapq.nlargest, we can change the number of sentences we want to include in our summary ().</p><p><strong>Conclusion</strong></p><p>To sum up, NLTK offers a strong collection of tools for natural language processing, and by utilizing these tools, we can use Python to build a text summarizer. The method shown above is just one of many that could be used, and you could alter it to suit your requirements. Summarizing text can be helpful in a variety of situations, including summarizing news stories, academic papers, and legal documents. We can speed up information search and save time by automating the summarization process.</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=532f4446efc3" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/building-a-text-summarization-model-532f4446efc3">Building a Text Summarization Model</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[Understanding Popular Algorithms in Deep Learning]]></title>
            <link>https://heartbeat.comet.ml/understanding-popular-algorithms-in-deep-learning-7557f3c48369?source=rss-bd97610a8ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7557f3c48369</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[cnn-model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[rnn]]></category>
            <dc:creator><![CDATA[Sandy M.]]></dc:creator>
            <pubDate>Tue, 02 May 2023 12:31:14 GMT</pubDate>
            <atom:updated>2023-05-02T12:31:14.077Z</atom:updated>
            <content:encoded><![CDATA[<p>Artificial intelligence has undergone a revolution thanks to deep learning. Deep learning allows machines to learn from vast amounts of data and carry out complex tasks that were previously only considered possible by humans (like translation between languages, recognizing objects etc.).</p><p>Deep learning is based in algorithms, which are mathematical operations that let computers learn from data and get better over time. In this article, we will examine some different popular deep learning algorithms and how they operate.</p><h3><strong>Neural Networks</strong></h3><p>Neural networks are a popular deep learning algorithm that are inspired by the structure and function of the human brain. They have several use cases, from image recognition to natural language processing and self-driving vehicles.</p><p>A neural network is a collection of connected neurons, also known as nodes, that are organized in layers. Each of the nodes gets an input, processes it, and produces an output. Training a neural network involves adjusting the biases and weights of the connections between the nodes so that the output of the network is close to the desired output, this is achieved by feeding the network with a set of training data and adjusting the weights and biases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NF8z-GOYzzzbJA3jusAoFQ.png" /><figcaption>image from upgrad.com</figcaption></figure><h4><strong>How neural networks work</strong></h4><p>What a neural network does is learn the patterns in the input data and then map it to the desired output. Each node in the network carries out a mathematical operation on the input it received, and then the output of the node is passed on to the other nodes in the next layer. Weights are used to determine the strength of the connection between nodes and the weights are tuned during the training so that the network can learn to give the desired output for a particular input.</p><p>To train a neural network you give the network a set of data and it compares the output with the desired output, the difference between the two will be known as an error which will be used in adjusting the weights till the outputs align.</p><h4><strong>Types of Neural Networks</strong></h4><p><strong>Convolutional neural networks (CNNs)</strong></p><p>Convolutional neural networks are a type of neural network that is perfect for video and image processing tasks. A convolutional neural network uses a series of various convolutional layers to get features from the input data, and the convolutional layers also use a set of filters known as kernels to carry out a series of convolutions on the input data. Then, the output of each of the layers is passed through a nonlinear activation function such as a ReLU function before it is then passed on the next layer.</p><p>The CNN architecture consists of various layers which involve convolutional layers, pooling layers, and fully connected layers, the convolutional layers extract the features from the input data while the pooling layers reduce the spatial dimensionality of the output of the convolutional layers. The fully connected layer then classifies the input data based on the features that were extracted by the convolutional layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jYXvGR3Z43G-CjTLF6VhWw.png" /><figcaption>image by <a href="https://medium.com/@jokerpt?source=post_page-----a3f5d6746697--------------------------------">Sai Balaji</a></figcaption></figure><p>The convolutional neural network works by learning a set of filters that can be used to extract features from the input data. During the training phase, the network adjusts the weights of the filters to minimize the differences between the predicted output and the actual output. The process of adjusting the weights is called back-propagation.</p><p><strong>Use Cases:</strong></p><ul><li>Object detection</li><li>Image segmentation</li><li>Video analysis</li><li>Images restoration</li></ul><blockquote>The MLOps difference? Visibility, reproducibility, and collaboration. <a href="https://go.comet.ml/ebook-Building-Effective-ML-Teams.html?utm_source=heartbeat&amp;utm_medium=referral&amp;utm_campaign=AMS_US_EN_MQL_heartbeat_CTA">Learn more about building effective ML teams with our free ebook.</a></blockquote><h4><strong>Recurrent neural networks (RNNs)</strong></h4><p>A recurrent network is a type of neural network that is good for sequential data processing tasks. A recurrent neural network is designed to handle data like time-series data or natural language processing texts.</p><p>RNNs use a hidden state which allows them to update at each step and the hidden state is passed through the network to allow the processing of a sequence of varying length. The architecture of the RNN consists hidden layers that have a connection to both the input and output layered. The hidden layer is meant to maintain a memory of the input sequence and this memory is updated each time step as the network receives new input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*upwhkADFI0AA4Lkqi2QlaA.png" /><figcaption>image by dataaspirant.com</figcaption></figure><p>A recurrent neural network uses a series of weights and biases to update the hidden state at every time step. The hidden state is represented as a vector and is updated base on the current input and the previous hidden state. In a language modeling task, the input vector might represent a single word in a sentence. The output vector can then be used to make predictions or classifications based on the input sequence.</p><p><strong>Use Cases:</strong></p><ul><li>Language modeling</li><li>Time-series analysis</li><li>Speech recognition</li><li>Sentiment analysis</li></ul><h4><strong>Generative Adversarial Network</strong></h4><p>Generative Adversarial Networks are a type of neural network that are used to generate new data samples that are similar to a given dataset. A Generative Adversarial Network has two sub-networks: a generator network and a discriminator network. The generator network is responsible for generating new sample data while the discriminate network is for evaluating whether a given data sample is either real or fake. During training, the generator network learns to generate more realistic data samples that are more difficult for the discriminate network to identify as fake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xxvNE5K807nCRORM28AGQw.png" /><figcaption>image by unite.ai</figcaption></figure><p>GANs work by training the generator and the discriminator networks at the same time using a process known as adversarial training. In each training iteration, the generator generates a batch of new data samples which will then be evaluated by the discriminator network. The discriminator network is trained on both fake and real data samples to aid its ability to differentiate between the two.</p><p><strong>Use Cases:</strong></p><ul><li>Image synthesis</li><li>Video synthesis</li><li>Data augmentation</li><li>Style transfer</li></ul><h3><strong>Conclusion</strong></h3><p>As a result of allowing machines to learn from data and carry out complex tasks that were previously considered to be only humanly possible, deep learning algorithms have revolutionized the field of artificial intelligence.</p><p>Among the methods used in deep learning are neural networks, convolutional neural networks, recurrent neural networks, and generative adversarial networks. It is possible that new and more complex algorithms will be created as the field develops, producing even more remarkable systems.</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=7557f3c48369" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/understanding-popular-algorithms-in-deep-learning-7557f3c48369">Understanding Popular Algorithms in Deep Learning</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[Pneumonia Diagnosis Detection with OpenCV]]></title>
            <link>https://heartbeat.comet.ml/pneumonia-diagnosis-detection-with-opencv-23dab22e7d94?source=rss-bd97610a8ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/23dab22e7d94</guid>
            <category><![CDATA[heartbeat]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sandy M.]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 11:24:04 GMT</pubDate>
            <atom:updated>2023-04-11T11:24:04.045Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJg_0hfDZoooJRFLZczhcw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nci?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">National Cancer Institute</a> on <a href="https://unsplash.com/photos/tFkXIxtYVjw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Pneumonia is a severe respiratory illness brought on by an infection that, particularly in groups at risk, can have life-threatening complications. It is essential to diagnose and treat pneumonia as soon as possible to maximize the patient’s chances of recovery. The process of diagnosis is not easy and requires some medical laboratory tools and advanced medical skill, but we can use deep learning and computer vision to build a fast and easy tool that will help doctors be able to detect pneumonia.</p><p>Applications for image and video analysis, such as x-ray results, can be created using the open-source computer vision and machine learning software library known as <a href="https://opencv.org/">OpenCV</a> (Open Source Computer Vision). Open CV is an open-source library for carrying out computer vision, machine learning, and image processing. We will discover how to use OpenCV to identify pneumonia in chest X-ray images in this lesson.</p><h4><strong>Install OpenCV</strong></h4><p>Installing OpenCV is the initial stage. There are various methods to install OpenCV depending on your operating system. Here are a few well-liked choices:</p><p>Windows: On the main <a href="https://opencv.org/releases/">OpenCV website</a> use the pre-built binaries.</p><p>Linux: OpenCV can be installed using the package manager included with your Linux distro. Run the following instruction in the terminal, for instance, on Ubuntu:</p><pre>Install libopencv-dev with sudo apt-get</pre><p>Mac OS: OpenCV can be set up using Homebrew the code below should be entered into the terminal.</p><pre>Brew install opencv</pre><p>Once OpenCV is loaded, you can use the following Python code to check that it is working properly.</p><pre>import cv2<br>print(cv2.__version__)</pre><p>You should see the version number displayed in the terminal if OpenCV was properly installed.</p><h4><strong>Download the Dataset</strong></h4><p>The dataset that will be used to train our pneumonia detection algorithm can be downloaded next. We’ll make use of the Chest X-Ray pictures (Pneumonia) <a href="https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia">dataset </a>from Kaggle in this exercise. There are 5,856 chest X-ray images overall in the dataset, divided into two categories: pneumonia and normal.</p><p>You must sign up for a Kaggle account and agree to the dataset’s terms and conditions in order to obtain the dataset. Once you’ve done that, type the following command in the terminal to obtain the dataset:</p><pre>kaggle datasets download -d paultimothymooney/chest-xray-pneumonia</pre><p>A ZIP file containing the information will be downloaded. Create a subfolder on your local computer and extract the ZIP file.</p><h4>Prepare the Data</h4><p>The data must then be prepared for our pneumonia recognition model’s training. To create more training samples from the current ones, we’ll employ a method called data augmentation. This is done to increase the performance of the model and help the model build faster. In order to create different versions of the same picture, data augmentation involves applying random transformations to the images, such as rotation, scaling, and flipping.</p><p>We will make two directories to prepare the data: one for training pictures and one for validation images. 80% of the pictures will be used for training, and 20% will be used for validation.</p><p>Here is the code to get the info ready:</p><pre>import os<br>import shutil<br>import random<br><br># Define the paths<br>input_dir = &#39;path/to/input/dir&#39;<br>train_dir = &#39;path/to/train/dir&#39;<br>val_dir = &#39;path/to/val/dir&#39;<br><br># Create the directories<br>os.makedirs(train_dir, exist_ok=True)<br>os.makedirs(val_dir, exist_ok=True)<br><br># Get the list of images<br>image_paths = []<br>for root, dirs, files in os.walk(input_dir):<br>    for file in files:<br>        if file.endswith(&#39;.jpeg&#39;):<br>            image_paths.append(os.path.join(root, file))<br><br># Shuffle the images<br>random.shuffle(image_paths)<br><br># Split<br><br>split_idx = int(0.8 * len(image_paths))<br>train_image_paths = image_paths[:split_idx]<br>val_image_paths = image_paths[split_idx:]</pre><p>Now copy the images to the directories. Change “path/to/input/dir” to the path to the directory where you extracted the information in this code. The paths to the directories where you want to keep the training and validation images, respectively, should be substituted for “path/to/train/dir” and “path/to/val/dir.”</p><blockquote>Struggling to track and reproduce complex experiment parameters? Artifacts are just one of the many tools in the Comet toolbox to help ease model management. <a href="https://www.comet.com/site/blog/debugging-your-machine-learning-models-with-comet-artifacts/?utm_source=heartbeat&amp;utm_medium=referral&amp;utm_campaign=AMS_US_EN_AWA_heartbeat_CTA">Read our PetCam scenario to learn more.</a></blockquote><h4><strong>Train the model</strong></h4><p>Using the training images we created in the previous stage, we must now train the pneumonia detection model. The core of our model will be a pre-trained convolutional neural network (CNN) named <a href="https://keras.io/api/applications/vgg/">VGG16</a>. The popular CNN architecture VGG16 has attained state-of-the-art success on numerous image recognition tasks after being trained on a sizable dataset of images.</p><p>Here’s the code to train the model:</p><pre>from tensorflow.keras.models import Model<br>from tensorflow.keras.layers import Dense, GlobalAveragePooling2D<br>from tensorflow.keras.applications import VGG16<br>from tensorflow.keras.preprocessing.image import ImageDataGenerator<br><br># Define the input shape of the images<br>input_shape = (224, 224, 3)<br><br># Load the VGG16 model<br>base_model = VGG16(weights=&#39;imagenet&#39;, include_top=False, input_shape=input_shape)<br><br># Add a global average pooling layer<br>x = base_model.output<br>x = GlobalAveragePooling2D()(x)<br><br># Add a fully connected layer<br>x = Dense(128, activation=&#39;relu&#39;)(x)<br><br># Add the output layer<br>output = Dense(1, activation=&#39;sigmoid&#39;)(x)<br><br># Define the model<br>model = Model(inputs=base_model.input, outputs=output)<br><br># Freeze the layers of the VGG16 model<br>for layer in base_model.layers:<br>    layer.trainable = False<br><br># Compile the model<br>model.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br><br># Define the data generators for training and validation<br>train_datagen = ImageDataGenerator(rescale=1./255,<br>                                   rotation_range=10,<br>                                   width_shift_range=0.1,<br>                                   height_shift_range=0.1,<br>                                   shear_range=0.1,<br>                                   zoom_range=0.1,<br>                                   horizontal_flip=True,<br>                                   fill_mode=&#39;nearest&#39;)<br><br>val_datagen = ImageDataGenerator(rescale=1./255)<br><br>train_generator = train_datagen.flow_from_directory(train_dir,<br>                                                    target_size=input_shape[:2],<br>                                                    batch_size=32,<br>                                                    class_mode=&#39;binary&#39;)<br><br>val_generator = val_datagen.flow_from_directory(val_dir,<br>                                                target_size=input_shape[:2],<br>                                                batch_size=32,<br>                                                class_mode=&#39;binary&#39;)<br><br># Train the model<br>model.fit(train_generator,<br>          steps_per_epoch=len(train_generator),<br>          epochs=10,<br>          validation_data=val_generator,<br>          validation_steps=len(val_generator))<br><br></pre><p>First, we loaded the pre-trained weights from the ImageNet dataset into the VGG16 model. We also include an output layer with a sigmoid activation function, a completely connected layer with 128 neurons, and a global average pooling layer. The VGG16 model’s layers are frozen, and the Adam algorithm and binary cross-entropy loss are used to build the model. Following that, we specify data generators for training and validation that augment the data and rescale the pixel values to the [0, 1] range.</p><p>Using the fit approach and the training and validation data generators, we train the model for 10 epochs.</p><h4><strong>Evaluate the model</strong></h4><p>To determine how well the model generalizes to new data after training, we must evaluate its performance on a test set. To evaluate the model, we will make use of the dataset’s test collection. Additionally, we will display some illustrations of both properly and incorrectly classified images.</p><p>Use the code below to evaluate the model and display some instances.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Define the path to the test directory<br>test_dir = &#39;path/to/input/dir/chest_xray/test&#39;<br><br># Define the data generator for test<br>test_datagen = ImageDataGenerator(rescale=1./255)<br><br>test_generator = test_datagen.flow_from_directory(test_dir,<br>                                                  target_size=input_shape[:2],<br>                                                  batch_size=32,<br>                                                  class_mode=&#39;binary&#39;,<br>                                                  shuffle=False)<br><br># Evaluate the model on the test set<br>loss, accuracy = model.evaluate(test_generator, steps=len(test_generator))<br>print(f&#39;Test accuracy: {accuracy:.2f}&#39;)<br><br># Get the predictions and true labels<br>predictions = model.predict(test_generator, steps=len(test_generator))<br>predictions = np.squeeze(predictions)<br>true_labels = test_generator.labels<br><br># Get the image filenames<br>filenames = test_generator.filenames<br><br># Find the indices of the correctly and incorrectly classified images<br>correct_indices = np.where((predictions &gt;= 0.5) == true_labels)[0]<br>incorrect_indices = np.where((predictions &gt;= 0.5) != true_labels)[0]<br><br># Plot some correctly classified images<br>plt.figure(figsize=(10, 10))<br>for i, idx in enumerate(correct_indices[:9]):<br>    plt.subplot(3, 3, i+1)<br>    img = plt.imread(os.path.join(test_dir, filenames[idx]))<br>    plt.imshow(img, cmap=&#39;gray&#39;)<br>    plt.title(&#39;PNEUMONIA&#39; if predictions[idx] &gt;= 0.5 else &#39;NORMAL&#39;)<br>    plt.axis(&#39;off&#39;)<br><br># Plot some incorrectly classified images<br>plt.figure(figsize=(10, 10))<br>for i, idx in enumerate(incorrect_indices[:9]):<br>    plt.subplot(3, 3, i+1)<br>    img = plt.imread(os.path.join(test_dir, filenames[idx]))<br>    plt.imshow(img, cmap=&#39;gray&#39;)<br>    plt.title(&#39;PNEUMONIA&#39; if predictions[idx] &gt;= 0.5 else &#39;NORMAL&#39;)<br>    plt.axis(&#39;off&#39;)<br><br>plt.show()</pre><p>In this code, we created a test and evaluation set data generator to assess the model. We also get the predictions and true labels for the test set and find the indices of the correctly and incorrectly classified images. Then, using Matplotlib, we plot some instances of properly and incorrectly classified images.</p><h4><strong>Conclusion</strong></h4><p>In this tutorial, we built a pneumonia detection model using OpenCV and TensorFlow. We read, processed, and visualized the images using OpenCV, and we trained and tested the model using TensorFlow. The model was successful in classifying the majority of the test set’s images with a high degree of precision.</p><p>Computer vision can be a huge asset to medical diagnostics. While they’re not a replacement for trained healthcare providers, they can decrease time to diagnosis and improve diagnostic accuracy. You can see more CV medical use-cases in action <a href="https://arxiv.org/pdf/2203.15269.pdf">here.</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=23dab22e7d94" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/pneumonia-diagnosis-detection-with-opencv-23dab22e7d94">Pneumonia Diagnosis Detection with OpenCV</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[Unlocking the Power of Data: Understanding the concepts of Databases, Data Warehouses, and Data…]]></title>
            <link>https://medium.com/@sandy_m/unlocking-the-power-of-data-understanding-the-concepts-of-databases-data-warehouses-and-data-c5ffcff7ea2?source=rss-bd97610a8ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5ffcff7ea2</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-lake]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Sandy M.]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 13:10:46 GMT</pubDate>
            <atom:updated>2023-03-13T15:03:08.816Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unlocking the Power of Data: Understanding the concepts of Databases, Data Warehouses, and Data Lakes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dxc8nGTt5ibtc7iYjQOiOQ.jpeg" /><figcaption>Photo by Christina Morillo: <a href="https://www.pexels.com/photo/software-engineer-standing-beside-server-racks-1181354/">https://www.pexels.com/photo/software-engineer-standing-beside-server-racks-1181354/</a></figcaption></figure><p>Data is produced at an unprecedented rate in the digital age, so it is crucial for companies to effectively manage and use this data. Three key concepts - databases, data warehouses, and data lakes - that are essential to this job are frequently misunderstood or used interchangeably. In this piece, we will examine the distinctions between these three ideas, their potential applications, and how to use them to unleash the power of data.</p><p><strong>What is a Database?</strong></p><p>A structured collection of data that has been managed and organized for a particular reason is referred to as a database. Databases hold data in tables with rows and columns, where each row denotes a record or instance of the data and each column denotes a field or attribute. Data of all kinds, including client information, product details, financial information, and much more, can be stored in databases.</p><p><strong>Types of Databases</strong></p><p>There are different kinds of databases, each created for a particular use case. The following are a few of the popular database types:</p><ul><li>Relational databases: The most popular kind of database is a relational database. They keep data in databases with connections between them already established. Structured Query Language (SQL) is a data manipulation language used by relational systems.</li><li>NoSQL databases: are non-relational databases that don&#39;t use tables to organize data. In addition to structured data, they can also hold unstructured data like writing, images, and videos. NoSQL systems are made to be scalable, highly available, and extremely fast.</li><li>Object-Oriented Databases: Databases that are object-oriented are made to hold objects rather than just data. They enable developers to store complicated data structures like networks and graphs and can manage complex relationships and queries.</li></ul><p><strong>What is a Data Warehouse?</strong></p><p>A data warehouse is a sizable, centralized database that supports business information operations. Data warehouses gather information from various sources, standardize it, and store it in a way that makes it easy to access and analyze. Data warehouses offer past and current data that can be used to spot trends, patterns, and relationships, supporting decision-making processes.</p><p><strong>Characteristics of Data Warehouses</strong></p><p>Data warehouses can be distinguished from other kinds of datasets by a number of features. Several of the essential traits include:</p><ul><li>Subject-Oriented: Data warehouses that are subject-oriented are built to assist industries like sales, marketing, or finance. These topics serve as the framework around which the data in a data repository is arranged to facilitate analysis and comprehension.</li><li>Time-Variant: By storing historical data, data warehouses allow users to evaluate data over time and spot trends and patterns. This function is especially helpful for predicting and forecasting upcoming trends.</li><li>Non-Volatile: Data warehouses are non-volatile, which means that after being added to the warehouse, the data cannot be altered or removed. By doing this, historical data is guaranteed to be preserved and usable for research in the future.</li></ul><p><strong>What is a Data Lake?</strong></p><p>A data lake is a sizable storage space where unedited, raw data is kept. Data lakes store data from various sources, including structured and unstructured data, without the need for previous organization or transformation, in contrast to conventional data storage techniques. Big data analytics, machine learning, and other data-intensive apps are all supported by data lakes.</p><p><strong>Characteristics of Data Lakes</strong></p><p>Data lakes can be distinguished from other kinds of data storage by a number of features. Several of the essential traits include:</p><ul><li>Flexibility: Text, images, video, and audio are just a few of the many data types and formats that data lakes are built to handle. Since data can be kept in its unprocessed state, processing and analyzing it can be done with more flexibility and variety.</li><li>Scalability: Data lakes are capable of storing petabyte- and exabyte-sized quantities of data. Organizations can keep and analyze massive amounts of data thanks to this scalability without investing in costly infrastructure.</li><li>Cost-Effectiveness: For storing and processing large amounts of data, data lakes are an affordable option. They eliminate the need for numerous data storage solutions by enabling organizations to store data in a single place.</li></ul><p><strong>Use case of Database, Data warehouse, and Data lake</strong></p><p>Applications that need fast and accurate data processing, like online banking or e-commerce websites, use databases. Data warehouses are used for reporting and analysis tasks like client segmentation and sales analysis. Data lakes are used for machine learning and exploratory analysis, such as fraud discovery or predictive maintenance.</p><p><strong>Conclusion</strong></p><p>In conclusion, databases, data warehouses, and data lakes are created for various kinds of data processing and have different functions. Data lakes are used for exploratory analysis and machine learning, while data warehouses are designed for transactional processing. Organizations that want to successfully manage their data and make wise business decisions must comprehend the differences between these three ideas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5ffcff7ea2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentiment Analysis With SparkNLP and Comet]]></title>
            <link>https://heartbeat.comet.ml/sentiment-analysis-with-sparknlp-and-comet-14a09eedcb46?source=rss-bd97610a8ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/14a09eedcb46</guid>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[heartbeat]]></category>
            <category><![CDATA[comet]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[spark-nlp]]></category>
            <dc:creator><![CDATA[Sandy M.]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 14:16:05 GMT</pubDate>
            <atom:updated>2023-02-21T14:16:05.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A desk full of graphs and charts with a magnifying glass, a few pens, and a pair of eyeglasses lying on top." src="https://cdn-images-1.medium.com/max/1024/1*crmBmr5sXOkj44ZNzZY2fw.jpeg" /><figcaption>Picture by <a href="https://www.pexels.com/@anna-nekrashevich/">Anna Nekrashevich</a>, Pexels.com</figcaption></figure><h3>Introduction</h3><p>Sentiment analysis is a natural language processing technique which identifies and extracts subjective information from source materials using computational linguistics and text analysis. It is employed to ascertain a speaker’s or writer’s feelings, attitudes, and opinions with regard to a particular subject or general contextual polarity of a work. Applications for sentiment analysis include market research, customer service, and social media monitoring. Among other things, companies use it to get insight from their customers on social media and know what is being said about their products.</p><p>Spark NLP is a natural language processing library built on Apache Spark. It is used to carry out precise annotation for machine learning pipelines that can scale quickly in a distributed environment.</p><p>We will build a pipeline for performing sentiment analysis on text data using the Spark NLP library and use Comet to monitor the metrics of our model. Comet is an online platform that allows you to track and monitor logs experiments and we are using Comet in this tutorial to track the metrics of our model.</p><p>But first, let’s understand how sentiment analysis works.</p><h3>Sentiment Analysis</h3><p>One common approach to sentiment analysis is using supervised machine learning techniques to classify text into various sentiment categories, such as positive, negative, or neutral. This is often done by training a classifier on a labeled dataset of text, where each piece of text has been manually annotated with a sentiment label. Once the classifier is trained, it can be used to classify new text into the appropriate sentiment category.</p><p>Another approach is to use lexicon-based methods, which involve looking up words or phrases in a pre-defined lexicon to determine the sentiment. This can be done by using a lexicon of positive and negative words and counting the number of positive and negative words in the text. The sentiment of the text is then determined based on the ratio of positive to negative words.</p><blockquote>How does the team at Uber manage to keep their data organized and their team united? Comet’s experiment tracking. <a href="https://www.comet.com/site/customers/uber/">Learn more from Uber’s Olcay Cirit</a>.</blockquote><p>Now let’s begin by installing the necessary packages:</p><pre>​​pip install spark-nlp==4.2.6<br>pip install comet_ml</pre><figure><img alt="A screenshot of the Comet ML homepage with the logo “less friction, more ML.”" src="https://cdn-images-1.medium.com/max/1024/1*cX2fG8Jwc8_bIYfiAcUR5Q.png" /><figcaption>Comet homepage</figcaption></figure><p>If you don’t already have a Comet account, you can <a href="http://www.comet.com/site">create one here</a>. Once your account is set up, you can manually create a project from the UI, or, as you’ll see in this tutorial, we can create our project with a simple experiment parameter.</p><figure><img alt="A screenshot of the Comet ML interface when manually creating a new project; there is a text box with options for “Name,” “Description,” and “Project Visibility.”" src="https://cdn-images-1.medium.com/max/1024/1*9beLdArlH7aWPPIBWVgfEQ.png" /><figcaption>Creating a new Comet project manually in the UI</figcaption></figure><p>After creating an account, navigate to the top right of the Comet website and click on your avatar. Then select Account Settings and finally pick the API keys tab and generate an API key.</p><figure><img alt="A screenshot of the Account Settings tab within the Comet UI indicating where to find your personalized API key." src="https://cdn-images-1.medium.com/max/1024/1*U7mC-awhcIX-sfw7Rm7wNA.png" /><figcaption>Getting API keys</figcaption></figure><p>Now let’s import our libraries:</p><pre># Import Spark NLP<br>import sparknlp<br>from sparknlp.base import *<br>from sparknlp.annotator import *<br>from sparknlp.pretrained import PretrainedPipeline<br><br><br>from pyspark.ml import Pipeline<br>from pyspark.sql import SparkSession<br>import pyspark.sql.functions as F<br> <br>spark = sparknlp.start()<br> <br># Import comet<br>import comet_ml<br>from sparknlp.logging.comet import CometLogger</pre><p>Note that <a href="https://nlp.johnsnowlabs.com/api/python/third_party/Comet.html">Comet integrates with Spark automatically</a>. Next, we instantiate our experiment object:</p><pre>experiment = comet_ml.Experiment(&quot;YOUR-API-KEY&quot;)</pre><p>Now we’ll give our project a name using the project_name parameter:</p><pre>comet_ml.init(project_name=&#39;test-sparknlp &#39;)</pre><p>Next, we start Spark, set the logger, and set an output log path:</p><pre>spark = sparknlp.start()<br>logger = CometLogger()<br>OUTPUT_LOG_PATH = &quot;./run&quot;</pre><h3>Building the pipeline</h3><p>We have five stages in our pipeline:</p><ol><li>The first stage is the DocumentAssembler, which creates a column from the text that is imputed. This allows us to easily use the text when we want to train the model.</li></ol><pre># Create a document assembler<br>document = DocumentAssembler() \<br>    .setInputCol(&quot;text&quot;) \<br>    .setOutputCol(&quot;document&quot;)</pre><p>2. The second stage is the Tokenizer, which tokenizes the text from the document column into separate words in the output as token. We don&#39;t know what the input text will look like, so we’ll have to format it to fit our guidelines by slicing sentences into words that our model can easily digest.</p><pre># Create a tokenizer<br>token = Tokenizer() \<br>    .setInputCols([&quot;document&quot;]) \<br>    .setOutputCol(&quot;token&quot;)</pre><p>3. The third step is the Normalizer, which removes the punctuation from the token column, makes the text lowercase, and then saves the output column as normal.</p><pre># Create a normalizer<br>normalizer = Normalizer() \<br>    .setInputCols([&quot;token&quot;]) \<br>    .setOutputCol(&quot;normal&quot;)</pre><p>4. The fourth step is instantiating the ViveknSentimentModel. Here we’re using a pre-trained model to classify the sentiment of the text as positive, negative, or neutral by taking the document and normal columns as input and setting its output column to result_sentiment. Now we’re ready to actually train the model on our dataset.</p><pre># Load a pretrained sentiment analysis model<br>vivekn = ViveknSentimentModel.pretrained() \<br>    .setInputCols([&quot;document&quot;, &quot;normal&quot;]) \<br>    .setOutputCol(&quot;result_sentiment&quot;)</pre><p>5. The fifth stage takes the output of the previous stage, result_sentimentand sets the final output column as final_sentiment. The aim is just to generate a final sentiment output for the user and save it as finisher.</p><pre># Create a finisher<br>finisher = Finisher() \<br>    .setInputCols([&quot;result_sentiment&quot;]) \<br>    .setOutputCols(&quot;final_sentiment&quot;)<br><br>logger.monitor(logdir=OUTPUT_LOG_PATH, model=vivekn)<br><br># Create a pipeline with all the stages<br>pipeline = Pipeline().setStages([document, token, normalizer, vivekn, finisher])<br></pre><p>After creating the pipeline, let’s fit in a small dataset of two sentences and get the sentiment of each of them displayed.</p><pre># Create the data as a Spark dataframe<br>data = spark.createDataFrame([<br>    [&quot;I recommend this movie&quot;],<br>    [&quot;Dont waste your time!!!&quot;]<br>]).toDF(&quot;text&quot;)<br> <br># Fit the pipeline to the data<br>pipelineModel = pipeline.fit(data)<br><br># Transform the data and show the final sentiment<br>result = pipelineModel.transform(data)<br>result.select(&quot;final_sentiment&quot;).show(truncate=False)<br>logger.log_pipeline_parameters(pipelineModel)<br>logger.end()</pre><figure><img alt="Screenshot of a dark mode IDE that defines the pipeline in Python for SparkNLP." src="https://cdn-images-1.medium.com/max/1024/1*n6U624hwxxpIKB2XHHb0Lg.png" /></figure><p>Now you can see the sentiment of the text that you passed it. You can display the evaluation metrics directly in your interactive notebook using the code below, or head over to the Comet UI to check out the results more in-depth.</p><figure><img alt="A screenshot of the output of the model to the Comet interface." src="https://cdn-images-1.medium.com/max/1024/1*Z323ED0GjCPzTxzA64-dgQ.png" /><figcaption>Comet dashboard</figcaption></figure><h3>Conclusion</h3><p>This is how to build a sentiment analysis pipeline with SparkNLP, while also using Comet to track your project metrics. You can check out the code on this <a href="https://colab.research.google.com/drive/1l5Q73ipjA9QTUZjngfi9VrcN9Tl_kD8F?usp=sharing">Colab notebook</a> to easily get started. There are many other cool ways to use Comet and you can check them out and try more examples from their <a href="https://www.comet.com/docs/v2/">documentation</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=14a09eedcb46" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/sentiment-analysis-with-sparknlp-and-comet-14a09eedcb46">Sentiment Analysis With SparkNLP 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>
    </channel>
</rss>