<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: thebadcoder</title>
    <description>The latest articles on DEV Community by thebadcoder (@thebadcoder96).</description>
    <link>https://dev.to/thebadcoder96</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1270417%2Fd7651cdc-47fa-4821-8480-23c8d03f8935.jpeg</url>
      <title>DEV Community: thebadcoder</title>
      <link>https://dev.to/thebadcoder96</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/thebadcoder96"/>
    <language>en</language>
    <item>
      <title>The Sustainability Impacts of ChatGPT: A Comprehensive Analysis</title>
      <dc:creator>thebadcoder</dc:creator>
      <pubDate>Wed, 17 Apr 2024 14:44:01 +0000</pubDate>
      <link>https://dev.to/thebadcoder96/the-sustainability-impacts-of-chatgpt-a-comprehensive-analysis-2ll8</link>
      <guid>https://dev.to/thebadcoder96/the-sustainability-impacts-of-chatgpt-a-comprehensive-analysis-2ll8</guid>
      <description>&lt;p&gt;Large Language Models (LLMs) like GPT (Generative Pre-trained Transformer) and LLaMA (Large Language Model Meta AI) have revolutionized the way we interact with data and machines, providing deep insights and enhancing human-machine interactions. As transformative as LLMs are for tasks like translation, content generation, and customer support, they come with substantial environmental costs primarily due to their high energy demands.&lt;/p&gt;

&lt;p&gt;This article provides an essential technical backdrop, how LLMs affect our environment, the ongoing efforts to mitigate these effects, and how policies and personal actions can contribute to more sustainable AI practices.&lt;/p&gt;

&lt;h2&gt;
  
  
  What are Large Language Models?
&lt;/h2&gt;

&lt;p&gt;ChatGPT, Claude, Gemini, and yes BERT (Bidirectional Encoder Representations from Transformers) are all Large Language Models but what are they and why are they so energy extensive?&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1712002641366-f59bbbee71c7%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wzMDAzMzh8MHwxfHNlYXJjaHwzM3x8Y2hhdGdwdHxlbnwwfHx8fDE3MTMyNzUxMDV8MA%26ixlib%3Drb-4.0.3%26q%3D80%26w%3D1080" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1712002641366-f59bbbee71c7%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wzMDAzMzh8MHwxfHNlYXJjaHwzM3x8Y2hhdGdwdHxlbnwwfHx8fDE3MTMyNzUxMDV8MA%26ixlib%3Drb-4.0.3%26q%3D80%26w%3D1080" title="a person holding a cell phone with icons on the screen" alt="a person holding a cell phone with icons on the screen"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Large Language Models (LLMs) are a type of artificial intelligence system that is trained on vast amounts of text data, allowing them to generate human-like responses, understand and process natural language, and perform a wide range of language-related tasks. It is like looking for patterns in the texts to figure out what to say back to you, and these texts are huge amounts of articles/books/posts/etc., also called training data.&lt;/p&gt;

&lt;p&gt;Essentially, LLMs work by using neural networks to identify patterns and relationships in the training data, which can then be used to generate new text, answer questions, translate between languages, and more. These neural networks have layers of algorithms, each designed to recognize different elements of human language, from simple grammar to complex idioms and mainly context.&lt;/p&gt;

&lt;p&gt;If you enjoy reading this so far, Subscribe for free and &lt;a href="https://www.linkedin.com/in/mishalsalim/" rel="noopener noreferrer"&gt;follow me&lt;/a&gt; for more content :)&lt;/p&gt;

&lt;p&gt;The training process involves repeatedly adjusting these layers to minimize errors in output, requiring multiple iterations across potentially billions of parameters. For example, GPT-3 has &lt;strong&gt;about 175 billion&lt;/strong&gt; parameters. It is trained on about &lt;strong&gt;45TB&lt;/strong&gt; of text data from different datasets. This, right now, is a medium to small LLM. The more ‘better’ a model is the more complex and resource-intensive it gets.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fsubstackcdn.com%2Fimage%2Ffetch%2Fw_1456%2Cc_limit%2Cf_auto%2Cq_auto%3Agood%2Cfl_progressive%3Asteep%2Fhttps%253A%252F%252Fsubstack-post-media.s3.amazonaws.com%252Fpublic%252Fimages%252Fa6c9da08-2fe6-4d75-9f4d-18b7b655718d_847x936.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fsubstackcdn.com%2Fimage%2Ffetch%2Fw_1456%2Cc_limit%2Cf_auto%2Cq_auto%3Agood%2Cfl_progressive%3Asteep%2Fhttps%253A%252F%252Fsubstack-post-media.s3.amazonaws.com%252Fpublic%252Fimages%252Fa6c9da08-2fe6-4d75-9f4d-18b7b655718d_847x936.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Source: &lt;a href="https://informationisbeautiful.net/visualizations/the-rise-of-generative-ai-large-language-models-llms-like-chatgpt/" rel="noopener noreferrer"&gt;Information is Beautiful&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This computation is not only data-intensive (remember the huge amounts of training data?) but also requires a lot of electrical power, typically executed on specialized hardware like GPUs (Graphics Processing Units) or TPUs (Tensor Processing Units). You can already see the storage, training/processing, and operational costs that it can incur.&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding the Environmental Impacts of LLMs
&lt;/h2&gt;

