<?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 Evelyn Chung on Medium]]></title>
        <description><![CDATA[Stories by Evelyn Chung on Medium]]></description>
        <link>https://medium.com/@echung682?source=rss-0724932c3bb5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ylqE9u-TpSx5cq5H3Evi3w.png</url>
            <title>Stories by Evelyn Chung on Medium</title>
            <link>https://medium.com/@echung682?source=rss-0724932c3bb5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:55:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@echung682/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[How I Made My Hydrogels Smarter and How I Can Make Them More Practical]]></title>
            <link>https://medium.com/@echung682/how-i-made-my-hydrogels-smarter-and-how-i-can-make-them-more-practical-d77321f721b4?source=rss-0724932c3bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d77321f721b4</guid>
            <category><![CDATA[biotechnology]]></category>
            <category><![CDATA[bioengineering]]></category>
            <dc:creator><![CDATA[Evelyn Chung]]></dc:creator>
            <pubDate>Tue, 26 May 2026 00:35:16 GMT</pubDate>
            <atom:updated>2026-05-26T00:35:16.637Z</atom:updated>
            <content:encoded><![CDATA[<h3>Catching Up on What I’ve Done Already</h3><p>I’m really excited to share that this is the third article I’ve written on my experiments and journey with hydrogels. I’ve learned so much about them already, and yet I still feel like I’ve only just scratched the surface.</p><p>Here’s a quick summary of everything I’ve done until now:</p><ul><li>Learned about hydrogels — specifically the type that starts as a liquid and gelates (solidifies) under certain conditions or over time — and how they can be used as wound dressings</li><li>Researched one of the largest feasibility barrier to making hydrogels more accessible: controlling the degradation of hydrogels in the body</li><li>First experiment (first step to learning to tackle hydrogel degradation barrier): used safe-at-home materials, such as sodium alginate and calcium chloride, to discover what combination of biomaterials will produce a fast-gelating hydrogel at room temperature</li><li>Following the first experiment: researched what other feasibility barriers there are and learned about “smart” hydrogels</li></ul><p>For more details and information, you can check out my <a href="https://medium.com/@echung682/controlling-the-degradation-of-injectable-hydrogels-is-the-next-step-to-achieve-tissue-regeneration-2e235a629329">first research article</a> and my <a href="https://medium.com/@echung682/i-made-my-first-hydrogels-and-now-i-want-to-make-smarter-ones-300d732a55ed">article</a> on my first experiment.</p><h3>Infected Wounds Have a Different pH</h3><p>The human skin is naturally slightly acidic (a pH of about 4–5). This helps to fight bacteria, which are the primary cause of infection. However, an <strong>infected wound has a more basic pH (about 8)</strong>, which makes sense since it is no longer acidic and able to fight off the bacteria.</p><p>Liquid hydrogels are a promising solution for deep, irregularly shaped wounds, and once they are applied, the hydrogels will solidify and it isn’t like a band-aid that someone can take on and off. So the ability to monitor the health of the wound is extremely important.</p><h4>pH Sensitive Bandages Already Exist</h4><p>There are actually quite a few bandages that can monitor wound pH for infection. Scientists have achieved this by adding pH indicators (or similarly functioning chemicals) that will change the color of the bandage to signal whether the wound was getting infected or not.</p><p>This prompted me to try adding pH indicators to my hydrogels and see if I could make them change color in different pH levels too.</p><h3>How I Made my Own pH Sensitive Hydrogels</h3><h4>The Goal of my Experiment was to See if a Fully Gelated Hydrogel Would Change Colors in Different pH Levels</h4><p>The procedure for the experiment was simple. Using the formula I tested in my first experiment that yielded the fastest gelation time — sodium alginate and calcium chloride — I would create hydrogels and add different pH indicators into their solutions before they solidified. I specifically tested the pH indicators BTB (bromothymol blue), phenolphthalein, and a universal indicator due to their biocompatibility. Additionally, I included a control group that had no indicators added.</p><p>Once the hydrogels fully solidified, which took about 36–48 hours, I cut three roughly equal sized pieces to be placed in acid, neutral, and base solutions. From there, I observed whether there was any color change in the pieces.</p><p>On a side note, I would like to thank my chemistry teacher for lending me the crucial pH indicators that I needed to carry out this experiment and I would like to thank my biology teacher for lending me the lab space and equipment to carry out this experiment. I couldn’t have done it without you!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFqHBflBb-dAMYdx2QkCew.jpeg" /></figure><h4>Phenolphthalein and Universal pH Indicators are Promising</h4><p>Upon testing the phenolphthalein + hydrogel and universal + hydrogel in the solutions, I was able to see that the pH indicators did work in the hydrogel. My experiment was a success, resulting in a color change in the phenolphthalein + hydrogel in the base solution and a color change in the universal + hydrogel in both the acid and base solutions. In regards to my goal of seeing if hydrogels can detect infection, the fact that both of the indicators successfully change color in base solution is a promising result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vG0iyj2mrRAUgqsElrrwhA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hM2SRcrUk79QPZDEzEOPaA.jpeg" /><figcaption>Universal indicator + Hydrogel: to the left is the hydrogel in an acid solution and to the right is the hydrogel in a base solution</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HxL_xrShueEf2ebc7kKQzQ.jpeg" /><figcaption>The phenolphthalein + hydrogel turning pink in a base solution</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rHsh2fKoqBYbAiX0g-f6bQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G4u-VpFEjo26ONYyfJvlNg.jpeg" /><figcaption>Once removed from the solution, there is a subtle color difference on the edges of the hydrogel</figcaption></figure><p>In these images, the hydrogels have not turned completely into a different color, rather the edges are changing color. This is due to diffusion. The hydrogels’ structure allows for liquid to flow into them, however, this process takes time. The first parts of the hydrogel that come into contact with the solution are the surfaces and edges.</p><p>This now leads me to bring up a couple of concerns regarding my experiment’s observations and results. The hydrogels were left in solution for 10 minutes. While the subtle change in color is noticeable, a new concern would be whether the color would change enough and soon enough to be able to get help.</p><p>Another observation that I had while working on this experiment was the texture of the hydrogel. When the hydrogels first solidified, there were two distinct textures. One was where the hydrogel remained in contact with solution, and therefore stayed much more hydrated. This made it very easy to cut through, kind of like a jelly. The second texture was predominantly along the surface of the hydrogel that had been exposed to air the longest. This texture was rougher and tougher, making it harder to cut, but still doable. So, this raises a concern of how protective and sturdy this hydrogel is as a wound dressing since it could be cut through with a knife. Perhaps if self healing properties were added then it would resolve this issue?</p><h4>BTB + Hydrogel Sample Didn’t Gelate Likely Due to the pH of the Solution</h4><p>An unexpected outcome in my experiment was how the BTB + hydrogel never solidified. Instead, it remained in a gooey state that wouldn’t be very useful for wound dressing applications. Therefore, I was unable to test it. That being said though, why didn’t it solidify? Upon further research, I learned that the way the sodium alginate + calcium chloride hydrogels solidify is through the bonding of calcium ions to the sodium alginate. The calcium chloride dissociates once it is added to the solution which leave calcium ions free to bond with the sodium alginate. However, with the addition of BTB, a pH indicator, it contains free H+ and OH- ions, the latter of which will bond to the calcium ions. Also indicated by my research, the rate of gelation increases as the amount of calcium ions increases, so the lack of gelation of the BTB + hydrogel solution is likely due to the lack of calcium ions to bond with the sodium alginate. Instead, these calcium ions bonded with the OH- ions from the BTB.</p><p>But phenolphthalein and the universal indicator also function in the same way, so how come the hydrogels mixed with them gelated? This could be because the pH of the actual hydrogel solution was no longer in the functional range. According to other experiments, BTB has been successfully incorporated into a liquid hydrogel so the reason why my BTB + hydrogel sample didn’t gelate could instead be due to how the BTB was prepared or the pH of the BTB that I used.</p><h3>How I Could Test my Hydrogel in “Real” Environments</h3><p>Before being used in the body, any medical product needs to go through extensive testing. So far, I have found that certain biomaterials, when combined, can create a hydrogel that will gelate quickly at room temperature. However, I do not know how these materials will interact with a human body. For obvious reasons, I cannot test the hydrogel in the human body however, perhaps I could simulate it. Specifically, how could I simulate a third degree burn wound, which is what my hydrogel research is focused on being applied to?</p><p>When it comes to burn wounds, specifically infected ones, there are three main aspects of the environment that the hydrogel needs to be tested in. The first is wound fluid. When a wound is healing, a certain type of fluid gets expelled. In order for the hydrogel to be successful, it needs to be able to absorb that fluid, as letting it accumulate would lead to negative effects in the wound such as maceration, infection, and more pain. The second aspect is the bacteria and/or biofilm. The skin does a very good job of keeping bacteria out but when there is an open wound, bacteria can easily get inside if the wound isn’t taken care of. If bacteria gets into the wound, then it can cause infection, which is the third aspect. This is why my second experiment focused on incorporating pH indicators into hydrogels. If they could sense a change in pH, then they could indicate that there is an infection. However, there is still the issue of the bacteria. Should the hydrogel sense an infection, would a doctor’s intervention be required? Or could antibiotics be incorporated into the hydrogel and be released once an infection is detected?</p><p>Following my second experiment, I realize how I’ve only begun to scratch the surface of the complexities of hydrogels and how hydrogels are only one small part of tissue engineering. There is a lot more to explore with hydrogels and tissues, and I can’t wait to branch out and dive deeper into the field as a whole.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d77321f721b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Made My First Hydrogels and Now I Want to Make “Smarter” Ones]]></title>
            <link>https://medium.com/@echung682/i-made-my-first-hydrogels-and-now-i-want-to-make-smarter-ones-300d732a55ed?source=rss-0724932c3bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/300d732a55ed</guid>
            <category><![CDATA[biotechnology]]></category>
            <category><![CDATA[bioengineering]]></category>
            <dc:creator><![CDATA[Evelyn Chung]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 18:23:12 GMT</pubDate>
            <atom:updated>2026-02-08T18:23:12.780Z</atom:updated>
            <content:encoded><![CDATA[<p>Following <a href="https://medium.com/@echung682/controlling-the-degradation-of-injectable-hydrogels-is-the-next-step-to-achieve-tissue-regeneration-2e235a629329">my last article</a>, I bought the materials to make my own hydrogels.</p><p>As a quick summary, hydrogels present themselves as an exciting alternative to the usual wound dressings. This is largely in part due to their versatile properties that can be easily tweaked and added to enhance their effects. However, I learned that controlling the degradation of the hydrogel, particularly for wound healing and tissue regneration, remains a tough barrier to overcome in order to achieve feasibility.</p><p>I envision hydrogels as the next all-purpose “band-aid” that can heal wounds faster, more effectively, and with less risk of complications. Of course, the issue of controlling degradation needs but addressed, but I started with making my own hydrogels and understand the process of making them. This is what I learned.</p><h3>Making My Own Hydrogels</h3><p>I bought gelatin, sodium alginate, chitosan and hyaluronic acid (HA), and I borrowed calcium chloride and agarose from my teacher. The compounds I made were:</p><ul><li>sodium alginate + calcium chloride</li><li>gelatin</li><li>gelatin + chitosan</li><li>agarose</li><li>agarose + HA</li></ul><h4>The Goal: Find the Materials that Gelated the Fastest</h4><p>Due to the lack of access to materials and having to work on a budget, I focused my first experiment on testing a different aspect of liquid hydrogel feasibility: gelation time.</p><p>Most hydrogels need colder temperatures to gelate, but when people get injured, they might not always be in those cold temperatures. So, the liquid hydrogels will need to gelate in room temperature, and quickly. This is because we want to seal up the wound to prevent as much blood loss and chances of infection as possible.</p><p>Surprisingly (or maybe not to you), the adult body contains about 10–12 pints of blood, and losing about half or more of that usually results in death. Following an accident or trauma, time until death from hemorrhage (blood loss) depends on how fast the person is losing blood. In severe cases of blood loss, such as a cut artery, a person could die in less than five minutes.</p><h4>Sodium Alginate + Calcium Chloride Shows Greatest Promise</h4><p>I poured each mixture into its own small square compartment in a silicon tray. While the other mixtures remained in liquid form for days, the sodium alginate + calcium chloride mixture started gelating immediately and was completely solidified within 24 hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTrUYEDIbXUBhK4_msKBQA.png" /><figcaption>Fully gelated sodium alginate hydrogel</figcaption></figure><p><a href="https://drive.google.com/file/d/1IeICtwsjzc5E6e6l2oKpBL8LqhqTkWlq/view?usp=drive_link">IMG_2524.MOV</a></p><p>It was really thick, soft, and jelly-like. But then I accidentally left it out overnight…which was not completely a bad thing. In fact, it led me to my next research question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qj2sBVZe_ztsR9xQ8q3LBg.png" /><figcaption>The hydrogel after being left out overnight</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EKxtOdfEnAKOJA0-McNOPg.png" /><figcaption>This is what the dried hydrogel looked like under a microscope</figcaption></figure><h4>Could the Hydrogel Drying Out be Another Feasibility Barrier?</h4><p>Would it have any detrimental effects on humans? Could it leave people dehydrated?</p><p>After some research, I found that the answer is <strong>no</strong>. A little bit of an anti-climatic conclusion, yet it is still important to keep in mind. Hydrogels have a high water content and are able to retain water very well. They can maintain a moist environment for the wound, the benefits of which include, but are not limited to:</p><ul><li>increased keratinocyte migration and reepithelialization (which help to rebuild the epidermis, close the wound, and restore the skin’s protective barrier)</li><li>decreased inflammation</li><li>decreased scarring</li><li>transporting growth factors secreted by cells that signal for healing more effectively</li><li>promotes autolysis of necrotic tissue (break down of dead tissue)</li></ul><p>Fortunately, hydrogels drying out within the body seems to not be a feasibility barrier that will need to be addressed before reaching market. However, my research to answer this question has led me to articles from which I have been exposed to some other feasibility questions.</p><h4>Hydrogels can’t absorb heavy exudate</h4><p>Wound exudate is the water-based leakage from capillaries that contains proteins, cells involved with the healing process, enzymes, glucose, secreted bacteria (in certain cases), and waste products. Usually, this exudate is good. It supports the healing process by preventing the wound from drying and contributes to cell migration and diffusion of immune and growth factors. However, an abnormal/over production of exudate can have negative effects. For example, the over production of exudate in prolonged inflammatory stages of chronic wounds can lead to skin maceration (break down of skin from prolonged exposure to moisture).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*53-m0fFN1KBsFYlUwwAuhw.gif" /><figcaption>Examples of different pore sizes in a hydrogel. (Source: <a href="https://pubs.rsc.org/en/content/articlehtml/2023/ma/d2ma00932c">https://pubs.rsc.org/en/content/articlehtml/2023/ma/d2ma00932c</a>)</figcaption></figure><p><a href="https://www.sciencedirect.com/science/article/pii/S2590156724000604">One study</a> found that hydrogel pores larger than 400 micrometers “may not facilitate exudate absorption” and such absorption could “compromise the consistency (strength) or the hydrogel dressing.” Additionally, the study found thick hydrogels show slower removals of wound exudate. What these results mean is that hydrogels could be a dangerous wound dressing for chronic wounds that have heavy exudate. If hydrogels cannot absorb the heavy exudate of chronic wounds, it can lead to the accumulation of this exudate in the wound, leading to consequences like skin maceration.</p><h4>Many Sources Call for “Smarter” Hydrogels</h4><p>A hydrogel applied as a liquid that then gelates on the wound would act as a cover over the wound, making it hard for doctors to access and constantly check up on. After all, it is not like a bandage that can be removed. This means that it is crucial for healthcare professionals to be able to monitor the wound. Additionally, the ability to monitor the wound’s microenvironment would make it more feasible for hydrogels to release specific chemicals and molecules to drive faster healing and decrease inflammation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*tarPrECtwyXSn2wERPxHrQ.png" /><figcaption>Hydrogels can be triggered by environmental changes like pH and temperature that cause them to morph or react in a certain way that is beneficial to specific applications (Source: <a href="https://www.researchgate.net/figure/Smart-hydrogel-system-and-some-applications_fig3_372849617">https://www.researchgate.net/figure/Smart-hydrogel-system-and-some-applications_fig3_372849617</a>)</figcaption></figure><h3>Taking My Project Farther — Tackling the Challenge of Monitoring the Wound Microenvironment</h3><p>I think that making hydrogels that can monitor the wound microenvironment is interesting. Furthermore, success in this area would open doors to wireless, asynchronous monitoring of the wound as well as more precise drug delivery. Hydrogels are in a unique position where they are in direct contact with the wound, which I hypothesize will be an advantage towards their ability to monitor the microenvironment.</p><p>Already, there are bandages that change color if there is an infection. One such bandage uses a <a href="https://www.medicaldesignbriefs.com/component/content/article/36253-color-changing-bandages-sense-and-treat-bacterial-infections">material developed by Xiaogang Qu and colleagues</a>. It changes from green to yellow when it senses a decrease in pH levels, indicating that the environment is more acidic, which correlates to the development of a bacterial infection. Additionally, this bandage releases an antibiotic in response to the changing pH and turns red if it detects resistant bacteria.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kBfBbOJXH8SrZPGjK4bIIw.jpeg" /><figcaption>A bandage that changes color if it detects an infection (Source: <a href="https://www.borntoengineer.com/meet-smart-bandages-changes-colour-detects-infections">https://www.borntoengineer.com/meet-smart-bandages-changes-colour-detects-infections</a>)</figcaption></figure><p>Just this feature alone could level up the capabilities of hydrogels, and possibly wound dressings, altogether. I am excited to start with this for my next experiment. Can I get my own hydrogel to sense a change in pH levels? Then, can I get it to visibly show that change, whether through color-changing or a different kind of indicator?</p><p>Yet, I am also curious about wound exudate. Could there be molecules in there that can serve as biosensors for how well the wound is healing? Could they be used as well to determine whether there is any complications or infections present in the wound? I can’t wait to write an article exploring the composition of wound exudate!</p><p>Finally, the hydrogels’ difficulty with absorbing wound exudate is an issue, and I am also wondering how hydrogels could be removed if there is an infection that doctors must treat. But, that is a question to be explored a little later down the line…For now, I’ll be focusing on how hydrogels can monitor the wound microenvironment!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=300d732a55ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Controlling the Degradation of Injectable Hydrogels is the Next Step to Achieve Tissue Regeneration]]></title>
            <link>https://medium.com/@echung682/controlling-the-degradation-of-injectable-hydrogels-is-the-next-step-to-achieve-tissue-regeneration-2e235a629329?source=rss-0724932c3bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e235a629329</guid>
            <dc:creator><![CDATA[Evelyn Chung]]></dc:creator>
            <pubDate>Sat, 15 Nov 2025 00:42:40 GMT</pubDate>
            <atom:updated>2025-11-15T00:42:40.038Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, injectable hydrogels are largely associated cosmetics industry due to their use as dermal fillers, a procedure that affected <a href="https://www.cbsnews.com/news/lip-cheek-fillers-risks-what-to-know/"><strong>over 5 million people</strong> in 2023.</a> But did you know that the tissue engineering and regeneration market is projected to <a href="https://www.bccresearch.com/pressroom/hlc/tissue-engineering-and-regeneration-market-set-to-surge-at-128-cagr?srsltid=AfmBOooXzzpsFnv7y8evqhib-W3EmlUHBt1SdwYd-MU7OWcBx1bg3IUB"><strong>increase from $5.4 billion in 2025 to $9.8 billion by the end of 2030</strong></a>? While as dermal fillers hydrogels are very beneficial to a lot of people for reducing the effects of aging, injectable hydrogels have an even greater potential — saving lives. Recently, the hydrogel technology has seen more research being poured into it due to its potential to promote <strong>tissue regeneration</strong>, not just augmentation. Researchers have made discoveries and innovations in this field that show promise for the use of hydrogels to promote the regeneration of tissues that suffer severe injuries and traumas like cartilage, bone, muscle, and skin. Yet, in order to achieve this, the main barrier that scientists and researchers have been racing to overcome is <strong>controlling the hydrogel’s degradation in the body</strong>.</p><h3>Science Behind Controlling the Degradation</h3><p>The degradation of injected soft tissues into the human body are mainly influenced by four factors:</p><ul><li>tissues’ scaffold composition</li><li>microarchitecture</li><li>local injection site tissue environment</li><li>human body’s immune response</li></ul><h4><em>The Most Important Influencer of Degradation is Materials Used</em></h4><p>Many modern injectable tissues involve the use of hyaluronic acid (HA)(most commonly used in dermal fillers for tissue augmentation) or adipose tissue engineering, which involves autologous tissues. Due to their natural origins in the human body, they are easily and quickly degraded by the human body’s immune system, making them unable to stay in the body for very long term — which is unfortunate since HA does possess many properties that would make them beneficial for wound healing. They are degraded by enzymes called hyaluronidases found throughout the human body and how fast they degrade is dependent on multiple factors such as the crosslinked structure of the molecule and the concentration of the enzymes.</p><p><em>Therefore, carboxymethylcellulose (CMC) and other biomaterials have been investigated as solutions for much longer-term applications in the body.</em></p><p>Ultimately, all biomaterials will degrade <em>eventually</em> due to the synergetic efforts of biodegradation by a variety of enzymes and cells found in the body. Although now, scientists and researchers have found ways of controlling the degradation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*cBpY8KEOYxfXK6pmEEOwhA.jpeg" /><figcaption>Powder form of carboxymethylcellulose (CMC), a polysaccharide derived from cellulose that is being explored as a potential biomaterial for creating “permanent” injectable hydrogels</figcaption></figure><p>When it comes to controlling degradation, there are two major categories for it:</p><ul><li>enzymatic treatment to degrade more permanent materials</li><li>using specific materials to create a specific degradation rate</li></ul><h4>Enzymatic Treatments Can Degrade “Permanent” Injected Tissues</h4><p>CMC is commonly used for “permanent” injectable tissues since it is derived from cellulose, a polysaccharide that is mainly degradable by the enzyme cellulase, which is only found in plants. In the case that it needs to be removed once injected from the body — perhaps it isn’t needed anymore or it is causing harm — an enzymatic treatment could be injected to the site of the hydrogel to degrade it. For example, a cellulase-based treatment injected at the site of the CMC-based hydrogel. Despite its many benefits (such as biocompatibility and low-cost), CMC does have weaknesses, like reduced mechanical stability in its un-crosslinked form. So, many scientists have experimented with combining CMC with other polymers and molecules to manipulate its properties to serve different purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*_QVr-u7J78FRwf1uGUgoIg.png" /><figcaption><a href="https://www.mdpi.com/2073-4360/2/3/252">Prof. Leach’s Study</a>; <a href="https://www.aidic.it/cet/19/74/260.pdf">Prof Wiwatwongwana’s Study</a></figcaption></figure><h4>Hydrogel Degradation Can be In-Tune With the Healing Process</h4><p>The other category of long-term survival involves controlling the degradation of the injected tissue to occur at a certain rate or time. In this category, scientists are exploring the methods of controlling the degradation of multiple different materials, not just CMC. Some hydrogels can be designed with crosslinks that are sensitive to the enzymes secreted by cells which will cause them to degrade. More interestingly, some researchers have found methods that allow injected hydrogels to degrade in tune with wound healing process.</p><h3>Controlling Degradation to Support Tissue Regeneration</h3><p>Injected biomaterials like hydrogels are designed to be injected into the body as a liquid and then solidify to form a biocompatible scaffold that will allow for wound healing. Since these materials are just meant to be a scaffold, it is unnecessary for them to remain in the body once their job is complete and the wound has healed. Yet, we don’t want them to degrade too fast before the wound has healed, which is why getting the timing of the degradation of these materials is so crucial, and the most obvious way to do that is by designing a solution that will heal in tune with the body’s natural tissue regeneration process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qTd1h5RoQlBAsbVdMLS3gw.png" /><figcaption>Simple diagram explaining the process of applying an injectable hydrogel to a burn wound (<a href="https://www.researchgate.net/figure/Hydrogel-based-therapy-for-burn-wound-healing-1-Burn-injury-induces-skin-tissue-damage_fig3_394310411">Source</a>)</figcaption></figure><p>While obvious, the solution is not very simple. Depending on what tissue needs to be regenerated, different materials will be used for their unique properties that will support the growth of the tissue. For example, an injectable hydrogel designed to support burn wound healing wouldn’t contain the same molecules as an injectable designed to support bone regeneration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*IMR2aRtfZ16cwkzWEWCIOg.png" /><figcaption><a href="https://advanced.onlinelibrary.wiley.com/doi/10.1002/advs.202501053">Prof. Jiang and Prof. Dong’s Study</a>; <a href="https://analyticalsciencejournals.onlinelibrary.wiley.com/doi/10.1002/bit.28755">Prof. Kocak and Prof. Rehman’s Study</a></figcaption></figure><p>These are not the only ways that hydrogels can be combined with different molecules to achieve different effects, further highlighting versatility of hydrogels, including injectable ones. The variety of materials and molecules that can be combined together truly bring endless possibilities to this area.</p><h3>Expectations for an Ideal Solution</h3><p>Although the possibilities are endless, we often have a specific task in mind that we want the solution to perform. Therefore, it is crucial to begin our analysis and decision making with first determining what the solution needs in order to perform the task.</p><p>The first question to address is why an injectable hydrogel is preferable to other forms of aiding tissue regeneration. The answer to this lies in its advantages over topical solutions like hydrocolloid bandages:</p><ul><li>minimally invasive</li><li>deliver treatment to specific place (including under the skin)</li><li>can mold to irregular sizes (applied in a liquid state and then gels, attaching to the wound)</li></ul><p>This brings me to my next point: the hydrogel needs to gel fast. It would be inconvenient and potentially dangerous to wait too long for the hydrogel to transform from a liquid into a gel, especially for a serious injury.</p><h4>Different Biomaterials are Better for Regenerating Different Tissues</h4><p>Next, the properties of the biomaterials need to meet certain requirements, both in general and for their specific applications. The ideal solution needs to be biocompatible to prevent any foreign immune response from the body and mechanically stable enough to support the regeneration of the tissue it is designed for. For example, solutions for bone regeneration require stable and strong mechanical properties since they are supporting the formation of bones. Additionally, these materials are meant to be injected as liquid and then solidify into scaffolds for cells to grow on and for the extracellular matrix to use, which means it needs to be hydrophilic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vt0-dDkUBxYf_7myqDUyYQ.jpeg" /><figcaption>Diagram illustrating how injectable hydrogels could be used for bone regeneration (<a href="https://www.researchgate.net/figure/Schematic-diagram-of-hyaluronic-acid-based-hydrogel-loaded-with-exosomes-for-bone_fig3_369751189">Source</a>)</figcaption></figure><p>Finally, a solution like this could help millions of people around the world. <a href="https://www.moorelaw.com/resources/surprising-burn-injury-statistics/">About 180,000 people die each year due to burns (even non-fatal ones) globally</a>, and <a href="https://medicalupdate.pennstatehealth.org/orthopedics/exploring-genetic-factors-in-impaired-bone-healing/">about 800,000 bone fractures in Americans will show impaired or incomplete healing.</a> With the help of hydrogels, these burns could be sealed in minutes. With the help of injectable hydrogels, we can target regenerative treatment of the bone for these serious cases. But in order to reach all those people, the solution needs to be cost-effective.</p><h3>Opportunities for Innovation</h3><p>A solution that can be used to support tissue regeneration for serious injuries could save lives around the world. Despite the current research, there is still a long way to go. Not enough in vivo studies have been done with these proposed ideas to test the theories, which is crucial for making this medicine available to people. Additionally, since this solution is meant help tissue regeneration, perhaps some of the proposed hydrogels could have drug delivery particles incorporated into them to speed up the healing process.</p><p>With every discovery made, more questions are raised. How would drug delivery particles interact with the other molecules in an injectable hydrogel? Would they have an effect on the gelation time and degradation time? Would they stay in the body or find their way out? Additionally, with such a variety of combinations, which one is most effective? Is chitosan a better material than CMC? What are the best molecules for supporting a different tissue that isn’t skin or bone? Finally, perhaps most importantly, how can we bring this solution cost effectively to scale to serve the hundreds of thousands of people who need it worldwide?</p><p>Of these questions, the one I find myself wondering the most is: what are the most optimal materials for an injectable hydrogel for skin regeneration? What properties would they need? What materials can we combine for a balance of strength and flexibility when it attaches to the skin? What materials would be most effective in aiding in drug delivery to promote faster wound healing? How can we make the hydrogel in liquid form when it is applied but doesn’t sting when applied to an open wound? And finally, of course, what materials and properties can check as many of these boxes as possible while degrading in tune with the healing process?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e235a629329" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prototyping LifeVein AI]]></title>
            <link>https://medium.com/@echung682/prototyping-lifevein-ai-9e68544cb14f?source=rss-0724932c3bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e68544cb14f</guid>
            <dc:creator><![CDATA[Evelyn Chung]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 21:04:34 GMT</pubDate>
            <atom:updated>2025-06-04T21:04:34.055Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>LifeVein AI is designed to be an app that will help nurses worldwide to successfully and safely administer a blood transfusion — regardless of their prior experience, training, knowledge, or skill. It leverages computer vision and Arduino robotics to assist nurses with the entire process of administering a blood transfusion, from monitoring the patient’s vitals to providing the steps to take in emergency cases. This prototype of LifeVein AI has been created to address the varying amounts of experienced nurses around the world and bridge the gaps in knowledge in order to ensure a lack of experience is not a barrier to a successful procedure that could save a life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CH9meSSb8RTRGQTPyzCxXg.png" /></figure><p>In many cases, blood transfusions could be the difference between life or death in the emergency. They can be vital in saving the life of a person who is losing a lot of blood from an injury or has a low red blood cell count.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PvRkEcJaCBRmSEQx" /><figcaption>Photo by <a href="https://unsplash.com/@olga_kononenko?utm_source=medium&amp;utm_medium=referral">Olga Kononenko</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Yet, the World Health Organization estimates that there is an <a href="https://sites.google.com/d/1vsfcY_aN2uBARcN8dgKTn7Cq49R0t28l/p/1mspBaFSpuSsXxzUZTq7XorpGDCFVA1qQ/edit">approximate 5 million nursing workforce shortage</a>, the very people who are vital in the process of administering a blood transfusion. Furthermore, the more experienced nurses are retiring faster than they can be replaced by newer nurses. This means that these new nurses, who are less experienced and have had less training, will lack the mentorship that rapidly increase their professional capabilities. This experience gap is even more felt in low-middle income countries, especially the least fortunate, where <a href="https://www.weforum.org/stories/2018/09/people-across-africa-have-to-travel-far-to-get-to-a-hospital-we-worked-out-how-far/#:~:text=More%20than%2095%25%20of%20their,within%20the%20two%2Dhour%20band.">over half of their residents live over two hours away from the nearest hospital</a> and many of their more talented and skilled nurses tend to work in hospitals in higher-income countries where they can be paid better.</p><p>LifeVein AI was created as a way to bridge this experience gap. It is designed to be a singular program that contains the knowledge and perception of the most experienced nurses, and uses its features and ability to adapt in real-time to help users, anywhere in the world, to successfully and safely administer a blood transfusion.</p><p>Here’s a behind the scenes of LifeVein AI, a program that combines AI, computer vision, and Arduino robotics hardware to guide users in real-time to perform a successful blood transfusion.</p><h3>Vein Detection Model</h3><p>This model is meant to be able to find veins in the patients inner elbow. It is able to show the user, in real-time, where the vein is to insert the intravenous (IV) catheter. The IV is what transports the blood product (from the donor) into the patient’s body. The model is based off of <a href="https://github.com/EdwinTSalcedo/CUBITAL/tree/master">one that has an 83% accuracy</a>. Check out the github for the model I made <a href="https://github.com/echung849/VeinDetectionModel">here</a>.</p><p>NEXT STEPS: I plan on fine-tuning and improving the model to increase its accuracy to 90% or higher. Additionally, an IV can be inserted into other places within the patient’s body, such as the hand, so I plan on adding an additional feature to the model so it will be able to find veins in other places.</p><h3>Urticaria Detection Model</h3><p>This <a href="https://github.com/echung849/UrticariaReactionDetection">model</a> searches for signs and symptoms of urticaria, a type of allergic reaction that could occur when a patient gets a blood transfusion. It could come in the form of hives, rashes, and redness and it means that the transfusion needs to be stopped immediately. This is because urticaria could be an early sign of angioedema (swelling) that could lead to the more serious anaphylaxis where the patient has difficulties breathing — and could potentially die if left untreated. This model is being initially trained on a <a href="https://universe.roboflow.com/urticaria/urticaria">dataset that was used to create a model with ~73% accuracy</a>.</p><p>NEXT STEPS: I plan on training the model with more images to reach an accuracy of 90% or higher. Additionally, urticaria isn’t the only allergic reaction that a patient could have. I want to expand my model to have features to detect other types of allergic reactions.</p><h3>Detecting Skin Redness and Skin Shininess</h3><p>The redness of the skin and the shininess of the skin — an indicator of sweat — could also be used to detect signs of an allergic reaction. LifeVein AI uses computer vision to detect how shiny and red the skin is particularly in the arm area.</p><pre>#MODEL TO DETECT SKIN REDNESS<br>import cv2<br>import mediapipe as mp<br>import numpy as np<br><br>mp_pose = mp.solutions.pose<br>pose = mp_pose.Pose()<br>mp_drawing = mp.solutions.drawing_utils<br><br># Function to start webcam feed, process frames, and detect emotions<br>def find_redness(camIndex):<br>    # Initialize the webcam<br>    cap = cv2.VideoCapture(camIndex)  # 0 for default webcam<br><br>    # Check if the webcam is successfully opened<br>    if not cap.isOpened():<br>        print(&quot;Error: Could not open webcam&quot;)<br>        return<br><br>    # Initialize face detector (Haar Cascade)<br>    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + &#39;haarcascade_frontalface_default.xml&#39;)<br><br>    while True:<br>        # Capture frame-by-frame<br>        ret, frame = cap.read()<br><br>        if not ret:<br>            print(&quot;Error: Failed to capture image&quot;)<br>            break<br><br>        # Convert color for MediaPipe<br>        image_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)<br>        result = pose.process(image_rgb)<br><br>        #right_arm = landmarks[mp_pose.PoseLandmark.RIGHT_ELBOW.value]<br><br>        # Draw pose landmarks (including arms)<br>        if result.pose_landmarks:<br>            h, w, _ = frame.shape<br>            landmarks = result.pose_landmarks.landmark #list of landmarks<br><br>            left_arm = landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value]<br>            &quot;&quot;&quot;<br>            mp_drawing.draw_landmarks(<br>                frame,<br>                result.pose_landmarks,<br>                mp_pose.POSE_CONNECTIONS<br>            )<br>            &quot;&quot;&quot;<br>            if left_arm.visibility &gt; 0:<br>                cx, cy = int(left_arm.x * w), int(left_arm.y * h)<br><br>                # Define ROI around the wrist<br>                size = 40  # Size of the box around the landmark<br>                x1, y1 = max(cx - size, 0), max(cy - size, 0)<br>                x2, y2 = min(cx + size, w), min(cy + size, h)<br>                if x1 &lt; x2 and y1 &lt; y2:<br>                    roi = frame[y1:y2, x1:x2]<br>                else:<br>                    print(&quot;Invalid ROI: Out of bounds&quot;)<br>                    continue<br>                # Convert the frame from BGR (OpenCV) to RGB (FER)<br>                rgb_frame = cv2.cvtColor(roi, cv2.COLOR_BGR2RGB)<br><br>                # Define red color range<br>                lower_red1 = np.array([0, 70, 50])<br>                upper_red1 = np.array([10, 255, 255])<br>                lower_red2 = np.array([170, 70, 50])<br>                upper_red2 = np.array([180, 255, 255])<br><br>                # Create masks and combine them<br>                mask1 = cv2.inRange(rgb_frame, lower_red1, upper_red1)<br>                mask2 = cv2.inRange(rgb_frame, lower_red2, upper_red2)<br>                red_mask = cv2.bitwise_or(mask1, mask2)<br><br>                # Calculate redness percentage<br>                red_pixels = cv2.countNonZero(red_mask)<br>                total_pixels = roi.shape[0] * roi.shape[1]<br>                redness_ratio = red_pixels / total_pixels<br>                <br>                # Show the ROI and mask<br>                cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)<br>                cv2.imshow(&quot;Red Mask&quot;, red_mask)<br><br>        #cv2.putText(frame, f&#39;{redness_ratio}&#39;, (10, 30), <br>                        #cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)<br><br>        # Display the frame with emotion text<br>        cv2.imshow(&quot;Arm&quot;, frame)<br><br>        # Exit loop on pressing &#39;q&#39;<br>        if cv2.waitKey(1) &amp; 0xFF == ord(&#39;q&#39;):<br>            break<br><br>    # Release the webcam and close the window<br>    cap.release()<br>    cv2.destroyAllWindows()</pre><pre>#MODEL TO DETECT SKIN SHININESS<br>import cv2<br>import time<br><br># Function to start webcam feed, process frames, and detect emotions<br>def find_shiny_skin(camIndex):<br>    # Initialize the webcam<br>    cap = cv2.VideoCapture(camIndex)  # 0 for default webcam<br><br>    # Check if the webcam is successfully opened<br>    if not cap.isOpened():<br>        print(&quot;Error: Could not open webcam&quot;)<br>        return<br><br>    # Initialize face detector (Haar Cascade)<br>    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + &#39;haarcascade_frontalface_default.xml&#39;)<br><br>    while True:<br>        # Capture frame-by-frame<br>        ret, frame = cap.read()<br>        h, w, _ = frame.shape<br><br>        if not ret:<br>            print(&quot;Error: Failed to capture image&quot;)<br>            break<br><br>        # convert RBG to Grayscale<br>        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)<br>        <br>        _, shiny_mask = cv2.threshold(gray, 220, 255, cv2.THRESH_BINARY)  # Bright spots<br><br>        # Find contours or calculate shiny pixel percentage<br>        shiny_ratio = (shiny_mask &gt; 0).sum() / shiny_mask.size<br>        shiny_ratio = round(shiny_ratio * 100, 2)<br><br>        # Draw rectangles around shiny areas<br>        contours, _ = cv2.findContours(shiny_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)<br>        for contour in contours:<br>            if cv2.contourArea(contour) &gt; 100:<br>                x, y, w, h = cv2.boundingRect(contour)<br>                # Draw rectangle around shiny area<br>                cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)<br><br>        cv2.putText(frame, f&#39;{shiny_ratio}%&#39;, (10, 30), <br>                        cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)<br><br>        cv2.imshow(&quot;Shiny&quot;, frame)<br><br>        # Exit loop on pressing &#39;q&#39;<br>        if cv2.waitKey(1) &amp; 0xFF == ord(&#39;q&#39;):<br>            break<br><br>    # Release the webcam and close the window<br>    cap.release()<br>    cv2.destroyAllWindows()</pre><p>NEXT STEPS: I plan on improving the accuracy of these detectors.</p><h3>Arduino Uno Body Temperature Sensor</h3><p>Using an <a href="https://www.amazon.com/EC-Buying-Non-Contact-Temperature-Acquisition/dp/B0B63K5V7T/ref=sr_1_2_sspa?crid=2HJX7QJT8PN1R&amp;dib=eyJ2IjoiMSJ9.LmSuBCjOcNQdbtf-bGvQ7JCZfKIYePr4LiAXS2k-R8AbrrPXOiYSodD7ujcQ6V9TJU8RQsoLhS0HBEg1Xi4juaEzx-ukvtI2jI0T1xnygSEovjeyMCiVbUinf3w25SWgzkIkHoiHiyHeg0kV4pcoZVjNNJ47PNEAC_b3RAzrCksyyXKQ5rND8NM1ReesC2XGypvdkpI9dotlU7OPoJD6KHhycwEoZPqtFjJjON3Cd4o.8kY2SVFHzdz92XciJvnkmrAs32H6jKsp7Dyson4qJC8&amp;dib_tag=se&amp;keywords=mlx90614+sensor&amp;qid=1747496021&amp;sprefix=mlx%2Caps%2C135&amp;sr=8-2-spons&amp;sp_csd=d2lkZ2V0TmFtZT1zcF9hdGY&amp;psc=1">infrared sensor</a> connected to the Arduino Uno, the program is able to measure the body heat of a person with in a certain distance. This body heat is able to be used as a signal of a rising body temperature.</p><pre>#Source: https://www.programmingboss.com/2023/05/how-to-interface-mlx90614-temperature-sensor--with-Arduino.html#gsc.tab=0<br>#include &lt;Arduino.h&gt;<br>#include &lt;Wire.h&gt;<br>#include &lt;Adafruit_MLX90614.h&gt;<br><br>Adafruit_MLX90614 mlx = Adafruit_MLX90614();<br><br><br>void setup() {<br>  // put your setup code here, to run once:<br>  Serial.begin(9600);<br>  mlx.begin();  <br>}<br><br>void loop() {<br>  // put your main code here, to run repeatedly:<br>  Serial.print(&quot;Ambient Temperature: &quot;); <br>  Serial.print(mlx.readAmbientTempC()); <br>  Serial.print(&quot;C / &quot;); <br>  Serial.print(mlx.readAmbientTempF()); <br>  Serial.println(&quot;F&quot;);<br>  Serial.print(&quot;Object Temperature:  &quot;); <br>  Serial.print(mlx.readObjectTempC()); <br>  Serial.print(&quot;C / &quot;); <br>  Serial.print(mlx.readObjectTempF()); <br>  Serial.println(&quot;F&quot;);<br>  Serial.println();<br>  delay(500);<br>}</pre><p>NEXT STEPS: I plan on adding more ways for LifeVein AI to monitor other vitals, such as heart rate and blood pressure. This would also require other physical materials for LifeVein AI to be connected to in order to monitor these vitals.</p><h3>The LifeVein AI App</h3><p>Currently a work in progress, but the end design is this: a singular program that includes all of these components as well as any additional features to be created in the future. It is designed to be able to be used on a phone through a downloadable app.</p><p>In regards to its functionality upon combining all of these features: LifeVein AI first gets the baseline of the patient’s vitals and status (skin redness, body temperature, skin shininess, etc). In the program, there will already be an established threshold value for if the patient’s vitals during or after the transfusion exceed that threshold from the baseline, then the program will alert the user to stop the transfusion. Throughout the entire process, LifeVein AI will guide the user through the process of administering the blood transfusion through a user interface on the phone. It will leverage its vein detection software to find the vein in the patient’s arm and instruct the user where to administer the needle. If an allergic reaction occurs, the app will communicate to the user the steps to handling it.</p><h3>Future Plans</h3><p>Before deployment, I want to ensure that LifeVein AI is as safe and effective as possible. Therefore, I want to put it through clinical trials and numerous rounds of validation phases to ensure that LifeVein AI is constantly up to date with the latest technology and is constantly improving for our users.</p><p>The end goal of LifeVein AI is to be affordable and accessible to those who need it most, especially those in low-middle and low income countries. Being that these people are far from quality care in the first place, it becomes even more important that LifeVein AI is safe, effective, and affordable.</p><p>For now though, I am building and improving LifeVein AI’s capabilities and features.</p><p><strong>Did you enjoy reading the article?</strong></p><p>I know I enjoyed writing it! Want to read more? Check out my <a href="https://medium.com/@echung682">Medium</a> account. Want to follow my journey? Connect with me on <a href="https://www.linkedin.com/in/evelyn-chung-a8b4a3334/">LinkedIn</a> or subscribe to my <a href="https://evelynchung.substack.com/">monthly newsletter</a> on Substack.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e68544cb14f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an App to Track Text and Face Emotions Over Time]]></title>
            <link>https://medium.com/@echung682/creating-an-app-to-track-text-and-face-emotions-over-time-7a70dce83349?source=rss-0724932c3bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a70dce83349</guid>
            <dc:creator><![CDATA[Evelyn Chung]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 01:31:39 GMT</pubDate>
            <atom:updated>2025-04-07T01:31:39.548Z</atom:updated>
            <content:encoded><![CDATA[<p>In one of my <a href="https://medium.com/@echung682/making-an-ai-therapist-behind-the-scenes-391f6eccb2aa">previous projects</a>, I worked with something that I have come to discover is called “Emotion AI.” Following the project, I became very interested in doing something more with Emotion AI, hence this project! In this article, I will talk about the errors I had to resolve and how I coded the program. You can follow along with the code or play with the finished app <a href="https://huggingface.co/spaces/echung682/emotion_detection_from_text_and_face/">here</a>!</p><h3>Objective</h3><p>The goal of this project is to create an app using Gradio that takes two user inputs: text (typed messages) and images (pictures of the user’s face). Using these two inputs, the app would then run each type of input through their respective model in order to output the emotions detected from each. In this way, the app would not save the user’s messages and face, instead it would only save the emotions. In addition, I wanted this model to track these emotions over time, so I added code that would record the timestamp of when the emotion was detected.</p><h3>Setting Up</h3><p>These are the libraries I used:</p><pre>from transformers import (<br>    AutoModelForSequenceClassification,  # For text emotion detection model<br>    AutoTokenizer, <br>    pipeline,                           # For creating inference pipeline<br><br>)<br>from datetime import datetime # For timestamping<br>import matplotlib.pyplot as plt # For rendering the data on a graph<br>import gradio as gr<br>from fer import FER<br>import cv2<br>import os</pre><h3>Getting the Emotions</h3><h4>From Text</h4><p>I created a dictionary to store the data. There are three main keys: “Time” (for the timestamp), “Emotion”, and “Confidence Score” (which is technically not outputted for the user to see). Each key maps to a list that will contain all of their values.</p><p>I used a <a href="https://huggingface.co/borisn70/bert-43-multilabel-emotion-detection">pre-trained emotion detection model</a> to detect the emotions from the messages inputted by the user. Using HuggingFace, it was really easy to import the model, tokenizer, and I used HuggingFace’s <em>pipeline()</em> in order to feed input into the model.</p><p>I created a format that would be used by the <em>datetime() </em>function to save the timestamp in a readable format.</p><pre>text_dataDict = {&quot;Time&quot;: [], &quot;Emotion&quot;: [], &quot;Confidence Score&quot;: []}<br><br># Load model and tokenizer directly from HuggingFace<br>emotionDetectModel = AutoModelForSequenceClassification.from_pretrained(&quot;borisn70/bert-43-multilabel-emotion-detection&quot;)<br>tokenizer = AutoTokenizer.from_pretrained(&quot;borisn70/bert-43-multilabel-emotion-detection&quot;)  # Load tokenizer directly from model in order to ensure that the tokenizer is compatible with the model<br>pipe = pipeline(task=&quot;text-classification&quot;, model=emotionDetectModel, tokenizer=tokenizer)<br><br>localFormat = &quot;%Y-%m-%d %H:%M:%S&quot; #this is how will print the timestamp: year-month-day hour-minutes-seconds (army time)</pre><p>What’s important to note is that this part of the code is located outside of the functions and Gradio implementation. By putting it outside of all of that, all of this code is only run once when the app is used, rather than run every time a user inputs something into the app.</p><p>The main function that handles the emotion detection is the <em>emotionAnalysis()</em> model. It is called by Gradio and I will start by walking through the code to handle the text emotion detection (face emotion detection is later in the article!). The function takes in two arguments, <em>message</em> and <em>face</em>, which are a String input and Image input, respectively, that are passed into the function by Gradio.</p><pre>def emotionAnalysis(message, face):<br>    if (message.lower() == &quot;finish&quot;):<br>        return &quot;Quitting...&quot;, displayResults()<br>    <br>    # Process text emotion<br>    result = pipe(message) # pipe refers to the emotion detection model and takes a String input to run through the model<br>    # result is a list of dictionaries with the keys &quot;label&quot; and &quot;score&quot; that correspond, respectively, to the detected emotion and the confidence score<br><br>    text_emotion = result[0][&quot;label&quot;] # since result is a list of dictionaries, I access the first element in the list and get the value at the key &quot;label&quot; for the emotion<br>    text_score = result[0][&quot;score&quot;]<br>    words_timestamp = datetime.now().astimezone().strftime(localFormat) # this formats the time into the specified local format<br>    <br>    # Store text emotion data for plotting, the data is added to its respective list that is stored at its respective key<br>    text_dataDict[&quot;Time&quot;].append(words_timestamp) <br>    text_dataDict[&quot;Emotion&quot;].append(text_emotion)<br>    text_dataDict[&quot;Confidence Score&quot;].append(round(text_score, 2))</pre><h4>From Facial Expressions</h4><p>The set up for the detection facial emotions is relatively simple, but its processing and handling is a little bit more complex. I used the <em>FER()</em> model and it also records the timestamp of when it was taken (however, when the app runs, it should have the same timestamp as the text part).</p><pre>face_emotion_detector = FER()<br><br># ...text emotion detection code...<br><br>localFormat = &quot;%Y-%m-%d %H:%M:%S&quot; # don&#39;t declare this variable twice, I just put it here for convenient reference</pre><p>Similar to the text emotion detection portion of the code, I also created a dictionary of keys for the face emotions: “Time,” “Emotion,” and “Confidence Score.” I also did the documentation of the face emotion detection in the same function as the text emotion detection.</p><pre>face_dataDict = {&quot;Time&quot;: [], &quot;Emotion&quot;: [], &quot;Confidence Score&quot;: []}<br><br>def emotionAnalysis(message, face):<br><br>   # .....Other code.....<br><br>   face_timestamp = datetime.now().astimezone().strftime(localFormat)<br><br>    <br>   # Capture and process facial emotion<br>   img_rgb = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)<br><br>   face_emotion, face_score = face_emotion_detector.top_emotion(img_rgb)<br><br>   # Store facial emotion data for plotting<br>   face_dataDict[&quot;Time&quot;].append(face_timestamp)<br>   face_dataDict[&quot;Emotion&quot;].append(face_emotion)<br>   face_dataDict[&quot;Confidence Score&quot;].append(face_score)</pre><p>Note that, within this function, I am also processing the image taken from the webcam and feeding it through the <em>face_emotion_detector.top_emotion()</em> function from <em>fer. </em>This function will detect all the emotions in the face but only return the one with the highest confidence score.</p><h3>Displaying Results in a Timeline</h3><p>I decided to display my results in a timeline. On the x-axis, I will keep track of the time, saved in the dictionaries, in the format of “Year-Month-Day Hour-Minutes-Seconds” where the hours are based on a 24-hour clock.</p><pre>def displayResults():<br>    # Create a new figure with specified size<br>    plt.figure(figsize=(10, 6))<br>    <br>    # Set up plot labels and title<br>    plt.title(&quot;Emotions Detected Through Facial Expressions and Text Over Time&quot;)<br>    plt.xlabel(&quot;Time&quot;)<br>    plt.ylabel(&quot;Emotions&quot;)<br><br>    #plot facial emotions versus time where time is on the x-axis<br>    plt.plot(face_dataDict[&quot;Time&quot;], face_dataDict[&quot;Emotion&quot;], marker=&#39;o&#39;, linestyle=&#39;-&#39;, label=&quot;Facial Emotions&quot;)<br><br>    #plot facial emotions versus time where time is on the x-axis<br>    plt.plot(text_dataDict[&quot;Time&quot;], text_dataDict[&quot;Emotion&quot;], marker=&#39;o&#39;, linestyle=&#39;-&#39;, color=&#39;red&#39;, label=&quot;Text Emotions&quot;)<br><br>    #showing the graph and the legend<br>    plt.legend()<br>    plt.xticks(rotation=45)  # Rotate timestamps for better readability<br>    plt.tight_layout()       # Adjust layout to prevent label cutoff</pre><h3>Using Gradio to Build the App</h3><p>This is where everything comes together! Since I wanted to some unique things with Gradio and I had a very specific format in mind, I built my Gradio application using Gradio blocks. Just as a tip: When using the Markdown Gradio Component, skip lines in the code to start a new line in the text displayed.</p><pre># Gradio has some built in themes (with different fonts, color schemes, etc) and I chose the Ocean theme<br>with gr.Blocks(title=&quot;Emotion Reader&quot;, theme=gr.themes.Ocean()) as emotion_reader:<br>    gr.Markdown(<br>    &quot;&quot;&quot;<br>    # Emotion Analysis from Text and Face<br>    ⚠️ This application will use your webcam to detect facial emotions. By using this app, you consent to webcam access. Type text and press Enter to analyze both text and facial emotions.<br>    <br>    Steps to use the app:<br>        <br>        1. Turn on the camera clicking where it says &quot;Click to Access Webcam&quot; and Allow access<br>        <br>        2. Click &quot;Record&quot; (the dropdown arrow is for if you want to change your camera)<br>        <br>        3. Type a sentence into the text input box<br>        <br>        4. Press &quot;Enter&quot; to see your results<br>        <br>        5. In the &quot;Emotion Results&quot; box, you will see something like &quot;Text: {emotion} | Face {emotion} &quot; and the timeline will update<br>        <br>        6. You can press &quot;Stop&quot; to turn off the camera or type &quot;finish&quot; as your message to stop the program<br>    &quot;&quot;&quot;<br>    )<br>    with gr.Row():<br>        with gr.Column(): #user text input<br>            text_input = gr.Textbox(<br>                label=&quot;Enter your text&quot;,<br>                placeholder=&quot;Type your message here. Type &#39;finish&#39; to see final results.&quot;<br>            )<br>            examples = gr.Examples(<br>                examples=[<br>                    &quot;I am feeling happy today!&quot;,<br>                    &quot;I am feeling sad today.&quot;,<br>                    &quot;I wish I could go on vacation.&quot;<br>                ],<br>                inputs=text_input<br>            ) # these are example input text that the user can use<br>        with gr.Column(): #emotion results<br>            emotion_result = gr.Textbox(label=&quot;Emotion Results&quot;)<br>    <br>    with gr.Row():<br>        with gr.Column(): #camera live feed<br>            input_img = gr.Image(label=&quot;Webcam Feed&quot;, sources=&quot;webcam&quot;)<br>        with gr.Column(): #plt graph<br>            output_img = gr.Image(label=&quot;Emotion Detection&quot;, visible=False)<br>            plot_output = gr.Plot(value=displayResults(), label=&quot;Emotion Timeline&quot;)</pre><p>There’s a lot going on in that block! Let’s break it down. The Markdown component is the title and description that will be displayed for the app. I have two rows, each with two columns. So that’s four “boxes.” The one on the top left takes in user text input and saves it to <em>text_input</em>. The top right box will have the emotion detection results saved to it in <em>emotion_result </em>and that will update to show the emotion detection results. The bottom left box will be the live feed for the camera that is saved to <em>input_img</em>, the user will get to see themselves. The bottom right is the emotion timeline graph that is save to <em>plot_output</em> and will update according to the results from the <em>displayResults()</em>. There is a fifth component, called <em>output_img</em>, where screenshots from the live feed in <em>input_img</em> would be saved, however, I did not want that to show so I set it equal to false.</p><p>Next, I am going to call functions on these input components. But before I do that, I need to add a couple more lines of code to the functions.</p><pre># .....Other Code......<br><br>def emotionAnalysis(message, face):<br><br>  # ......Other Code......<br><br>  return f&quot;Text: {text_emotion} | Face: {face_emotion}&quot;, displayResults()<br><br>def displayResults():<br><br>  # ......Other Code......<br><br>  return plt</pre><p>Additionally, I added one more function to process the live stream to output images.</p><pre>def process_webcam(img):<br>    &quot;&quot;&quot;<br>    Process webcam frame and draw emotion detection results<br>    &quot;&quot;&quot;<br>    if img is None:<br>        return None<br>        <br>    try:<br>        <br>        return img<br>    except Exception as e:<br>        print(f&quot;Error processing image: {str(e)}&quot;)<br>        return img</pre><p>With that, I write two functions, one for each of my Gradio inputs.</p><pre>input_img.stream(<br>        process_webcam,<br>        inputs=input_img,<br>        outputs=output_img,<br>        time_limit=15,<br>        stream_every=0.1,<br>        concurrency_limit=30<br>    )<br>    <br>    # Process text input<br>    text_input.submit(<br>        emotionAnalysis,<br>        inputs=[text_input, output_img],  # Direct access to webcam frame<br>        outputs=[emotion_result, plot_output]<br>    )</pre><p>However, there is a big issue I needed to address. In the <em>process_webcam()</em>, there was a possibility that the function would return <em>None</em>. If that was the case, then the <em>top_emotion()</em> would not work. In order to handle that, I first check if the <em>output_img </em>passed to the <em>emotionAnalysis()</em> as <em>face</em> was equal to <em>None</em>. Yet I was still getting errors, particularly when the webcam was working but no face was detected.</p><pre>def emotionAnalysis(message, face):<br>  # .....Other Code.....<br><br>  &quot;&quot;&quot;<br>  REPLACE:<br>  # Capture and process facial emotion<br>   img_rgb = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)<br><br>   face_emotion, face_score = face_emotion_detector.top_emotion(img_rgb)<br><br>  WITH...<br>  &quot;&quot;&quot;<br><br>  # Initialize with default values<br>    face_emotion = &quot;No image&quot;  # Default value<br>    face_score = 0.0<br><br>    if face is not None:<br>        try:<br>            img_rgb = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)<br>            result = face_emotion_detector.top_emotion(img_rgb)<br>            if result is not None:  # Only update if we got a valid result<br>                face_emotion, face_score = result<br>            else:<br>                face_emotion = &quot;No face detected&quot;<br>                face_score = 0.0<br>        except Exception as e:<br>            face_emotion = f&quot;Error processing image: {str(e)}&quot;<br>            face_score = 0.0</pre><h4>Allowing Users to Download Their Results</h4><p>Being able to detect the users’ emotions through text and face is pretty cool. Displaying the results on a graph with a timeline is even cooler. But adding a feature for users to download their emotion timeline is the coolest! So that’s what I did. Gradio has a handy component for this, so I began with incorporating that.</p><pre>with gr.Blocks(title=&quot;Emotion Reader&quot;, theme=gr.themes.Ocean()) as emotion_reader:<br>    # ...Other Code...<br>    with gr.Row():<br>        # ...Other Code...<br>        with gr.Column(): #emotion results<br>            emotion_result = gr.Textbox(label=&quot;Emotion Results&quot;)<br>            download_button = gr.DownloadButton(label=&quot;Download Emotion Timeline&quot;, visible=False)</pre><p>The reason why I made this download button not <em>visible</em> is because when the program first starts up, I don’t want the button to be visible. I only want it to be visible when the user types “finish” as text input. In order to handle this though, I would need the <em>emotionAnalysis </em>function to return the button, as well as the item to be downloaded. However, this item needs to specifically be a filepath. I wanted the user to be able to download their emotion timeline, but it had to be saved as an image first. Then, the method would return the button, with its <em>value</em> referencing the filepath.</p><pre>def emotionAnalysis(message, face):<br>    # ...Other Code...<br>    if (message.lower() == &quot;finish&quot;):<br>        graph = displayResults()<br>        filename = &quot;Emotion_Timeline.png&quot;<br>        graph.savefig(filename)<br>        download = gr.DownloadButton(label=&quot;Download Emotion Timeline&quot;, value=filename, visible=True)<br>        return &quot;Quitting...&quot;, graph, download<br><br>    # ...Other Code...<br><br>    data = displayResults()<br>    file_name = &quot;unfinishedPLT.png&quot;<br>    data.savefig(file_name)<br>    dL = gr.DownloadButton(label=&quot;Download Emotion Timeline&quot;, value=file_name, visible=False)<br>    <br>    # Return both the text result and the updated plot<br>    return f&quot;Text: {text_emotion} | Face: {face_emotion}&quot;, data, dL</pre><p>So this handles the functionality of the download button. It appears when the user enters “finish” and it returns the image file of the emotion timeline. However, I am storing all of these images in temporary files that need to be cleaned up. I needed to make sure that I cleaned up the files after the image of the timeline was downloaded though. Therefore, I used Gradio’s built in button <em>.click()</em> method to call a function that would delete all of these temporary image files.</p><pre># List of temporary files to clean up (this code is placed near the top, close to the import statements)<br>temp_files = []<br><br>def emotionAnalysis(message, face):<br>    # ...Other Code...<br>    if (message.lower() == &quot;finish&quot;):<br>        graph = displayResults()<br>        filename = &quot;Emotion_Timeline.png&quot;<br>        graph.savefig(filename)<br>        temp_files.append(filename) # adding the file to the list of files that will be cleaned up<br>        download = gr.DownloadButton(label=&quot;Download Emotion Timeline&quot;, value=filename, visible=True)<br>        return &quot;Quitting...&quot;, graph, download<br><br>    # ...Other Code...<br><br>    data = displayResults()<br>    file_name = &quot;unfinishedPLT.png&quot;<br>    data.savefig(file_name)<br>    temp_files.append(file_name) # adding the file to the list of files that will be cleaned up<br>    dL = gr.DownloadButton(label=&quot;Download Emotion Timeline&quot;, value=file_name, visible=False)<br>    <br>    # Return both the text result and the updated plot<br>    return f&quot;Text: {text_emotion} | Face: {face_emotion}&quot;, data, dL<br><br># ...Other Code...<br>&quot;&quot;&quot;<br>Function to handle cleaning up temporary files<br>&quot;&quot;&quot;<br>def cleanUp_Files():<br>    for file in temp_files:<br>        try:<br>            if os.path.exists(file):<br>                os.remove(file)<br>                print(f&quot;Cleaned up {file}&quot;)<br>        except Exception as e:<br>            print(f&quot;Error cleaning up {file}: {str(e)}&quot;)<br><br>with gr.Blocks(title=&quot;Emotion Reader&quot;, theme=gr.themes.Ocean()) as emotion_reader:<br>    # ...Other Code...<br>    <br>    #cleanup files - implementation!<br>    download_button.click(<br>        cleanUp_Files<br>    )</pre><p><strong>Finally,</strong> I launched this Gradio app and I uploaded the code into a file in HuggingFace Space called <em>app.py</em>.</p><pre># Launch the interface (added at the very end of the code outside the Gradio block)<br>if __name__ == &quot;__main__&quot;:<br>    emotion_reader.launch()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YxQrDfZciCB7a0bJ36ttfQ.png" /><figcaption>Finished Application UI</figcaption></figure><h3>Final Takeaways</h3><p>This project took a while because for a month I worked on it here and there. But once I started dedicating an hour a day or 3 hours on the weekend to it, I saw my progress and productivity increase significantly. I also found that I was able to keep track of what I was doing much easier. It was complex, but getting into the flow state to work on it really helped. It also helped when I started to write this article. I was able to break down the major components and what order I should present the steps in order for it to make the most sense.</p><p>Looking back on everything I wrote, I realized that I combined so much of what I learned into one big project. Yet, I still didn’t know everything. There was a lot of searching on Google (at some points I had 15 tabs open) and a lot of reading through documentations (which I found pretty enjoyable surprisingly). I ran into some errors that I found it hard to find an answer to and often had to figure it out. So, in this article, I talked about them as well as the little details so that you are able to learn something from it and find some of the answers you need. I hope you did!</p><p><strong>Did you enjoy reading the article?</strong></p><p>I know I enjoyed writing it! Want to read more? Check out my <a href="https://medium.com/@echung682">Medium</a> account. Want to follow my journey? Connect with me on <a href="https://www.linkedin.com/in/evelyn-chung-a8b4a3334/">LinkedIn</a> or subscribe to my <a href="https://evelynchung.substack.com/">monthly newsletter</a> on Substack.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a70dce83349" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep Dive Into Creating a CNN with Distributed Training]]></title>
            <link>https://medium.com/@echung682/a-deep-dive-into-creating-a-cnn-with-distributed-training-fcc3d4c508f5?source=rss-0724932c3bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcc3d4c508f5</guid>
            <category><![CDATA[convolutional-neural-net]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[distributed-training]]></category>
            <dc:creator><![CDATA[Evelyn Chung]]></dc:creator>
            <pubDate>Sat, 30 Nov 2024 15:19:12 GMT</pubDate>
            <atom:updated>2025-01-10T03:26:09.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*t8UZqMfczSjz23OpI-4h8A.png" /></figure><h3>Why Use Distributed Training?</h3><p>Well, first: What is Distributed Training? Distributed training is where the AI model uses multiple computers, or GPUs, to train itself.</p><p>To train an AI model, it takes a lot of time and computational power. This is especially true when the model has a lot of data to train on. By using distributed training, the model uses multiple GPUs to train the model simultaneously, resulting in an accurate model in less time.</p><h3>The Set Up</h3><p>For this project, I used Google Colab and <a href="https://pytorch.org/tutorials/beginner/ddp_series_theory.html">PyTorch</a> libraries, such as DDP (DistributedDataParallel), to create a CNN that incorporates distributed training. Using the Python coding language, the CNN trains on data from one of PyTorch’s libraries and initializes the system to run distributed training.</p><p>This model also uses torchrun, which handles any errors that the model might run into while training. Usually, if the model hits an error while training, it exits the training process. With torchrun, the trained model is saved at every certain interval of epochs, and if it hits an error while training, it will reload the model from that save point and continue the process.</p><h3>Diving Into the Code</h3><p><strong>Getting the Dataset</strong></p><p>The model is training on data from one of PyTorch’s pre-loaded datasets found in their <em>Dataset</em> library.</p><pre>import torch<br>from torch.utils.data import Dataset<br><br>class MyTrainDataset(Dataset):<br>    def __init__(self, size): #initializes the dataset<br>        self.size = size<br>        self.data = [(torch.rand(20), torch.rand(1)) for _ in range(size)]<br><br>    def __len__(self): #returns the number of samples in the dataset<br>        return self.size<br><br>    def __getitem__(self, index): #returns the sample in the dataset at the given index<br>        return self.data[index]</pre><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>Initializing and Setting Up the Distributed Training Framework</strong></p><p>The model uses the <em>torch.distributed </em>library to automatically figure out the world size (which is the total number of processors in a group) and the rank (which is a unique identifier for each process in the group).</p><pre>def initialize_distributed():<br>    dist.init_process_group(backend=&quot;gloo&quot;, init_method=&quot;env://&quot;)<br>    rank = dist.get_rank()<br>    world_size = dist.get_world_size()<br>    print(f&quot;Initialized distributed training: rank {rank}/{world_size}&quot;)<br>    return rank</pre><p>This function is called by a method that will set up the DDP and set the device that it will be using (cpu, cuda, etc.).</p><pre>def ddp_setup():<br>    #print(os.environ)<br>    print(&quot;going to assign rank now...&quot;)<br>    rank = initialize_distributed()<br>    print(&quot;finished assigning rank...&quot;)<br>    device = torch.device(f&quot;cuda:{rank}&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>    print(f&quot;Using device {device}&quot;)<br>    #init_process_group(backend=&quot;nccl&quot;)</pre><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>Creating the Trainer Class</strong></p><p>The <em>Trainer</em> class initializes the variables that the model needs in order to run and contains the definitions for functions that will run the model. The most important ones relating to torchrun are the <em>_save_snapshot()</em> function and the <em>_load_snapshot()</em> function.</p><p>The <em>_save_snapshot()</em> function saves the trained model at a certain epoch so the <em>_load_snapshot()</em> function can load it from that epoch if it runs into an error. This prevents the model from starting back at square one if there is any error in the training.</p><pre>    def _save_snapshot(self, epoch):<br>        snapshot = {}<br>        snapshot[&quot;MODEL_STATE&quot;] =  self.model.module.state_dict(),<br>        snapshot[&quot;EPOCHS_RUN&quot;] =  epoch<br><br>        torch.save(snapshot, self.snapshot_path)<br>        print(f&quot;Epoch {epoch} | Training snapshot saved at {self.snapshot_path}&quot;)</pre><pre>    def _load_snapshot(self, snapshot_path):<br>        snapshot = torch.load(snapshot_path, map_location=loc)<br>        self.model.load_state_dict(snapshot[&quot;MODEL_STATE&quot;])<br>        self.epochs_run = snapshot[&quot;EPOCHS_RUN&quot;]<br>        print(f&quot;Resuming training from snapshot at Epoch {self.epochs_run}&quot;)</pre><p>The <em>train() </em>function of the <em>Trainer</em> class, when called, is what trains the model to run for a certain number of epochs, on data in certain batch sizes, and saves the data every x number of epochs.</p><pre>    def train(self, max_epochs: int):<br>        for epoch in range(self.epochs_run, max_epochs): <br>        #the parameters are set so the train() function itself will not start back at 0 every time it is called,<br>        #but rather where the last epoch was when the error occurred<br>            self._run_epoch(epoch) #this function runs the epoch and contains a function called _run_batch()<br>                                   #that feeds the model through the neural network layers for training<br>            if self.gpu_id == 0 and epoch % self.save_every == 0:<br>                self._save_snapshot(epoch)</pre><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>Determining the Arguments for the Model</strong></p><p>In order to train the model, it needs to know how many total epochs it is running for, at what intervals of epochs is it saving the model, and how big is the batch size.</p><p>It is possible to determine the values for these arguments using <em>sys.argv </em>(in which case the <em>sys</em> library would need to be imported), however if that doesn’t work, a list of arguments could be created and parsed.</p><pre>import argparse<br><br>def parse_arguments():<br>    parser = argparse.ArgumentParser(description=&quot;Script for training&quot;)<br>    parser.add_argument(&quot;total_epochs&quot;, type=int, help=&quot;Number of epochs to run&quot;) #total_epochs represents the number of epochs the model trains for<br>    parser.add_argument(&quot;save_every&quot;, type=int, help=&quot;Frequency of saving the model&quot;) #save_every represents how often the trained model is saved (ie. every 10, every 20)<br>    parser.add_argument(&#39;--batch_size&#39;, default=32, type=int, help=&#39;Input batch size on each device (default: 32)&#39;)<br><br>    # Only parse arguments if running from the command line<br>    if len(sys.argv) &gt; 1 and &quot;kernel&quot; not in sys.argv[0]:<br>        return parser.parse_args()<br>    else:<br>        # Provide defaults for notebook usage<br>        class Args:<br>            total_epochs = 10<br>            save_every = 5<br>            batch_size = 32<br>        return Args()</pre><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>Writing the Main Function</strong></p><p>The <em>main</em> function is where all of the defined functions are called to set off a chain of events that train the model on the data using distributed training.</p><pre>def main(save_every: int, total_epochs: int, snapshot_path: str = &quot;snapshot.pt&quot;):<br>    ddp_setup() #function that will set up ddp and calls the function to initialize ddp<br>    dataset, model, optimizer = load_train_objs() #this function initializes the dataset, the layer that the model is fed through, and the optimizer (SGD for this model)<br>    train_data = prepare_dataloader(dataset, batch_size=32) #this function returns the values of PyTorch&#39;s DataLoader which takes the inputted dataset, breaks into batches, and returns the input values and labels<br>    trainer = Trainer(model, train_data, optimizer, save_every, snapshot_path)<br>    trainer.train(total_epochs)<br>    dist.destroy_process_group()</pre><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>Putting All In Motion</strong></p><p>The <em>main</em> function is called via this code:</p><pre>if __name__ == &quot;__main__&quot;:<br>    args = parse_arguments() #calls the function that determines the arguments needed for the main function<br><br>    world_size = torch.cuda.device_count()  # shorthand for cuda:0<br>    #mp.spawn(main, args=(world_size, args.save_every, args.total_epochs, args.batch_size), nprocs=world_size)<br>    os.environ[&quot;CUDA_VISIBLE_DEVICES&quot;] = &quot;0&quot;  # Forces Colab to use GPU 0<br><br>    main(args.save_every, args.total_epochs) #calls the main function using the arguments determined by the parse_arguments()</pre><p>This sets in motion all of the functions that are called in the <em>main</em> function that train this model using distributed training.</p><h3>What Did I Learn?</h3><p>Going into this project I did a lot of research at first. I started by learning more about CNNs, building a CNN, and then doing more research on the components I used in the CNN (such as torch.nn.Linear). Although this helped give me the background to understand what I was working with while incorporating DDP, I found that I was terribly underprepared.</p><p>I have almost no background knowledge in hardware, so while I knew what I was writing and understood the functions being called from each library, any errors I got relating to hardware were completely new. Learning to understand those was probably the hardest part.</p><p>Despite the trial and error and amount of time it took to research and create this project, I don’t regret a thing. I learned a ton and I feel that I accomplished what I set out to do: build a CNN with distributed training and understand all of its components. I can’t wait to take what I learned an apply it to creating a new, innovative build!</p><p><strong>Did you enjoy reading the article?</strong></p><p>I know I enjoyed writing it! Want to read more? Check out my <a href="https://medium.com/@echung682">Medium</a> account. Want to follow my journey? Connect with me on <a href="https://www.linkedin.com/in/evelyn-chung-a8b4a3334/">LinkedIn</a> or subscribe to my <a href="https://evelynchung.substack.com/">monthly newsletter</a> on Substack.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcc3d4c508f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making an AI Therapist: Behind the Scenes]]></title>
            <link>https://medium.com/@echung682/making-an-ai-therapist-behind-the-scenes-391f6eccb2aa?source=rss-0724932c3bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/391f6eccb2aa</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[ai-therapist]]></category>
            <dc:creator><![CDATA[Evelyn Chung]]></dc:creator>
            <pubDate>Fri, 29 Nov 2024 13:43:46 GMT</pubDate>
            <atom:updated>2024-11-29T16:54:36.994Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OQwCR7U3z76q_k8i" /><figcaption>Photo by <a href="https://unsplash.com/@mimithian?utm_source=medium&amp;utm_medium=referral">Mimi Thian</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine a world where whenever you feel sad, happy, angry, or just want someone to confide in. Well, that someone could be a <em>something</em>. An AI therapist located in your phone that you can talk to whenever you need to get something off your chest.</p><p>Now, there are many AI therapists that already exist, but with one major limitation. Unlike a human therapist, these AI therapists aren’t reading your facial expressions and interpreting your emotions. Instead, they rely on the words you speak or type into the chat, which can be anywhere from misleading to completely inaccurate - an outcome that is more than likely given how complex human emotions are.</p><p>That’s why my team (<a href="https://www.linkedin.com/in/theo-kertesz-389144330/">Theo Kertesz</a>, <a href="https://www.linkedin.com/in/cyrus-andaz-785662307/">Cyrus Andaz</a>, <a href="https://substack.com/@shawndmello">Shawn D’Mello</a>) and I created Pandora AI.</p><h3>What Did We Build?</h3><p>Pandora AI is a protype AI therapist, using a <a href="https://github.com/avocadopelvis/pandora/blob/main/README.md">model on GitHub</a> as a starting point, that interprets micro-expressions in the user’s face to detect emotions. The model identifies minute differences in the user’s face that signal specific emotions that a text-to-text chatbot wouldn’t detect. This can enhance the understanding of user expression and input to allow Pandora AI to foster a more effective, personalized therapy experience that is accessible to all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P7Sx96d591hXJpJ3z3-ESg.png" /></figure><h3>A Brief Overview</h3><p>Pandora AI contains two major components: code using a webcam to handle recognizing emotions from facial expressions and code to handle the therapist chatbot. The two components are connected by a few lines of code that input the emotion detected from the webcam into the chatbot. Let’s go through some of the major functions of each component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rwczfHYTsZfH0lTY" /><figcaption>Photo by <a href="https://unsplash.com/@der_maik_?utm_source=medium&amp;utm_medium=referral">Maik Jonietz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Going Deeper</h3><p><strong>A Closer Look (Smile for the Camera!)</strong></p><p>All of the action for the webcam happens in one function defined as <em>capture_webcam()</em>. In it, we initialize the webcam, emotion detector, and face detector; as well as running the code that reads the facial expression to predict the emotion being expressed. Reading the facial expression and predicting the emotion happens in a while loop that continues until “q” is pressed.</p><p>Pandora AI uses a webcam and <a href="https://www.geeksforgeeks.org/opencv-python-tutorial/">Python’s OpenCV library</a> to see the user’s emotions. It takes specific frames at set intervals of the video feed from the webcam as image inputs using the following lines of code:</p><pre>ret, frame = cap.read() #here, cap refers to the webcam</pre><p>The image is then compressed into a format that is usable by a <a href="https://www.edps.europa.eu/system/files/2021-05/21-05-26_techdispatch-facial-emotion-recognition_ref_en.pdf">FER (Facial Emotion Recognition)</a>. The compressed image is inputted into the FER that outputs the predicted emotion and confidence score. The FER uses a pre-trained micro-expression model that has an accuracy of over 95%:</p><pre>emotion_detector = FER() #use FER(mtcnn=True) for more accurate results<br><br>#the frame captured from the webcam is converted to a color scale that is used by FER<br>rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)<br><br>emotion, score = emotion_detector.top_emotion(rgb_frame)</pre><p>Pandora AI uses the <em>top_emotion()</em> function of FER in order to detect the emotion that is expressed in the user’s face, specifically only the emotion with the highest prediction score.</p><p>The model uses <a href="https://towardsdatascience.com/face-detection-with-haar-cascade-727f68dafd08">Haar Cascades</a> to detect the face in the frame from the video feed using these lines of code:</p><pre>gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)#converting the image to grayscale<br>faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))</pre><p>The image is first converted into grayscale because it is necessary for the Haar Cascades function to work. This is because the Haar Cascades is measuring the intensity (lightness/darkness) of the pixels to find edges in the images in order to identify where in the image the face is. Putting the image in grayscale makes the process easier and more effective.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>A Talk-through the Chatbot Code</strong></p><p>Before writing the chatbot code, some platforms need to be added first.</p><pre>tensorflow<br>scikit-learn<br>nltk<br>colorama<br>flask</pre><p>Pandora AI has two scripts to run the model, using TensorFlow libraries. It first uses the <em>model </em>script that trains the model on data present in a certain json file. This file contains tags to identify subjects the user could be talking about, patterns (which are sentence patterns the user could use), and responses (lists of responses to what the user could be talking about). One example is shown below:</p><pre>{&quot;tag&quot;: &quot;happy&quot;,<br>        &quot;patterns&quot;: [&quot;I feel happy&quot;],<br>        &quot;responses&quot;: [&quot;That&#39;s amazing! What else are you feeling? &quot;]<br>    }</pre><p>The <em>model</em> script runs a for loop that adds all of the data from this json file into list variables in the script. It uses sklearn’s <em>LabelEncoder() </em>function to assign a numerical value to each of the tags.</p><pre>lbl_encoder = LabelEncoder()<br>lbl_encoder.fit(training_labels) #training_labels is the script&#39;s list of &quot;tag&quot; from the json file<br>training_labels = lbl_encoder.transform(training_labels)</pre><p>Since, in the real world, it is unlikely the user will use only the words that are in the computer’s vocab (as established by the data in the json file), it needs a generalized way to label words it doesn’t know. It does this by creating an “unknown word” token and using a Tokenizer (in this case, imported from TensorFlow). Tokens are the words or subwords of a text. The Tokenizer takes the input text and breaks it down into a list of tokens. These tokens are each assigned a numerical value (like how the <em>LabelEncoder() </em>assigned numerical values to each “tag”) and puts them into a list, in which each value corresponds with each unique word of the sentence. These values are placed in the same order as the words were placed in the sentence. Any words from the user input that are not in its vocabulary are replaced with the “unknown word” token.</p><pre>#text-preprocessing<br>vocab_size = 1000<br>embedding_dim = 16<br>max_len = 20<br>oov_token = &quot;&lt;OOV&gt;&quot;<br><br>tokenizer = Tokenizer(num_words = vocab_size, oov_token = oov_token)<br>tokenizer.fit_on_texts(training_sentences)<br>word_index = tokenizer.word_index<br>sequences = tokenizer.texts_to_sequences(training_sentences)<br>padded_sequences = pad_sequences(sequences, truncating = &#39;post&#39;, maxlen = max_len)</pre><p>Once all of the data has been prepared, the model is fed through a neural network with multiple layers for training.</p><pre>model = Sequential()<br>model.add(Embedding(vocab_size, embedding_dim, input_length=max_len))<br>model.add(GlobalAveragePooling1D())<br>model.add(Dense(16, activation=&#39;relu&#39;))<br>model.add(Dense(16, activation=&#39;relu&#39;))<br>model.add(Dense(num_classes, activation=&#39;softmax&#39;))</pre><p>The <em>chat</em> script is where the action happens. Once the model is done training, it is saved in the <em>model</em> script:</p><pre>#save the trained model<br>model.save(&#39;chat-model.keras&#39;)</pre><p>To then be loaded into the <em>chat </em>script to chat with the user.</p><pre>#load trained model<br>    model = tf.keras.models.load_model(&#39;chat-model.keras&#39;) <br>    model.save(&quot;chat-model.keras&quot;, save_format=&quot;keras&quot;)<br>    model = load_model(&quot;chat-model.keras&quot;) </pre><p>The <em>chat</em> script uses the function <em>chat()</em> to actually run the conversation with the user. To chat with the user, the function takes in user input (until “quit” is inputted) and reverse engineers to find the right response. It uses the Tokenizer and the <em>LabelEncoder() </em>to predict what the user is saying, then uses that knowledge to figure out what “tag” (from the json file) that the sentence corresponds to. From there, the chatbot can determine a possible response from the list of responses that correlate with that tag.</p><pre>result = model.predict(keras.preprocessing.sequence.pad_sequences(tokenizer.texts_to_sequences([inp]), truncating = &#39;post&#39;, maxlen = max_len))<br>tag = lbl_encoder.inverse_transform([np.argmax(result)])<br><br>for i in data[&#39;intents&#39;]:<br>    if i[&#39;tag&#39;] == tag:<br>        print(Fore.GREEN + &#39;Pandora:&#39; + Style.RESET_ALL, np.random.choice(i[&#39;responses&#39;]))</pre><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>Integrating the Components</strong></p><p>The <em>capture_webcam()</em> function is what runs the code to not only detect the face, but also to read the emotion expressed in it. To utilize this function and integrate it into the chatbot, we imported the function and called it in the chatbot code:</p><pre>from WebCam import capture_webcam<br><br>&#39;&#39;&#39;<br>much later in the code...<br>&#39;&#39;&#39;<br><br>my_feeling = capture_webcam()</pre><p>Originally, the <em>capture_webcam()</em> function can only be exited by pressing the “q” button. However, we wanted to access the emotion predicted by the webcam and not have to press “q” to exit the webcam. So we added this line of code to the while loop in the <em>capture_webcam()</em> function:</p><pre>return emotion</pre><p>The return statement ends the while loop and exits the <em>capture_webcam()</em> function, which allows the rest of the chatbot code to continue running. It also assigns the value of <em>emotion </em>to<em> </em>the variable <em>my_feeling, </em>so it can be used later in the chat. For simplicity reasons, we used <em>my_feeling</em> (an emotion such as “happy,” “sad,” etc) and added it to a string beginning with “I feel ”.</p><pre>inp = &quot;I feel &quot; + str(my_feeling)<br>print(Fore.LIGHTBLUE_EX + &#39;User: &#39; + inp)</pre><p>This sentence was inputted into the chatbot as the user input for Pandora AI to respond to. Since this left no way for the program to exit the chatbot, we changed the while loop to a for loop. Additionally, sometimes the <em>capture_webcam()</em> function might return the value “None” for <em>emotion</em>. This is because the person might not be looking at the camera or there is no face present in the camera to read the face of. To account for such a circumstance, we added a while loop before the user input assignment statement:</p><pre>while (str(my_feeling) == &quot;None&quot;):<br>     my_feeling = capture_webcam()<br><br>inp = &quot;I feel &quot; + str(my_feeling) #input statement mentioned in previous code block</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h1uwf1_jcB74LKHm" /><figcaption>Photo by <a href="https://unsplash.com/@blavon?utm_source=medium&amp;utm_medium=referral">S&amp;B Vonlanthen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Addressing Current Limitations with Future Improvements</h3><p>As it is now, Pandora AI is trained to recognize a small selection of emotions: happy, sad, angry, neutral, disgust, surprise, and fear. Humans have a much larger range of emotions that are a complex blend of these seven and more. Therefore, in order to make Pandora AI more accurate at detecting emotions, we want to expand Pandora AI’s emotional library with more specific emotions. Pandora AI also cannot read facial expressions unless it sees the entire face fully and clearly. Another next step would be to train Pandora AI to read facial expressions even if it can only see half of the face.</p><p>Additionally, emotions aren’t the only sign of inner turmoil. We also want to integrate physiological data, such as heart rate and sleep patterns. By integrating this data, Pandora AI will not only be able to recognize users’ emotions, but also their well-being and behavior.</p><p>Furthermore, Pandora AI runs on a for loop that inputs statements “I feel” + emotion into the chat. This isn’t exactly ideal. Our vision is to make Pandora AI able to see the user’s emotions in real time, in the background, and be able to factor it into its responses.</p><p>With these new features, Pandora AI will be able to understand a wider range of emotions and user behavior that will lead to more personalized conversations that are more beneficial and insightful to the user.</p><h3>My Learning Curve</h3><p>Although I have a little experience with creating neural networks, specifically CNNs (Convolutional Neural Networks), this application of it was completely new. I ran into many errors that I’ve never seen before, particularly involving libraries. From this experience, I learned a lot more about working in the terminal in Visual Studio Code and gained a deeper understanding of the Deep Learning models that run chatbots.</p><p>Despite the hardships and the number of times that I wanted to throw my computer out the window, I can honestly say I enjoyed working on this project and especially loved working with my team. This project has broadened and deepened my understanding and knowledge of Deep Learning overall. I am so excited to work on my next project and continue on this journey!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PUSYziZt4qok8Nvn" /><figcaption>Photo by <a href="https://unsplash.com/@jupp?utm_source=medium&amp;utm_medium=referral">Jonathan Kemper</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Did you enjoy reading the article?</strong></p><p>I know I enjoyed writing it! Want to read more? Check out my <a href="https://medium.com/@echung682">Medium</a> account. Want to follow my journey? Connect with me on <a href="https://www.linkedin.com/in/evelyn-chung-a8b4a3334/">LinkedIn</a> or subscribe to my <a href="https://evelynchung.substack.com/">monthly newsletter</a> on Substack.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=391f6eccb2aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solar Panel Energy Production and Electric Grid Energy Optimization (feat.]]></title>
            <link>https://medium.com/@echung682/solar-panel-energy-production-and-electric-grid-energy-optimization-feat-196a2672bdcf?source=rss-0724932c3bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/196a2672bdcf</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[solar-energy]]></category>
            <category><![CDATA[electric-grid]]></category>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[predictive-modeling]]></category>
            <dc:creator><![CDATA[Evelyn Chung]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 20:06:25 GMT</pubDate>
            <atom:updated>2024-10-23T20:22:47.611Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solar Panel Energy Production and Electric Grid Energy Optimization (feat. AI Predictive Analysis Models)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QjKQf4jcILJwchWC" /><figcaption>Photo by <a href="https://unsplash.com/@publicpowerorg?utm_source=medium&amp;utm_medium=referral">American Public Power Association</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The sun is one the largest energy sources for Earth. It provides the light that is crucial for a plant’s survival, the heat that evaporates water, and the energy with the capability of powering the world (for as long as it exists). Over the course of a year, an average of 342 watts of solar energy descend on a single square meter of the Earth. That’s around 44 quadrillion watts of solar energy falling on the Earth’s surface every year! Just one hour of energy absorption at this rate could power the entire world for a whole year!</p><p>Thanks to technological innovation, society has a way to absorb this energy: solar panels, which are also called photovoltaic (PV) panels. Although this innovation has seen numerous significant advancements in recent years, current solar panels operate at less than 23% efficiency. This means that even the best modern solar panels only absorb 23% of the energy that the sun is providing, which means that a single one square meter solar panel only absorbs about 79 watts of energy over the course of a year. With solar panels not being able to absorb every drop of energy it can from the sun, scientists are working on ways to make each drop this technology collects count. This is development is crucial towards making the world run on cleaner energy and protect the environment.</p><p>Currently, modern United States power systems rely on the electric grid that uses a lot of fossil fuels to power the nation. The grid is already unstable, and if solar panels aren’t able to produce large amounts of energy consistently, then there will be a lot more blackouts. If the world is going to have cleaner energy, all the energy from solar panels needs to be able to be predicted accurately. To do this, scientists are working on energy optimization in the electric grid and predicting energy productivity in solar panels. Energy optimization is all about using electricity as efficiently as possible. Predicting energy productivity is all about predicting and anticipating changes in energy production, from solar panels in this case. How are they doing this? The first step is using AI, specifically its predictive analysis models, to find patterns in data collected from sensors.</p><h3>Predicting the Unpredictable</h3><p>Solar panels’ productivity relies on many factors, especially weather, which fluctuates often. For predictions based on weather, AI specifically uses solar forecasting and cloud-imaging technology. Solar forecasting uses meteorological and past solar energy production data to predict how much solar energy will be produced at any given place in any type of weather. Cloud-imaging technology uses sky cameras that collect real-time data on the current and local atmospheric conditions. This technology then enhances the quality of solar forecasting by increasing its precision. Their algorithms identify patterns in weather patterns, historical energy production data, and satellite imagery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NYuKwU8l0d0WGOvt" /><figcaption>Photo by <a href="https://unsplash.com/@daveballew?utm_source=medium&amp;utm_medium=referral">David Ballew</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What does a Cloud have to do with AI?</h3><p>As suggested by the name, <strong>cloud-imaging technology</strong> is based on data collected from studying the clouds. This data provides lots of information that impacts weather prediction and climate prediction, two key factors that affect solar panel productivity. The data is observed by satellite remote sensing and ground-based sky cameras, both of which take pictures of the sky at set intervals of time. Both of these methods collect images of clouds, however the former captures low resolution images. The latter has a smaller observation range which allows it to focus more on the details of the clouds, which provides more valuable information.</p><p>For example, ground-based sky cameras are able to capture, in better resolution, specific details of clouds, which are obtained through retrieval algorithms. These details are cloud textures, colors, and spectral features (which, in this case, is referring to the specific light waves in the electromagnetic spectrum that are related to the properties of clouds). Using these data points, AI algorithms and predictive models can help scientists and solar operators make decisions on the best methods to increase solar productivity.</p><h3>Sky Cameras and Decision Trees</h3><p>The decision trees can be physically described as a flow chart that utilizes a strategy commonly known as “divide and conquer.” The general idea is that the large group gets broken down into smaller and smaller groups of <strong>atoms</strong> (the data points relating to an object such as a person). The data points themselves are called <strong>indicators</strong>. The tree begins with the root at the top and branches into either-or scenarios (marked by <strong>nodes</strong>), which then branch into more nodes, until it reaches a terminal node (called a <strong>leaf</strong>) where the group of atoms can’t be broken down further, or it would overcomplicate the tree to do so. This decision tree will ultimately lead to a prediction of a piece of information that is called the <strong>target indicator</strong>.</p><p>The goal of the decision tree is to take a piece of information and be able to make a prediction based on the information it trained off of to predict the likely output. It does this by categorizing the data it trained off of, isolating groups of data based on specific characteristics. For this application, sky cameras would collect data about a cloud that it captures and a decision tree would use the data to come to a conclusion about what type of cloud it is. From there, it is able to predict the weather. To explain how a decision tree works, an example has been provided.</p><p>The following data, which are some statistics considered when classifying a cloud, is used to construct a decision tree (of course much more data would have been collected than what is shown in the table, but for simplicity purposes this example will stick to three):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*nsCMDNXlPUjCnOHxwZkRHA.png" /></figure><p>Using the terms defined previously, each type of cloud would be an atom and each data point (VIS spectral region, cloud top height, and optical thickness) is an indicator. The target indicator is the cloud types column. In other words, if given the inputs of each of these indicators, the tree predicts that these inputs are describing a specific cloud type.</p><p>Changing these values to x and y help to plot the data visually on a graph. However, the coordinate points are in regards to the variables compared to each other. In this example, x1 is plotted against x3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*ViBTCyFvcbz2hP4SChDDxg.png" /></figure><p>In order to be able to have the best prediction, the decision tree needs to break up the data into a way that will separate a defining indicator. This is done by drawing lines that best separate each group, like how they were done here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/0*NSlfWtp0D8o6Z18_" /><figcaption>(Note: This data in this graph is unrelated to the data used in the example. It is meant for visualization purposes only)</figcaption></figure><p>Continuing with the example of x1 vs. x3 (x3 being along the x-axis), a line x1 = 80 will work because it draws a line between the VIS spectral regions (x1) of the cumulonimbus clouds and the others, thus isolating the VIS values that will indicate a cumulonimbus cloud. In order to separate the data that classifies a stratus cloud from a cumulus cloud, a line x3 = 1.0 would separate the optical thickness values (x3) that differentiate a stratus cloud from a cumulus cloud. Note that this will not be a perfect separation because some stratus clouds AND some cumulus clouds have an optical thickness of 1.0; in other words, the two overlap. In this case, more data points would be needed to differentiate them, or the <a href="http://www.ams.org/publicoutreach/feature-column/fc-2014-12">decision tree is expanded to account</a> for the overlap. For example, another node could be added to see whether the VIS value is greater than or less than 30%.</p><h3>What is that in “tree” form?</h3><p>Now that there is a graph, to visualize it into a tree involves using either-or statements that are represented at each node. The tree can almost be thought of as a big if-else loop. Using the example used for the graph :</p><ul><li><strong>If </strong>x1 80, the tree predicts “Cumulonimbus Cloud”; <strong>Else </strong>(x &gt; 58), the tree moves onto the next node</li><li>Note that since the x2 58 condition leads to a prediction, it ends with a leaf (a terminal node), the other condition (else, x &gt; 58) leads to another node that does not end in a prediction so it is not a leaf</li><li>For the next node: <strong>If </strong>x3 1.0, the tree predicts “Cumulus Cloud”; <strong>Else </strong>(x &gt; 56), the tree predicts “Stratus Cloud”</li></ul><p>Each condition (x1 80, x3 1.0, etc) is a branch that connects any two nodes (whether it is a root, a leaf, or just a node). In the end, the tree would look something like this (in terms of shape):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/0*ZVpGmNnJ15rt-FII" /><figcaption>(Note: This data in this model is unrelated to the data used in the example. It is meant for visualization purposes only)</figcaption></figure><h3>In Practice…</h3><p>A sky camera, using <a href="https://amt.copernicus.org/articles/11/409/2018/#abstract">cloud retrieval algorithms</a>, has taken an image of a cloud that it has determined to have a VIS with 87% reflectance, a cloud top height of 6,000 meters, and an optical thickness of 3.1. Using the decision tree constructed in the example, the prediction is obtained by starting at the root and deciding: is the “input VIS spectral value” 80? The statement results to true and so the tree follows the branch that correlates to the true statement of input 80. This leads to a leaf that is labeled as “cumulonimbus cloud” and so the tree predicts that this is cumulonimbus cloud.</p><h3>Applying the Prediction</h3><p>AI can identify cumulonimbus clouds and so many others which helps it to predict when it will rain. It can “see” the different clouds and use algorithms to identify the patterns in clouds that will lead to the formation of cumulonimbus clouds. For reference, a cumulonimbus cloud is the only type of cloud that produces lightning, thunder, and hail (earning it the nickname of “thunderstorm cloud”). This kind of weather is not very good news for solar panels.</p><p>Weather like rain and snow will lower the productivity of the solar panels by 10%-25%. Since energy production is lower on these kinds of days, AI can limit the energy usage to conserve energy by turning off unneeded household appliances, for example.</p><h3>AI and the 142-year-old American Electric Grid</h3><p>That’s right, the current United States’ electric grid is 142-years-old, dating all the way back to the good old days with Thomas Edison! Now, AI is being implemented in the grid, and there are many benefits to its involvement. Similar to how AI identifies patterns in clouds, AI can observe patterns in energy usage and production, and then is able to decide how to distribute resources accordingly. For example, in a person’s home, an AI system knows what appliances are non-essential, and can turn them off when energy production is low. This system can also be used on a larger scale. Throughout an energy grid, AI is able to apply the data it has absorbed to make informed decisions on efficient energy distribution, preventing grid instability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SDANEl7oQnjzuZfd" /><figcaption>Photo by <a href="https://unsplash.com/@matthewhenry?utm_source=medium&amp;utm_medium=referral">Matthew Henry</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is the the Electric Grid?</h3><p>The United States electric grid powers millions of buildings through a network of power plants, transmission lines and distribution centers. In the United States, there are 11,000 power plants, 3,000 utilities, and over 2 million miles of power lines. It starts with generating electricity in a power plant. Then, long distance transmission lines carry the electricity across the country at high voltages. In order to be used in homes, high-voltage electricity is converted into a lower voltage in a process called <strong>stepping down</strong>. This is done at substations and local facilities that also distribute the lower voltage electricity. In 2020, natural gas (from fossil fuels) produced 1.6T kilowatt hours of electricity in the U.S. while renewable energy sources produced only 834.1B kilowatt hours. However, renewable resources, such as solar energy, are projected to generate about 40% of U.S. electricity by 2050. In order to keep up with the energy demand, energy usage needs to become efficient, and in order to integrate more solar energy, the electric grid needs to be optimized. This is where AI and technology comes into help.</p><h3>Introducing the Smart Grid</h3><p>The <strong>“smart” grid</strong> uses technology to optimize the efficiency of the electricity grid. It uses a variety of technologies such as sensors and smart meters to provide two-way communication between the consumer and the energy providers. This two-way communication is useful in making sure that the right amount of energy is being produced and distributed to stay even with demand. If demand becomes higher than the supply, a blackout happens.</p><p><strong>Smart meters</strong> automatically read residential and commercial energy usage and are able to send the data to energy suppliers through wireless networks. It can track energy costs, usage, and wasted energy. It uses a power system to measure the amount of power being used, a microcontroller (a small, single-chip computer) to manage the smart meter technology, and a communication system to send and receive data. This data could also be inputted into an AI algorithm that uses the data from the smart meters to collect data that is needed for their predictive models.</p><p><strong>Synchrophasors</strong>, also called synchronized phasors, are able to measure energy flow and usage in real time. It can measure the data from voltage, phase angle, and frequency. Then, it is sent to a phasor data concentrator (PDC), or phasor measurement unit (PMU). These real-time measurements can be used with AI algorithms and predictive models to make the most efficient real-time decision.</p><p>Using historical and real-time data gathered from sensors like smart meters and synchrophasors, AI’s predictive models can optimize energy usage and distribution throughout the grid to avoid blackouts.</p><h3>How is Energy Usage predicted?</h3><p>With a process called <strong>load forecasting</strong>, which simply defined, is predicting how much electricity will be needed at a given time and how it will affect the grid. Load forecasting is the method used to manage energy distribution and usage throughout the grid and its capability directly impacts the electric grid’s reliability, efficiency, and cost. Its goal is to generate enough energy to keep up with demand while also not wasting energy and being inefficient. There are three main load forecasting time frames that each are used for specific strategic planning decisions.</p><ul><li><strong>Short-term load forecasting</strong>, covering about a week-long period, is most important for managing the grid in real-time. Therefore, it relies on recent weather forecasts and production data. It is used to make in-the-moment decisions about where to distribute energy and how much to distribute.</li><li><strong>Medium-term load forecasting</strong> usually covers a period from a week to a year and is most important for scheduling maintenance and managing fuel reserves. It uses data that considers seasonal energy usage variations as opposed to ones in real-time.</li><li><strong>Long-term load forecasting</strong> usually refers to periods of time greater than a year and is most important for system planning and optimization, as well as future investments in energy sources.</li></ul><h3>Load Forecasting and Regression Models</h3><p>Regression models, specifically <strong>linear regression models</strong>, are a type of predictive analysis model that is used to find linear relationships in large data sets that can usually be defined with a formula. In this case, regression models find patterns between data from energy consumption, external weather conditions, and internal building conditions.</p><p>Linear regression uses the equation:</p><p>Y = β0 + β1X1 + β2​X2 ​+ … + βn​Xn​ + ϵ</p><p>Where (in the case of load forecasting and energy grids):</p><ul><li><strong>Y </strong>is how much electricity is needed, the dependent variable</li><li><strong>β0</strong> is how much energy is needed without factoring in all the other variables</li><li><strong>β1, β2…βn</strong> is how much their corresponding variable input (such as time, temperature, weather, etc) will affect how much electricity is needed</li><li><strong>X1, X2…Xn</strong> is the variable input/independent variable (time, temperature, etc.) that affects the amount of electricity needed</li><li><strong>ϵ</strong> is called the error term because it accounts for the difference between the actual values and the predicted ones that could cause an error</li></ul><p>Data collected from sensors like smart meters, synchrophasors, and sky cameras is all taken into consideration for determining how much energy is needed. Once outliers have been removed, each independent variable is studied to see how they affect and relate to the dependent variable, and in some cases to each other. For example, time and temperature are both independent variables, however they can correlate with one another: midday is usually the hottest part of the day. Now, the linear regression model comes into play. It trains on the data that it is given and adjusts the coefficients of the equation to find the best-fit line to most accurately predict results based on any given input. It continues to train and learn by estimating the coefficients, and then using the equation with those coefficients to generate a prediction. Then, it compares its predicted value to the actual value, which is included in the training data, to continue to adjust the equation. This constant learning and reevaluation helps the model minimize the difference between its prediction and the actual, making the linear regression model more accurate in predicting how much electricity is needed and then only distributing that amount of energy.</p><h3>How is AI Reinforced Load Forecasting Changing the Grid Game?</h3><p>As load forecasting becomes more accurate, it becomes easier to implement renewable energy sources into the grid. There will still be some challenges, but an extremely accurate and reliable load forecasting system will be able to handle fluctuations in the energy production and adjust accordingly in real-time. Not only does this reduce the need for fossil fuels, but it also reduces energy waste. Less energy is wasted, but there is enough energy to keep up with demand, preventing blackouts.</p><h3>A Bright Future Ahead (Pun Intended)</h3><p>Powering the United States requires about <a href="https://www.freeingenergy.com/how-much-solar-would-it-take-to-power-the-u-s/#:~:text=Given%20the%20U.S.%20consumes%20about,United%20States%20for%20a%20year.">4 petawatts (4 x 10¹⁵) hours of electricity</a> every year, <a href="https://www.eia.gov/tools/faqs/faq.php?id=427&amp;t=3">60%</a> of which came from fossil fuels in 2023 (about 2,505 billion kWh (kilowatthours)). If <a href="https://www.eia.gov/tools/faqs/faq.php?id=74&amp;t=11">about 0.86 pounds</a> of CO2 emissions are produced per kWh, that means in 2023, the United States alone released about 2.15 x 10¹² pounds of CO2 into the air. That is equal to over 5 million Antarctic blue whales!</p><p>How much of that energy came from solar? About <a href="https://www.eia.gov/tools/faqs/faq.php?id=427&amp;t=3"><strong>3.9%</strong></a>, or 165 billion kWh. But there is good news! The U.S. Energy Information Administration (EIA) predicts that solar energy generation will <a href="https://www.forbes.com/home-improvement/solar/solar-energy-facts/">increase by 75% in the next few years</a>. They project that solar panels will generate about 286 billion kWh in 2025. With the help of AI, this projection is not only likely to happen, but also likely to be surpassed, since AI can help solar panels make larger strides in advancements in the next few years. Not only will AI’s improvements in solar panels help drastically reduce carbon emissions, it will also <a href="https://tech-stack.com/blog/solar-panel-efficiency/">increase energy production by up to 25% while also cutting operation costs by 30%</a>.</p><p>Solar panels are key to creating a global source of renewable energy, and with the help of AI, they are closer to achieving that goal. AI’s predictive analysis models are able to predict solar panels’ productivity in real-time–information that can then be used by linear regression models, in addition to energy usage data, to determine how to distribute electricity and when to expect to need to use energy reserves.</p><p>Although there are still improvements to be made, scientists and researchers are actively finding ways to overcome these challenges. Furthermore, the solar panel and AI industries are constantly and rapidly advancing, working towards making a cleaner atmosphere and more efficient electrical system for generations to come. Here’s to a brighter future!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P3El7BYiTfKY2fHX" /><figcaption>Photo by <a href="https://unsplash.com/@davealmine?utm_source=medium&amp;utm_medium=referral">Dawid Zawiła</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Did you enjoy reading the article?</strong></p><p>I know I enjoyed writing it! Want to read more? Check out my <a href="https://medium.com/@echung682">Medium</a> account. Want to follow my journey? Connect with me on <a href="https://www.linkedin.com/in/evelyn-chung-a8b4a3334/">LinkedIn</a> or subscribe to my <a href="https://evelynchung.substack.com/">monthly newsletter</a> on Substack.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=196a2672bdcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>