&lt;p&gt;Each phase of the LLMs has its own footprint:&lt;/p&gt;

&lt;h3&gt;
  
  
  Training Impacts:
&lt;/h3&gt;

&lt;p&gt;The training process requires considerable computational resources, typically involving multiple high-powered GPUs or TPUs that run continuously for weeks or even months. This consumes large amounts of electricity, contributing to the carbon footprint of LLMs. All these AI companies boast about how amazing and powerful their new model is, and how much information it can process but they rarely discuss the computational and environmental cost of said models.&lt;/p&gt;

&lt;p&gt;For example, students from the University of Copenhagen developed a tool to predict the &lt;a href="https://aibusiness.com/nlp/danish-students-develop-tool-to-measure-the-carbon-footprint-of-ai" rel="noopener noreferrer"&gt;carbon footprint of algorithms&lt;/a&gt; and found that one training session with GPT-3 uses the &lt;strong&gt;same amount of energy that is needed by 126 homes&lt;/strong&gt; in Denmark annually.&lt;/p&gt;

&lt;p&gt;Another &lt;a href="https://arxiv.org/pdf/1906.02243v1.pdf" rel="noopener noreferrer"&gt;famous study&lt;/a&gt; by researchers at the University of Massachusetts, Amherst, performed an analysis of the carbon footprint of transformer models.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fsubstackcdn.com%2Fimage%2Ffetch%2Fw_1456%2Cc_limit%2Cf_auto%2Cq_auto%3Agood%2Cfl_progressive%3Asteep%2Fhttps%253A%252F%252Fsubstack-post-media.s3.amazonaws.com%252Fpublic%252Fimages%252Ff417f257-27f1-4dcd-9141-397a4f982ac3_639x231.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fsubstackcdn.com%2Fimage%2Ffetch%2Fw_1456%2Cc_limit%2Cf_auto%2Cq_auto%3Agood%2Cfl_progressive%3Asteep%2Fhttps%253A%252F%252Fsubstack-post-media.s3.amazonaws.com%252Fpublic%252Fimages%252Ff417f257-27f1-4dcd-9141-397a4f982ac3_639x231.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Source: &lt;a href="https://www.technologyreview.com/2019/06/06/239031/training-a-single-ai-model-can-emit-as-much-carbon-as-five-cars-in-their-lifetimes/" rel="noopener noreferrer"&gt;MIT Technology Review&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;They found that a simple transformer with around 213 million parameters emits almost 5 times the lifetime emissions of the average American car or about 315 round trip flights from New York to San Francisco.&lt;/p&gt;

&lt;p&gt;Just to put things in perspective, let’s see what an actual model’s carbon footprint is like. A simple 213-parameter model produces &lt;strong&gt;626,155 lbs of CO2&lt;/strong&gt;. Claude 3 is rumored to have &lt;strong&gt;500 billion parameters&lt;/strong&gt;. Let’s assume a linear scaling (for our simple brain to comprehend), which would be an increase of &lt;strong&gt;2348x&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;So 626,155 x 2348 is a whopping &lt;strong&gt;1,469,456,540 or 1.5 Billion lbs of CO2&lt;/strong&gt; for a model like Claude 3 that we are using nowadays.&lt;/p&gt;

&lt;p&gt;This is of course due to the energy-intensive nature of the training process, which involves running the model through billions of computations. But why companies are shy about revealing such numbers?&lt;/p&gt;

&lt;h3&gt;
  
  
  Storage and Operational Impacts:
&lt;/h3&gt;

&lt;p&gt;The data centers that power LLMs are also a major source of environmental impact. These facilities require large amounts of energy for cooling, ventilation, and other operational needs. They also generate e-waste from the constant upgrading and replacement of hardware.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1558494949-ef010cbdcc31%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wzMDAzMzh8MHwxfHNlYXJjaHwxfHxkYXRhJTIwY2VudGVyfGVufDB8fHx8MTcxMzI4NDcxNHww%26ixlib%3Drb-4.0.3%26q%3D80%26w%3D1080" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1558494949-ef010cbdcc31%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wzMDAzMzh8MHwxfHNlYXJjaHwxfHxkYXRhJTIwY2VudGVyfGVufDB8fHx8MTcxMzI4NDcxNHww%26ixlib%3Drb-4.0.3%26q%3D80%26w%3D1080" title="cable network" alt="cable network"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A recent &lt;a href="https://arxiv.org/pdf/2304.03271.pdf" rel="noopener noreferrer"&gt;study&lt;/a&gt; at the University of California, Riverside, revealed the significant water footprint of LLMs. Microsoft used approximately &lt;strong&gt;700,000 liters of freshwater&lt;/strong&gt; during GPT-3’s training in its data centers which is equal to how much water is needed to make 320 Tesla vehicles.&lt;/p&gt;

&lt;p&gt;I know it says during the training process but the model also uses a lot of water in the inference process (when you are using it). For a brief exchange involving 20-50 queries, the water usage is comparable to a 500 ml bottle. Given its billions of users, the cumulative water footprint for processing these interactions is quite significant. Even if we take 1 billion users that is &lt;strong&gt;500 million liters of water&lt;/strong&gt;; it can fill up around 200 Olympic-sized swimming pools.&lt;/p&gt;

&lt;p&gt;Moreover, the storage and hosting of LLMs, which can be terabytes in size, requires dedicated server infrastructure, further adding to the environmental footprint.&lt;/p&gt;

&lt;p&gt;In response to &lt;a href="https://www.bloomberg.com/news/articles/2023-03-09/how-much-energy-do-ai-and-chatgpt-use-no-one-knows-for-sure?leadSource=uverify%20wall" rel="noopener noreferrer"&gt;Bloomberg&lt;/a&gt; asking OpenAI about the sustainability concern, they had this to say:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;‘OpenAI runs on Azure, and we work closely with Microsoft’s team to improve efficiency and our footprint to run large language models.‘&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Also found these discussions on the &lt;a href="https://community.openai.com/t/sustainable-development-and-ai/377448" rel="noopener noreferrer"&gt;OpenAI Community&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Hardware and Other Impacts:
&lt;/h3&gt;

&lt;p&gt;LLMs also require significant hardware resources, such as high-performance GPUs, storage, and memory. I was reading &lt;a href="https://towardsdatascience.com/the-carbon-footprint-of-chatgpt-66932314627d#:~:text=Carbon%20footprint%20from%20training%20ChatGPT&amp;amp;text=It%20has%20been%20estimated%20that,552%20tons%20CO2e%20%5B1%5D" rel="noopener noreferrer"&gt;this article&lt;/a&gt; when I read the author’s update that they had assumed ChatGPT runs on 16 GPUs, but in fact, it runs on more than 29,000 GPUs. The manufacturing, transportation, and eventual disposal of these hardware can also have environmental impacts.&lt;/p&gt;

&lt;p&gt;This raises concerns about environmental justice, as the resource-intensive nature of these models may disproportionately affect marginalized communities and developing regions that have less access to clean energy and sustainable infrastructure.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to be more sustainable with AI?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1569163139500-66446e2926ca%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wzMDAzMzh8MHwxfHNlYXJjaHwxNXx8c3VzdGFpbmFibGV8ZW58MHx8fHwxNzEzMjk3NjY1fDA%26ixlib%3Drb-4.0.3%26q%3D80%26w%3D1080" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1569163139500-66446e2926ca%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wzMDAzMzh8MHwxfHNlYXJjaHwxNXx8c3VzdGFpbmFibGV8ZW58MHx8fHwxNzEzMjk3NjY1fDA%26ixlib%3Drb-4.0.3%26q%3D80%26w%3D1080" title="Earth is more valuable than money signage" alt="Earth is more valuable than money signage"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As the concerns around the environmental impacts of LLMs have grown, there have been various efforts and advancements to make these models more sustainable. But I can’t lie, I do not feel like these efforts are enough. I am not convinced that the speed of these advancements can keep up with the exponential growth of LLMs and AI.&lt;/p&gt;

&lt;p&gt;Some of the key areas that we need to start or continue focusing on:&lt;/p&gt;

&lt;h3&gt;
  
  
  1. What can companies do?
&lt;/h3&gt;

&lt;p&gt;Companies are investing heavily to reduce the energy consumption of AI tools and models. Some are exploring using carbon offsets to counterbalance the emissions generated by their LLMs. Microsoft, Google, Apple, and Meta all have pledged to be carbon-neutral and net-zero. I mean Google developed tensor processing units (TPUs) that are more energy-efficient than traditional GPUs.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fsubstackcdn.com%2Fimage%2Ffetch%2Fw_1456%2Cc_limit%2Cf_auto%2Cq_auto%3Agood%2Cfl_progressive%3Asteep%2Fhttps%253A%252F%252Fsubstack-post-media.s3.amazonaws.com%252Fpublic%252Fimages%252Facb6a7cd-86fe-47e8-9c45-e5ca36046b28_810x1409.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fsubstackcdn.com%2Fimage%2Ffetch%2Fw_1456%2Cc_limit%2Cf_auto%2Cq_auto%3Agood%2Cfl_progressive%3Asteep%2Fhttps%253A%252F%252Fsubstack-post-media.s3.amazonaws.com%252Fpublic%252Fimages%252Facb6a7cd-86fe-47e8-9c45-e5ca36046b28_810x1409.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Source: &lt;a href="https://www.dentallace.com/blogs/news/45-stats-about-big-tech-s-carbon-footprint-by-tom-read" rel="noopener noreferrer"&gt;Dental Lace&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;But there is still a need for awareness of how much impact AI has on the Earth publicly. Companies need to be transparent with footprints and work with the public to make Earth more sustainable. Not only that, they need to implement renewable and recycling programs.&lt;/p&gt;

&lt;p&gt;This is not just about being green in the public eye; it’s about pushing the sustainable agenda to the forefront and setting industry standards.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. What can developers do?
&lt;/h3&gt;

&lt;p&gt;There is already an emphasis on researching and developing more efficient models. Techniques such as transfer learning, pruning, quantization, knowledge distillation, etc. are being employed to make models more efficient without sacrificing performance.&lt;/p&gt;

&lt;p&gt;Developers should prioritize building and contributing to open-source projects focused on sustainable AI practices. More training in eco-conscious programming can also be embedded in developer education.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. What can policymakers do?
&lt;/h3&gt;

&lt;p&gt;Policymaking plays a crucial role in guiding the development and implementation of AI technologies sustainably. Policies that incentivize energy-efficient AI, set emissions targets, and encourage the use of renewable energy can help drive companies to adopt more sustainable practices.&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://commission.europa.eu/strategy-and-policy/priorities-2019-2024/european-green-deal_en" rel="noopener noreferrer"&gt;EU’s Green Deal&lt;/a&gt; includes specific provisions for digital sector sustainability, aiming to significantly reduce its carbon and electronic waste footprint. The &lt;a href="https://digital-strategy.ec.europa.eu/en/policies/regulatory-framework-ai" rel="noopener noreferrer"&gt;AI Act&lt;/a&gt; is the first-ever legal framework on AI, which addresses the risks of AI. These are a good start but we need more, especially in the US. We need to enact policies that require tech companies to report and reduce their carbon footprints. Transparency in energy consumption should be mandatory, not optional.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. What can YOU do?
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1600493572531-c056ef2eaac4%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wzMDAzMzh8MHwxfHNlYXJjaHwxfHx5b3V8ZW58MHx8fHwxNzEzMjI2NTYwfDA%26ixlib%3Drb-4.0.3%26q%3D80%26w%3D1080" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1600493572531-c056ef2eaac4%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wzMDAzMzh8MHwxfHNlYXJjaHwxfHx5b3V8ZW58MHx8fHwxNzEzMjI2NTYwfDA%26ixlib%3Drb-4.0.3%26q%3D80%26w%3D1080" title="silver framed eyeglasses on yellow surface" alt="silver framed eyeglasses on yellow surface"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Of course, as individuals, raising awareness and supporting green AI initiatives is crucial, but it starts with being well-informed. Understanding the environmental implications of AI use and sharing this knowledge can catalyze collective action toward sustainable practices. Being vocal and using our influence matters significantly.&lt;/p&gt;

&lt;p&gt;Additionally, on the technical side, using concise prompts and selecting models that are efficient in processing can reduce computational demands. By streamlining the complexity and length of prompts and reducing unnecessary interactions, we can significantly cut down on the computational resources needed. This not only conserves energy but also aligns with more sustainable AI usage practices.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;While LLMs offer unprecedented capabilities, their environmental impact cannot be overlooked. It’s clear that bold steps are needed from all stakeholders—companies, developers, policymakers, and users alike. The path to sustainable AI is complex and challenging, but with concerted effort and innovation, it’s possible to harness the benefits of AI without compromising our planet.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fsubstackcdn.com%2Fimage%2Ffetch%2Fw_1456%2Cc_limit%2Cf_auto%2Cq_auto%3Agood%2Cfl_progressive%3Asteep%2Fhttps%253A%252F%252Fsubstack-post-media.s3.amazonaws.com%252Fpublic%252Fimages%252F6c2592ac-8d50-4551-a511-bae27f1d5c5a_717x202.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fsubstackcdn.com%2Fimage%2Ffetch%2Fw_1456%2Cc_limit%2Cf_auto%2Cq_auto%3Agood%2Cfl_progressive%3Asteep%2Fhttps%253A%252F%252Fsubstack-post-media.s3.amazonaws.com%252Fpublic%252Fimages%252F6c2592ac-8d50-4551-a511-bae27f1d5c5a_717x202.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Response from ChatGPT 4&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;That is it from me! I hope this exploration was helpful in some way! What are your thoughts on sustainable AI? What are some trends you noticed?&lt;/p&gt;

&lt;p&gt;If you found value in this article, please share it with someone who might also benefit from it. Your support helps spread knowledge and inspires more content like this. Let's keep the conversation going—share your thoughts and experiences below!&lt;/p&gt;

</description>
      <category>ai</category>
      <category>discuss</category>
      <category>learning</category>
    </item>
    <item>
      <title>Generator Functions in Python</title>
      <dc:creator>thebadcoder</dc:creator>
      <pubDate>Mon, 04 Mar 2024 01:42:58 +0000</pubDate>
      <link>https://dev.to/thebadcoder96/generator-functions-in-python-17bb</link>
      <guid>https://dev.to/thebadcoder96/generator-functions-in-python-17bb</guid>
      <description>&lt;p&gt;Today, we are going to learn about one of Python's most intriguing features—&lt;strong&gt;generator functions&lt;/strong&gt;. These are obviously not your normal functions; they're a handy tool for dealing with data more efficiently, especially when you have extremely large datasets that could give traditional functions a run for their memory.&lt;/p&gt;

&lt;h2&gt;
  
  
  What are Generator functions?
&lt;/h2&gt;

&lt;p&gt;Any function that uses &lt;code&gt;yield&lt;/code&gt; instead of &lt;code&gt;return&lt;/code&gt; is a generator function. Simple right? but what does yield do? The &lt;code&gt;yield&lt;/code&gt; keyword here produces a sequence of values over time, instead of returning a single value. For example, instead of returning a list of items or a whole dataset, it produces a sequence of items from a list or rows from the dataset at a time.&lt;/p&gt;

&lt;p&gt;This allows generator functions to produce values on the fly and pauses their state between outputs, making them memory-efficient and performance-friendly.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;This has nothing to do with the trending and cool &lt;em&gt;Generative AI&lt;/em&gt; that's been capturing everyone's attention; we are talking about functions that help us streamline our data processing tasks with elegance and efficiency.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  How does it do that?
&lt;/h3&gt;

&lt;p&gt;A normal function runs through all the lines of codes within it and returns a value. The generator function, however, returns an iterator, or in this case, a generator object. This produces only one value at a time so no other values will be stored. When the &lt;code&gt;next()&lt;/code&gt; function is used on the object, the next value is produced. &lt;/p&gt;

&lt;p&gt;Basically, we can loop through something without storing everyone all at once with the help of generators. You can learn more in detail about this &lt;a href="https://betterprogramming.pub/yield-in-python-76413d5e2a27"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Let’s try to understand it from an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;infinite_counter&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;yield&lt;/span&gt; &lt;span class="n"&gt;count&lt;/span&gt;
        &lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;

&lt;span class="c1"&gt;# Using the generator
&lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;number&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;infinite_counter&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;number&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;number&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;  &lt;span class="c1"&gt;# Stop at 10 to keep things sane!
&lt;/span&gt;        &lt;span class="k"&gt;break&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a simple infinite counter. Here's what's happening:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;infinite_counter&lt;/code&gt; defines a generator function that starts counting from 0.&lt;/li&gt;
&lt;li&gt;Inside an infinite loop, it yields the current count, then increments it.&lt;/li&gt;
&lt;li&gt;In the &lt;code&gt;for&lt;/code&gt; loop, the function is called so it produces numbers from 0 upwards.&lt;/li&gt;
&lt;li&gt;The loop prints each number, and we've added a break condition to stop the loop after it prints 10, preventing an actual infinite loop.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This example shows the power of generators to handle potentially infinite sequences in a memory-efficient way, yielding one item at a time!&lt;/p&gt;

&lt;h4&gt;
  
  
  Generative Expressions:
&lt;/h4&gt;

&lt;p&gt;Generator functions are just one way to create generator objects. Another way is &lt;em&gt;Generator Expressions&lt;/em&gt;. They are just like list comprehensions but for generators; you can convert a list comprehension into a generator expression by replacing the square brackets &lt;code&gt;[]&lt;/code&gt; with parentheses &lt;code&gt;()&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;squares&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This generator expression creates a sequence of squared numbers, showcasing the elegance and simplicity of using generative functions for on-the-fly data processing.&lt;/p&gt;

&lt;h2&gt;
  
  
  Generator Functions in Data Processing
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5hws0n8kvk7axaeirg2l.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5hws0n8kvk7axaeirg2l.jpeg" alt="Image description" width="800" height="534"&gt;&lt;/a&gt;&lt;br&gt;
Generative functions are the unsung heroes of memory management. Their ability to yield data incrementally means they can process information piece by piece, rather than loading everything into memory at once. This approach is not just about being resourceful; it's a necessity when dealing with datasets that can go across gigabytes or even terabytes. &lt;/p&gt;

&lt;p&gt;Generative functions are incredibly versatile, fitting a wide range of scenarios beyond the basics:&lt;br&gt;
-&lt;strong&gt;Real-time data streams&lt;/strong&gt;: Perfect for processing live data feeds, where data is continuous and potentially infinite.&lt;br&gt;
-&lt;strong&gt;Large files&lt;/strong&gt;: Useful for reading and processing data without the need to load everything into memory simultaneously.&lt;br&gt;
-&lt;strong&gt;Data transformation pipelines&lt;/strong&gt;: Implement stages of data transformation where each function passes its output to the next, efficiently handling data at each step.&lt;/p&gt;

&lt;p&gt;Let’s run through some examples because &lt;a href="https://www.linkedin.com/in/mishalsalim/"&gt;the author&lt;/a&gt; is not happy with the length of this article so far.&lt;/p&gt;
&lt;h3&gt;
  
  
  Example 1: Processing large files
&lt;/h3&gt;

&lt;p&gt;Let’s say you want to filter out specific entries from a file based on certain criteria, such as error messages in a log file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;filter_errors&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;log_file&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nf"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;log_file&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;r&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;line&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;ERROR&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;line&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;yield&lt;/span&gt; &lt;span class="n"&gt;line&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function goes through each line of the log, yielding only those that contain error messages, showing us how generative functions can be used for real-time data filtering.&lt;/p&gt;

&lt;h3&gt;
  
  
  Example 2: Data Loading and Preprocessing
&lt;/h3&gt;

&lt;p&gt;Generators are particularly useful in machine learning for data loading and preprocessing. Libraries like TensorFlow and PyTorch support data loaders that can be used to stream data from disks in batches using generator functions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;TensorFlow&lt;/strong&gt; extensively uses the concept of generators through its &lt;code&gt;tf.data.Dataset&lt;/code&gt; API, which allows for efficient data loading, preprocessing, and augmentation on the fly during model training. &lt;/p&gt;

&lt;p&gt;The &lt;code&gt;from_generator&lt;/code&gt; method allows you to create a Dataset from a Python generator. Here, TensorFlow uses the generator function indirectly to stream data:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;tensorflow&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;tf&lt;/span&gt;

&lt;span class="n"&gt;dataset&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;tf&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Dataset&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;from_generator&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;generator&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;load_data&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;output_types&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tf&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;float32&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;tf&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;float32&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
    &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arg1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;arg2&lt;/span&gt;&lt;span class="p"&gt;,)&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;dataset&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;dataset&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;batch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;32&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# Batching data for training
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Example 3: Principles in Pandas
&lt;/h3&gt;

&lt;p&gt;Pandas offers functionality that aligns with the principles of generators, useful when dealing with large datasets that might not fit into memory.&lt;/p&gt;

&lt;p&gt;For row-wise iteration, &lt;code&gt;iterrows&lt;/code&gt; and &lt;code&gt;itertuples&lt;/code&gt; can be used, though it's important to note that these methods may not always be the most efficient way to iterate over a data frame.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;pandas&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;pd&lt;/span&gt;

&lt;span class="n"&gt;df&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;pd&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;DataFrame&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;a&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;b&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;)})&lt;/span&gt;

&lt;span class="c1"&gt;# iterrows example
&lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;df&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;iterrows&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;a&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;b&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;

&lt;span class="c1"&gt;# itertuples example
&lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;df&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;itertuples&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;False&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;Pro-Tip&lt;/em&gt;&lt;/strong&gt;: Pandas' &lt;code&gt;read_csv&lt;/code&gt; function allows processing large CSV files in manageable chunks, a method particularly beneficial for large datasets. When you use the &lt;code&gt;chunksize&lt;/code&gt; parameter, the function will return an iterator object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;chunk&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;pd&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;read_csv&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;large_file.csv&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;chunksize&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;100000&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="c1"&gt;# Process each chunk here
&lt;/span&gt;    &lt;span class="nf"&gt;process&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;chunk&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Example 4: Web Crawling with Generators
&lt;/h3&gt;

&lt;p&gt;Scrapy, an asynchronous web scraping framework, uses generators and coroutines to handle web requests and responses efficiently. Here's a simplified example of a Scrapy spider that uses generators to crawl web pages:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;scrapy&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ErrorLogSpider&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;scrapy&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Spider&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;error_log_spider&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
    &lt;span class="n"&gt;start_urls&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;http://example.com/logs&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;parse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# Extract log page URLs
&lt;/span&gt;        &lt;span class="n"&gt;log_urls&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;css&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;a::attr(href)&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;getall&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;url&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;log_urls&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;yield&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;follow&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;url&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parse_log&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;parse_log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# Extract error messages
&lt;/span&gt;        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;error_msg&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;css&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;.error::text&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;getall&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
            &lt;span class="k"&gt;yield&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;error&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;error_msg&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We start from a main page, follow links to log pages, and extract error messages, all while using generators to facilitate efficient data extraction and processing in web crawling tasks.&lt;/p&gt;

&lt;h3&gt;
  
  
  Example 5: Related concepts in other libraries
&lt;/h3&gt;

&lt;p&gt;This concept of deferring computation and efficiently managing resources is a common thread that ties together various Python libraries. Libraries like &lt;code&gt;numpy&lt;/code&gt; leverage iterators for creating arrays from iterable sequences, optimizing memory usage in data manipulation. Similarly, &lt;code&gt;PySpark&lt;/code&gt; employs lazy evaluation to efficiently process big data across distributed systems, executing transformations only when an action requires the result, thereby optimizing computation and resource utilization. &lt;/p&gt;

&lt;p&gt;Understanding and leveraging these principles allows data professionals to handle larger datasets, speed up data processing, and write more efficient and scalable Python code.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6dvd5oah7yrpii54x0eh.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6dvd5oah7yrpii54x0eh.gif" alt="Funny Gif" width="480" height="320"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hopefully, these examples illustrate the power of generators, iterators, and related concepts, highlighting their importance in efficient data processing and analysis in various contexts. Whether you're processing streams of real-time data or chipping away at massive datasets, embracing generative functions can elevate your data handling to new heights.&lt;/p&gt;




&lt;p&gt;That is it from me! Have you used similar techniques before, or do you see new opportunities to apply them in your work? I hope this exploration was helpful in some way! &lt;/p&gt;

&lt;p&gt;If you found value in this article, please share it with someone who might also benefit from it. Your support helps spread knowledge and inspires more content like this. Let's keep the conversation going—share your thoughts and experiences below!&lt;/p&gt;

</description>
      <category>python</category>
      <category>beginners</category>
      <category>learning</category>
      <category>data</category>
    </item>
    <item>
      <title>What is Brand Safety Analysis? : A Data Nerd’s Perspective</title>
      <dc:creator>thebadcoder</dc:creator>
      <pubDate>Thu, 01 Feb 2024 17:08:32 +0000</pubDate>
      <link>https://dev.to/thebadcoder96/what-is-brand-safety-analysis-a-data-nerds-perspective-6gg</link>
      <guid>https://dev.to/thebadcoder96/what-is-brand-safety-analysis-a-data-nerds-perspective-6gg</guid>
      <description>&lt;p&gt;The concept of Brand Safety Analysis (BSA) has emerged as a crucial tool for marketers, content creators, and data enthusiasts. But what does it really mean, and why is it gaining such traction?&lt;/p&gt;

&lt;p&gt;I came across BSA through Conan O’Brien’s podcast, “Conan O’Brien Needs A Friend.”, and I decided that I want to make my first written article on this topic. So critique me on how I’m doing?&lt;/p&gt;

&lt;p&gt;Anyway, if you don’t know Conan or haven’t seen his work, I highly recommend &lt;a href="https://www.youtube.com/@TeamCoco"&gt;checking him out&lt;/a&gt;. But... you definitely don’t know me, so &lt;a href="https://www.linkedin.com/in/mishalsalim/"&gt;check me out too.&lt;/a&gt; :P&lt;/p&gt;

&lt;p&gt;Conan O’Brien is not just a household name; he’s a seasoned comedian, writer, and producer known for his quick wit and innovative comedy. He used to work as a writer for The Simpsons and IS my favorite talk show host, who is also now podcasting. Every year on his podcast, they have a ‘State of the Podcast’ session similar to how the United States of America holds their ‘State of the Union’, where they kinda analyze and see how the podcast is doing overall.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz1xvjwsuk6rr7h6j63o0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz1xvjwsuk6rr7h6j63o0.png" alt="Conan at TBS" width="800" height="449"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Brand Safety Analysis?
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Targeted Advertising&lt;/strong&gt;: BSA enables brands to place their advertisements more strategically, ensuring creators align with the content’s values and reach the desired audience.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Content Strategy&lt;/strong&gt;: It offers content creators insight into how their thematic choices or language use might influence potential brand partnerships.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Consumer Insights&lt;/strong&gt;: By understanding what content resonates with audiences, brands can tailor their marketing strategies more effectively.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Essence of Brand Safety Analysis
&lt;/h2&gt;

&lt;p&gt;At its core, Brand Safety Analysis is an evaluative process used by brands to ensure that a platform’s content aligns with their values and public image. When you start out creating content and getting sponsorships, it is very unlikely that you come across BSA. This is because the smaller companies do not really care about your brand when they set you up with sponsorship “codes” that they track to know how much sales are coming from your audience.&lt;/p&gt;

&lt;p&gt;But as you get bigger and get approached by bigger companies for partnerships, BSA plays a huge role. If a company is partnering with you, and you do not align with their views/values, it can hurt both parties. This analysis acts like a compatibility check for potential partnerships between advertisers and content creators. In the case of Conan’s podcast, a detailed BSA provided insights into various content dimensions that advertisers scrutinize, such as:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Obscenity and Profanity&lt;/strong&gt;: Quantifying the use of language that might be deemed inappropriate.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Adult and Sexual Content&lt;/strong&gt;: Assessing references to sexual content, innuendos, or adult themes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hate Speech and Aggression&lt;/strong&gt;: Identifying content that could be perceived as discriminatory or promoting violence.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Illegal Drug References&lt;/strong&gt;: Highlighting mentions of illegal substances or activities.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Military Conflict&lt;/strong&gt;: Analyzing discussions related to wars or military actions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Violation of Human Rights&lt;/strong&gt;: Scrutinizing content for potential endorsements of human rights violations.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8tjerpp8s8ly7bxzxf1v.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8tjerpp8s8ly7bxzxf1v.gif" alt="Conan at TBS" width="480" height="257"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The challenge here, particularly for a data nerd, lies in the methodology. How do we develop algorithms capable of understanding humor, sarcasm, and the nuanced dynamics of conversation? Conan’s content, renowned for its comedic genius and sarcasm, brings to light the intricate challenge of quantifying content properly.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Future of Content and Brand Synergy
&lt;/h2&gt;

&lt;p&gt;Brand Safety Analysis is not just the simple goal of avoiding controversy. It’s about creating a harmonious relationship between content and advertising, benefiting brands, creators, and consumers. As we delve deeper into the digital content era, the significance of Brand Safety Analysis only grows, opening new avenues for exploration and understanding; especially in the field of data.&lt;/p&gt;

&lt;p&gt;For tech professionals, marketers, and business people, BSA promises a blend of challenges and opportunities, all aimed at enhancing the digital content landscape.&lt;/p&gt;

&lt;p&gt;That is it from me! What’s your take on Brand Safety Analysis? Have you encountered similar methodologies in your work, or do you see potential applications in your field? Hope you enjoyed this article and was helpful in some way! I would really appreciate it if you would like, comment, or share this article with someone who might find some value.&lt;/p&gt;

&lt;p&gt;Check out the video that talks about BSA from Conan that inspired me to write my first medium article :)&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/eVJNCq2ZuYE"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

</description>
      <category>contentwriting</category>
      <category>beginners</category>
      <category>datascience</category>
      <category>analytics</category>
    </item>
  </channel>
</rss>
