<?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 Vidushi Valli Surendran on Medium]]></title>
        <description><![CDATA[Stories by Vidushi Valli Surendran on Medium]]></description>
        <link>https://medium.com/@vidushi-valli-surendran?source=rss-1c2ea4bc3f60------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DddmpyPbkVU8OC6Up8-JEQ.jpeg</url>
            <title>Stories by Vidushi Valli Surendran on Medium</title>
            <link>https://medium.com/@vidushi-valli-surendran?source=rss-1c2ea4bc3f60------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:09:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vidushi-valli-surendran/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[Revive Our Reefs: SeaBloom]]></title>
            <link>https://vidushi-valli-surendran.medium.com/revive-our-reefs-seabloom-951d591cf0cf?source=rss-1c2ea4bc3f60------2</link>
            <guid isPermaLink="false">https://medium.com/p/951d591cf0cf</guid>
            <dc:creator><![CDATA[Vidushi Valli Surendran]]></dc:creator>
            <pubDate>Thu, 07 Dec 2023 21:37:26 GMT</pubDate>
            <atom:updated>2023-12-07T21:37:26.445Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using AI, LiDAR, and micro fragmentation to combat coral bleaching</h4><p>In collaboration with <a href="https://medium.com/@AnushkaPunukollu">Anushka Punukollu</a>.</p><p>Global temperatures are rising at alarming rates at <strong>0.14° Fahrenheit per decade</strong>, Climate Change, caused by this warming, poses an undeniable threat to humanity, affecting anything from industry to ecology. Moreover, it significantly threatens Earth’s biodiversity and introduces uncertainty to the future of the marine life living in our oceans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*qARtZqibrjQw2T9q" /><figcaption>Graph showing annual average temperatures over time</figcaption></figure><p>The problem is not just our warming world but the consequences caused by climate change. Wildlife around the earth is struggling to adapt, with their habitats changing rapidly, not giving animals the chance to adapt. Earth’s landscapes, from Saharan desserts to rain forests in South America, are changing entirely, with flowers blooming in the cold environment of Antarctica. However, one of the most overlooked transformations is that of the sea, which covers <strong>70% of the Earth</strong> and accounts for <strong>50–80% of Earth’s wildlife.</strong></p><h3>ROOT PROBLEM: Rising Sea Temperatures</h3><p>Global warming has caused sea temperatures to rise by about <strong>0.2°C </strong>in the last 5 years, which is a drastically higher rate than other years, fitting the same trend as we see in atmospheric temperature.</p><p>The oceans are the lifeblood of our planet, covering <strong>over 70%</strong> of its surface and providing a home for countless species of marine life. However, as the world warms, the oceans are feeling the heat. Warmer ocean temperatures have been linked to a wide range of consequences that threaten the health and survival of marine life and disrupt entire ecosystems.</p><p>Rising ocean temperatures have direct and immediate impacts on marine life, many of which are unable to adapt to the changes. Some species are sensitive to even slight changes in water temperature and cannot survive in warmer conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*7_jRW-wf8VtvO1kC" /><figcaption>The impact of climate change on land/ocean temperatures over time</figcaption></figure><h3>AFFECT: Coral Bleaching</h3><p>Rising sea temperatures cause another problem of coral bleaching, with coral reefs being destroyed and unable to survive in the warmer conditions of the ocean. Coral reefs are incredibly delicate and are being rapidly destroyed, even though they are a pillar of our society, as their destruction poses a threat to society, the economy and the environment.</p><p>Coral reefs are some of the most diverse and productive ecosystems on the planet. They provide a home to <strong>over 25% of all marine life</strong> and support the livelihoods of millions of people around the world, even though coral reefs cover less than 1% of the ocean itself. <strong>Over 500 million people in over 100 countries and territories</strong> depend on the reefs for food and resources.</p><p>Coral reefs critical for the fight against climate change. They are vital to maintaining the health of our planet, not only because they provide a home to numerous marine species but also because they play a vital role in regulating the carbon cycle. When photosynthetic organisms such as algae live within the tissues of corals, they <strong>absorb carbon dioxide</strong> from the surrounding water and produce oxygen, just like plants on land. These tiny photosynthetic cells are what make coral reefs so effective at absorbing and storing large amounts of carbon dioxide.</p><p>In fact, coral reefs are estimated to suck up carbon at a rate of up to <strong>70 to 90 million tonnes per year</strong>, making them one of the most efficient carbon sinks on the planet. To put that in perspective, this is equivalent to the annual carbon emissions from <strong>approximately 2,000,000 passenger cars.</strong></p><p>The problem is that they are now being wiped out since they are made of small plankton-eating invertebrate animals called <strong>polyps </strong>and inside the tissues, <strong>algae called zooxanthellae </strong>reside. This algae provides the coral with essential nutrients produced by photosynthesis and gives them their vibrant colours. When the coral expels the symbiotic algae, it appears white or “bleached.” This means that the coral is unable to perform its function or support marine life.</p><h3>CASE STUDY: The Great Barrier Reef</h3><p>The Great Barrier Reef is the largest coral reef system on the planet and is home to a staggering array of marine life. Stretching over 2,300 kilometers off the coast of Australia, this UNESCO World Heritage site is an ecosystem like no other. It is composed of <strong>over 2,900 individual reefs, 900 islands, and thousands of species</strong> of fish, sharks, turtles, and other marine creatures. The reef is located in the Coral Sea, off the coast of Queensland, Australia.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*fN8Kv0aJ8uqg-hla" /><figcaption>Credit: Great Barrier Reef Marine Park Authority</figcaption></figure><p>It’s not only a natural wonder but also a vital contributor to the Australian economy, generating billions of dollars each year from tourism and fishing. Unfortunately, in one single bleaching event, <strong>50%</strong> of the Great Barrier Reef’s coral was destroyed, resulting in the loss of thousands of animal habitats. <strong>In 2022 alone, 91% </strong>of reefs surveyed on the Great Barrier Reef were affected by coral bleaching, affecting thousands of marine animals and the economies that depend on the reef. Protecting and preserving the Great Barrier Reef is crucial for the future health of the planet’s marine ecosystem and the people who depend on it.</p><h3>CURRENT STATE: The Search For a Time-Effective Solution</h3><p>Governments and non-profits alike are all searching for a solution, from genetically modifying algae into being more heat resistant to re-planting synthetic coral to support our marine life, coral bleaching is recognized as a major problem. However, the time and economic resources required to restore our reefs using current solutions can’t currently be met.</p><p>Many governmental organizations like the National Oceanic and Atmospheric Administration (NOAA) are actively searching for a solution and forming partnerships to harness technology to battle the current state of our reefs. For example, the Waitt Institute has set out a multitude of projects to find a solution that effectively tackles the problem, such as replanting reefs which can take over 10 years to establish an ecosystem.</p><h4>Current Solutions:</h4><p>Many current solutions do show promise, but they are not without their flaws and are still lacking the technology required to deploy</p><p><strong>Algae Farming</strong></p><p>Algae farming involves cultivating certain types of algae in controlled environments, such as large tanks or ponds, to produce a variety of products. To grow algae, water, light, and nutrients are added to the tanks to create optimal conditions for the algae to thrive. The algae then photosynthesize and produce oxygen while absorbing carbon dioxide, making it an effective carbon sink. The harvested algae can be used to help stressed coral recover.</p><p>While promising, algae farming is not a silver bullet solution. It can be costly and time-consuming to cultivate enough algae to make a significant impact. This process requires trained experts to identify the right types of algae and carefully monitor their growth.</p><p><strong>Transferring Healthy Corals between Reefs</strong></p><p>This process, also known as “coral gardening,” involves growing corals in nurseries until they are mature enough to be transplanted onto damaged reefs. Once they are mature enough, the corals are carefully transplanted onto the damaged reef site. The goal is to create new colonies of coral that will help to rebuild the damaged ecosystem and provide a new habitat for marine life. This process has been successful in several locations, including the Philippines, where coral gardens have been established to help restore damaged reefs.</p><p>While this method can be effective, it is also labour-intensive and requires careful consideration to prevent the spread of disease and other environmental stressors. Additionally, it’s crucial to ensure that the transplanted corals are genetically diverse and can withstand the local environmental conditions.</p><p><strong>Marine Protected Areas and Enforcing Regulations</strong></p><p>Marine-protected areas can provide a safe haven for coral ecosystems and allow them to recover from stressors such as bleaching. By enforcing regulations that limit human activities such as fishing and tourism in these areas, we can help protect and preserve these important ecosystems.</p><p>However, monitoring human activities and enforcing restrictions can also be difficult, especially in remote or hard-to-reach locations. In some cases, the establishment of marine protected areas can also lead to conflicts with local communities that rely on fishing and other activities for their livelihoods.</p><h4>THE GAP: We Have No Effective Solutions</h4><p>The gap in tackling coral bleaching stems from the search for inclusive, scalable, and enduring solutions that can effectively counteract the threats to coral reefs. Despite the promise seen in approaches like algae farming, coral gardening, and marine protected areas, each encounters hurdles, including time constraints and a staggering global economic cost of $1 trillion as coral bleaching persists, highlighting the ongoing ineffectiveness of current solutions.</p><p><strong>Resource Intensity:</strong></p><ul><li>Algae farming, though beneficial, is resource-intensive, both in terms of cost and time. The cultivation process requires specialized expertise and careful monitoring.</li></ul><p><strong>Labour-Intensive Techniques:</strong></p><ul><li>Coral gardening, involving the transplantation of mature corals, is labour-intensive. It demands careful consideration to prevent disease spread and necessitates genetic diversity to withstand local environmental conditions.</li></ul><p><strong>Enforcement and Monitoring:</strong></p><ul><li>Establishing marine protected areas is challenged by the difficulty of monitoring and enforcing restrictions, particularly in remote or hard-to-reach locations. This may lead to continued stress on coral ecosystems in unprotected areas.</li></ul><p><strong>Social and Economic Impacts:</strong></p><ul><li>Conservation measures, such as marine protected areas, can create conflicts with local communities reliant on activities like fishing. Striking a balance between environmental conservation and the socio-economic needs of communities is crucial.</li></ul><h3>INTRODUCING: SeaBloom</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/0*NJKL2RlcihNTQgTJ" /></figure><p>SeaBloom is a system equipped with AI, LiDAR mapping, and micro-fragmentation tools to revive, support, and protect marine ecosystems from the impacts of coral bleaching.</p><h4>BACKGROUND: Types of Coral Reproduction</h4><p><strong>Sexual</strong> —</p><p>Coral larvae undergo sexual reproduction, which occurs through two methods: internal fertilization within a polyp’s body or external fertilization in the water, known as spawning. In certain regions, mass coral spawning events take place on a specific night each year, determined by environmental factors like temperature, day length, and lunar cycles. These events require coordination among coral species to minimize hybridization.</p><p>Sexual reproduction plays a crucial role in maintaining genetic diversity among coral populations, enhancing their capacity to adapt to environmental changes. This mode of reproduction also fosters the creation of new coral colonies, generating genetically distinct individuals with unique adaptations suited to their specific environments.</p><p><strong>Asexual</strong> —</p><p>Asexual reproduction occurs when individual polyps or small clusters of polyps clone themselves by budding off new polyps. This type of reproduction can result in the growth of large colonies of genetically identical corals, which can be useful in restoration efforts. However, it can also lead to decreased genetic diversity, making these colonies more susceptible to environmental stressors such as disease outbreaks or bleaching events.</p><p><strong>Fragmentation</strong> —</p><p>Fragmentation reproduction is a type of asexual reproduction in which a piece of coral breaks off from the parent colony and grows into a new colony. This process can occur naturally through storms or other environmental stressors, or it can be induced through human intervention, such as coral gardening. Fragmentation reproduction serves as a valuable tool for coral restoration as it allows for the establishment of new coral colonies derived from pre-existing ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*wtUVC-u_MbJu6xd-" /><figcaption>Visual diagram of each reproduction method</figcaption></figure><h3>Our Technology</h3><p>At SeaBloom we aim to combine AI, LiDAR, and Micro-Fragmentation technologies to help ensure our world’s marine life and reefs do not continue to worsen due to the impacts of coral bleaching.</p><h3>STEP 1: LiDAR</h3><p>LiDAR, an acronym for Light Detection and Ranging, has revolutionized our ability to map landscapes in remarkable detail and shed light on the mysteries of coral ecosystems. By combining LiDAR’s remote 3D mapping capabilities with colour imaging, researchers can now unlock a comprehensive understanding of coral growth and conditions like never before.</p><h4>The Essence of LiDAR: Mapping with Pinpoint Precision</h4><p>At its core, LiDAR operates by emitting laser pulses and measuring the time it takes for the light to bounce back after interacting with objects in its path. This fundamental principle allows LiDAR to construct precise 3D maps of landscapes, including intricate coral reef structures.</p><p>By capturing millions of data points per second, LiDAR generates a dense point cloud that faithfully represents the physical features of the environment. This enables researchers to not only obtain a detailed view of the reef but also pinpoint the exact location of the collected data, facilitating targeted analysis and intervention.</p><p>While LiDAR provides invaluable topographic information, it can be further enhanced by integrating detailed colour images captured by drones. By combining the richness of colour imaging with LiDAR’s topographical data, researchers can gain a holistic understanding of coral growth patterns, distribution, and overall health. The fusion of LiDAR mapping and colour imaging forms a comprehensive toolkit that empowers researchers and divers to study coral reefs more efficiently and effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*vY9sTmpGBJrSi8GU" /></figure><h3>STEP 2: Harnessing AI - Pairing RNNs and CNNs</h3><p>Through the utilization of two key neural networks, <strong>Recurrent Neural Networks (RNN)</strong> and <strong>Convolutional Neural Networks (CNN)</strong>, we aim to revolutionize coral restoration efforts. Let’s dive deeper into the intricate workings of SeaBloom’s AI systems (especially the CNN portion) and understand how they propel our mission to save the coral reefs.</p><p>In short, the RNN acts as the navigational compass, enabling autonomous exploration of the ocean floor. By leveraging the data generated by LiDAR technology, the RNN processes the routes and maps to chart a course through the depths. The RNN enables SeaBloom to make informed decisions, autonomously navigate, and perform vital arm operations for coral sample collection.</p><h4>Healthy Coral Detection with CNNS</h4><p>Imagine a super-powered magnifying glass that unveils the intricacies of coral reefs. With its ability to zoom in and analyze small parts of images, CNNs unlock crucial features and patterns within coral samples. This CNN will allow SeaBloom to make data-driven decisions, prioritize restoration efforts, and contribute to the overall well-being of coral ecosystems. Using past data and images we can train our CNN models to identify if the coral in an area is healthy or not (<a href="https://github.com/Anushka-Punukollu/SeaBloom">example code</a>). This information is then used to identify areas that need restoration and find heat-resistant, healthy coral.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kcf8MrkLYLyF5rKl" /><figcaption>Example of the data our AI models will output</figcaption></figure><h3>STEP 3: Fragmentation and Re-planting</h3><p>SeaBloom uses micro-fragmentation which harnesses the potential of healthy coral colonies by carefully collecting small samples and meticulously processing them. By precisely cutting these samples into tiny fragments, measuring less than 1 cm in diameter, SeaBloom maximizes their growth potential and resilience.</p><p>Once obtained, these fragments are nurtured in carefully designed on-land nurseries. Here, they receive the ideal conditions to thrive, including controlled lighting, water quality, and nutrient supply. Under the watchful eyes of marine experts, the fragments are nurtured until they reach an optimal size for transplantation.</p><p>The next stage of the SeaBloom process involves replanting the mature fragments onto frameworks strategically placed on the sea bed. These frameworks act as the foundation for the coral colonies to establish themselves and flourish. By selectively breeding and cultivating the most resilient corals, SeaBloom aims to create climate-stable reefs that can withstand the mounting challenges posed by environmental stressors.</p><p>This micro-fragmentation technique offers insights into the genetic makeup of corals. By studying the genetic diversity within these fragments, scientists gain a deeper understanding of the adaptive capacities and vulnerabilities of different coral populations. This knowledge not only aids in identifying the most adaptable strains but also allows for the preservation and potential reintroduction of corals that have yet to adapt, contributing to future biodiversity enhancement efforts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*UBKRbLq1ZCQ9jqDy" /></figure><h3>Partnering with NGOs and Governments as a B-Corp</h3><p>SeaBloom poses itself as a B-corp with our main mission to restore our reefs. Operationally, we plan to parter with these NGOs and Governments searching for solutions to deploy our solution, such as using their employees to re-plant our corals once they are fragmented.</p><p>SeaBloom’s collaboration with NGOs and governments involves various operational strategies to enhance coral reef restoration efforts. For instance, partnering with NGOs such as Reef Check could involve joint expeditions for underwater surveys and data collection. These surveys provide valuable insights into the health of coral reefs, helping SeaBloom make informed decisions about the selection of coral fragments and transplantation sites.</p><p>Partnering with NGOs and governments is pivotal for SeaBloom’s mission as a B-Corp dedicated to coral reef restoration. Collaborating with established non-profit organizations like The Coral Reef Alliance or the World Wildlife Fund brings valuable expertise, resources, and networks to amplify SeaBloom’s impact. NGOs often have experience in community engagement, scientific research, and policy advocacy, crucial elements in the success of coral restoration projects. For instance, SeaBloom can leverage partnerships with NGOs to engage local communities in the restoration process, ensuring sustainable practices and promoting environmental awareness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*oG6zMHhPeotSzdYQ" /></figure><h3>The Impact:</h3><p>SeaBloom helps us restore our reefs by:</p><h4>Creating a Heat-Resistant Ecosystem</h4><p>Healthy coral reefs maintain a crucial symbiotic relationship with algae, aiding in their growth and vitality. Scientific studies consistently demonstrate that well-nourished and thriving corals are more resilient to thermal stress, showing a higher capacity to resist bleaching and recover from temperature fluctuations. This assumption is grounded in factors such as genetic diversity and optimal environmental conditions. Conservation initiatives like SeaBloom leverage this understanding, focusing on cultivating and transplanting robust coral fragments to enhance the overall resilience of coral ecosystems in response to climate change.</p><p>SeaBloom’s innovative coral restoration strategy accelerates the replenishment process and aims to create an overall heat-resistant ecosystem. By selectively breeding and cultivating the most resilient corals, SeaBloom focuses on enhancing the climate stability of reefs. This intentional cultivation, combined with advanced AI systems ensuring optimal placement and growth conditions, contributes to the development of coral colonies better equipped to withstand environmental stressors, including rising sea temperatures. In doing so, SeaBloom aspires to foster the establishment of coral ecosystems that are inherently more heat-resistant, thereby promoting long-term ecological resilience in the face of climate challenges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vSlshb-sIZpvEpNf" /></figure><h4>Reducing the Time and Cost of Current Solutions</h4><p>SeaBloom significantly reduces both time and cost in coral reef restoration process through a combination of innovative techniques and strategic decision-making. The utilization of micro-fragmentation expedites the growth of healthy coral colonies, minimizing the time required for natural development. On-land nurseries provide controlled environments, optimizing the growth conditions before transplantation, and further accelerating the replenishment process.</p><p>Additionally, the precise placement of mature fragments onto sea frameworks ensures efficient establishment, contributing to a quicker recovery of coral ecosystems. The integration of advanced AI, including the Recurrent Neural Networks and Convolutional Neural Networks, streamlines operational tasks such as autonomous navigation and coral sample collection, reducing the need for extensive manual labour. This holistic approach accelerates the restoration timeline and enhances cost-effectiveness. Additionally, through our system scientists have the ability to analyze coral through our open source data for heat resistance, find target areas, and maintain the genetic diversity of reefs. It allows them to have access to more data and research material to continue the fight against coral bleaching. Overall, through leveraging technology and targeted interventions SeaBloom offers a promising and efficient solution for coral reef preservation.</p><h3>TL;DR</h3><ul><li>The fusion of RNNs and CNNs help to guide SeaBloom’s actions, facilitating precise navigation, efficient sample collection, and accurate classification of corals.</li><li>By leveraging AI, SeaBloom maximizes the chances of success in its mission to combat coral bleaching and promote the recovery of these ecosystems.</li><li>The knowledge gained from the RNN and CNN allows researchers to delve into the genetics of corals, identify resilient strains, and preserve genetic diversity.</li><li>This data empowers scientists and conservationists to make informed decisions, implement targeted interventions, and develop long-term strategies for coral reef conservation.</li></ul><h3>The Future &amp; Impact 🌊</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*3WZHkioECSMn3j9f" /></figure><p>As SeaBloom sets sail, its impact on coral reefs and the future of our planet holds immense promise. By harnessing the power of micro-fragmentation, advanced technologies like LiDAR and drones, and the intelligence of artificial neural networks, SeaBloom pioneers a new era of coral restoration and conservation. Its efforts not only aim to reverse the devastating effects of coral bleaching but also to unlock the secrets of coral genetics and biodiversity, paving the way for a more resilient and vibrant underwater world.</p><p>As we dive deeper into the future, I hope SeaBloom will help us nurture our connection with the oceans and ensuring the survival of these magnificent ecosystems for generations to come. Together, we can forge a path towards a more sustainable and resilient future for our oceans and the remarkable coral reefs that grace their depths.</p><h3>References</h3><p>Goreau, T.J.F., Hayes, R.L. Global warming triggers coral reef bleaching tipping point. <em>Ambio</em> <strong>50</strong>, 1137–1140 (2021).<a href="https://doi.org/10.1007/s13280-021-01512-2"> https://doi.org/10.1007/s13280-021-01512-2</a></p><p>Hoegh-Guldberg O, Poloczanska ES, Skirving W and Dove S (2017) Coral Reef Ecosystems under Climate Change and Ocean Acidification. <em>Front. Mar. Sci</em>. 4:158. doi: 10.3389/fmars.2017.00158</p><p>Howells, Emily J et al. “Enhancing the heat tolerance of reef-building corals to future warming.” <em>Science advances</em> vol. 7,34 eabg6070. 20 Aug. 2021, doi:10.1126/sciadv.abg6070</p><p>Page, Christopher &amp; Muller, Erinn &amp; Vaughan, David. (2018). Microfragmenting for the successful restoration of slow growing massive corals. Ecological Engineering. 123. 10.1016/j.ecoleng.2018.08.017.</p><p>Quigley, K.M., van Oppen, M.J.H. Predictive models for the selection of thermally tolerant corals based on offspring survival. <em>Nat Commun</em> <strong>13</strong>, 1543 (2022).<a href="https://doi.org/10.1038/s41467-022-28956-8"> https://doi.org/10.1038/s41467-022-28956-8</a></p><p>Reaser, Jamie K., et al. “Coral Bleaching and Global Climate Change: Scientific Findings and Policy Recommendations.” <em>Conservation Biology</em>, vol. 14, no. 5, 2000, pp. 1500–11. <em>JSTOR</em>,<a href="http://www.jstor.org/stable/2641802."> http://www.jstor.org/stable/2641802</a>.</p><p>Sully, S., Burkepile, D.E., Donovan, M.K. <em>et al.</em> A global analysis of coral bleaching over the past two decades. <em>Nat Commun</em> <strong>10</strong>, 1264 (2019).<a href="https://doi.org/10.1038/s41467-019-09238-2"> https://doi.org/10.1038/s41467-019-09238-2</a></p><p>van Woesik, R., Kratochwill, C. A global coral-bleaching database, 1980–2020. <em>Sci Data</em> <strong>9</strong>, 20 (2022).<a href="https://doi.org/10.1038/s41597-022-01121-y"> https://doi.org/10.1038/s41597-022-01121-y</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=951d591cf0cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GBDT to predict drug response of fluoxetine]]></title>
            <link>https://vidushi-valli-surendran.medium.com/gbdt-to-predict-drug-response-of-fluoxetine-13d4e2314763?source=rss-1c2ea4bc3f60------2</link>
            <guid isPermaLink="false">https://medium.com/p/13d4e2314763</guid>
            <dc:creator><![CDATA[Vidushi Valli Surendran]]></dc:creator>
            <pubDate>Mon, 24 Apr 2023 18:12:11 GMT</pubDate>
            <atom:updated>2023-04-24T18:12:11.505Z</atom:updated>
            <content:encoded><![CDATA[<p>Gradient boosting decision trees — sound pretty cool right? Today I am trying a new approach using GBDT to predict the drug response of Fluoxetine in hopes of making a more accurate model.</p><p>So why does what we are doing matter?</p><h3>The problem</h3><p>Today we are trying to predict the reduction in depression symptoms based on depression severity, age, sex, height, BMI, weight, and fluoxetine dose.</p><p>This is in hopes that instead of having a trial and error cycle to prescribe drugs, we can predict how a patient would react to the suggested dose beforehand.</p><p>The trial and error cycle of prescription involves starting a patient on an initial dose of a medication and then adjusting the dose based on their response and any side effects they experience. The goal is to find the optimal dose that achieves the desired therapeutic effect with minimal side effects.</p><p>In the case of antidepressant medications, the trial and error cycle typically involves starting with a low dose and gradually increasing the dose until the patient achieves a reduction in symptoms or experiences intolerable side effects. The initial dose may be based on the patient’s age, weight, and severity of depression, as well as any comorbidities they may have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/0*lf3SuBVLHMvcYUmY.png" /></figure><p>The trial and error cycle is the system currently in place, and by ending it we can end all of its drawbacks (hopefully):</p><ol><li><strong>Delayed response:</strong> It can take several weeks or even months for antidepressant medications to take full effect, and during this time, the patient may continue to experience symptoms of depression. This can be frustrating for the patient and may lead to a lack of compliance with the medication regimen.</li><li><strong>Side effects:</strong> Antidepressant medications can cause a range of side effects, including nausea, dizziness, insomnia, and sexual dysfunction. Finding the right dose and medication can be a balancing act between achieving a therapeutic benefit and minimizing side effects.</li><li><strong>Non-response: </strong>In some cases, patients may not respond to a particular medication, even after trying several different doses or formulations. This can be frustrating for both the patient and healthcare provider, as it may require trying multiple medications or combinations of medications.</li><li><strong>Cost: </strong>Some antidepressant medications can be expensive, and the trial and error cycle can result in multiple prescriptions and doctor visits, which can add up in terms of cost.</li><li><strong>Risk of withdrawal: </strong>Stopping antidepressant medications abruptly can lead to withdrawal symptoms, which can be uncomfortable and potentially dangerous. Therefore, the trial and error cycle must be managed carefully to ensure that the patient is gradually tapered off the medication if necessary.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*xFlQoz3PZ5z-KPBV.png" /></figure><h4>Why are antidepressants so important?</h4><p>The number of antidepressant items prescribed per year more than tripled over the past two decades, from 18.4 million in 1998 to 70.9 million in 2018</p><p>Antidepressants are an important class of medications that are used to treat depression and other mood disorders. Depression is a common and serious mental illness that can have a significant impact on a person’s quality of life, work, and relationships. Depression can cause a range of symptoms, including low mood, lack of energy, feelings of hopelessness, and suicidal thoughts.</p><p>Antidepressants work by altering the levels of certain neurotransmitters in the brain, such as serotonin and norepinephrine. By increasing the levels of these neurotransmitters, antidepressants can help to improve mood, reduce anxiety, and alleviate other symptoms of depression. Antidepressants are generally considered to be safe and effective, although they may not work for everyone.</p><p>In addition to treating depression, antidepressants may also be used to treat other mental health conditions, such as anxiety disorders, obsessive-compulsive disorder, and post-traumatic stress disorder. Antidepressants can also be used to manage chronic pain conditions, such as fibromyalgia and chronic headaches.</p><p>As you can see, what we are doing does have quite an impact, but why are we using age, height, BMI, etc to do this?</p><h3>The Features</h3><p>We are using a range of variables today, but why so many and why these variables?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/0*IrmGPJ7AANhgORw1.png" /></figure><p><strong>Depression Severity: </strong>The severity of depression is a known factor that can affect the response to treatment with antidepressants. Patients with more severe depression may have a greater potential for improvement and a larger reduction in symptoms, compared to patients with milder symptoms. This is because antidepressants work by altering the balance of certain neurotransmitters in the brain, and more severe depression may involve greater imbalances in these neurotransmitters that can be corrected by medication.</p><p><strong>Age: </strong>Age can also play a role in treatment response, as younger patients may have a more robust response to antidepressant medications due to their brain being more plastic and responsive to changes. However, elderly patients may have reduced liver or kidney function, which may affect how the medication is metabolized and excreted from the body. Additionally, elderly patients may have comorbidities or be taking other medications that can interact with the antidepressant.</p><p><strong>Sex:</strong> Studies have shown that there may be sex differences in response to antidepressant medications, with women generally showing a greater response than men. This may be due to differences in hormone levels or genetic factors, among other reasons.</p><p><strong>Height, BMI, and Weight: </strong>These variables can affect the distribution and metabolism of medications in the body, which in turn can affect the efficacy and side effects of the medication. For example, taller patients may require higher doses of medication to achieve the same concentration in the bloodstream as a shorter patient, and patients with higher BMI or weight may require adjustments to their dosages to account for their increased body mass.</p><p><strong>Fluoxetine Dose: </strong>The dose of fluoxetine administered to the patient can have a direct impact on the reduction of depression symptoms. Higher doses of fluoxetine have been shown to be more effective in treating depression in some patients, but can also increase the risk of side effects. The optimal dose for each patient depends on a number of factors, including the patient’s age, weight, and severity of depression.</p><p>So now we know why these features, why are we using GBDT?</p><h3>What is GBDT?</h3><p>Gradient boosting decision trees is an ML technique that is used for many applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/0*GmmxURm8HNCWWyb0" /></figure><p>It works by building an ensemble of decision trees sequentially, where each new tree tries to correct the errors of the previous trees in the ensemble.</p><p>To be more specific, GBDT starts by building a single decision tree to predict the target variable. Then, it calculates the errors (also called residuals) of the predictions made by the first tree. These residuals represent the differences between the true values and the predictions made by the first tree.</p><p>Then, GBDT builds a second decision tree that is trained to predict these residuals. This new tree is added to the ensemble, and the predictions of both trees are combined to create a new set of predictions. The process is repeated, with each new tree trying to further reduce the errors of the previous trees, until a specified stopping criterion is met.</p><p>During the training process, GBDT uses a gradient descent algorithm to minimize the loss function. The loss function is a measure of how well the ensemble is performing, and it is typically defined as the mean squared error (MSE) for regression problems or the cross-entropy loss for classification problems. The gradient descent algorithm iteratively adjusts the weights of the trees in the ensemble to minimize the loss function.</p><h3>Pros and cons</h3><p>GBDT can be a good choice for predicting the % of reduction in depression symptoms based on a fluoxetine dose because it has several advantages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/0*oBqDOBqc-RlEeXVi" /></figure><ol><li><strong>High predictive accuracy: </strong>GBDT has been shown to achieve high predictive accuracy in many applications. This means that it can accurately predict the % of reduction in depression symptoms based on a fluoxetine dose, which can help healthcare professionals make informed treatment decisions.</li><li><strong>Robustness to noise: </strong>GBDT is robust to noisy and missing data, which is common in real-world medical datasets. This means that it can handle missing values or noisy data that might exist in the depression symptom dataset.</li><li><strong>Non-linear relationships: </strong>GBDT can capture non-linear relationships between the fluoxetine dose and the % of reduction in depression symptoms. This is important because the relationship between the dose and the response may not be linear and GBDT can help capture these non-linearities.</li><li><strong>Feature importance:</strong> GBDT provides feature importance measures that can help identify which factors are most important in predicting the % of reduction in depression symptoms. This can help healthcare professionals identify which factors to prioritize when making treatment decisions.</li><li><strong>Scalability:</strong> GBDT is scalable to large datasets, making it suitable for medical datasets with a large number of observations and features.</li></ol><p>However, with pros there are cons, however, with the appropriate training, the cons can be easily overcome.</p><ol><li><strong>Overfitting:</strong> GBDT can be prone to overfitting, especially if the model is too complex or if the dataset is small. Overfitting occurs when the model learns to fit the training data too closely and is not able to generalize well to new data.</li><li><strong>Computationally intensive: </strong>GBDT can be computationally intensive, especially when the dataset is large or the model is complex. This can increase the time and resources required for training the model, which may not be feasible in some settings.</li><li><strong>Interpretability:</strong> GBDT is not as interpretable as some other machine learning models, such as linear regression or decision trees. It can be difficult to understand how the model arrived at its predictions, which may be a concern for some applications.</li><li><strong>Data preprocessing: </strong>GBDT requires careful data preprocessing, such as handling missing values and encoding categorical variables, to ensure that the model can learn meaningful relationships in the data. This can be time-consuming and require expertise.</li></ol><h3>The dataset</h3><p>I used the “Antidepressant Treatment Response” dataset, and you can tell by the name that it was proved to be useful.</p><p>The “Antidepressant Treatment Response” dataset is a collection of data on the response of patients with major depressive disorder (MDD) to treatment with an antidepressant drug. The data was collected from a clinical trial that investigated the efficacy of fluoxetine (Prozac), a commonly used antidepressant medication.</p><p>The dataset contains information on the following variables:</p><ul><li>patient_id: A unique identifier for each patient.</li><li>sex: The patient&#39;s gender (male or female).</li><li>age: The patient&#39;s age in years.</li><li>height: The patient&#39;s height in centimeters.</li><li>weight: The patient&#39;s weight in kilograms.</li><li>BMI: The patient&#39;s body mass index (BMI) — calculated as weight in kilograms divided by height in meters squared.</li><li>severity: A clinical measure of depression severity, as assessed by the Hamilton Depression Rating Scale (HAM-D).</li><li>fluoxetine_dose: The dose of fluoxetine administered to the patient.</li><li>treatment: Whether the patient received the fluoxetine treatment or a placebo.</li><li>percent_reduction: The percentage reduction in depression symptoms after treatment, calculated as 100*(baseline HAM-D score - post-treatment HAM-D score)/baseline HAM-D score.</li></ul><p>The dataset contains 500 rows, each representing a unique patient in the trial. The data includes both categorical and continuous variables. There are 250 male and 250 female patients in the dataset. The patients’ ages range from 18 to 65 years, with a mean age of approximately 38 years. The patients’ BMIs range from 17 to 45, with a mean BMI of approximately 27. The doses of fluoxetine range from 20 to 80 mg/day.</p><p>The goal of using this dataset is to build a model to predict the percentage reduction in depression symptoms based on the patient’s fluoxetine dose, age, height, BMI, weight, and depression severity.</p><h3>The code</h3><p>Finally, we can get to coding this thing!</p><h4>An overview</h4><ol><li><strong>Preprocessing: </strong>The first step is to preprocess the data by handling missing values and encoding categorical variables, if any. We also need to standardize or normalize the continuous variables to ensure that they are on the same scale.</li><li><strong>Splitting the data:</strong> Next, we need to split the data into a training set and a testing set. The training set is used to train the model, while the testing set is used to evaluate its performance.</li><li><strong>Model training:</strong> The next step is to train the GBDT model on the training set. This involves specifying the hyperparameters of the model, such as the number of trees, the learning rate, and the maximum depth of the trees. We use cross-validation to tune these hyperparameters and avoid overfitting.</li><li><strong>Model evaluation: </strong>Once the model is trained, We can evaluate its performance on the testing set. This involves calculating metrics such as the mean squared error (MSE) or the coefficient of determination (R-squared) to assess how well the model is able to predict the % of reduction in depression symptoms based on the input features.</li><li><strong>Feature importance: </strong>GBDT provides feature importance measures that can help identify which factors are most important in predicting the % of reduction in depression symptoms. We can use these measures to identify which factors to prioritize when making treatment decisions.</li></ol><p>The first step of course is importing our libraries.</p><h4>Step 1: import libraries</h4><pre>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import GradientBoostingRegressor<br>from sklearn.metrics import mean_squared_error</pre><p>Today we are using the Pandas library and the sci-kit library.</p><p>I will not go into too much detail about the libraries today, but you can check that out in my previous articles</p><h4>Step 2: preprocess our data</h4><p>Now let’s get our dataset into this code.</p><p>Import the dataset: I imported this via CSV file using the Pandas library in Python.</p><pre>import pandas as pd<br>data = pd.read_csv(&#39;antidepressant_data.csv&#39;)</pre><p>Handling missing values: Check for missing values in the dataset and handle them appropriately. One way to do this is to replace missing values with the median or mean value of the feature.</p><pre>data.fillna(data.median(), inplace=True)</pre><p>Encoding categorical variables: If there are categorical variables in the dataset, we need to encode them before using them in a machine learning model. To do this we used one-hot encoding.</p><pre>data = pd.get_dummies(data, columns=[&#39;sex&#39;, &#39;treatment&#39;])</pre><p>Standardizing continuous variables: Since the variables in the dataset have different units and scales, we need to standardize or normalize them to ensure that they are on the same scale. One way to do this is to use scikit-learn’s StandardScaler() function.</p><pre>from sklearn.preprocessing import StandardScaler<br>scaler = StandardScaler()<br>data[[&#39;age&#39;, &#39;height&#39;, &#39;weight&#39;, &#39;BMI&#39;, &#39;severity&#39;, &#39;sex&#39; &#39;fluoxetine dose&#39;]] = scaler.fit_transform(data[[&#39;age&#39;, &#39;height&#39;, &#39;weight&#39;, &#39;BMI&#39;, &#39;severity&#39;]])</pre><p>Splitting the data: now we split the dataset into a training set and a testing set</p><pre>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(data[[&#39;fluoxetine_dose&#39;, &#39;ag</pre><p>Now this data is ready to be used, and we can establish the model!</p><h4>Step 3: Train the model</h4><p>Now we can train out GBDT model — finally!</p><pre># Train a GBDT model<br>gbdt = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=3, random_state=42)<br>gbdt.fit(X_train, y_train)</pre><p>gbdt = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=3, random_state=42) - This line creates an instance of the GradientBoostingRegressor class with several hyperparameters specified.</p><p>n_estimators determines the number of trees in the model, learning_rate controls the contribution of each tree to the final prediction, max_depth sets the maximum depth of each decision tree, and random_state ensures reproducibility of the results.</p><p>gbdt.fit(X_train, y_train) - This line fits the GBDT model to the training data X_train and y_train. X_train is a matrix of input features, and y_train is the corresponding target variable (in this case, the percentage of reduction in depression symptoms based on a fluoxetine dose, age, height, BMI, weight, and depression severity).</p><p>By calling the fit method on the gbdt object, the GBDT model will train on the training data by creating a series of decision trees that iteratively improve the model&#39;s performance. The model will learn to predict the target variable based on the input features, and the hyperparameters specified in the first line of code will guide the learning process.</p><p>And now we have trained the model, it can be used to make predictions on the data.</p><h4>Step 4: test the model</h4><pre># Evaluate the model on the testing set<br>y_pred = gbdt.predict(X_test)<br>mse = mean_squared_error(y_test, y_pred)<br>print(&quot;Mean squared error: &quot;, mse)</pre><p>So, after we trained our GBDT model to predict the percentage of reduction in depression symptoms based on several input features, we want to know how well it performs on new, unseen data. This is where the testing set comes in — it’s like a practice run for the model.</p><p>To see how well our model does on the testing set, we use the predict method to generate predictions based on the input features in the testing set. Then we compare those predictions to the true target values in the testing set using a metric called the mean squared error (MSE).</p><p>MSE measures the average squared difference between the predicted values and the true values. A lower MSE means that the model is doing a better job of predicting the target variable. We print the MSE to the console so we can see how well our model performed.</p><p>By evaluating our model on a separate testing set, we get a sense of how well it will perform on new data that it hasn’t seen before. This is important because we want our model to be able to generalize to real-world scenarios, not just perform well on the data it was trained on.</p><h4>Step 5: Get feature importance</h4><pre># Get the feature importance measures<br>feature_importance = gbdt.feature_importances_<br>print(&quot;Feature importance: &quot;, feature_importance)</pre><p>After training our GBDT model and evaluating its performance, we might want to understand which features are the most important in predicting the target variable. This can help us better understand the relationship between the input features and the target variable.</p><p>In this code block, we’re using a method called feature_importances_ to get the importance scores for each input feature. This tells us which features had the greatest impact on the model&#39;s predictions.</p><p>The feature importance scores are represented as an array, with each element corresponding to a different input feature. The larger the score, the more important the feature is in predicting the target variable.</p><p>By looking at the feature importance scores, we can gain insights into which input features are most useful for predicting the target variable. We can use this information to focus our attention on the most important features when interpreting the model and making decisions based on its predictions.</p><p>and we are done!</p><h3>Takeaways and conclusion:</h3><p>Rather than seeing if someone will respond well or not — as we did with logistic regression, this can help us see how well they will respond.</p><h4>My key takeaways:</h4><ul><li>GBDT can provide a more accurate way of predicting drug response</li><li>Predicting drug response can help end the trial and error cycle in prescribing drugs — which is a costly and mentally straining cycle.</li><li>We used more features this time around and it provided a higher accuracy, but it was more computationally expensive</li><li>GBDT is great at finding non-linear relationships, very useful for this task!</li></ul><h3>Here is a note from the writer of this article:</h3><p>Hi readers, I am a 13-year-old girl in the UK and would love your support.</p><p>Thank you for reading this and I would love it if you checked out some of my other articles as well!</p><p>Please check out my monthly newsletter: <a href="https://substack.com/profile/106867284-vidushi-valli-surendran">https://substack.com/profile/106867284-vidushi-valli-surendran</a></p><p>My LinkedIn:</p><p><a href="https://www.linkedin.com/in/vidushi-valli-surendran-075a06250/">https://www.linkedin.com/in/vidushi-valli-surendran-075a06250/</a></p><p>My personal website:</p><p><a href="http://vidushivs.com/">Vidushivs.com</a></p><p>My previous article on this:</p><p><a href="https://medium.com/@vidushi-valli-surendran/predicting-drug-response-of-fluexotine-based-on-a-cyp2d6-activity-scale-76a2c7e649bb">https://medium.com/@vidushi-valli-surendran/predicting-drug-response-of-fluexotine-based-on-a-cyp2d6-activity-scale-76a2c7e649bb</a></p><p>And thank you for reading again!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13d4e2314763" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using QML to aid in Antibiotic drug discovery]]></title>
            <link>https://vidushi-valli-surendran.medium.com/using-quantum-computing-and-machine-learning-techniques-to-simulate-and-analyze-the-properties-of-a-b03ccf3be302?source=rss-1c2ea4bc3f60------2</link>
            <guid isPermaLink="false">https://medium.com/p/b03ccf3be302</guid>
            <dc:creator><![CDATA[Vidushi Valli Surendran]]></dc:creator>
            <pubDate>Tue, 28 Mar 2023 11:59:03 GMT</pubDate>
            <atom:updated>2023-03-31T15:54:52.122Z</atom:updated>
            <content:encoded><![CDATA[<p>Quantum is a word that seems quite daunting, in actuality it is tricky but any reader of this article can learn about it. However, explaining both quantum machine learning and quantum chemistry in one article is quite daunting. Yes, in the future maybe I will be writing explanations of the two, but today I want to focus on using these techniques to create new antibiotics.</p><p>So, If you would like to learn a bit about quantum, you can find info here: <a href="https://qiskit.org/textbook/ch-states/introduction.html">https://qiskit.org/textbook/ch-states/introduction.html</a></p><p><em>And without further ado, let’s get into the article!</em></p><p>Analyzing the properties of a molecular structure can be useful <strong><em>for creating new antibiotics</em></strong>, and using quantum computing can be beneficial for this because it allows us to <strong><em>identify novel drug targets and validate them</em></strong> at a very high speed.</p><h3>But why do we need new antibiotics?</h3><p>Play along with me… You are experiencing cold and flu symptoms — headache, sore throat, fever, runny nose, etc — so naturally you go to your doctor. He says that you should rest up, drink fluids (regular stuff) and take paracetamol for the headache. You then follow up with “could you prescribe me antibiotics” — <strong><em>this is where the mistake happens</em></strong></p><p>Bacteria have actually evolved into “superbugs”, this basically means that they are resistant to antibiotics — so if your lying in a hospital bed with no medicine to help you with a superbug, blame people who take antibiotics for no real reason.</p><p>If nothing is done to halt the rise of superbugs, global deaths from drug-resistant infections could rise from the currently estimated <strong><em>700,000 every year to 10 million people every year by 2050.</em></strong></p><h3>What do we do about it?</h3><p>So, it is clear that we need to do something about it, but what?</p><p>Well, the obvious answer would be to make new drugs — but that is quite a complex task.</p><p>Nanotechnology researchers are working on using <strong><em>nanobots to deliver medicine</em></strong>, this is quite a good way to <strong><em>get past the barriers</em></strong> bacterial cells have in place to prevent a medicine from attaching to its ribosomes — hence killing it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*UO810m4osd8yuesQw1JVRA.png" /></figure><p>Another way is using <strong><em>AI to aid drug discovery</em></strong>!</p><p>This can be done in more things than antibiotics, but AI can be a very useful tool to aid drug discovery.</p><ul><li><strong><em>Predicting drug response: </em></strong>Predicting drug response is an important aspect of drug discovery because it helps researchers identify<strong><em> which drugs are likely to be effective in treating a particular disease,</em></strong> and which patients are <strong><em>likely to respond well to a given drug.</em></strong></li><li><strong><em>GANs: </em></strong>We can use GANs to simulate molecular structure, Simulating molecular structures helps in drug discovery by allowing researchers to understand how potential drug molecules<strong><em> interact with their target proteins or enzymes at a molecular level</em></strong>. This information can help in designing new drugs<strong><em> with greater specificity, efficacy, and fewer side effects.</em></strong></li><li><strong><em>QML: </em></strong>QML allows for <strong><em>faster and more accurate</em></strong> predictions of molecular properties and drug interactions. QML can also be used to predict molecular properties such as <strong><em>solubility, stability, and toxicity</em></strong>, which are important factors in drug development. By accurately predicting these properties, researchers can identify potential drug candidates that are <strong><em>safe, effective, and have a higher chance of success in clinical trials.</em></strong></li></ul><h3>What are the benefits of QML?</h3><p>If you are in the AI world, you must be super excited about QML</p><p>It can have so many benefits and is probably the most exciting thing in AI currently — if you ask me at least.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*jc3f9vOq0WgUblM9hAKLYA.png" /></figure><ol><li><strong>Faster computing:</strong> Quantum computers can solve certain problems much faster than classical computers, which could have a significant impact on fields such as cryptography, optimization, and drug discovery.</li><li><strong>Improved data security: </strong>Quantum computers can potentially break certain encryption schemes used to secure sensitive data, but they can also be used to create more secure encryption protocols that are impossible to break using classical computers.</li><li><strong>Simulation of complex systems:</strong> Quantum computers can simulate the behavior of complex systems that are difficult to model with classical computers, such as large molecules or materials.</li><li><strong>Advances in machine learning:</strong> Quantum computers can be used to improve machine learning algorithms and enable more accurate and efficient data analysis.</li><li><strong>Scientific breakthroughs: </strong>Quantum computers could help scientists make significant advances in fields such as chemistry, physics, and materials science by allowing them to simulate and analyze complex systems with greater accuracy and detail.</li></ol><h3>What are we doing today — an overview</h3><p>Today we will use quantum computing and machine learning techniques to simulate and analyze the properties of a molecular structure, as said in the title, but what are the steps to doing that?</p><ol><li><strong>Quantum circuit design: </strong>The first step is to design a quantum circuit that can efficiently encode the molecular structure of a drug. This requires expertise in quantum chemistry and quantum computing. The goal is to encode the relevant information about the molecular structure in a way that can be processed by a quantum computer.</li><li><strong>Quantum simulation: </strong>Once the quantum circuit is designed, the next step is to simulate the molecular structure of the drug using a quantum computer. This involves using quantum algorithms to calculate the electronic structure of the drug and its interactions with other molecules.</li><li><strong>Feature extraction: </strong>The output of the quantum simulation is a complex quantum state that contains information about the molecular structure of the drug. The next step is to extract relevant features from this quantum state that can be used as input to a classical machine learning model.</li><li><strong>Classical machine learning: </strong>The extracted features are then used to train a classical machine learning model to predict the effectiveness of the drug. The model can be trained using a variety of techniques, including supervised learning, unsupervised learning, or reinforcement learning.</li><li><strong>Optimization: </strong>The final step is to use the machine learning model to optimize the molecular structure of the drug. This involves searching for a molecular structure that maximizes the desired properties of the drug, such as its effectiveness or safety.</li></ol><p>So now we know what we are doing — lets do it!</p><h3>The dataset:</h3><p>To do this today, I used the PubChem dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*ko6L9DTDmv-s3-1fOeC-Jg.png" /></figure><p>So, PubChem is a public database that contains information about millions of chemical compounds. It’s like a giant library, but instead of books, it has information about chemicals!</p><p>Scientists and researchers use PubChem to study <strong><em>chemical compounds and their properties. </em></strong>You can search for a specific chemical or browse through the database to find chemicals that match certain criteria.</p><p>The dataset contains a lot of information about each <strong><em>chemical compound, such as its molecular formula, weight, structure,</em></strong> and other properties. There are also links to research articles and other resources related to the compound.</p><p>The PubChem dataset is a large collection of chemical compounds and their associated properties, such as molecular weight and boiling point. These properties can be used as input features for machine learning models, including those based on quantum machine learning (QML).</p><p>QML algorithms are designed to take advantage of the quantum properties of matter to perform certain types of computations more efficiently than classical algorithms. In the case of chemistry, QML can be used to simulate the behavior of molecules and predict their properties. By using the PubChem dataset as training data for QML models, it is possible to de<strong><em>velop highly accurate models for predicting the properties of new molecules, which can have applications in drug discovery and materials science.</em></strong></p><h3>Step 1: Import our libraries</h3><p>As usual, the first thing we do is import our libraries, these are gonna be all the libraries needed for all the steps.</p><p>As it is QML, we need loads of libraries, So today I will not be explaining each one of them, but I do want to talk briefly about the qiskit library.</p><p>Qiskit is a software development kit (SDK) for building quantum computing applications. It’s like a set of tools that allows developers to create and run <strong><em>quantum circuits on real or simulated quantum devices.</em></strong></p><p>Qiskit is a popular open-source platform that’s widely used in the quantum computing community. It has a lot of built-in functionality for things like <strong><em>circuit design, quantum algorithm development, and optimization.</em></strong></p><p>One of the great things about Qiskit is that it’s designed to be accessible to people with different levels of quantum computing knowledge. You can start using Qiskit with just a<strong><em> basic understanding of quantum mechanics,</em></strong> and then gradually build up your skills as you go along.</p><p>Qiskit also has a lot of documentation, tutorials, and other resources available online, which makes it easier to learn and get started with. So, if you’re interested in quantum computing, Qiskit is definitely a platform worth exploring.</p><pre>#import libraries<br>import numpy as np<br>from qiskit import Aer, execute<br>from qiskit.aqua import aqua_globals<br>from qiskit.aqua.components.optimizers import COBYLA<br>from qiskit.aqua.components.variational_forms import RYRZ<br>from qiskit.aqua.operators import Z2Symmetries, WeightedPauliOperator<br>from qiskit.aqua.algorithms import VQE<br>from qiskit.chemistry import FermionicOperator<br>from qiskit.chemistry.drivers import PySCFDriver, UnitsType<br>from rdkit import Chem<br>from rdkit.Chem import AllChem<br>from qiskit.aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name<br>from qiskit.chemistry import FermionicOperator<br>from qiskit.chemistry.core import Hamiltonian, QubitMappingType<br>from qiskit.aqua.algorithms import VQE<br>from qiskit.aqua.components.optimizers import L_BFGS_B<br>from qiskit.aqua import aqua_globals<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler<br>from qiskit.result import Result<br>from qiskit.quantum_info import partial_trace<br>from qiskit.circuit.library import PauliFeatureMap<br>from qiskit.opflow import Z, X, I<br>from qiskit.aqua.algorithms import VQC<br>from sklearn.linear_model import LogisticRegression</pre><h3>Step 2: Load and preprocess the data</h3><p>Now let’s get our dataset in the mix, because without a dataset what even is AI?</p><pre># Load the bioassay data from a CSV file<br>bioassay_df = pd.read_csv(&#39;PubChem_BioAssay.csv&#39;)</pre><p>Now we need to make sure we are looking at the part of the data about antibiotics</p><pre># Filter the data to include only compounds with relevant bioactivity data<br>filtered_df = bioassay_df[bioassay_df[&#39;Antibiotic Activity&#39;] != &#39;&#39;]</pre><p>Now we standardize the data</p><pre># Standardize the molecular structures using RDKit<br>filtered_df[&#39;Molecule&#39;] = filtered_df[&#39;SMILES&#39;].apply(lambda x: Chem.MolFromSmiles(x))<br>filtered_df[&#39;Molecule&#39;] = filtered_df[&#39;Molecule&#39;].apply(lambda x: Chem.AddHs(x))<br>filtered_df[&#39;Molecule&#39;] = filtered_df[&#39;Molecule&#39;].apply(lambda x: Chem.MolToSmiles(x))<br>filtered_df[&#39;Molecule&#39;] = filtered_df[&#39;Molecule&#39;].apply(lambda x: Chem.MolFromSmiles(x))</pre><p>First, we take the ‘SMILES’ column of the dataset, which contains the SMILES notation for each molecule, and use the RDKit function ‘Chem.MolFromSmiles’ to convert <strong><em>each SMILES notation into a molecule object.</em></strong></p><p>SMILES stands for Simplified Molecular Input Line Entry System. It’s basically a way to represent the structure of a molecule using a short string of characters.</p><p>For example, instead of drawing out the structure of caffeine on a piece of paper, you could use the SMILES notation to represent it as <strong><em>“CN1C=NC2=C1C(=O)N(C(=O)N2C)C”.</em></strong></p><p>This notation is really useful for computer programs because it’s easy to read and write, and can be used to search large databases of molecules.</p><p>Then, we <strong><em>add hydrogen atoms to the molecule objects</em></strong> using ‘Chem.AddHs’. Hydrogen atoms are not usually included in SMILES notation but are important for determining the geometry and properties of the molecule.</p><p>The next line of code converts the modified molecule objects back into SMILES notation using ‘Chem.MolToSmiles’, and then again back into molecule objects using ‘Chem.MolFromSmiles’. This step is important for standardizing the molecule structures and ensuring that they are consistent and can be properly processed by the subsequent steps of the analysis.</p><pre># Calculate the relevant molecular descriptors using RDKit<br>filtered_df[&#39;Descriptors&#39;] = filtered_df[&#39;Molecule&#39;].apply(lambda x: AllChem.GetMorganFingerprintAsBitVect(x, 2))</pre><p>In this part of the code, we are calculating the relevant molecular descriptors for our filtered dataset using the RDKit library in Python. These descriptors are important because they provide numerical representations of the molecules that we can use to train our machine learning model.</p><p>We start by taking the ‘Molecule’ column from our filtered dataset, which contains the molecular structures standardized using the SMILES notation, and apply the RDKit function ‘AllChem.GetMorganFingerprintAsBitVect’ to each molecule. This function calculates the <strong><em>Morgan fingerprint of the molecule, </em></strong>which is a binary vector that encodes the presence or absence of molecular substructures (called “features”) at different radii around each atom in the molecule.</p><p>The function takes two arguments: the first argument is the molecule itself, which we pass as an argument to the lambda function. The second argument is the <strong><em>radius of the fingerprint,</em></strong> which we set to 2 in this case. This means that the function will consider all features that are within two bonds of each atom.</p><p>Finally, we store the calculated molecular descriptors in a new column called ‘Descriptors’ in our filtered dataset. This column contains a binary vector for each molecule, which we can use as input features for our machine learning model.</p><pre># Calculate the relevant molecular descriptors using RDKit<br>filtered_df[&#39;Descriptors&#39;] = filtered_df[&#39;Molecule&#39;].apply(lambda x: AllChem.GetMorganFingerprintAsBitVect(x, 2))</pre><p>Now, We are labeling the compounds in the<strong><em> filtered dataframe based on their antibiotic activity. </em></strong>If the antibiotic activity is ‘Active’, we label it as 1, indicating that it is active against bacteria. Otherwise, we label it as 0, indicating that it is not active. This will help us in training our machine learning model to predict the antibiotic activity of compounds based on their molecular descriptors.</p><pre># Label the compounds according to their antibiotic activity<br>filtered_df[&#39;Antibiotic Label&#39;] = filtered_df[&#39;Antibiotic Activity&#39;].apply(lambda x: 1 if x == &#39;Active&#39; else 0)</pre><p>And we can consider this data preprocessed!</p><h3>Step 3: Define the quantum circuit to encode the molecular structure</h3><p>As said before, now we design a quantum circuit that can efficiently encode the molecular structure of a drug. This requires expertise in quantum chemistry and quantum computing. We want to <strong><em>encode the relevant information about the molecular structure in a way that can be processed by a quantum computer.</em></strong></p><pre># Define the molecule to encode<br>molecule = &#39;O=C(NC1CC1)c1ccc(Cl)cc1&#39;</pre><p>This line defines the molecule that we want to encode. In this case, it&#39;s a molecule called &quot;O=C(NC1CC1)c1ccc(Cl)cc1&quot;.</p><pre># Define the feature map to encode the molecule<br>num_qubits = 4 # You may need to adjust this based on the size of your molecule<br>paulis = []<br>for i in range(num_qubits):<br>    for j in range(i):<br>        paulis.append(Z ^ (i &amp; j) * X ^ ((i + j) % num_qubits))<br>feature_map = PauliFeatureMap(feature_dimension=num_qubits, reps=1, paulis=paulis)</pre><p>This section defines the feature map that we will use to encode the molecule into a quantum circuit. The feature map is essentiall<strong><em>y a set of instructions that we will use to translate the properties of the molecule into a format that can be represented by a quantum computer.</em></strong></p><p>First, we define the number of qubits that we will use to represent the molecule. In this case, we have set the number of qubits to 4, <strong><em>but this number may need to be adjusted depending on the size of the molecule.</em></strong></p><p>Next, we create an empty list called &quot;Paulis&quot;. We will use this list to <strong><em>store the set of instructions that make up our feature map.</em></strong></p><p>The next few lines of code create the set of instructions for our feature map. Specifically, we are creating a <strong>set of Pauli gates that we will use to represent the molecule.</strong> Pauli gates are a type of quantum gate that are commonly used in quantum computing.</p><p>Pauli gates are a set of quantum logic gates in quantum computing that are used to manipulate the state of qubits. There are three types of Pauli gates: <strong><em>the X gate, the Y gate, and the Z gate.</em></strong></p><p>We used the<strong><em> X and Z gates </em></strong>in the context of quantum computing, specifically in the context of encoding a molecule using a quantum circuit. In this context, we used the X and Z gates as part of a feature map to <strong><em>encode the molecular structure of a given molecule onto a quantum circuit.</em></strong></p><p>The X gate is often referred to as the “bit-flip” gate because it maps the computational basis state 0 to 1 and vice versa. It is a<strong><em> one-qubit gate </em></strong>that flips the state of a qubit from |0⟩ to |1⟩ or vice versa. The Z gate, on the other hand, is often referred to as the “phase-flip” gate because it maps the computational basis state |0⟩ to itself, while mapping the state |1⟩ to -|1⟩. It <strong><em>is also a one-qubit gate that applies a phase shift to a qubit.</em></strong></p><p>In the feature map we used, we constructed Pauli strings that consisted of tensor products of X and Z gates acting on different qubits. These Pauli strings acted as a way of <strong><em>encoding the molecular structure of the molecule onto the quantum circuit</em></strong>, with each Pauli string representing a different aspect of the molecule’s structure.</p><p>By using X and Z gates in this way, we were able to e<strong><em>ffectively map the molecular structure of the given molecule onto the quantum circuit</em></strong>, which is important for further analysis and simulations.</p><pre># Initialize the circuit to encode the molecule<br>circuit = feature_map.construct_circuit(molecule)</pre><p>Finally, we use our feature map to initialize the quantum circuit that will encode the molecule. We do this by calling the <strong><em>&quot;construct_circuit&quot; method</em></strong> of our feature map and passing in the molecule that we want to encode. The resulting circuit is a representation of the molecule that can be used as input to a quantum algorithm.</p><h3>Step 4: Simulate the molecular structure using a quantum computer</h3><p>Of course I do not have a quantum computer laying around at home, but this is what I would do if I did have access to one.</p><p>So, in this code, we’re basically trying to <strong><em>simulate the behavior of a molecule called ‘O=C(NC1CC1)c1ccc(Cl)cc1’</em></strong> using a quantum computer.</p><pre># Define the molecule<br>molecule = &#39;O=C(NC1CC1)c1ccc(Cl)cc1&#39;<br>basis = &#39;sto-3g&#39;<br>charge = 0<br>spin = 0<br>driver = PySCFDriver(molecule=molecule, basis=basis, charge=charge, spin=spin)<br>molecule_data = driver.run()</pre><p>We&#39;re defining a molecule using its chemical formula O=C(NC1CC1)c1ccc(Cl)cc1. We&#39;re also <strong><em>setting other parameters</em></strong> such as the basis set to sto-3g, the charge to 0 and the spin to 0. Then we&#39;re creating a PySCF driver object to compute molecular data for the given molecule and its parameters. We store this data in a variable called molecule_data.</p><pre># Define the Hamiltonian<br>hamiltonian = Hamiltonian(qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True, orbital_reduction=[-3, -2])</pre><p>Here we&#39;re defining a <strong><em>Hamiltonian</em></strong> which is an operator that describes the energy of a quantum system. The Hamiltonian takes parameters such as the qubit mapping, which is set to QubitMappingType.PARITY, and the two-qubit reduction flag, which is set to True to allow for more efficient computations. We also set the freeze_core flag to True to remove the core electrons and orbital_reduction to remove some of the virtual orbitals.</p><p>In quantum computing, the Hamiltonian is used to <strong><em>represent the problem to be solved as a set of quantum states, </em></strong>which can then be manipulated and measured using quantum algorithms. This allows for the <strong><em>simulation of complex quantum systems</em></strong>, such as chemical reactions or materials properties, which are difficult to study using classical computers.</p><p>By using the Hamiltonian to represent a system, we can <strong><em>take advantage of the properties of quantum mechanics</em></strong>, such as superposition and entanglement, to perform computations in a way that is exponentially faster than classical algorithms.</p><pre># Map the fermionic operator to the qubit operator<br>ferm_op = FermionicOperator(h1=molecule_data.one_body_integrals, h2=molecule_data.two_body_integrals)<br>qubit_op = ferm_op.mapping(map_type=hamiltonian.qubit_mapping, threshold=hamiltonian.mapping_threshold)<br>qubit_op = qubit_op.two_qubit_reduced_operator(hamiltonian.two_qubit_reduction)</pre><p>We&#39;re mapping the<strong><em> fermionic operator, which describes the behavior of electrons in the molecule, </em></strong>to a qubit operator which is used in quantum computing. We&#39;re using the molecular data computed earlier to create the fermionic operator. Then, we&#39;re using the Hamiltonian object to map the fermionic operator to a qubit operator. Finally, we&#39;re reducing the number of qubits in the qubit operator using the two_qubit_reduced_operator function.</p><pre># Define the VQE algorithm<br>optimizer = L_BFGS_B(maxfun=1000)<br>vqe = VQE(qubit_op, ansatz=None, optimizer=optimizer)</pre><p>We&#39;re defining a Variational Quantum Eigensolver (VQE) algorithm, which is used to<strong><em> find the minimum energy of a molecule</em></strong>. We&#39;re using the qubit operator we mapped earlier and an optimizer called L_BFGS_B. We also set the maximum number of function evaluations to 1000.</p><pre># Run the VQE algorithm<br>backend = Aer.get_backend(&#39;statevector_simulator&#39;)<br>result = vqe.run(backend)</pre><p>Here we&#39;re running the VQE algorithm using the statevector_simulator backend provided by IBM&#39;s Qiskit. The statevector_simulator backend simulates the behavior of a quantum system using a classical computer. We store the result of the computation in a variable called result.</p><pre># Print the results<br>print(f&quot;Optimal energy: {result.optimal_value}&quot;)<br>print(f&quot;Optimal parameters: {result.optimal_point}&quot;)</pre><p>Finally, we&#39;re printing the optimal energy and parameters found by the VQE algorithm</p><h3>Step 5: define relevant features</h3><p>The result of a quantum simulation aimed at understanding the molecular structure of a drug is a complex quantum state. This state contains a wealth of information that can provide insights into the drug’s properties and behavior. However, to make use of this information in practical applications, it is necessary to <strong><em>extract relevant features from the quantum state. </em></strong>This involves analyzing and interpreting the data to identify the most significant details, which can then be used as input to a classical machine learning model.</p><pre># Get the result of the quantum simulation<br>result = vqe.run(backend)</pre><p>In this block, the code is running a quantum simulation using a Variational Quantum Eigensolver (VQE) algorithm on the specified backend. The result of this simulation is stored in the result variable.</p><pre># Extract the statevector from the result<br>statevector = result.get_statevector()</pre><p>Here, the statevector is extracted from the result of the quantum simulation and stored in the statevector variable. The statevector represents the quantum state of the system at the end of the simulation.</p><pre># Compute the density matrix from the statevector<br>density_matrix = np.outer(statevector, np.conj(statevector))</pre><p>This code block computes the <strong><em>density matrix from the statevector.</em></strong> The density matrix is a mathematical object that describes the statistical properties of a quantum system. The np.outer() function calculates the outer product of the statevector with its complex conjugate, which results in a matrix representation of the density matrix.</p><pre># Trace out the qubits corresponding to the electrons<br>electrons = [0, 1, 2, 3]  # Example: trace out the first 4 qubits<br>rdm = partial_trace(density_matrix, electrons)</pre><p>This block of code performs a partial trace on the density matrix to obtain <strong><em>the reduced density matrix (RDM) for a subset of qubits. </em></strong>The electrons variable specifies the subset of qubits that correspond to the electrons, and the partial_trace() function calculates the trace over these qubits to obtain the RDM.</p><pre># Flatten the RDM to a 1D array<br>features = np.ndarray.flatten(rdm)</pre><p>Finally, the RDM is flattened into a 1D array using the np.ndarray.flatten() function and stored in the features variable. This is done to obtain a feature vector that can be used for further analysis or processing.</p><h3>Step 6: Classic machine learning model</h3><p>After extracting features from the data, a classical machine learning model can be trained to predict the efficacy of the drug using different techniques such as supervised learning, unsupervised learning, or reinforcement learning.</p><pre># Split the dataset into training and test sets<br>X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42)</pre><p>This line of code uses the train_test_split function from the scikit-learn library to randomly split the dataset into two parts: X_train and y_train, which will be used to train the model, and X_test and y_test, which will be used to evaluate the model&#39;s performance. features and labels are the input data and output data, respectively. test_size=0.2 specifies that 20% of the data should be used for testing, while the remaining 80% will be used for training. The random_state=42 parameter ensures that the random split is reproducible.</p><pre># Train a logistic regression model<br>model = LogisticRegression(max_iter=1000)<br>model.fit(X_train, y_train)</pre><p>The LogisticRegression function from scikit-learn is used to create a logistic regression model. max_iter=1000 specifies the maximum number of iterations the solver should run for convergence. model.fit(X_train, y_train) fits the model to the training data X_train and y_train.</p><p>Logistic regression is a good choice for <strong>binary classification problems where the goal is to predict one of two possible outcomes.</strong> In this case, the aim is to predict whether<strong><em> a molecule is stable or not based on its features,</em></strong> which is a binary classification problem. Logistic regression models the probability of a binary response variable as a function of the predictor variables, which in this case are the features extracted from the reduced density matrix.</p><p>Logistic regression is also relatively simple and fast to train compared to other machine learning models, making it a popular choice for binary classification problems with small to medium-sized datasets. <strong><em>It is also less prone to overfitting than more complex models</em></strong>, which can be an advantage when working with limited amounts of data. Finally, the output of logistic regression is easily interpretable, as it provides a probabilistic estimate of the likelihood of a molecule being stable based on its features.</p><pre># Evaluate the model on the test set<br>accuracy = model.score(X_test, y_test)<br>print(&quot;Accuracy:&quot;, accuracy)</pre><p>The score method of the logistic regression model is used to evaluate the accuracy of the model on the test set. The resulting accuracy score is stored in the accuracy variable. Finally, the accuracy score is printed to the console using print(&quot;Accuracy:&quot;, accuracy).</p><h3>Step 7: Optimise</h3><p>Finally, we use the machine learning model to optimize the molecular structure of the drug.</p><pre># Define the molecule to optimize<br>molecule = &#39;O=C(NC1CC1)c1ccc(Cl)cc1&#39;</pre><p><strong><em>This line of code sets the SMILES string of the molecule to be optimized.</em></strong></p><pre># Set up the PySCF driver to compute the molecular integrals<br>driver = PySCFDriver(atom=molecule, unit=UnitsType.ANGSTROM, charge=0, spin=1)</pre><p>This uses the PySCFDriver class from the Qiskit Chemistry module to set up the driver to compute the molecular integrals. atom=molecule specifies the molecular structure to compute the integrals for, unit=UnitsType.ANGSTROM sets the unit of length to angstroms, and charge=0 and spin=1 specify the charge and spin of the molecule.</p><pre># Use the driver to compute the one- and two-electron integrals<br>molecule_data = driver.run()<br>one_body_integrals = molecule_data.one_body_integrals<br>two_body_integrals = molecule_data.two_body_integrals</pre><p>Here we use the run method of the driver object to compute the one- and two-electron integrals of the molecule. The results are stored in molecule_data. one_body_integrals and two_body_integrals are then extracted from molecule_data for further processing.</p><pre># Convert the integrals to a fermionic operator<br>fermionic_op = FermionicOperator(h1=one_body_integrals, h2=two_body_integrals)</pre><p>This code creates a FermionicOperator object from the one- and two-electron integrals. A FermionicOperator is a class that represents a molecular Hamiltonian in the second quantization formalism.</p><pre># Map the fermionic operator to a qubit operator using the parity mapping<br>num_particles = molecule_data.num_alpha + molecule_data.num_beta<br>num_spin_orbitals = molecule_data.num_orbitals * 2<br>qubit_op = fermionic_op.mapping(map_type=&#39;parity&#39;, threshold=0.00000001).two_qubit_reduced_operator(num_particles)</pre><p>This maps the fermionic_op object to a qubit_op object using the parity mapping. The map_type=&#39;parity&#39; parameter specifies that the parity mapping should be used, and threshold=0.00000001 specifies the threshold for eliminating small terms in the mapping. The two_qubit_reduced_operator method reduces the number of qubits required to represent the operator. The num_particles and num_spin_orbitals variables are used to determine the number of particles and spin orbitals in the system.</p><pre># Convert the qubit operator to a weighted Pauli operator<br>qubit_op = WeightedPauliOperator(qubit_op)</pre><p>This code converts the qubit_op object to a WeightedPauliOperator object. A WeightedPauliOperator is a class that represents a weighted sum of Pauli operators.</p><pre># Define the optimizer and variational form for the VQE algorithm<br>optimizer = COBYLA(maxiter=1000)<br>var_form = RYRZ(qubit_op.num_qubits, depth=3)</pre><p>Finally, this defines the optimizer and variational form for the Variational Quantum Eigensolver (VQE) algorithm. COBYLA is the optimizer used, and</p><p>And we are done!!!</p><h3>Conclusion</h3><p>Quantum Machine Learning (QML) can be a powerful tool in drug discovery due to its ability to potentially <strong><em>handle and analyze vast amounts of complex data with high accuracy and efficiency</em></strong>. QML algorithms have the potential to analyze large datasets in parallel, which can be useful for tasks such as<strong><em> identifying correlations between molecular structure and biological activity.</em></strong></p><p><strong><em>Key takeaways:</em></strong></p><ul><li><strong><em>QML can be a very powerful tool in drug discovery</em></strong></li><li><strong><em>New antibiotics are needed soon, and this can be a powerful tool in that</em></strong></li><li><strong><em>QML is very very cool</em></strong></li></ul><h4>Here is a note from the writer of this article:</h4><p>Hi readers, I am a 13-year-old girl in the UK and would love your support.</p><p>Thank you for reading this and I would love it if you checked out some of my other articles as well!</p><p>Please check out my monthly newsletter: <a href="https://substack.com/profile/106867284-vidushi-valli-surendran">https://substack.com/profile/106867284-vidushi-valli-surendran</a></p><p>My LinkedIn:</p><p><a href="https://www.linkedin.com/in/vidushi-valli-surendran-075a06250/">https://www.linkedin.com/in/vidushi-valli-surendran-075a06250/</a></p><p>My personal website:</p><p><a href="http://vidushivs.com/">Vidushivs.com</a></p><p>My recent article:</p><p><a href="https://medium.com/@vidushi-valli-surendran/predicting-drug-response-of-fluexotine-based-on-a-cyp2d6-activity-scale-76a2c7e649bb">https://medium.com/@vidushi-valli-surendran/predicting-drug-response-of-fluexotine-based-on-a-cyp2d6-activity-scale-76a2c7e649bb</a></p><p>And thank you for reading again!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b03ccf3be302" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using GANs to aid discovery of new Bipolar disorder treatments]]></title>
            <link>https://vidushi-valli-surendran.medium.com/using-gans-to-aid-discovery-of-new-bipolar-disorder-treatments-4814ba018763?source=rss-1c2ea4bc3f60------2</link>
            <guid isPermaLink="false">https://medium.com/p/4814ba018763</guid>
            <dc:creator><![CDATA[Vidushi Valli Surendran]]></dc:creator>
            <pubDate>Mon, 27 Mar 2023 13:55:55 GMT</pubDate>
            <atom:updated>2023-03-27T13:55:55.993Z</atom:updated>
            <content:encoded><![CDATA[<p>Before I get into this article I want to note that Bipolar disorder is something very complex and I hope to spread awareness of it.</p><p>Hopefully in the future using these technologies we can provide better patient outcomes with better treatment for bipolar disorder.</p><p>Thank you for reading so far!</p><h3>1. Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-u8mKHnNq6bNxO3D.jpg" /></figure><p>Bipolar disorder is a significant public health problem, affecting millions of people worldwide.</p><p>According to the World Health Organization, bipolar disorder is the sixth leading cause of disability globally among people aged 15–44 years. In the United States alone, it is estimated that approximately 2.8% of the adult population, or about 5.7 million people, have bipolar disorder.</p><p>Bipolar disorder is characterized by periods of mania or hypomania (elevated or irritable mood, increased energy, decreased need for sleep, racing thoughts) and periods of depression (persistent sadness, loss of interest in activities, fatigue, feelings of worthlessness). These mood episodes can be severe and disabling and can interfere with an individual’s ability to work, attend school, and maintain relationships.</p><p>In addition to the direct impact on individuals with bipolar disorder, the condition also has significant economic and societal costs.</p><p>The costs associated with bipolar disorder include direct healthcare costs, such as hospitalization and medication costs, as well as indirect costs, such as lost productivity and reduced quality of life.</p><p>Despite the significant impact of bipolar disorder, many people with the condition do not receive appropriate treatment. This may be due to a lack of access to mental healthcare services, stigma associated with mental illness, or inadequate recognition or diagnosis of the condition.</p><h3>2. Types of treatment</h3><p>There are several types of treatments available for bipolar disorder, which may be used alone or in combination depending on the individual’s specific symptoms and needs. These treatments can be broadly categorized into pharmacological treatments and psychotherapeutic treatments.</p><h4>2.1 Pharmacological treatments:</h4><ul><li><strong>Mood stabilizers:</strong> These medications help regulate mood swings and prevent manic and depressive episodes. They work by changing the levels of certain chemicals, such as serotonin and norepinephrine, in the brain. Examples of mood stabilizers include lithium, valproate, and carbamazepine.</li><li><strong>Antipsychotic medications: </strong>These medications are often used to treat symptoms of mania and psychosis in bipolar disorder. They work by blocking the activity of dopamine and other neurotransmitters in the brain. Examples of antipsychotic medications used in bipolar disorder include risperidone, olanzapine, and quetiapine.</li><li><strong>Antidepressants:</strong> These medications are used to treat symptoms of depression in bipolar disorder. They work by increasing the levels of certain neurotransmitters, such as serotonin and norepinephrine, in the brain. However, their use is controversial as they can trigger manic episodes in some people. Examples of antidepressants used in bipolar disorder include SSRIs and SNRIs.</li><li><strong>Benzodiazepines:</strong> These medications are used to treat anxiety, insomnia, and agitation associated with bipolar disorder. They work by increasing the activity of a neurotransmitter called gamma-aminobutyric acid (GABA) in the brain, which can have a calming effect. Examples of benzodiazepines used in bipolar disorder include clonazepam and lorazepam.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fBw9K2tPeX9TlWeZ.png" /></figure><h4>2.2 Psychotherapeutic treatments:</h4><ul><li><strong>Cognitive-behavioral therapy (CBT):</strong> CBT helps individuals identify and change negative thought patterns and behaviors associated with bipolar disorder. It involves setting goals, developing coping strategies, and challenging negative beliefs. CBT has been shown to be effective in reducing symptoms of bipolar disorder.</li><li><strong>Interpersonal therapy:</strong> This type of therapy focuses on improving communication and relationship skills, and helps individuals develop strategies for dealing with conflict and stress. It can be effective in reducing symptoms of bipolar disorder and improving quality of life.</li><li><strong>Family-focused therapy:</strong> This type of therapy involves family members in the treatment process and helps improve communication and problem-solving skills within the family. It can be effective in reducing symptoms of bipolar disorder and improving family functioning.</li><li><strong>Psychoeducation: </strong>This involves providing information to individuals and their families about bipolar disorder, its symptoms, and treatments. It can help individuals understand their condition better and develop strategies for managing symptoms.</li><li><strong>Mindfulness-based interventions: </strong>These interventions involve practicing mindfulness, which is a form of meditation that involves focusing on the present moment without judgment. Mindfulness-based interventions can help reduce stress and improve overall well-being.</li><li><strong>Group therapy:</strong> Group therapy involves meeting with a therapist and other individuals with bipolar disorder to discuss experiences and develop coping strategies. It can provide social support and a sense of community, which can be helpful in managing symptoms.</li></ul><h4>2.3 Other treatments:</h4><ul><li><strong>Electroconvulsive therapy (ECT): </strong>ECT involves delivering a small electrical current to the brain to induce a seizure, which can help alleviate symptoms of bipolar disorder. ECT is typically used as a last resort when other treatments have not been effective.</li><li><strong>Transcranial magnetic stimulation (TMS):</strong> TMS involves using a magnetic field to stimulate certain areas of the brain, which can help alleviate symptoms of bipolar disorder. TMS is a newer treatment and is still being studied for its effectiveness.</li><li><strong>Light therapy: </strong>This involves exposure to bright light, which can help regulate circadian rhythms and improve mood. Light therapy is typically used in the treatment of seasonal affective disorder, but may also be helpful in managing bipolar disorder.</li><li><strong>Exercise and physical activity: </strong>Exercise and physical activity have been shown to improve mood and reduce symptoms of bipolar disorder. Regular exercise can also improve overall health and well-being.</li></ul><h3>3. Challenges in treatment</h3><p>One of the major challenges in treating bipolar disorder is finding a medication that effectively manages both the manic and depressive phases of the illness. Currently, medications such as lithium, anticonvulsants, and antipsychotics are used to stabilize mood and prevent relapses. However, these medications have significant side effects and are not effective for everyone. In addition, many patients with bipolar disorder experience periods of rapid cycling, where they quickly alternate between manic and depressive episodes, making treatment even more challenging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*UrPeEMOnSUKAvvnQ.jpg" /></figure><p>Another challenge is that bipolar disorder is a complex and heterogeneous illness, with a wide range of symptoms and severity. This means that different patients may require different treatment approaches, making it difficult to develop a one-size-fits-all medication. There is a need for drugs that can be tailored to individual patients and their specific symptoms.</p><p>One promising area of research is the development of drugs that target specific neurotransmitter systems in the brain. For example, drugs that target the glutamate system have shown promise in treating bipolar depression. Other drugs that target the dopamine and serotonin systems may also be effective in managing symptoms of bipolar disorder. The development of these targeted therapies has the potential to improve treatment outcomes and reduce side effects.</p><p>In addition to developing new medications, there is a need for better understanding of the underlying biology of bipolar disorder. Advances in genetics and neuroscience have identified potential biomarkers and pathways that may be involved in the development and progression of the illness. By identifying these targets, researchers can develop drugs that specifically address the underlying biology of bipolar disorder, potentially leading to more effective treatments.</p><p>Finally, there is a need for drugs that are more tolerable and have fewer side effects. Many patients with bipolar disorder experience significant side effects from current medications, such as weight gain, sedation, and cognitive impairment. These side effects can make it difficult for patients to adhere to their medication regimen and can negatively impact their quality of life. Developing medications with fewer side effects would greatly improve treatment outcomes for these patients.</p><p><strong>3.1 Why can’t people tolerate treatment?</strong></p><p>There are several reasons why people with bipolar disorder may not tolerate medications well. Especially since we are all different, men and women experience bipolar disorder very differently and we have so many differences not everyone can tolerate treatment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Zs_nEEcMB4JdYiVL" /></figure><p>One common issue is side effects. Many of the medications used to treat bipolar disorder can cause significant side effects, such as weight gain, sedation, cognitive impairment, and sexual dysfunction. These side effects can be difficult to tolerate, especially over the long term, and may lead some patients to discontinue treatment.</p><p>Another factor that can affect medication tolerance is individual differences in metabolism and physiology. Some people may metabolize medications more quickly or slowly than others, which can affect how well the medication works and how quickly it is eliminated from the body. Additionally, some people may have genetic variations that affect how they respond to certain medications, making them more or less sensitive to side effects.</p><p>Psychosocial factors can also play a role in medication tolerance. For example, patients who struggle with adherence to medication regimens may not tolerate their medications well because they are not taking them consistently or as directed. Similarly, patients who have negative beliefs or attitudes about their medications may be less likely to tolerate them well, even if the medications are effective.</p><p>It is also worth noting that bipolar disorder itself can affect how well patients tolerate medications. During manic or depressive episodes, patients may experience changes in appetite, sleep, and energy levels that can affect how they respond to medications. For example, patients who are experiencing a manic episode may be more sensitive to the sedative effects of medications, while patients who are depressed may be more sensitive to side effects that affect mood and motivation.</p><h3>4. Pharmacogenetics and Bipolar disorder</h3><p>Pharmacogenomics is the study of how an individual’s genetic makeup affects their response to medications. Pharmacogenomic testing can identify genetic variations that may affect how an individual metabolizes or responds to specific medications. By understanding these genetic variations, healthcare providers can make more informed decisions about which medications to prescribe and at what doses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*2-0vGljoEDweUYjuB_MMmw.png" /></figure><p>In the case of bipolar disorder, pharmacogenomics can be particularly useful in identifying patients who may be at higher risk of experiencing side effects or who may not respond well to certain medications. For example, pharmacogenomic testing can identify patients who have genetic variations that affect their ability to metabolize certain medications, leading to higher levels of the drug in the body and an increased risk of side effects.</p><p>Pharmacogenomics can also help healthcare providers choose medications that are more likely to be effective for a particular patient. For example, a patient with a certain genetic variation may be more likely to respond well to an antipsychotic medication than to a mood stabilizer, or vice versa. By tailoring treatment to an individual’s genetic makeup, healthcare providers can improve treatment outcomes and reduce the risk of side effects.</p><p>There are several genes that have been identified as potentially affecting the response to bipolar drugs. However, it is important to note that the genetics of bipolar disorder and its treatment response is complex and multifactorial, and more research is needed to fully understand the role of genetics in medication response.</p><p>One of the most well-studied genes in relation to bipolar disorder treatment response is CYP2D6. This gene encodes an enzyme that is involved in the metabolism of many psychotropic medications, including some commonly used to treat bipolar disorder, such as the mood stabilizer lithium and the atypical antipsychotic risperidone. Variations in the CYP2D6 gene can affect how quickly or slowly a person metabolizes these medications, which can in turn affect their efficacy and risk of side effects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*0oLDaI9q2_CuZKj_90wx8g.png" /></figure><p>Another gene that has been implicated in bipolar drug response is the HTR2A gene, which encodes a receptor for the neurotransmitter serotonin. Serotonin is involved in the regulation of mood and is a target for several medications used to treat bipolar disorder, such as selective serotonin reuptake inhibitors (SSRIs) and some atypical antipsychotics. Variations in the HTR2A gene have been associated with differences in response to these medications, although the exact mechanisms underlying this association are not yet fully understood.</p><p>Other genes that have been implicated in bipolar drug response include the ANK3 gene, which is involved in the regulation of ion channels in neurons and has been associated with the response to lithium, and the BDNF gene, which encodes a neurotrophic factor that is important for the survival and growth of neurons and has been implicated in the response to several medications used to treat bipolar disorder.</p><h3>5. GANs for drug discovery</h3><h4>5.1 what are GANs and how do they work?</h4><p>Generative Adversarial Networks (GANs) are a type of machine learning model that can be used to generate new data, such as images, videos, and even molecular structures. GANs consist of two neural networks, a generator network and a discriminator network, that are trained together in an adversarial setting.</p><p>The generator network takes as input a random noise vector and generates a sample, such as an image or a molecule, that is similar to the real data. The discriminator network takes as input a sample and predicts whether it is real or generated by the generator network. During training, the generator network tries to generate samples that are indistinguishable from the real samples, while the discriminator network tries to correctly distinguish between the real and generated samples.</p><p>The training process of GANs can be divided into two phases: the generator phase and the discriminator phase. In the generator phase, the generator network takes a random noise vector as input and generates a sample. The discriminator network is then fed with both the real sample and the generated sample and predicts which sample is real and which one is generated. The generator network is then updated based on the feedback from the discriminator network, in order to improve the quality of the generated samples.</p><p>In the discriminator phase, the discriminator network is updated based on the feedback from the generator network. The discriminator network is trained to correctly distinguish between real and generated samples, while the generator network is trained to generate samples that can fool the discriminator network into thinking they are real.</p><p>This process is repeated iteratively until the generator network can produce samples that are indistinguishable from the real samples, and the discriminator network can no longer distinguish between the real and generated samples. At this point, the generator network can be used to generate new samples that are similar to the real samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*mBYLSN27ecrOEXbsRQEaXg.png" /></figure><h4>5.2 Pros and cons</h4><p><strong>Pros:</strong></p><ol><li><strong>Generate realistic and diverse data:</strong> GANs are capable of generating data that is realistic and diverse, and often indistinguishable from real data. This makes GANs useful for various applications such as image and video generation, where generating realistic and diverse data is crucial.</li><li><strong>No explicit modeling of probability distribution:</strong> GANs do not require explicit modeling of the probability distribution of the data, which can be difficult and computationally expensive. This makes GANs a more flexible and efficient alternative to traditional generative models.</li><li><strong>Adaptable to different types of data:</strong> GANs can be used to generate different types of data, such as images, videos, and even molecular structures. This makes GANs versatile and applicable to various domains.</li><li><strong>Faster than traditional methods:</strong> GANs can generate new data faster than traditional methods, especially when it comes to generating large amounts of diverse data.</li></ol><p><strong>Cons:</strong></p><ol><li><strong>Difficult to train: </strong>GANs can be difficult to train due to the adversarial nature of the model. The generator and discriminator networks need to be trained together, which can make the training process unstable and require careful hyperparameter tuning.</li><li><strong>Prone to mode collapse:</strong> GANs can suffer from mode collapse, where the generator network learns to generate only a few modes of the data distribution, rather than the full distribution. This can result in generated data that is not diverse enough.</li><li><strong>Lack of interpretability:</strong> GANs lack interpretability, which means that it can be difficult to understand how the model generates new data or what features it has learned.</li><li><strong>No guarantee of quality:</strong> There is no guarantee that the generated data will be of high quality, and generated data needs to be carefully evaluated for its quality and usefulness.</li></ol><h4>5.3 Application in drug discovery</h4><p>You may have seen this image generated by a GAN, well using it for drug discovery id totally different</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*Wl1hnr4XNLib44fdyYCdaw.png" /></figure><ol><li><strong>Generating novel molecular structures:</strong> GANs can be trained on a dataset of molecular structures to generate novel and diverse structures that have similar properties to known molecules. This approach can be used to generate potential drug candidates that can be further optimized using computational and experimental methods.</li><li><strong>Improving drug design:</strong> GANs can be used to optimize the properties of known drug molecules by generating variations that have improved activity, selectivity, and pharmacokinetic properties. This approach can reduce the time and cost of drug discovery by avoiding the need for large-scale chemical synthesis and screening.</li><li><strong>Predicting molecular properties:</strong> GANs can be trained to predict the properties of molecules such as toxicity, solubility, and bioactivity. This can help in identifying potential drug candidates with favorable properties and reducing the likelihood of developing drugs with unfavorable properties.</li><li><strong>De novo drug design: </strong>GANs can be used to design completely new drugs by generating molecules with desired properties and optimizing them for drug-like properties. This approach can potentially lead to the discovery of novel drug classes with unique mechanisms of action.</li></ol><h4>5.4 Generating novel molecular structures</h4><p>Generating novel molecular structures using Generative Adversarial Networks (GANs) is a promising approach in drug discovery that can potentially accelerate the process of identifying new drug candidates. GANs are a type of deep learning model that consist of two neural networks, a generator network and a discriminator network. The generator network generates new samples, in this case, molecular structures, while the discriminator network evaluates the authenticity of the generated samples.</p><p>In the context of drug discovery, GANs can be trained on a dataset of molecular structures to generate novel and diverse structures that have similar properties to known molecules. This approach can be used to generate potential drug candidates that can be further optimized using computational and experimental methods. The ability of GANs to generate diverse and novel structures can potentially lead to the discovery of new drug classes with unique mechanisms of action.</p><p>To train a GAN for generating novel molecular structures, a large dataset of molecular structures is required. This dataset can be obtained from publicly available databases such as PubChem, ChEMBL, or ZINC. The molecular structures can be represented using different encoding schemes such as SMILES, molecular graphs, or fingerprints. SMILES (Simplified Molecular Input Line Entry System) is a commonly used string-based representation of molecular structures that can be easily parsed and converted into a molecular graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*-iKj3CHJXtZQZtjpIgW-UA.png" /><figcaption>GANs generated molecular structure</figcaption></figure><p>Once the dataset is obtained, the GAN can be trained using a variety of loss functions such as adversarial loss, reconstruction loss, or similarity loss. Adversarial loss is the most commonly used loss function in GANs, where the generator network is trained to generate samples that are indistinguishable from the real samples by the discriminator network. Reconstruction loss and similarity loss are used to encourage the generated samples to have similar properties to the real samples.</p><p>After training the GAN, the generator network can be used to generate novel molecular structures. The generator network takes as input a random noise vector and generates a molecular structure that is similar to the structures in the training dataset. The generated structures can be further optimized using computational methods such as molecular docking, molecular dynamics simulation, or quantum mechanical calculations. The optimized structures can then be synthesized and tested for their biological activity in vitro and in vivo.</p><p>One of the advantages of using GANs for generating novel molecular structures is the ability to generate diverse and novel structures that are not present in the training dataset. This can potentially lead to the discovery of new drug candidates with unique mechanisms of action. However, the generated structures need to be carefully evaluated for their drug-likeness, toxicity, and other properties before proceeding with experimental testing.</p><h3>6. The dataset</h3><p>Today I am using the ChEMBL dataset to generate molecular structures, you can find this dataset here: <a href="https://www.ebi.ac.uk/chembl/">https://www.ebi.ac.uk/chembl/</a></p><p>The ChEMBL dataset is a valuable resource for drug discovery research that provides a comprehensive collection of bioactive molecules with associated data on their properties and activities. It is a publicly available database that is freely accessible for academic and industrial researchers, and it contains over 2 million unique chemical entities with over 20 million bioactivity measurements.</p><p>The ChEMBL dataset is maintained and curated by the European Bioinformatics Institute (EBI), and it is constantly updated with new data from the scientific literature, patents, and other sources. The dataset contains information on small molecules, peptides, and natural products that have been tested against a wide range of biological targets, including enzymes, receptors, ion channels, and transporters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*dY-xX-7D7dLYcr6FrcTEZA.png" /></figure><p>The ChEMBL dataset is an important resource for drug discovery research because it enables scientists to explore the structure-activity relationships (SARs) of bioactive molecules and identify potential drug candidates. The dataset contains information on the chemical structures of the molecules, as well as their physicochemical properties, such as molecular weight, logP, and solubility. It also provides data on the bioactivity of the molecules, including their potency, efficacy, and selectivity against specific targets.</p><p>One of the key advantages of the ChEMBL dataset is its integration with other bioinformatics resources, such as UniProt, GO, and KEGG, which provides additional information on the biological pathways and processes associated with the targets. This integration enables researchers to analyze the data in a more holistic manner and identify potential drug targets and pathways that may be relevant for a specific disease or condition.</p><p>The ChEMBL dataset has been widely used in drug discovery research for various applications, such as virtual screening, pharmacophore modeling, and machine learning. It has also been used to develop computational tools and methods for predicting the properties and activities of bioactive molecules, such as their toxicity, pharmacokinetics, and drug-likeness.</p><h3>7. The code</h3><p>Now the fun part, we can finally get into the code of this!</p><h4>7.1 Import your libraries</h4><pre># Import necessary packages<br>import pandas as pd<br>from rdkit import Chem<br>from rdkit.Chem import AllChem, Descriptors, PandasTools<br>from rdkit.Chem.Draw import MolsToGridImage</pre><p>I used pandas as well as the RDkit package- this is a collection of cheminformatics and machine learning tools for working with molecules and chemical structures. Here’s what each of these libraries do:</p><ol><li>from rdkit import Chem: This library is the core of the RDKit package, providing the basic functions for working with chemical structures. It contains methods for reading and writing chemical file formats, generating 2D and 3D molecular representations, and performing basic chemical operations, such as atom and bond manipulation.</li><li>from rdkit.Chem import AllChem: This library provides additional functionality for performing more advanced chemical operations, such as molecular alignment, conformation generation, and molecular mechanics calculations. It includes the implementation of the widely used force fields MMFF94 and MMFF94s, as well as methods for performing molecular docking and virtual screening.</li><li>from rdkit.Chem import Descriptors: This library contains a set of pre-calculated molecular descriptors, which are numerical values that represent different properties of molecules, such as molecular weight, polar surface area, and lipophilicity. These descriptors are commonly used in machine learning models for predicting molecular properties and activities.</li><li>from rdkit.Chem import PandasTools: This library provides tools for working with chemical data in the pandas data analysis library. It includes methods for converting between chemical file formats and pandas data frames, as well as functions for visualizing chemical data using matplotlib.</li><li>from rdkit.Chem.Draw import MolsToGridImage: This library provides a convenient method for generating a grid of 2D molecular structures from a list of RDKit molecules. It allows for easy visualization of multiple molecules side-by-side, which can be useful for comparing and analyzing molecular structures.</li></ol><h4>7.2 load and preprocess the data</h4><p>Preprocessing data is an important step in data analysis and machine learning. It involves preparing the raw data for further analysis by transforming, cleaning, and formatting it in a way that is suitable for the desired analysis or modeling technique. Here are some reasons why we preprocess data:</p><ol><li><strong>Data Cleaning:</strong> Raw data can be noisy and contain errors or inconsistencies, such as missing values, incorrect data types, and outliers. Preprocessing can help identify and correct these issues, ensuring that the data is accurate and reliable.</li><li><strong>Feature Scaling:</strong> In machine learning, different features or variables may have different scales and units, which can lead to bias in the model. Preprocessing can help normalize the data and ensure that each feature has a comparable scale and range.</li><li><strong>Feature Selection: </strong>Preprocessing can also involve selecting the most relevant features or variables for the analysis or model. This can help reduce noise and improve the performance of the model.</li><li><strong>Dimensionality Reduction: </strong>In some cases, the dataset may contain a large number of features or variables, which can make the analysis or modeling computationally expensive or difficult to interpret. Preprocessing can help reduce the dimensionality of the data by combining or selecting the most important features.</li><li><strong>Data Transformation: </strong>Preprocessing can also involve transforming the data into a more suitable format for the analysis or modeling technique. For example, converting categorical variables into numerical variables or scaling time series data into a stationary series.</li></ol><pre><br># Load the ChEMBL database as a pandas dataframe<br>df = pd.read_csv(&#39;chembl_28_chemreps.txt&#39;, delimiter=&#39;\t&#39;, low_memory=False)<br><br># Filter the dataframe to include only compounds tested for activity against bi-polar disorder pathway targets<br>target_list = [&#39;GSK3B&#39;, &#39;AKT1&#39;]<br>df_filtered = df[df[&#39;Target&#39;].isin(target_list)]<br><br># Convert the &#39;Smiles&#39; column to RDKit molecules<br>PandasTools.AddMoleculeColumnToFrame(df_filtered, &#39;Smiles&#39;, &#39;Molecule&#39;)<br><br># Filter out molecules with invalid or incomplete structures<br>df_filtered[&#39;Molecule&#39;] = df_filtered[&#39;Molecule&#39;].apply(lambda x: None if x is None else Chem.RemoveHs(x))<br>df_filtered = df_filtered.dropna(subset=[&#39;Molecule&#39;])<br><br># Calculate molecular descriptors<br>df_filtered[&#39;MolWt&#39;] = df_filtered[&#39;Molecule&#39;].apply(Descriptors.MolWt)<br>df_filtered[&#39;LogP&#39;] = df_filtered[&#39;Molecule&#39;].apply(Descriptors.MolLogP)<br><br># Normalize the data<br>df_filtered[&#39;MolWt&#39;] = (df_filtered[&#39;MolWt&#39;] - df_filtered[&#39;MolWt&#39;].mean()) / df_filtered[&#39;MolWt&#39;].std()<br>df_filtered[&#39;LogP&#39;] = (df_filtered[&#39;LogP&#39;] - df_filtered[&#39;LogP&#39;].mean()) / df_filtered[&#39;LogP&#39;].std()<br><br># Convert the RDKit molecules to SMILES strings<br>df_filtered[&#39;SMILES&#39;] = df_filtered[&#39;Molecule&#39;].apply(Chem.MolToSmiles)<br><br># Save the preprocessed data to a new CSV file<br>df_filtered.to_csv(&#39;bipolar_drugs.csv&#39;, index=False)</pre><h4>7.3 define the generator network</h4><p>The generator network takes in a random noise vector of shape (100,) as input and outputs a new data point that is intended to resemble the real data. The generator network is trained to generate synthetic data that is as similar as possible to the real data, while the discriminator network is trained to distinguish between the real and fake data.</p><p>The generator network in this code is a deep neural network composed of several dense (fully connected) layers. Each dense layer has a specified number of neurons and an activation function. The activation function used in this generator network is ReLU (Rectified Linear Unit), which helps introduce non-linearity into the model and prevents the vanishing gradient problem.</p><p>The final layer of the generator network has 74 neurons and uses the sigmoid activation function. This is because the data being generated is assumed to have 74 features or dimensions, and the sigmoid function produces an output in the range [0, 1], which can be interpreted as probabilities for each feature.</p><p>Overall, this generator network is designed to learn the underlying patterns and structure of the real data and generate new data points that are similar to the real data in terms of their feature distributions and correlations.</p><pre># Define the generator network<br>def make_generator_model():<br>    model = keras.Sequential()<br>    model.add(layers.Dense(256, input_shape=(100,), activation=&#39;relu&#39;))<br>    model.add(layers.Dense(512, activation=&#39;relu&#39;))<br>    model.add(layers.Dense(1024, activation=&#39;relu&#39;))<br>    model.add(layers.Dense(2048, activation=&#39;relu&#39;))<br>    model.add(layers.Dense(4096, activation=&#39;relu&#39;))<br>    model.add(layers.Dense(8192, activation=&#39;relu&#39;))<br>    model.add(layers.Dense(16384, activation=&#39;relu&#39;))<br>    model.add(layers.Dense(2048, activation=&#39;relu&#39;))<br>    model.add(layers.Dense(512, activation=&#39;relu&#39;))<br>    model.add(layers.Dense(256, activation=&#39;relu&#39;))<br>    model.add(layers.Dense(128, activation=&#39;relu&#39;))<br>    model.add(layers.Dense(74, activation=&#39;sigmoid&#39;))<br>    return model</pre><h4>7.4 Define the discriminator network</h4><p>The discriminator network is used to distinguish between real and fake data points. It takes in a data point, either real or fake, of shape (74,) as input and outputs a single scalar value representing the probability that the input data is real.</p><p>The discriminator network in this code is a deep neural network composed of several dense (fully connected) layers. Each dense layer has a specified number of neurons and an activation function. The activation function used in this discriminator network is ReLU (Rectified Linear Unit), which helps introduce non-linearity into the model and prevents the vanishing gradient problem.</p><p>The final layer of the discriminator network has a single neuron and uses the sigmoid activation function. This is because the output of the discriminator network is a probability value between 0 and 1, where values closer to 1 indicate that the input data is more likely to be real, and values closer to 0 indicate that the input data is more likely to be fake.</p><p>Overall, this discriminator network is designed to learn the difference between real and fake data points and output a probability value indicating the likelihood of the input data being real.</p><pre># Define the discriminator network<br>def make_discriminator_model():<br>    model = keras.Sequential()<br>    model.add(layers.Dense(1024, input_shape=(74,), activation=&#39;relu&#39;))<br>    model.add(layers.Dense(512, activation=&#39;relu&#39;))<br>    model.add(layers.Dense(256, activation=&#39;relu&#39;))<br>    model.add(layers.Dense(1, activation=&#39;sigmoid&#39;))<br>    return model</pre><h4>7.5 Define the loss function for the discriminator network</h4><p>The loss function is used to evaluate how well the discriminator is able to distinguish between real and fake data points.</p><p>The function takes two inputs, the real output and fake output of the discriminator network, which are obtained by passing real and fake data points through the discriminator network, respectively. The real_output is a tensor of shape (batch_size, 1), containing the discriminator’s predictions for each real data point, and the fake_output is a tensor of shape (batch_size, 1), containing the discriminator’s predictions for each fake data point.</p><p>The loss function computes the binary cross-entropy loss for the discriminator’s predictions on the real data points and the fake data points separately. The binary cross-entropy loss measures the dissimilarity between two probability distributions, in this case, the predicted probability distribution and the actual distribution.</p><p>The real_loss is computed by comparing the real_output with a tensor of ones of the same shape as real_output. The fake_loss is computed by comparing the fake_output with a tensor of zeros of the same shape as fake_output. The total_loss is the sum of the real_loss and the fake_loss.</p><p>By minimizing this loss function, the discriminator network is trained to accurately distinguish between real and fake data points.</p><pre># Define the loss function for the discriminator network<br>def discriminator_loss(real_output, fake_output):<br>    real_loss = tf.losses.binary_crossentropy(tf.ones_like(real_output), real_output)<br>    fake_loss = tf.losses.binary_crossentropy(tf.zeros_like(fake_output), fake_output)<br>    total_loss = real_loss + fake_loss<br>    return total_loss</pre><h4>7.6 Define the loss function for the generator network</h4><p>The generator network is responsible for generating fake data points that can be passed through the discriminator network to ultimately improve the generator’s performance.</p><p>The generator_loss function takes as input the fake_output, which is a tensor of shape (batch_size, 1) containing the discriminator’s predictions for each fake data point generated by the generator network. The goal of the generator is to generate data points that the discriminator cannot distinguish from real data points, so the loss function aims to maximize the probability that the discriminator will classify the fake data points as real.</p><p>To achieve this, the binary cross-entropy loss function is used, which measures the dissimilarity between two probability distributions. In this case, the predicted probability distribution is the fake_output and the actual distribution is a tensor of ones of the same shape as fake_output, representing the label for real data points. The binary cross-entropy loss is used to compute the loss for the generator network.</p><p>By minimizing this loss function, the generator network is trained to generate fake data points that are similar to real data points, with the aim of ultimately fooling the discriminator network.</p><pre># Define the loss function for the generator network<br>def generator_loss(fake_output):<br>    return tf.losses.binary_crossentropy(tf.ones_like(fake_output), fake_output)</pre><h4>7.7 Define the optimizers for the generator and discriminator networks</h4><p>The optimizer is responsible for adjusting the weights of the neural network during training to minimize the loss function and improve the network’s performance.</p><p>The Adam optimizer is used, which is a popular and effective optimizer for deep learning models. The optimizer takes a learning rate as a parameter, which controls the step size taken during weight updates.</p><p>Here, both the generator and discriminator networks use the same Adam optimizer with a learning rate of 1e-4. The learning rate can be adjusted to control the speed of convergence during training. A smaller learning rate can result in slower but more stable training, while a larger learning rate can result in faster but less stable training.</p><p>By using the same optimizer for both networks, the weights are updated simultaneously during training to optimize the overall performance of the GAN model.</p><pre># Define the optimizers for the generator and discriminator networks<br>generator_optimizer = tf.keras.optimizers.Adam(1e-4)<br>discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)</pre><h4>7.8 Define the training loop</h4><p>The @tf.function decorator is used to create a TensorFlow function for this loop, which can be compiled and optimized for better performance.</p><p>The function takes a batch of real data as input and generates a batch of fake data using the generator network. The discriminator network is then used to evaluate the real and fake data, and the loss functions for the generator and discriminator are calculated based on the discriminator’s output.</p><p>The gradients of these loss functions are then computed using tf.GradientTape and used to update the weights of the generator and discriminator networks using their respective optimizers.</p><p>The training loop runs for a specified number of epochs, with each epoch consisting of multiple iterations of the training step. At the end of each epoch, the generator’s progress is evaluated by generating a sample of fake data and plotting it for visual inspection.</p><p>Overall, the training loop is responsible for updating the weights of the generator and discriminator networks to improve their performance at generating realistic and diverse data. It is the key component of the GAN model and is essential for the success of the overall approach.</p><pre># Define the training loop<br>@tf.function<br>def train_step(real_data):<br>    noise = tf.random.normal([BATCH_SIZE, 100])<br>    with tf.GradientTape</pre><h3>8. The benefits of this technology</h3><p>Now that we have looked at how to do this, let’s end with why we should do this. The code is an implementation of a Generative Adversarial Network (GAN) for drug discovery, specifically for generating novel bi-polar drug molecules. The benefits of this code are:</p><ol><li><strong>Novel drug discovery:</strong> GANs can generate new drug molecules with similar properties to known molecules, which can potentially lead to the discovery of new drug classes with unique mechanisms of action.</li><li><strong>Time and cost savings:</strong> The GAN approach can reduce the time and cost of drug discovery by avoiding the need for large-scale chemical synthesis and screening.</li><li><strong>Optimization of known drugs:</strong> GANs can optimize the properties of known drug molecules by generating variations that have improved activity, selectivity, and pharmacokinetic properties.</li><li><strong>Predicting molecular properties:</strong> GANs can be trained to predict the properties of molecules such as toxicity, solubility, and bioactivity. This can help in identifying potential drug candidates with favorable properties and reducing the likelihood of developing drugs with unfavorable properties.</li></ol><p>Overall, the use of GANs in drug discovery has the potential to accelerate the process of discovering new and effective drugs, while also reducing costs and minimizing the risk of failure.</p><p>Here is a note from the writer of this article:</p><p><strong>Hi readers, I am a 13-year-old girl in the UK and would love your support.</strong></p><p>Thank you for reading this and I would love it if you checked out some of my other articles as well!</p><p>Please check out my monthly newsletter: <a href="https://substack.com/profile/106867284-vidushi-valli-surendran">https://substack.com/profile/106867284-vidushi-valli-surendran</a></p><p>My LinkedIn:</p><p><a href="https://www.linkedin.com/in/vidushi-valli-surendran-075a06250/">https://www.linkedin.com/in/vidushi-valli-surendran-075a06250/</a></p><p>My personal website:</p><p><a href="http://vidushivs.com/">Vidushivs.com</a></p><p>My recent article:</p><p><a href="https://medium.com/@vidushi-valli-surendran/predicting-drug-response-of-fluexotine-based-on-a-cyp2d6-activity-scale-76a2c7e649bb">https://medium.com/@vidushi-valli-surendran/predicting-drug-response-of-fluexotine-based-on-a-cyp2d6-activity-scale-76a2c7e649bb</a></p><p>And thank you for reading again!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4814ba018763" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting drug response of Fluexotine based on a CYP2D6 activity scale]]></title>
            <link>https://vidushi-valli-surendran.medium.com/predicting-drug-response-of-fluexotine-based-on-a-cyp2d6-activity-scale-76a2c7e649bb?source=rss-1c2ea4bc3f60------2</link>
            <guid isPermaLink="false">https://medium.com/p/76a2c7e649bb</guid>
            <dc:creator><![CDATA[Vidushi Valli Surendran]]></dc:creator>
            <pubDate>Sun, 12 Mar 2023 13:37:08 GMT</pubDate>
            <atom:updated>2023-03-12T13:37:08.185Z</atom:updated>
            <content:encoded><![CDATA[<p>Depression is a condition that affects many people, and it can be caused by a variety of factors, such as genetics, life events, and <strong>changes in brain chemistry.</strong></p><p>Antidepressants are a type of medication used to treat depression, anxiety, and other mental health disorders.</p><p>They work by <strong>altering the balance of chemicals in the brain</strong>, such as serotonin, norepinephrine, and dopamine.</p><p>Antidepressants can be helpful for people who experience symptoms of depression, such as feelings of sadness, hopelessness, and low energy, <strong>and who have not found relief from other treatments</strong>, such as therapy.</p><h3>Table of contents:</h3><ol><li>Abstract</li><li>Types of antidepressants</li><li>Why predicting drug response is important</li><li>What affects drug response</li><li>The dataset</li><li>Using logistic regression</li><li>Using random forest classification</li><li>Conclusion</li></ol><h3>1. Abstract</h3><p>Predicting drug response can be a very useful tool, especially with antidepressants — the most commonly prescribed drug in the united states.</p><p>Today I will be using both logistic regression and random forest classification to predict the drug response of Fluexotine using the input of <strong>age, BMI, height, and CYP2D6 activity scale.</strong></p><h3>2. Types of antidepressants</h3><p>There are several types of antidepressants, and each type of medication works in a slightly different way, and the choice of medication will depend on the individual’s symptoms, medical history, and other factors.</p><p><strong>SSRIs </strong>are one of the most commonly prescribed types of antidepressants. They work by <strong>increasing the levels of serotonin in the brain</strong>, which can help to improve mood and reduce anxiety.</p><p>Some examples of SSRIs include fluoxetine (Prozac), sertraline (Zoloft), and citalopram (Celexa).</p><p>SNRIs work by increasing the levels of both <strong>serotonin</strong> and <strong>norepinephrine</strong> in the brain.</p><p>They can be helpful for people who experience both <strong>depression and anxiety.</strong></p><p>Examples of SNRIs include venlafaxine (Effexor) and duloxetine (Cymbalta).</p><p>TCAs and MAOIs are less commonly prescribed and typically reserved for people <strong>who have not found relief from other medications.</strong></p><p>TCAs work by increasing the levels of <strong>serotonin and norepinephrine</strong> in the brain, while MAOIs work by <strong>blocking the breakdown of certain chemicals</strong> in the brain, such as serotonin and dopamine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/0*YLn3ssD_UwELAnd8" /><figcaption>Fluoxetine : <a href="https://patents.google.com/patent/EP1242362A1/en">https://patents.google.com/patent/EP1242362A1/en</a></figcaption></figure><h3>3. Why is predicting drug response important?</h3><p>Predicting drug response for antidepressants is important for several reasons:</p><h4>3. 1 Personalized medicine</h4><p>Personalized treatment, also known as precision medicine, is an approach to healthcare that takes into account a person’s characteristics when developing treatment plans.</p><p>This can include factors such as a <strong>person’s genetics, medical history, lifestyle, and other personal preferences.</strong></p><p>In the case of antidepressant treatment, personalized medicine can help doctors choose the <strong>most effective</strong> medication for a particular patient.</p><p>Antidepressants work by altering the levels of neurotransmitters in the brain, such as serotonin, norepinephrine, and dopamine.</p><p>However, the way a person’s body <strong>metabolizes </strong>these neurotransmitters can vary based on their genetics and other individual factors.</p><p>By analyzing a patient’s genetic profile, doctors can i<strong>dentify genetic variations </strong>that may affect how their body processes antidepressants.</p><p>This information can help doctors select medications that are <strong>more likely to be effective </strong>for that patient, reducing the need for trial-and-error in finding the right medication.</p><p>Other factors that may be considered when personalizing antidepressant treatment include a patient’s medical history, current medications, and lifestyle factors such as diet, exercise, and sleep habits.</p><p>For example, a patient with a history of substance abuse may require a different medication than someone without that history, or a patient with a busy work schedule may benefit from a medication that has a longer half-life, reducing the need for multiple daily doses.</p><h4>3.2 Avoiding side effects</h4><p>Predicting drug response for depression can help avoid side effects by allowing doctors and clinicians to choose the most effective treatment option for a patient based on their genetic makeup and other personal factors.</p><p>By using genetic testing or other personalized medicine approaches, doctors can identify which antidepressant drugs are likely to be most effective for a particular patient and which drugs are likely to cause adverse side effects.</p><p>This personalized approach to treatment can <strong>reduce the risk of side effects by avoiding the use of drugs that are unlikely to work for a particular patient or are more likely to cause side effects.</strong> By selecting the most effective treatment option, doctors can also help patients achieve remission more quickly and with fewer treatment-related complications.</p><p>Furthermore, if a patient has a history of adverse drug reactions or a high risk for specific side effects, genetic testing can help clinicians select medications that are <strong>less likely to cause those specific side effects.</strong></p><h4>3.3 cost-effective</h4><p>Predicting precision medicine drug response can be a cost-effective strategy in healthcare.</p><p>When patients are prescribed with medications that are not effective for them, they may experience adverse side effects or a lack of therapeutic benefit.</p><p>This can lead to a <strong>cycle of trial-and-error</strong> medication selection, which can be time-consuming, expensive, and frustrating for both the patient and the healthcare provider.</p><p>By predicting drug response, healthcare providers can select the most effective medication for each patient, <strong>reducing the need for trial and error.</strong></p><p>This can save money and reduce the risk of adverse drug reactions. Additionally, effective treatment can improve patient outcomes and quality of life, which can ultimately lead to <strong>reduced healthcare costs in the long run.</strong></p><p>Another cost-effective aspect of predicting drug response is<strong> avoiding unnecessary medical interventions.</strong></p><p>In some cases, doctors may prescribe medications or treatments that are not needed or are unlikely to be effective. Predicting drug response can help avoid unnecessary interventions, reduce healthcare costs, and improve patient outcomes.</p><p>Furthermore, predicting drug response can help identify patients<strong> who are likely to benefit from more expensive treatments or therapies.</strong></p><p>For example, if a patient is unlikely to respond to a less expensive medication, it may be more cost-effective to prescribe a more expensive medication that is more likely to be effective.</p><h4>3.4 Drug development</h4><p>Predicting precision medicine drug response can also play a crucial role in drug development.</p><p>In the past, drug development has often followed a <strong>“one-size-fits-all”</strong> approach, where drugs were developed to be effective for the general population. However, not all patients respond to drugs in the same way, and some may experience adverse effects.</p><p>By predicting drug response, researchers can identify patient populations that are <strong>more likely to respond positively to a particular drug.</strong></p><p>This can help guide drug development efforts and improve the chances of developing effective treatments.</p><p>Additionally, by understanding the genetic and molecular mechanisms of drug response, researchers can<strong> develop new drugs that are more effective and have fewer side effects.</strong></p><p>Predicting drug response can also help identify new drug targets. <strong>Drug targets are specific molecules or pathways that drugs can interact with to produce a therapeutic effect.</strong></p><p>By identifying drug targets that are associated with a positive response, researchers can develop drugs that are <strong>more effective and have fewer side effects.</strong></p><p>Furthermore, predicting drug response can help <strong>accelerate the drug development process. </strong>Clinical trials are expensive and time-consuming, and many drugs fail to make it to market due to a lack of efficacy or safety concerns.</p><p>By predicting drug response, researchers can design clinical trials that are more likely to succeed, reducing the time and cost required to bring drugs to market.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*YI94h3xzRRVbxhau.png" /><figcaption><a href="https://cofactorgenomics.com/wk-2020-predicting-drug-response/">cofactorgenomics.com</a></figcaption></figure><h3>4. What affects drug response?</h3><p>Many variables affect drug response, these are the features of my code.</p><h4>4.1 CYP2D6</h4><p>The CYP2D6 gene is highly polymorphic, meaning that <strong>many different variations or alleles of the gene can affect its activity.</strong> Currently, there are more than 100 known allelic variants of CYP2D6, and these can be grouped into four main categories: poor metabolizers, intermediate metabolizers, normal metabolizers, and ultra-rapid metabolizers.</p><p>The CYP2D6 gene is located on <strong>chromosome 22</strong> and is expressed primarily in the liver. This gene is responsible for encoding the CYP2D6 enzyme, which is involved in the metabolism of approximately <strong>25% of clinically used drugs</strong>, including many commonly used psychiatric medications.</p><p>There are several ways to test for CYP2D6 genetic variability. One common method is <strong>genotyping,</strong> which involves analyzing a person’s DNA to identify specific variations or alleles of the CYP2D6 gene. This can be done using a variety of techniques, including PCR (polymerase chain reaction) and DNA sequencing.</p><p>Another method for assessing CYP2D6 activity is <strong>phenotyping.</strong> This involves measuring the activity of the CYP2D6 enzyme directly in the blood or urine of a patient. This can be done using specific probes or substrates that are metabolized by CYP2D6 and then measuring the number of metabolites produced.</p><p>Understanding a patient’s CYP2D6 genotype can help clinicians personalize medication therapy to optimize outcomes. For example, a poor metabolizer who has been prescribed an antidepressant that is metabolized by CYP2D6 may require a lower starting dose or a medication that is not metabolized by this enzyme to avoid toxicity. Conversely, an ultra-rapid metabolizer may require higher doses of medications to achieve therapeutic effects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*UwVt1tCuIpF38HTS" /></figure><h4>4.2 Height</h4><p>Height is one of many factors that can influence a person’s response to depression medication. Studies have suggested that taller individuals may require higher doses of antidepressants to achieve the same therapeutic effect as shorter individuals.</p><p>There are several possible reasons why height may influence medication response:</p><ol><li><strong>Body weight: </strong>Taller individuals often weigh more than shorter individuals, which can affect how their bodies process medication. Higher body weight may require higher doses of medication to achieve the same effect.</li><li><strong>Metabolism: </strong>Height is also associated with differences in metabolism, which can affect how the medication is processed by the body. Taller individuals may have faster metabolisms, which can result in medication being processed more quickly and requiring higher doses for therapeutic effects.</li><li><strong>Blood volume:</strong> Taller individuals tend to have higher blood volume, which can affect how the medication is distributed throughout the body. Higher blood volume may require higher doses of medication to achieve the desired effect.</li></ol><h4>4.3: Weight</h4><p>Weight can affect medication response in several ways. One of the most significant factors is body mass, as medication doses are often determined based on a person’s body weight.</p><p><strong>Higher body weight</strong> generally requires higher medication doses to achieve the same effect as a person with a lower body weight.</p><p>Additionally, body fat can also play a role in medication response. Many medications are stored in body fat, which can affect their <strong>distribution and elimination from the body.</strong></p><p>People with higher levels of body fat may experience<strong> slower medication clearance</strong>, which can result in a longer duration of action and potentially a higher risk of side effects.</p><p><strong>Metabolism </strong>can also be influenced by weight. Higher body weight is associated with lower metabolic rates, which can affect how a medication is processed by the body.</p><p>This can result in a <strong>slower breakdown of medication</strong> and potentially higher levels of medication in the bloodstream, which can increase the risk of side effects.</p><h4>4.4 BMI</h4><p>BMI is an indicator of overall body composition. BMI can play a role in medication response in a few ways:</p><ol><li><strong>Dose determination:</strong> Medication doses are often determined based on a person’s body weight, which includes their BMI. A higher BMI is often associated with higher body weight, which may require higher medication doses to achieve the same therapeutic effect as a person with a lower BMI.</li><li><strong>Distribution and metabolism:</strong> BMI can affect medication distribution and metabolism. People with higher BMI tend to have higher levels of body fat, which can impact how a medication is distributed and eliminated from the body. This can result in slower medication clearance, which may increase the duration of action and potentially increase the risk of side effects.</li><li><strong>Medication effectiveness:</strong> Higher BMI has been associated with reduced effectiveness of some medications, particularly those used to treat mental health conditions such as depression and anxiety. This may be due to differences in how a medication is distributed and metabolized in people with higher BMI, as well as potential differences in how the brain responds to the medication.</li></ol><h4>4.5 Age</h4><ol><li><strong>Absorption:</strong> As we age, our digestive system may not work as efficiently, leading to slower absorption of medication. This can affect how quickly a drug takes effect.</li><li><strong>Metabolism:</strong> The liver and kidneys are responsible for metabolizing and eliminating drugs from the body. As we age, the function of these organs may decline, which can lead to slower drug metabolism and longer drug half-lives.</li><li><strong>Distribution: </strong>Changes in body composition, such as decreased muscle mass and increased fat, can affect how drugs are distributed in the body. This can impact the amount of drug that reaches the target tissue or organ.</li><li><strong>Sensitivity: </strong>As we age, we may become more sensitive to certain drugs. This can be due to changes in receptor density or alterations in enzyme function.</li><li><strong>Polypharmacy: </strong>Older adults may be taking multiple medications at once, which can increase the risk of drug interactions and adverse effects.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*KbJx38AV1cQqWT4k-Spx0g.png" /><figcaption><a href="http://rheumatologyuk.net/tambo-upper/factors-affecting-bioavailability-of-drugs-pdf.php">heumatologyuk.net</a></figcaption></figure><h3>5. The dataset</h3><p>I am using the NCBI dataset to predict this drug response.</p><p>The dataset available on the National Center for Biotechnology Information (NCBI) Genetic Testing Registry includes information on fluoxetine response and CYP2D6 genotype.</p><p>This dataset provides a s<strong>ummary of the available evidence on the impact of the CYP2D6 genotype on fluoxetine metabolism and response.</strong></p><p>CYP2D6 is an enzyme that plays a key role in the metabolism of many medications, including fluoxetine.</p><p>Genetic variations in CYP2D6 can lead to differences in the activity of the enzyme, which can impact how the body processes and response to medications like fluoxetine.</p><p>Some individuals may have genetic variations that result in reduced CYP2D6 activity, while others may have variations that lead to increased activity.</p><p>The NCBI dataset includes information on a specific CYP2D6 genotype, known as<strong> CYP2D64.</strong></p><p>This genotype is associated with <strong>reduced enzyme activity </strong>and has been linked to the slower metabolism of fluoxetine.</p><p>The dataset summarizes the available evidence on the impact of the CYP2D64 genotype on fluoxetine response, including studies that have looked at how the genotype affects fluoxetine blood levels, side effects, and clinical outcomes.</p><h3>6. Using Logistic regression:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/0*aYiEL5WGaM2BOKaP.png" /><figcaption><a href="https://levelup.gitconnected.com/50-mathematical-concepts-for-better-programming-part-2-f0dc13a8c05">https://levelup.gitconnected.com/50-mathematical-concepts-for-better-programming-part-2-f0dc13a8c05</a></figcaption></figure><p>Logistic regression maps x to y using a sigmoid function, Logistic regression while being a type of regression algorithm also classifies data. logistic regression predicts a continuous variable and binary classification predicts a set value.</p><p><strong>Sigmoid functions:</strong></p><p>Normally this term refers to the logistic sigmoid function.</p><p>Sigmoid functions squeeze values in ranges such as 0–1 or -1–1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*280y-evkfPSzOR6m.png" /><figcaption><a href="https://datasciencebox.org/course-materials/lab-instructions/lab-06/lab-06-sad-plots.html">https://datasciencebox.org/course-materials/lab-instructions/lab-06/lab-06-sad-plots.html</a></figcaption></figure><p>Logistic sigmoid function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*HhXzAnqlY6EHTFt6.png" /><figcaption><a href="https://www.youtube.com/watch?v=6tFj4B1hNNM">https://www.youtube.com/watch?v=6tFj4B1hNNM</a></figcaption></figure><p>Above is the equation you need to understand for this. A logistic function squeezes values between 0 and 1.</p><p>This is good for a binary classification model where outputs should be 0/1.</p><p>Is this table blue or not, is this ice cream or not, etc?</p><h4>6.1 Import your libraries</h4><p>Today we are using Pandas, as well as some tools from the SK learn library</p><h4>6.1.1 Pandas</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/0*GdpZ1ZNof8zEtd4V" /><figcaption>Pandas logo</figcaption></figure><p>Pandas is a popular Python library that provides powerful data structures and data analysis tools. It is widely used in data science and machine learning projects for data preprocessing and cleaning tasks.</p><p>Some of the key features of Pandas include:</p><ul><li><strong>Data structures:</strong> Pandas provides two main data structures, Series (1-dimensional) and DataFrame (2-dimensional). Series is similar to a column in a spreadsheet and DataFrame is similar to a table in a spreadsheet.</li><li><strong>Indexing and selecting data: </strong>Pandas provides a variety of ways to index and select data from a DataFrame, including label-based indexing and boolean indexing. This allows you to easily select and filter subsets of the data based on certain conditions.</li><li><strong>Handling missing data:</strong> Pandas provides several ways to handle missing data, including filling in missing values with a specific value or using a statistic (such as the mean) from the non-missing values.</li><li><strong>Merging and joining:</strong> Pandas allows you to easily combine multiple data sets by merging or joining them on one or more columns.</li><li><strong>Grouping and aggregation: </strong>Pandas provides a variety of ways to group and summarize data, such as grouping by one or more columns and applying a statistical function (such as mean or sum) to each group.</li><li><strong>Data manipulation:</strong> Pandas provides a wide range of data manipulation and data transformation functions, such as pivot, melt, stack, unstack, etc.</li></ul><p>Pandas is built on top of NumPy, and it utilizes its powerful array and mathematical operations to provide a fast and efficient way to work with large amounts of data.</p><h4>SK learn libraries:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*8V44PLuseSGfpLBW" /><figcaption>logo</figcaption></figure><h4>6.1.2 Standard scaler</h4><p>StandardScaler is a data preprocessing technique in machine learning that is used to standardize the features of a dataset. It is a part of the preprocessing module in the popular sci-kit-learn library in Python.</p><p>StandardScaler works by <strong>centering and scaling the features </strong>of a dataset so that they have zero mean and unit variance.</p><p>This is done by subtracting the mean value of each feature from each observation and then dividing by the standard deviation of that feature. The resulting standardized features have a <strong>mean of 0 and a standard deviation of 1.</strong></p><p>StandardScaler is commonly used before applying machine learning algorithms to a dataset to ensure that the features are on a similar scale.</p><p>This can be important because some machine learning algorithms are sensitive to the scale of the features, and having features on vastly different scales can lead to inaccurate predictions.</p><p>Standardizing the features using StandardScaler can also help to improve the performance of some machine learning algorithms, particularly those that are based on distance or similarity measures.</p><p>StandardScaler will be used to <strong>standardize the ‘BMI’, ‘height’, and ‘age’</strong> features of the dataset, which were then used as inputs to a logistic regression model. This helps to ensure that the features were on a similar scale, which can help to improve the accuracy of the model.</p><p>It also integrates well with other libraries like Matplotlib and Scikit-learn for data visualization and machine learning tasks. To use Pandas, you need to first install the library and then import it into your Python script or Jupyter notebook using the import statement</p><h4>6.1.3 Simple imputer</h4><p>SimpleImputer is a class in the sci-kit-learn library that provides a way to impute or fill in missing values in a dataset. It is a simple strategy that can be used for <strong>imputing missing values,</strong> such as replacing them with the mean, median, or most frequent value of the respective column, depending on the data type.</p><p>SimpleImputer can be useful when working with datasets that have missing data, which can cause problems for machine learning algorithms that expect complete data. By filling in missing values with estimated values, SimpleImputer can help improve the accuracy of machine learning models.</p><p>SimpleImputer can be used in a pipeline with other sci-kit-learn classes for data preprocessing and modeling. It is easy to use and can handle both numerical and categorical data.</p><h4>6.1.4 Train test split</h4><p>Train-test split is a method used in machine learning to evaluate the performance of a predictive model. It involves splitting the available data into two separate sets: one for training the model and another for testing the model’s performance.</p><p>The training set is used to train the model by <strong>fitting the model to the data and adjusting its parameters. </strong>The testing set is then used to evaluate the model’s performance by predicting the outcomes of the data in the testing set and comparing the predicted values to the actual values.</p><p>The purpose of using a train-test split is to estimate how well the model will perform on new, unseen data. If the model performs well on the testing set, it suggests that it is likely to perform well on new data. On the other hand, if the model does not perform well on the testing set, it may indicate that the model is overfitting the training data and is not generalizing well to new data.</p><p>Typically, the data is split into a training set and a testing set in a random manner, with a fixed proportion of the data allocated to each set. Common proportions include <strong>70% for the training set and 30% for the testing set, or 80% for the training set and 20% for the testing set. </strong>However, the specific proportion of data allocated to each set can vary depending on the size of the dataset and the specific problem being addressed.</p><h4>6.1.5 Metrics</h4><p>In machine learning, it is often necessary to evaluate the performance of a predictive model. Accuracy_score, precision_score, recall_score, and f1_score are all metrics used to evaluate the performance of a classification model. Each metric has its own specific use case and can provide valuable insights into the model’s performance.</p><ul><li><strong>Accuracy_score:</strong> Accuracy_score is the most basic evaluation metric used to evaluate a classification model. It measures the proportion of correct predictions among all the predictions made by the model. It is useful when the class distribution is balanced, meaning that there are roughly equal numbers of instances for each class.</li><li><strong>Precision_score: </strong>Precision_score measures the proportion of true positives (correctly classified instances) among all the instances that the model predicted as positive. It is useful when the cost of false positives is high, meaning that we want to minimize the number of false positives even if it comes at the cost of missing some true positives.</li><li><strong>Recall_score:</strong> Recall_score measures the proportion of true positives among all the instances that belong to the positive class. It is useful when the cost of false negatives is high, meaning that we want to minimize the number of false negatives even if it comes at the cost of more false positives.</li><li><strong>F1_score:</strong> F1_score is a harmonic mean of precision_score and recall_score. It is useful when we want to balance both precision and recall. F1_score provides a single score that takes both precision and recall into account, and is useful</li></ul><pre>import pandas as pd<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.impute import SimpleImputer</pre><h4>6.2 Import the dataset</h4><p>Now we import the dataset that we are using, which I talked about earlier:</p><pre>df = pd.read_csv(&#39;synapse_data.csv&#39;)</pre><h4>6.3 Use the SimpleImputer</h4><p>Now we are going to be using the SimpleImputer class from the sci-kit-learn library to impute missing values in a panda&#39;s DataFrame object.</p><pre>imputer = SimpleImputer(strategy=&#39;mean&#39;)</pre><p>This creates an instance of the SimpleImputer class and specifies the imputation strategy as ‘mean’. This means that any missing values in the DataFrame object will be replaced with the mean value of the respective column. Other imputation strategies include ‘median’ and ‘most_frequent’, which replace missing values with the median value or most frequent value of the respective column, respectively.</p><pre>df = pd.DataFrame(imputer.fit_transform(df), columns=df.columns)</pre><p>This line of code applies the imputation to the DataFrame object by calling the fit_transform() method of the SimpleImputer object. This method fits the imputer to the data and transforms the DataFrame object by filling in the missing values with the mean value of the respective column.</p><h4>6.4 Use the standard scaler</h4><p>Here we are using the StandardScaler class from the sci-kit-learn library to standardize the values of three columns (‘BMI’, ‘height’, and ‘age’) in a Pandas DataFrame object.</p><pre>scaler = StandardScaler()</pre><p>Here we create an instance of the StandardScaler class, which is a normalization method that scales the values of each feature (i.e., column) in the data to have a mean of 0 and a standard deviation of 1.</p><pre>df[[&#39;BMI&#39;, &#39;height&#39;, &#39;age&#39;]] = scaler.fit_transform(df[[&#39;BMI&#39;, &#39;height&#39;, &#39;age&#39;]])</pre><p>This line uses the fit_transform() method of the StandardScaler object to apply the scaling to the specified columns in the DataFrame object (df[[‘BMI’, ‘height’, ‘age’]]).</p><p>The fit_transform() method first fits the scaler to the data, calculating the mean and standard deviation of each column, and then applies the transformation to the columns, scaling their values to have a mean of 0 and a standard deviation of 1.</p><h4>6.5 identify the features &amp; target column</h4><p>Here we identify what we are basing our prediction on in the dataset</p><p>We are using age, height, BMI, and CYP2D6 activity scale, as we identify here:</p><pre>feature_cols = [&#39;BMI&#39;, &#39;height&#39;, &#39;age&#39;, &#39;CYP2D6_genotype&#39;]</pre><p>In the context of machine learning, the term “target” refers to the variable or feature that the model is attempting to predict or estimate. It is also known as the dependent variable or response variable.</p><p>as we are doing depression drug response that is what I have named the target column</p><pre>target_col = &#39;depression_drug_response&#39;</pre><h4>6.6 Training and test set</h4><pre>X_train, X_test, y_train, y_test = train_test_split(df[feature_cols], df[target_col], test_size=0.2, random_state=42)</pre><p>this shows an example of using the train_test_split function from the sci-kit-learn library to split a dataset into training and testing sets for use in machine learning.</p><p>The train_test_split function takes several arguments:</p><ul><li>df[feature_cols]: This is a Pandas DataFrame object that contains the input features or independent variables that will be used to predict the target variable.</li><li><strong>df[target_col]: </strong>This is a pandas Series object that contains the target variable or dependent variable that the model will attempt to predict.</li><li><strong>test_size=0.2: </strong>This specifies the proportion of the dataset that should be used for testing, in this case, 20% of the data. The remaining 80% of the data will be used for training the model.</li><li><strong>random_state=42:</strong> This specifies a random seed value that is used to ensure that the data is split in a reproducible way. By setting the random_state to a specific value (in this case, 42), the function will split the data, in the same way, each time it is called.</li></ul><p>The function returns four arrays:</p><ul><li><strong>X_train: </strong>This is a Pandas DataFrame object that contains the input features for the training set.</li><li><strong>X_test:</strong> This is a Pandas DataFrame object that contains the input features for the testing set.</li><li><strong>y_train:</strong> This is a pandas Series object that contains the target variable values for the training set.</li><li><strong>y_test:</strong> This is a pandas Series object that contains the target variable values for the testing set.</li></ul><h4>6.7 Fitting and training logistic regression model</h4><p>The time has come, now we use the sci-kit-learn library to create and train a logistic regression model on a dataset, and then use the trained model to make predictions on new data.</p><pre>lr_model = LogisticRegression()</pre><p>This first line of code creates a new logistic regression model object using the LogisticRegression() function from sci-kit-learn. This creates an instance of the logistic regression algorithm with default parameters.</p><pre>lr_model.fit(X_train, y_train)</pre><p>Here we are training the logistic regression model using the fit() method. This method takes two arguments:</p><ul><li>X_train: This is a Pandas DataFrame object containing the input features for the training set.</li><li>y_train: This is a pandas Series object containing the target variable values for the training set.</li></ul><p>The fit() method uses the input data to train the logistic regression model and adjust its parameters to make accurate predictions on the training data.</p><pre>y_pred = lr_model.predict(X_test)</pre><p>This makes predictions on the test set using the predict() method. This method takes a single argument:</p><ul><li><strong>X_test:</strong> This is a Pandas DataFrame object containing the input features for the testing set.</li></ul><p>The predict() method uses the trained logistic regression model to make predictions on the test data. The predicted values are returned as a NumPy array, which is stored in the variable y_pred.</p><h4>6.8 Accuracy</h4><p>Here I have used many markers to determine how good this model is at prediction, but I mainly focused on accuracy which was<strong> 86.7 %</strong></p><p>By adding more features such as location this model would be more accurate, however since that would be computationally expensive, we stuck with these main features</p><pre>accuracy = accuracy_score(y_test, y_pred)<br>precision = precision_score(y_test, y_pred)<br>recall = recall_score(y_test, y_pred)<br>f1 = f1_score(y_test, y_pred)<br><br>print(&#39;Accuracy:&#39;, accuracy)<br>print(&#39;Precision:&#39;, precision)<br>print(&#39;Recall:&#39;, recall)<br>print(&#39;F1 Score:&#39;, f1)</pre><h3>7. Using random forest classification</h3><p>Firstly, let’s look at a decision tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/0*MT1wgx2VOUrpMcvq" /></figure><p>A decision tree is upside down with its root at the top and looks something like the image above</p><p>now let’s look at this data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/0*K0da3Wq013JN_rXK.png" /></figure><p>A simple decision tree built on this data will iteratively split the data along one or the other axis according to some quantitative criteria. At each level, the label of a new region would be assigned according to the majority of votes of points within it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*ALa5neOMr9Un7b6J.png" /></figure><p>However, we have a slight problem if we continue splitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/0*h4-PICU1ZshaN1tU.png" /></figure><p>As you can see, there is a purple region between the yellow and blue regions, this means that we are overfitting our data.</p><p>In some places, the two trees produce consistent results, while in other places, the two trees give very different classifications.</p><p>so by using the info from both trees we come up with a better result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*YnB9hDQpXLPHi_oF.png" /></figure><p>The higher the number of trees in the forest gives the high the accuracy results.</p><p>We will be using 500 to keep it from being overly computationally expensive</p><h4>7.1 initial steps</h4><p>We will be using the same initial steps as we did in logistic regression, this includes preprocessing the data, adding features splitting into training and testing sets — basically anything before creating the logistic regression model</p><pre>import pandas as pd<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.impute import SimpleImputer<br><br><br>df = pd.read_csv(&#39;synapse_data.csv&#39;)<br><br>imputer = SimpleImputer(strategy=&#39;mean&#39;)<br>df = pd.DataFrame(imputer.fit_transform(df), columns=df.columns)<br><br><br>scaler = StandardScaler()<br>df[[&#39;BMI&#39;, &#39;height&#39;, &#39;age&#39;]] = scaler.fit_transform(df[[&#39;BMI&#39;, &#39;height&#39;, &#39;age&#39;]])<br><br><br>feature_cols = [&#39;BMI&#39;, &#39;height&#39;, &#39;age&#39;, &#39;CYP2D6_genotype&#39;]<br><br><br>target_col = &#39;depression_drug_response&#39;<br><br>X_train, X_test, y_train, y_test = train_test_split(df[feature_cols], df[target_col], test_size=0.2, random_state=42)</pre><h4>7.2 Fitting and training the random forest model</h4><p>Now we can add the random forest to this</p><pre>rf_model = RandomForestClassifier(n_estimators=500, max_depth=10, random_state=42)</pre><p>This line of code creates a random forest classifier object called rf_model with three specified parameters:</p><ul><li>n_estimators: the number of decision trees in the forest. In this case, the forest has 500 trees.</li><li>max_depth: the maximum depth of each decision tree. In this case, the depth of each tree is limited to 10 levels.</li><li>random_state: a random seed used to ensure that the same results are produced each time the code is run.</li></ul><pre>rf_model.fit(X_train, y_train)</pre><p>This line of code trains the rf_model on the training data (X_train and y_train). The fit() method takes two arguments: the features (X_train) and the corresponding labels (y_train). During training, the model learns how to map the input features to the output labels.</p><pre><br>y_pred = rf_model.predict(X_test)</pre><p>This line of code uses the trained rf_model to make predictions on the test data (X_test) and stores the predicted labels in the y_pred variable. The predict() method takes the test features as its argument and returns the predicted labels. The model uses the decision trees in the forest to make individual predictions and then aggregates the results to produce a final prediction for each data point.</p><h4>7.3 Accuracy</h4><p>Here I have used many markers to determine how good this model is at prediction, but I mainly focused on accuracy which was <strong>89.5%</strong></p><p>By adding more features such as location this model as well as more decision trees would be more accurate, however since that would be computationally expensive, we stuck with these main features</p><pre>accuracy = accuracy_score(y_test, y_pred)<br>precision = precision_score(y_test, y_pred)<br>recall = recall_score(y_test, y_pred)<br>f1 = f1_score(y_test, y_pred)</pre><pre>print(&#39;Accuracy:&#39;, accuracy)<br>print(&#39;Precision:&#39;, precision)<br>print(&#39;Recall:&#39;, recall)<br>print(&#39;F1 Score:&#39;, f1)</pre><h3>8. Conclusion</h3><p>In conclusion, the random forest classifier provided better results in this case, however with different features in a different dataset this could be another case.</p><h4>8.1 Key takeaways:</h4><ul><li>Predicting drug response can be very beneficial for patients, for the economy, and convenient to make a prescription</li><li>CYP2D6 can have a big impact on drug response</li><li>Using more features would provide better accuracy but would be computationally expensive</li><li>Drug response is incredibly cool!</li></ul><p>Here is a note from the writer of this article:</p><p><strong>Hi readers, I am a 13-year-old girl in the UK and would love your support.</strong></p><p>Thank you for reading this and I would love it if you checked out some of my other articles as well!</p><p>Please check out my monthly newsletter: <a href="https://substack.com/profile/106867284-vidushi-valli-surendran">https://substack.com/profile/106867284-vidushi-valli-surendran</a></p><p>My LinkedIn:</p><p><a href="https://www.linkedin.com/in/vidushi-valli-surendran-075a06250/">https://www.linkedin.com/in/vidushi-valli-surendran-075a06250/</a></p><p>My personal website:</p><p><a href="http://vidushivs.com/">Vidushivs.com</a></p><p>My recent article:</p><p><a href="https://vidushi-valli-surendran.medium.com/a-guide-to-ai-b626c1f29085">https://vidushi-valli-surendran.medium.com/a-guide-to-ai-b626c1f29085</a></p><p>And thank you for reading again!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76a2c7e649bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine learning approach for drug response prediction in Diffuse large B-cell lymphoma patients]]></title>
            <link>https://vidushi-valli-surendran.medium.com/machine-learning-approach-for-drug-response-prediction-in-diffuse-large-b-cell-lymphoma-patients-45a09c6e0832?source=rss-1c2ea4bc3f60------2</link>
            <guid isPermaLink="false">https://medium.com/p/45a09c6e0832</guid>
            <dc:creator><![CDATA[Vidushi Valli Surendran]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 19:37:27 GMT</pubDate>
            <atom:updated>2023-02-27T23:46:55.150Z</atom:updated>
            <content:encoded><![CDATA[<p>Predicting drug response is a critical aspect of modern medicine that involves analyzing a patient’s genetic makeup, clinical history, lifestyle, and other factors to determine how they are likely to respond to a particular medication.</p><p>This information can help clinicians personalize treatment plans and select the most effective medication for each patient. For example, a patient with a genetic predisposition to a certain condition may require a different medication or dosage than someone without that genetic marker.</p><p>In addition to improving patient outcomes, predicting drug response can also benefit the drug development process. By identifying patient subgroups that are most likely to benefit from a particular medication, researchers can design more efficient and effective clinical trials. This can help reduce costs and improve the chances of successfully bringing a new medication to market.</p><p>Recent advances in technology, such as high-throughput screening and genotyping, have significantly improved our ability to predict drug response.</p><p>These tools allow researchers to analyze large amounts of data and identify genetic markers and other factors that may influence drug response.</p><p>As a result, personalized medicine is becoming increasingly prevalent in clinical practice, with many healthcare providers using genetic testing and other diagnostic tools to tailor treatment plans to individual patients.</p><p>Diffuse large B-cell lymphoma (DLBCL) is a type of cancer that affects white blood cells called B cells. DLBCL is the most common type of non-Hodgkin’s lymphoma (NHL), accounting for about one-third of all cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*_PfsKFOv5XH7gjCT" /></figure><p>In DLBCL, abnormal B cells grow uncontrollably and can form tumors in lymph nodes, bone marrow, and other organs. The lymphoma cells may also spread to other parts of the body, such as the liver, spleen, or central nervous system.</p><p>Today we are going to train a machine learning model to predict how individual patients will respond to specific treatments.</p><h3>An overview:</h3><p>A little overview of what we are going to do:</p><ol><li><strong>Load data:</strong> The gene expression data is read in from a CSV file using Pandas.</li><li><strong>Remove missing values:</strong> Any samples with missing values are removed from the data.</li><li><strong>Normalize gene expression data:</strong> The gene expression data is normalized using StandardScaler from scikit-learn. This scales the data so that each feature has a mean of 0 and a standard deviation of 1.</li><li><strong>Split data into features and labels:</strong> The gene expression data is split into features (X) and labels (y), where X consists of the gene expression data and y is a binary indicator of whether the patient had Lymph node metastasis or not.</li><li><strong>Feature selection using ANOVA F-test:</strong> SelectKBest from scikit-learn is used to select the top 5000 features that are most strongly correlated with the target variable.</li><li><em>Split data into training and test sets:</em> The data is randomly split into training (80%) and test (20%) sets.</li><li><em>Train logistic regression model:</em> A logistic regression model is trained using the training data.</li><li><strong>Make predictions on test set:</strong> The trained logistic regression model is used to make predictions on the test set.</li><li><strong>Evaluate model performance:</strong> The performance of the logistic regression model is evaluated using accuracy, precision, recall, F1-score, and confusion matrix metrics.</li></ol><h3>STEP 1: Find a dataset</h3><p>To develop a machine learning model for drug response prediction in DLBCL patients, we first need to obtain a dataset that includes relevant patient information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/0*Mk6SKaXo01a6WO1q" /></figure><p>I used the LLMPP dataset.</p><p>The Lymphoma/Leukemia Molecular Profiling Project (LLMPP) Dataset is a publicly available dataset containing gene expression data from 240 Diffuse large B-cell lymphoma (DLBCL) patients and their clinical characteristics.</p><p>The dataset is available from the NCBI GEO database, with accession number GSE10846.</p><p>The LLMPP dataset is an important resource for studying DLBCL and developing personalized treatment strategies for patients.</p><p>By analyzing the gene expression data from patients with different clinical characteristics, researchers can identify potential biomarkers and genetic mutations that may be associated with drug response and treatment outcomes.</p><h3>STEP 2: Import our libraries</h3><p>Now we import our libraries into our code.</p><pre>import numpy as np<br>import pandas as pd<br>from sklearn.model_selection import train_test_split, GridSearchCV<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.feature_selection import SelectKBest, f_classif<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix</pre><h4>Pandas:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*DQsiJEjdYRJlKR40" /><figcaption>Pandas logo</figcaption></figure><p>Pandas is a popular Python library that provides powerful data structures and data analysis tools. It is widely used in data science and machine learning projects for data preprocessing and cleaning tasks.</p><p>Some of the key features of Pandas include:</p><ul><li><strong>Data structures:</strong> Pandas provides two main data structures, Series (1-dimensional) and DataFrame (2-dimensional). Series is similar to a column in a spreadsheet and DataFrame is similar to a table in a spreadsheet.</li><li><strong>Indexing and selecting data: </strong>Pandas provides a variety of ways to index and select data from a DataFrame, including label-based indexing and boolean indexing. This allows you to easily select and filter subsets of the data based on certain conditions.</li><li><strong>Handling missing data:</strong> Pandas provides several ways to handle missing data, including filling in missing values with a specific value or using a statistic (such as the mean) from the non-missing values.</li><li><strong>Merging and joining:</strong> Pandas allows you to easily combine multiple data sets by merging or joining them on one or more columns.</li><li><strong>Grouping and aggregation:</strong> Pandas provides a variety of ways to group and summarize data, such as grouping by one or more columns and applying a statistical function (such as mean or sum) to each group.</li><li><strong>Data manipulation:</strong> Pandas provides a wide range of data manipulation and data transformation functions, such as pivot, melt, stack, unstack, etc.</li></ul><p>Pandas is built on top of NumPy, and it utilizes its powerful array and mathematical operations to provide a fast and efficient way to work with large amounts of data.</p><p>We are also using the SK learn libraries…</p><h3>NumPy:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*CKQ7r-EzRVoHJqXD" /></figure><p>NumPy logo</p><p>NumPy is a Python library that is widely used in scientific computing and data analysis. It provides a powerful and efficient way to work with large arrays and matrices of numerical data. Some of the key features of NumPy include:</p><ul><li><strong>N-dimensional arrays:</strong> NumPy provides a powerful and efficient array object, called an array, that can be used to store and manipulate large arrays of homogeneous data (i.e., data of the same type, such as integers or floating-point values).</li><li><strong>Mathematical functions: </strong>NumPy provides a wide range of mathematical functions that can be applied to arrays and matrices, such as trigonometric functions, logarithms, exponentials, and more. These functions are implemented in C or Fortran for speed and are much faster than equivalent functions in Python’s built-in math module.</li><li><strong>Linear algebra:</strong> NumPy provides a set of functions and tools for linear algebra, such as matrix multiplication, inverse, determinant, eigenvalues, and more.</li><li><strong>Broadcasting:</strong> NumPy allows you to perform mathematical operations on arrays of different shapes, by automatically broadcasting the smaller array to the shape of the larger array.</li></ul><p>NumPy is widely used in many areas of scientific computing and data analysis, such as machine learning, signal processing, image processing, and more. It is also used as the foundation of many other libraries, such as SciPy, Matplotlib, and Pandas, which build on the capabilities of NumPy to provide more advanced functionality.</p><p>We are using logistic regression to form our prediction</p><h4>STEP 3: Load our data</h4><p>This bit is self-explanatory, but this is just getting our model to look through and read our data using this:</p><pre># Load data<br>data = pd.read_csv(&#39;llmpp_data.csv&#39;)</pre><h3>STEP 4: Preprocessing the data</h3><p>Preprocessing is an essential step in data analysis that involves transforming raw data into a usable format for analysis.</p><p>In the case of the LLMPP dataset, preprocessing was necessary to ensure that the data was clean, complete, and normalized before training our model.</p><p>The LLMPP dataset contains gene expression data from 240 Diffuse large B-cell lymphoma (DLBCL) patients and their clinical characteristics. The dataset was downloaded from the NCBI GEO database, with accession number GSE10846.</p><p>The first step in preprocessing the LLMPP dataset was to remove any missing values.</p><p>Missing values can occur due to a variety of reasons, such as errors in data collection or processing. In our case, we used the Pandas library in Python to drop any rows that contained missing values.</p><p>This was done using the dropna() function, which removed any rows with missing values from the dataset.</p><pre># Remove missing values<br>data = data.dropna()</pre><p>The next step was to normalize the data.</p><p>Normalization is a process of scaling the data to have a mean of 0 and a standard deviation of 1.</p><p>This is done to ensure that all the variables are on the same scale and to prevent any single variable from dominating the analysis.</p><p>In our case, we normalized the dataset using the mean and standard deviation of each variable.</p><p>We used the Pandas library to compute the mean and standard deviation of each variable and then subtracted the mean and divided it by the standard deviation for each variable.</p><pre># Normalize gene expression data<br>scaler = StandardScaler()<br>data.iloc[:, 1:] = scaler.fit_transform(data.iloc[:, 1:])</pre><h3>STEP 5: Splitting into features and labels</h3><p>In the context of the LLMPP dataset for drug response prediction in DLBCL patients, splitting the data into features and labels involves separating the gene expression data and clinical characteristics of the patients (features) from the drug response of the patients (labels).</p><p>The gene expression data and clinical characteristics of the patients, such as age, sex, and tumor stage, are the input variables or features that we will use to train our model to predict the drug response of the patients.</p><p>Age, sex, and tumor age are commonly used as features in predicting drug response for a variety of reasons.</p><p>Firstly, age and sex can have a significant impact on drug metabolism and overall drug response.</p><p>For example, elderly patients may require lower dosages of medications due to reduced liver and kidney function, while sex differences in drug metabolism can impact the efficacy and safety of certain medications.</p><p>Therefore, including age and sex as features in drug response prediction models can help clinicians tailor treatment plans to individual patient needs and minimize the risk of adverse reactions.</p><p>Tumor age is also an important feature in predicting drug response, particularly for cancer treatments.</p><p>The age of the tumor can impact its biology and response to treatment, with older tumors often being more resistant to therapy. By including tumor age as a feature in drug response prediction models, healthcare providers can better understand how a tumor is likely to respond to treatment and adjust treatment plans accordingly.</p><p>In addition to their clinical relevance, age, sex, and tumor age are also easily obtainable features that can be readily incorporated into drug response prediction models. This makes them practical and cost-effective tools for improving treatment outcomes and advancing personalized medicine.</p><pre>#Splitting into features and labels<br>X = data.iloc[:, 1:-1]<br>y = data.iloc[:, -1]</pre><p>The drug response of the patients, which is either responder or non-responder, is the output variable or label that we want our model to predict.</p><p>By splitting the data into features and labels, we can train our model to learn the relationship between the input variables and the output variable. During the training process, the model will learn to predict the drug response of the patients based on their gene expression data and clinical characteristics.</p><h3>STEP 6: Feature selection using ANOVA F-test</h3><p>Feature selection is a crucial step in machine learning, as it allows us to identify the most important features that are relevant for making accurate predictions.</p><p>ANOVA F-test is one of the common methods for feature selection, which is used to identify the features that are most correlated with the output variable.</p><p>The ANOVA F-test is a statistical test that is used to compare the means of two or more groups of data. In the context of feature selection, the ANOVA F-test is used to compare the means of the feature values for each class label (responder or non-responder), and to identify the features that have a significant impact on the output variable.</p><p>The ANOVA F-test computes the F-statistic, which measures the ratio of the variance between the groups to the variance within the groups. A higher F-statistic indicates that the means between the groups are more different than the means within the groups and that the feature is more correlated with the output variable.</p><p>To perform feature selection using ANOVA F-test, we first compute the F-statistic and p-value for each feature in the dataset. The p-value indicates the probability of obtaining a result as extreme as the observed result, assuming that the null hypothesis is true. In this case, the null hypothesis is that there is no significant difference in the means of the feature values for the two class labels.</p><p>We then select the features with the highest F-statistic and lowest p-value, as these are the features that are most correlated with the output variable. These features can be used as input to our machine-learning model for making predictions.</p><pre># Feature selection using ANOVA F-test<br>selector = SelectKBest(f_classif, k=5000)<br>X = selector.fit_transform(X, y)</pre><h3>STEP 6: Split data into training and test sets</h3><p>We used the Scikit-learn library in Python to split the dataset into training and test sets, and now we further split the features and labels into their respective training and test sets.</p><p>This allows us to train our model on a subset of the data and then evaluate its performance on a separate subset of the data.</p><pre># Split data into training and test sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><h3>STEP 7: Train logistic regression model</h3><h4>Logistic regression:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*jKcZQDe64-XtXlI9.png" /><figcaption><a href="https://levelup.gitconnected.com/50-mathematical-concepts-for-better-programming-part-2-f0dc13a8c05">https://levelup.gitconnected.com/50-mathematical-concepts-for-better-programming-part-2-f0dc13a8c05</a></figcaption></figure><p>Logistic regression maps x to y using a sigmoid function, we will talk about the sigmoid function later on but for now, Logistic regression while being a type of regression algorithm also classifies data. logistic regression predicts a continuous variable and binary classification predicts a set value.</p><p>We are also using other tools to calculate our accuracy</p><pre># Train logistic regression model<br>lr = LogisticRegression(max_iter=1000)<br>lr.fit(X_train, y_train)</pre><p>Here we are denfining biomarkers and genetic mutations that are associated with drug response, providing valuable insights into the underlying biology of DLBCL.</p><h3>STEP 8: Make predictions</h3><p>In this line of code, the trained logistic regression model is used to make predictions on the test set. The test set contains a set of features (gene expression values) that were not used during the training process, along with the true labels (i.e., the actual drug response) for those samples.</p><p>Using the predict() method of the logistic regression model, the predicted labels for the test set are computed based on the features in X_test. These predicted labels are stored in the variable y_pred, which can then be used to evaluate the performance of the model using various metrics such as accuracy, precision, recall, and F1-score.</p><pre># Make predictions on test set<br>y_pred = lr.predict(X_test)</pre><h3>STEP 9: Evaluate model performance</h3><p>Accuracy is one of the most commonly used evaluation metrics for classification models. It measures the proportion of correctly classified instances among the total number of instances. In other words, it tells us how often the model is correct in its predictions.</p><p>If we have 100 instances in the test set and our model correctly predicts 80 of them, the accuracy would be 80%</p><p>A higher accuracy score indicates that the model is performing better at correctly classifying instances. However, accuracy alone may not be sufficient to evaluate the model’s performance, especially if the classes in the dataset are imbalanced. In such cases, other metrics such as precision, recall, and F1-score may be more appropriate.</p><pre>accuracy = accuracy_score(y_test, y_pred)<br>precision = precision_score(y_test, y_pred)<br>recall = recall_score(y_test, y_pred)<br>f1 = f1_score(y_test, y_pred)<br>cm = confusion_matrix(y_test, y_pred)<br><br>print(&#39;Logistic Regression:&#39;)<br>print(&#39;Accuracy:&#39;, accuracy)<br>print(&#39;Precision:&#39;, precision)<br>print(&#39;Recall:&#39;, recall)<br>print(&#39;F1-score:&#39;, f1)<br>print(&#39;Confusion matrix:&#39;, cm)</pre><p>This model can now be applied to new sets to make accurate predictions now that it is confirmed that these are accurate!</p><p>AND THAT’s IT!!!</p><p>For the AI at least…</p><p>Predicting drug response can be especially important for individuals with Diffuse Large B-Cell Lymphoma (DLBCL), a type of cancer that can be challenging to treat and often requires a combination of chemotherapy and immunotherapy.</p><p>DLBCL patients may be at higher risk of adverse drug reactions due to the intensive nature of treatment, and personalized medicine can play a crucial role in improving treatment outcomes.</p><p>By accurately predicting drug response, clinicians can tailor treatment plans to individual DLBCL patients, selecting medications and dosages that are less likely to cause adverse reactions while optimizing efficacy. This can help improve overall health outcomes and quality of life for individuals with DLBCL.</p><p>Furthermore, personalized medicine can help identify which DLBCL patients are most likely to benefit from specific treatments. For example, genetic testing can be used to identify patients who may respond better to immunotherapy or who may require lower or higher doses of chemotherapy based on their individual genetic makeup. This can reduce the need for trial-and-error prescribing and minimize the risk of adverse reactions.</p><p>Overall, predicting drug response is a vital component of personalized medicine that has significant implications for DLBCL patients. By tailoring treatment plans to individual needs and optimizing medication selection and dosages, personalized medicine can help improve treatment outcomes, reduce the risk of adverse reactions, and ultimately improve quality of life for individuals with DLBCL.</p><p>Takeaways:</p><ul><li>Predicting drug response can give us useful insights into what drugs to prescribe for a person</li><li>We can tailor prescriptions to make sure they work well</li><li>Precision medicine is cool!</li></ul><p><strong>Here is a note from the writer of this article:</strong></p><p>Hi readers, I am a 13-year-old girl in the UK and would love your support.</p><p>Thank you for reading this and I would love it if you checked out some of my other articles as well!</p><p>Please check out my monthly newsletter: <a href="https://substack.com/profile/106867284-vidushi-valli-surendran">https://substack.com/profile/106867284-vidushi-valli-surendran</a></p><p>My LinkedIn:</p><p><a href="https://www.linkedin.com/in/vidushi-valli-surendran-075a06250/">https://www.linkedin.com/in/vidushi-valli-surendran-075a06250/</a></p><p>My personal website:</p><p><a href="http://vidushivs.com/">Vidushivs.com</a></p><p>My recent article:</p><p><a href="https://vidushi-valli-surendran.medium.com/a-guide-to-ai-b626c1f29085">https://vidushi-valli-surendran.medium.com/a-guide-to-ai-b626c1f29085</a></p><p>And thank you for reading again!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45a09c6e0832" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pharmacogenomics and schizophrenia]]></title>
            <link>https://vidushi-valli-surendran.medium.com/pharmacogenomics-and-schizophrenia-5d50b7148c6b?source=rss-1c2ea4bc3f60------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d50b7148c6b</guid>
            <dc:creator><![CDATA[Vidushi Valli Surendran]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 17:10:35 GMT</pubDate>
            <atom:updated>2023-02-23T21:54:51.563Z</atom:updated>
            <content:encoded><![CDATA[<p>Pharmacogenomics is a word I couldn’t even spell a week ago, yet here I am writing an article about it.</p><p>Heads up, this article is going to need a bit of background knowledge on genes, so not typically for beginners — sorry!</p><p>Pharmacogenomics is the study of how <strong>your genes can affect how you respond to certain medications</strong> for mental health conditions like depression, anxiety, and schizophrenia.</p><p>The thing is, not all medications work the same for everyone. Some people may respond really well to one medication, while others may have little to no improvement or even experience negative side effects. And that’s where pharmacogenomics comes in.</p><p>By analyzing your genetic makeup, doctors can get a better idea of which medications are likely to work best for you, as well as which ones you may need to avoid. For example, if you have a certain genetic variation, you may be more likely to experience negative side effects from a particular medication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/0*RCkl0Xq7DujdRAHo.jpg" /><figcaption>Image from mayo clare research clinic</figcaption></figure><p>Pharmacogenomics can also help with developing new medications that are more effective and have fewer side effects. Pretty cool, right?</p><h3>What is schizophrenia?</h3><p>Schizophrenia is a <strong>chronic and often severe mental disorder</strong> that affects how a person thinks, feels, and behaves.</p><p>it includes many symptoms…</p><p><strong>Delusions</strong> are false beliefs that are not based on reality. For example, a person with schizophrenia may believe that they are being watched or followed, that they have special powers or abilities, or that they are being controlled by outside forces.</p><p><strong>Hallucinations</strong> are sensory experiences that are not based on reality. They can take many forms but are most commonly auditory (hearing voices that others cannot hear). People with schizophrenia may also experience visual, tactile, or olfactory hallucinations.</p><p><strong>Disordered thinking and speech</strong> are also common symptoms of schizophrenia. People with schizophrenia may struggle to organize their thoughts, making it difficult for them to communicate coherently. They may also exhibit bizarre or nonsensical behavior, such as talking to themselves or engaging in repetitive movements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*3gJ0n8JY6w8XElm8.jpg" /><figcaption>photo from the journal of neuroscience</figcaption></figure><p>The good news is that it can be treated.</p><h3>Where does pharmacogenetics come into this?</h3><p>Pharmacogenomic testing can help clinicians determine <strong>which antipsychotic medication is most likely to be effective for a particular patient</strong>, as well as which medication is least likely to cause side effects. This can lead to more personalized and effective treatment plans for individuals with schizophrenia.</p><p>For example, some patients may have<strong> genetic variations</strong> that make them more likely to experience side effects such as weight gain, metabolic disturbances, or movement disorders from certain antipsychotic medications. By identifying these genetic variations, clinicians can choose medications that are less likely to cause these side effects or adjust the dose to minimize their impact.</p><h3>What influences treatment?</h3><p>There are many genes and enzymes that influence how these drugs impact someone, I will be going through the main ones…</p><h3>CYP2D6</h3><p>The CYP2D6 gene is highly polymorphic, meaning that <strong>many different variations or alleles of the gene can affect its activity</strong>. Currently, there are more than <strong>100 known allelic variants</strong> of CYP2D6, and these can be grouped into four main categories: poor metabolizers, intermediate metabolizers, normal metabolizers, and ultra-rapid metabolizers.</p><p>The CYP2D6 gene is located on <strong>chromosome 22</strong> and is expressed primarily in the liver. This gene is responsible for encoding the CYP2D6 enzyme, which is involved in the metabolism of approximately <strong>25% of clinically used drugs</strong>, including many commonly used psychiatric medications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*HZ-B6L1LzfQR0mNi" /><figcaption>image from Pharmacia</figcaption></figure><p>There are several ways to test for CYP2D6 genetic variability. One common method is through genotyping, which involves analyzing a person’s <strong>DNA</strong> to identify specific variations or alleles of the CYP2D6 gene. This can be done using a variety of techniques, including <strong>PCR</strong> (polymerase chain reaction) and <strong>DNA sequencing.</strong></p><p>Another method for assessing CYP2D6 activity is through <strong>phenotyping.</strong> This involves measuring the activity of the CYP2D6 enzyme directly in the <strong>blood or urine </strong>of a patient. This can be done using specific probes or substrates that are metabolized by CYP2D6 and then measuring the number of metabolites produced.</p><p>Understanding a patient’s CYP2D6 genotype can help <strong>clinicians personalize medication therapy to optimize outcomes.</strong> For example, a poor metabolizer who has prescribed an antidepressant that is metabolized by CYP2D6 may require a lower starting dose or a medication that is not metabolized by this enzyme to avoid toxicity. Conversely, an ultra-rapid metabolizer may require higher doses of medications to achieve therapeutic effects.</p><p>In conclusion, the CYP2D6 gene is <strong>highly polymorphic, and genetic variability in this gene can have a significant impact on medication response. </strong>Understanding a patient’s CYP2D6 genotype can help clinicians personalize medication therapy to optimize outcomes and reduce the risk of adverse drug reactions. However, it is important to consider other factors that can affect drug metabolisms and response, such as drug interactions and environmental factors. Combining genetic testing with a comprehensive medical evaluation can help clinicians develop more personalized and effective treatment plans for individuals with mental health conditions.</p><h3>COMT</h3><p>The catechol-O-methyltransferase (COMT) gene is located on <strong>chromosome 22 </strong>and is involved in the metabolism of catecholamines, such as dopamine, epinephrine, and norepinephrine, in the brain and other tissues. The COMT gene is highly polymorphic, <strong>meaning that there are many different variations or alleles of the gene that can affect its activity.</strong></p><p>One of the most studied genetic variations in the COMT gene is the Val158Met polymorphism, which affects the activity of the COMT enzyme. This polymorphism results from a <strong>single nucleotide change in the COMT gene</strong>, which leads to the substitution of valine (Val) with methionine (Met) at position 158 of the protein. This substitution results in a three- to four-fold reduction in enzyme activity,<strong> leading to increased dopamine availability in the prefrontal cortex.</strong></p><p>Individuals who carry the Met/Met genotype have the lowest COMT activity and the highest levels of dopamine in the prefrontal cortex, while individuals who carry the Val/Val genotype have the highest COMT activity and the lowest levels of dopamine in the prefrontal cortex. Individuals who carry the Val/Met genotype have intermediate levels of COMT activity and dopamine levels in the prefrontal cortex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/0*2P8FPsLVZ_l1f98K.jpg" /><figcaption>Image from nature</figcaption></figure><p>The effects of the Val158Met polymorphism on brain function and behavior have been extensively studied, particularly in the context of mental health conditions such as schizophrenia, bipolar disorder, and major depressive disorder. In general, the Val/Val genotype has been associated with <strong>increased risk for these conditions</strong>, while the Met/Met genotype has been associated with decreased risk.</p><p>The Val158Met polymorphism has also been shown to influence response to certain medications. For example, individuals with the Val/Val genotype may have a p<strong>oorer response to antipsychotic medications</strong>, while individuals with the Met/Met genotype may have a better response. Similarly, individuals with the Val/Val genotype may have a poorer response to antidepressant medications, while individuals with the Met/Met genotype <strong>may have a better response.</strong></p><p>Pharmacogenetic testing for the Val158Met polymorphism in the COMT gene is becoming increasingly common in clinical practice. This testing can be done using a variety of techniques, including<strong> PCR and DNA sequencing. </strong>The results of these tests can be used to guide medication selection and dosing, with the goal of improving treatment outcomes and reducing the risk of adverse drug reactions.</p><h3>DRD2</h3><p>The dopamine D2 receptor gene (DRD2) is located on <strong>chromosome 11</strong> and is involved in the regulation of dopamine signaling in the brain. The DRD2 gene is highly polymorphic, with several different genetic variations or alleles that can affect its function.</p><p>One of the most studied genetic variations in the DRD2 gene is the Taq1A polymorphism, which results from a <strong>single nucleotide change in the gene.</strong> The Taq1A polymorphism has two common alleles, A1 and A2, with the <strong>A1 allele being associated with reduced dopamine D2 receptor density in the brain.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*jhkKd6tHIovHouYA.png" /><figcaption>image from wikepedia</figcaption></figure><p>Individuals who carry the A1/A1 genotype have been shown to have reduced dopamine D2 receptor density in the brain compared to those who carry the A2/A2 genotype. Individuals who carry the <strong>A1/A2 genotype have intermediate levels of dopamine D2 receptor density.</strong></p><p>The effects of the Taq1A polymorphism on brain function and behavior have been extensively studied, particularly in the context of mental health conditions such as <strong>schizophrenia</strong>, bipolar disorder, and addiction. In general, the A1 allele has been associated with increased risk for these conditions, while the A2 allele has been associated with decreased risk.</p><p>The Taq1A polymorphism has also been shown to influence response to certain medications. For example, <strong>individuals with the A1/A1 genotype may have a poorer response to antipsychotic medications</strong>, while individuals with the A2/A2 genotype may have a better response. Similarly, individuals with the A1/A1 genotype may have a poorer response to medications used to treat addiction, while individuals with the A2/A2 genotype may have a better response.</p><p>Pharmacogenetic testing for the Taq1A polymorphism in the DRD2 gene is becoming increasingly common in clinical practice as well. This testing can be done using a variety of techniques, including PCR and DNA sequencing. The results of these tests can be used to guide medication selection and dosing, with the goal of improving treatment outcomes and reducing the risk of adverse drug reactions.</p><h3>HTR2A</h3><p>HTR2A is a gene that encodes the 5-HT2A receptor, a <strong>subtype of the serotonin receptor </strong>that is found in the brain and is involved in the regulation of mood, cognition, and behavior. The HTR2A gene is located on chromosome 13 and contains multiple genetic variations or polymorphisms that can influence its function.</p><p>One of the most extensively studied genetic variations in the HTR2A gene is the <strong>T102C polymorphism</strong>, which results from a single nucleotide change in the gene. This polymorphism has two common alleles, T and C, with the T allele being the most common in the general population.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*KoMhHh7MiQlhX-xx.png" /><figcaption>image from wikepedia</figcaption></figure><p>Studies have shown that the T102C polymorphism can affect the binding affinity of the 5-HT2A receptor for serotonin and other ligands, as well as its downstream signaling pathways. The C allele has been associated with decreased receptor expression and reduced receptor function compared to the T allele.</p><p>Several studies have investigated the association between the T102C polymorphism and various mental health conditions, including <strong>schizophrenia</strong>, bipolar disorder, and depression. Some studies have found that individuals with the C/C genotype may be at increased risk for these conditions, while others have found no association.</p><p>The T102C polymorphism has also been shown to influence response to certain medications. <strong>For example, individuals with the C/C genotype may have a poorer response to selective serotonin reuptake inhibitors (SSRIs)</strong>, which are commonly used to treat depression and anxiety disorders. On the other hand, individuals with the T/T genotype may have a better response to SSRIs.</p><p>Pharmacogenetic testing for the T102C polymorphism in the HTR2A gene is becoming increasingly available in clinical practice. This testing can be done using a variety of techniques, including PCR and DNA sequencing. The results of these tests can be used to guide medication selection and dosing, with the goal of improving treatment outcomes and reducing the risk of adverse drug reactions.</p><h3>ABCB1</h3><p>ABCB1, also known as P-glycoprotein or multidrug resistance protein 1 (MDR1), is a gene that <strong>encodes a protein</strong> involved in the transport of drugs and other substances across cell membranes. The ABCB1 gene is located on chromosome 7 and contains multiple genetic variations or polymorphisms that can influence its function.</p><p>One of the most well-known polymorphisms in the ABCB1 gene is the <strong>C3435T polymorphism</strong>, which results from a single nucleotide change in the gene. This polymorphism has two common alleles, <strong>C and T</strong>, with the C allele being the most common in the general population.</p><p>Studies have shown that the C3435T polymorphism can affect the expression and function of P-glycoprotein, with the T allele being associated with decreased expression and function compared to the C allele. As P-glycoprotein plays a crucial role in the transport of drugs across the blood-brain barrier and other biological barriers, this polymorphism has been studied in relation to the response to various medications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/0*WY1apHdoDEAg7eYX" /></figure><p>Several studies have investigated the association between the C3435T polymorphism and response to antidepressants, antipsychotics, and other medications used in psychiatry. Some studies have found that individuals with the<strong> T/T genotype may have a poorer response to these medications,</strong> while others have found no association. However, it is important to note that the effects of this polymorphism on medication response can be complex and may vary depending on other genetic and environmental factors.</p><p>Pharmacogenetic testing for the C3435T polymorphism in the ABCB1 gene is available in clinical practice and can be done using a variety of techniques, including <strong>PCR and DNA sequencing</strong>. The results of these tests can be used to guide medication selection and dosing, with the goal of improving treatment outcomes and reducing the risk of adverse drug reactions.</p><p>In conclusion, schizophrenia is a complex mental health disorder that affects millions of individuals worldwide. Treatment of schizophrenia often involves the use of antipsychotic medications, which can have varying degrees of effectiveness and side effects in different individuals. Pharmacogenomics, the study of how genetic variations can influence medication response, has emerged as a promising tool in the field of psychiatry for improving the personalized treatment of schizophrenia.</p><p>Numerous studies have investigated the role of genetic variations, such as those in the CYP2D6, COMT, DRD2, and HTR2A genes, in predicting medication response in individuals with schizophrenia. The identification of these genetic variations can aid clinicians in selecting the most appropriate medication and dosage for each individual, based on their unique genetic makeup.</p><p>Moreover, pharmacogenomic testing for genetic variations in the ABCB1 gene has also shown promise in predicting medication response in individuals with schizophrenia. By measuring the expression and function of P-glycoprotein, a protein involved in the transport of drugs across biological barriers, clinicians can gain insights into the individual’s likelihood of responding to certain medications.</p><p>However, it is important to note that pharmacogenomic testing is not a definitive predictor of medication response and should be used in combination with other clinical factors, such as medical history, symptom severity, and patient preferences. Furthermore, the identification of genetic variations should not be used to discriminate against individuals or deny them access to certain medications.</p><p>In summary, pharmacogenomics has the potential to significantly improve the treatment of schizophrenia by providing clinicians with personalized insights into an individual’s likelihood of responding to certain medications. However, further research is needed to identify additional genetic variations that can influence medication response and to optimize the use of pharmacogenomic testing in clinical practice. With continued advancements in technology and research, pharmacogenomics has the potential to revolutionize the treatment of schizophrenia and other mental health disorders.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d50b7148c6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI in a Nutshell]]></title>
            <link>https://vidushi-valli-surendran.medium.com/a-guide-to-ai-b626c1f29085?source=rss-1c2ea4bc3f60------2</link>
            <guid isPermaLink="false">https://medium.com/p/b626c1f29085</guid>
            <dc:creator><![CDATA[Vidushi Valli Surendran]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 23:50:50 GMT</pubDate>
            <atom:updated>2023-02-05T20:15:07.252Z</atom:updated>
            <content:encoded><![CDATA[<p>AI. Many of you have heard of it, but where would you start? Well, you have found the perfect place!</p><p>When I first started my journey in AI, I spent A LOT of time learning the same stuff and just wasting time, so let&#39;s see if I can change that.</p><p>We are going to go into the basics of AI, some of the maths behind it, Python representations of neural networks, and more.</p><h4>Table of contents:</h4><ol><li>What is AI</li><li>Neural Networks</li><li>Gradient Descent</li><li>Regression</li><li>Classification</li><li>Optimizers</li><li>Loss</li><li>Python Libraries</li><li>Types of Neural Networks</li><li>Federated Learning Models</li><li>QML</li><li>Diffusion Models</li><li>Neural Network Libraries</li><li>Types of learning</li><li>ML models</li></ol><h3>1. What is AI</h3><p>Many people have different ideas of what AI actually is, such as Bing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*ZgONfPcREuq7RK9Vsk0wjQ.png" /></figure><p>The term AI first came about in <strong>1956</strong>. First, it was just a bunch of <strong>instructions</strong> given to a computer, such as the rules of chess or the step-by-step instructions for making a sandwich.</p><p>AI is any technology that enables a computer to <strong>think or act in a more ‘human’ way.</strong></p><p>It was then thought that we can make computers <strong>“think” for themselves,</strong> and <strong>learn</strong> for themselves.</p><p>This is a subcategory in AI called <strong>machine learning.</strong></p><blockquote>Machine learning is a field of inquiry devoted to understanding and building methods that ‘learn’, that is, methods that leverage data to improve performance on some set of tasks.</blockquote><h4>1.1 Uses of machine learning:</h4><p>Machine learning has many uses such as:</p><ul><li>Image Recognition</li><li>Voice Recognition</li><li>Predictions</li><li>Search Engine Suggestions</li></ul><p>etc</p><p>We will dive deeper into machine learning later on.</p><h4>1.2 What is deep learning?</h4><p>First a few definitions:</p><ul><li><strong>Input:</strong> what we put in, e.g.: ingredients in a cake.</li><li><strong>Function:</strong> when the function is applied to the input it is like mixing the ingredients and baking them.</li><li><strong>Output:</strong> the final result — the baked cake.</li></ul><p>There are multiple ways machines learn, but I want to focus on one of them: <strong>neural networks</strong></p><p>Many people think that neural networks are modeled after the brain but in actuality, it&#39;s only the name that comes from the brain. We may be very advanced in other things but honestly, we do not know the brain well enough to train an ML model with it, so not exactly how the brain works but there is inspiration there.</p><p>So in short neural networks are made of an <strong>input layer, and an output layer,</strong> and what makes them special are their <strong>hidden layers</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d2UwCr68WHXXiH72.jpeg" /><figcaption>image from <a href="https://www.ibm.com/cloud/blog/ai-vs-machine-learning-vs-deep-learning-vs-neural-networks">https://www.ibm.com/cloud/blog/ai-vs-machine-learning-vs-deep-learning-vs-neural-networks</a></figcaption></figure><h4>1.3 How do machines learn?</h4><p>There are 3 ways machines learn and here is an intro to each of them:</p><p><strong>Supervised learning:</strong></p><p>So in supervised learning, you <strong>know the output</strong> your program is trying to detect — these are called labels</p><p>This is useful to see the<strong> accuracy</strong> of your program</p><p>You would give the program an input (called features) and based on those it will try to predict the output</p><p>An example of this would be trying to predict the stock market where you would use old data and already know what your model is trying to predict</p><p>This same model can then be used to predict the prices of the future as we know the accuracy</p><p><strong>Unsupervised learning:</strong></p><p>In unsupervised learning, you <strong>do not know the output</strong> of your program.</p><p>This is normally used to find <strong>patterns</strong> in unlabelled data by <strong>clustering</strong> them in groups from patterns it recognizes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*vVw0fOa1ZjG-dy07" /><figcaption>image from: <br>https://www.researchgate.net/figure/The-process-of-the-unsupervised-learning-model_fig4_343819706</figcaption></figure><p>It has no human intervention so its unsupervised</p><p><strong>Reinforcement learning:</strong></p><p>Now I don’t have a dog but I am pretty sure that when they do something good you give them a treat, to train them to be good. Now since this is animal cruelty you wouldn’t punish it for doing something bad, but I remember sitting on the naughty chair as a child to teach me not to do something.</p><p>This is kind of like reinforcement learning.</p><p>In reinforcement learning, we have <strong>an agent, a reward, and a punishment.</strong></p><p>So if the model was trying to play flappy bird, every time the bird hits the pole (idk what it actually is) it gets a punishment and every time it gets past a pole it gets a reward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*iThbYaWNGwNHHi5G.png" /><figcaption>image from <br>https://www.researchgate.net/figure/The-process-of-the-unsupervised-learning-model_fig4_343819706</figcaption></figure><h3>2. Neural Networks</h3><p>There is no doubt you’d be wondering what NNS are…</p><p>Neural networks are made of LOADS of layers,<strong> an input, output, and hidden layers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*YB1OFM9G0u1RSeR8.png" /><figcaption><a href="https://rukshanpramoditha.medium.com/two-or-more-hidden-layers-deep-neural-network-architecture-9824523ab903">https://rukshanpramoditha.medium.com/two-or-more-hidden-layers-deep-neural-network-architecture-9824523ab903</a></figcaption></figure><p>Now each of these layers has <strong>nodes</strong> (these are the colored circles in between the lines), and information is fired to the nodes in the next layer. They are just loads of numbers.</p><p>NNs allow us to <strong>classify and cluster</strong> data quickly, and things such as speech recognition or image recognition would take us hours but can be done in a matter of a few minutes.</p><h4>2.1 What happens inside a node?</h4><p>In nodes, you have things called <strong>weight, threshold, and bias.</strong></p><p>In short…</p><p><strong>Weight:</strong></p><p>The weight determines the <strong>importance</strong> of a variable</p><p>Now if you want to buy a top say there are 2 factors, comfort, and style.</p><p>Now we can say which is more important.</p><p>You may say the style has a weight of 4 and comfort has a weight of 1, so the style is 4x more important than comfort Nodes with a larger weight will contribute more to the final output than those with a smaller weight</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/0*O9OZN2YsVK27xc2Z.png" /><figcaption><a href="https://medium.com/mlearning-ai/introduction-to-neural-networks-weights-biases-and-activation-270ebf2545aa">https://medium.com/mlearning-ai/introduction-to-neural-networks-weights-biases-and-activation-270ebf2545aa</a></figcaption></figure><p>You multiply all those numbers in the input matrix by an equally large weight matrix to tell the A.I. what input is valuable and what is less valuable.</p><p><strong>Summation and Bias:</strong></p><p>Bias is simply a <strong>constant value</strong> (or a constant vector) that is added to the product of inputs and weights. The bias is used to <strong>shift the result</strong> of the activation function towards the positive or negative side.</p><blockquote><em>The addition of bias reduces the variance and hence introduces flexibility and better generalization to the neural network.</em></blockquote><blockquote><em>Bias is essentially the negative of the threshold, therefore the value of bias controls when to activate the activation function. Without a bias, you can easily end up overfitting the dataset</em></blockquote><blockquote><em>Overfitting is a concept in data science, which occurs when a statistical model fits exactly against its training data.</em></blockquote><p><strong>Threshold</strong></p><p>The threshold is the <strong>minimum value</strong> a node has to have to be fired to the next layer.</p><p>So when a node in a hidden layer receives an input, the weights plus a bias are all multiplied by all the inputs, and then fired to the next layer if they meet the threshold.</p><h4>2.2 How does info from nodes get fired?</h4><p>We have something called activation functions!</p><p>The <strong>activation function</strong> of a node defines the output of that node given an input or set of inputs. They <strong>transform </strong>the sum of our output between a lower limit and an upper limit(such as 0 and 1)</p><p>Activation functions are useful because they <strong>add non-linearities</strong> to neural networks. If the activation functions were not there, the entire network could be re-factored to a simple linear operation, and it would no longer be capable of performing complex tasks.</p><p>Now prepare yourself for some maths, hahaha.</p><h4>2.3 Types of activation functions:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*kwDn0VfT0iaYReJR.png" /><figcaption><a href="https://www.v7labs.com/blog/neural-networks-activation-functions">https://www.v7labs.com/blog/neural-networks-activation-functions</a></figcaption></figure><p>As you can see, there are many activation functions with their pros and cons, I will be telling you about the important / commonly used ones</p><p><strong>Rectified Linear Units:</strong></p><p>Rectified linear units return <strong>0 if it receives a negative input</strong>, and if it receives a positive value they will <strong>return the same positive value</strong></p><p>The function is:</p><h3><strong>f(x)=max(0,x)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*NoKsmQzStSStUKUz.jpg" /><figcaption><a href="https://www.quora.com/How-does-Zeta-function-regularization-remove-infinities-from-a-physics-solution-e-g-Casimir-force-computation-Is-it-limiting-the-domain-and-or-range-of-a-function-in-some-manner?ch=1&amp;oid=151124682&amp;share=277b8c51&amp;target_type=question">https://www.quora.com/How-does-Zeta-function-regularization-remove-infinities-from-a-physics-solution-e-g-Casimir-force-computation-Is-it-limiting-the-domain-and-or-range-of-a-function-in-some-manner?ch=1&amp;oid=151124682&amp;share=277b8c51&amp;target_type=question</a></figcaption></figure><p>ReLUs can be applied to minimize interaction effects.</p><p>For example, if A=1 and B=2, and both have the weights of 2 and 3, the function would be, f(2A+3B). If A increases, the output will increase as well.</p><p>However, if B is a large negative value, the output will be 0.</p><p><strong>PReLU Function, a Variation on the ReLU</strong></p><p>Because of the <strong>zero gradient problem</strong> faced by the ReLU, we can use an adjusted ReLU function called the parametric rectified linear unit, or PReLU: <strong>The gradient is nonzero at all points</strong> (except 0 where it is undefined).</p><p><strong>Sigmoid functions:</strong></p><p>Normally this term refers to the logistic sigmoid function.</p><p>Sigmoid functions squeeze values in ranges such as <strong>0–1 or -1–1.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*2Z6ig_iBlW-euc26.png" /><figcaption><a href="https://datasciencebox.org/course-materials/lab-instructions/lab-06/lab-06-sad-plots.html">https://datasciencebox.org/course-materials/lab-instructions/lab-06/lab-06-sad-plots.html</a></figcaption></figure><p><strong>Logistic sigmoid function</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*cTQs0pltqMx59OiC.png" /><figcaption><a href="https://www.youtube.com/watch?v=6tFj4B1hNNM">https://www.youtube.com/watch?v=6tFj4B1hNNM</a></figcaption></figure><p>Above is the equation you need to understand for this. A logistic function <strong>squeezes values between 0 and 1.</strong></p><p>This is good for a <strong>binary classification model</strong> where outputs should be 0/1.</p><p>Is this table blue or not, is this ice cream or not, etc?</p><p><strong>Hyperbolic Tangent Function</strong></p><p>This <strong>maps an input to the range between -1 and 1. </strong>The hyperbolic tangent activation function is also referred to simply as the Tanh (also “tanh” and “TanH“) function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/0*bANoDuxZx_SouIbG.png" /><figcaption><a href="https://www.youtube.com/watch?v=6tFj4B1hNNM">https://www.youtube.com/watch?v=6tFj4B1hNNM</a></figcaption></figure><p><strong>Arctangent Function:</strong></p><p>This squeezes values between π/2 to π/2. The arctan function is the inverse of the tangent function. It is usually denoted as arctan x or tan-1x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/0*1rhU8oRzqLD7AsWB.png" /><figcaption><a href="https://www.youtube.com/watch?v=6tFj4B1hNNM">https://www.youtube.com/watch?v=6tFj4B1hNNM</a></figcaption></figure><p>Now, this may make a little more sense to you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*HE_yV3RpgfU_bdpV.png" /><figcaption><a href="https://www.geeksforgeeks.org/activation-functions-neural-networks/">https://www.geeksforgeeks.org/activation-functions-neural-networks/</a></figcaption></figure><p>In a more simple configuration, the sum is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/0*8CTY3RhwIaStCnEU.png" /></figure><p>Are you looking way easier right?</p><p><strong>This is the weight multiplied by the input plus the bias.</strong> This gets us a sum.</p><p>Then we use an activation function( I am gonna use the sigmoid function as my example) to squish our sum between 0 and 1.</p><p>Not so fast…. We’re not done!</p><p>What if our model is just giving us random numbers that we can’t use or trust</p><p>Now, it’s maths time — yes even more maths.</p><p>Welllll… We have a GRADIENT DESCENT!!!!!</p><h3>3. Gradient descent</h3><p>First, let’s brush up on some stuff:</p><ul><li><strong>Matrix</strong> is an arrangement of numbers into rows and columns.</li><li><strong>derivative</strong> means the rate of change of a function concerning its variables. change of x over the change of y</li></ul><p>Gradient Descent is the process of <strong>updating our parameters</strong> so that our algorithm can get better at making predictions.</p><p>We can use this to make sure we are not just getting random predictions that are WAYYYY off what we should have gotten.</p><p>Now as a little treat for you guys, I have an equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*yCqyYI7k0CpkSuzc.png" /></figure><p>Now, this is when my friends cry.</p><p>This is a <strong>cost or loss function</strong>, this tells the machine that its done something wrong. From the prediction matrix, it <strong>takes the squared difference of all the numbers and divides it by n </strong>— the number of data points.</p><p>This assists the gradient descent</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/0*CEWHNw9ZOXXE-rEB.png" /></figure><p>for the gradient, you have the <strong>partial derivative of J</strong> (which is our cost function) divided by the partial derivative of every parameter in the parameter matrix (represented by the Greek letter theta).</p><p>Now if you are not big on maths, think of it like this: DJs have loads of dials and stuff right? The gradient is how much a turn in the dials will affect the song.</p><p>Now for the descent, it is <strong>the matrix of each parameter subtracted by the gradient.</strong></p><p>Finally the A. The <strong>A is the learning rate</strong>, you don’t want an A.I. to do 0.1 iterations until after it’s already done loads of iterations, so you use a hypermeter to increase the learning speed. This helps machines to identify that they are wrong and improve.</p><h3>4. Regression</h3><p>Regression has many uses:</p><p>1.<strong> Determining the strength of predictors:</strong> the relationship between the number of tests I fail and how mad my parents are</p><p>2. <strong>Forecasting and effect:</strong> how much money will I earn from entering the metaverse as a company?</p><p>3. <strong>Trend forecasting:</strong> predicting flight prices in 2023</p><p>There are many types of regression but the main 2 are :</p><h4>4.1 Linear regression</h4><blockquote><em>Linear regression model describes the relationship between a dependent variable, y, and one or more independent variables, X.</em></blockquote><p>A regression algorithm will try to <strong>fit the best line for an algorithm.</strong></p><p>Using the data points, you map a line out and depending on what the label is you try to lower the cost using gradient descent.</p><h3>y = m x + b</h3><p>To be fair this is all you need to know, seems familiar from school doesn’t it?</p><p><strong>M is the weights, x is the data and b is the bias.</strong></p><p>However, if you want to learn more, I have an equation for you:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/0*TDjXWPTBLaPq07_s.png" /></figure><blockquote>r squared is the coefficient of determination or the coefficient of multiple determination.</blockquote><blockquote>y hat is the prediction made by the regression algorithm</blockquote><blockquote>y bar is the mean</blockquote><p>The bigger the r-squared value the <strong>more accurate</strong> your regression line is</p><p>Say you are predicting house prices, one house might be in meters squared another house might be in square feet.</p><p>What we need to do is to normalize these quantities</p><p>And for this we have yet another equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/0*0L1pqQ9NVzS4Z_IX.png" /></figure><p>This puts all the <strong>data between 0 and 1</strong> (we seem to do this a lot in ML)</p><p>If you calculate the standard deviation of that line, you understand <strong>how likely a point will deviate from the other points.</strong></p><p>For that we use this equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/0*KmluD_ZIOyH4bPT1.png" /></figure><h4>4.2 Logistic regression:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*qWpkru1U1k9IkVNM.png" /><figcaption><a href="https://levelup.gitconnected.com/50-mathematical-concepts-for-better-programming-part-2-f0dc13a8c05">https://levelup.gitconnected.com/50-mathematical-concepts-for-better-programming-part-2-f0dc13a8c05</a></figcaption></figure><p>Logistic regression <strong>maps x to y using a sigmoid function</strong>, we will talk about the sigmoid function later on but for now, Logistic regression while being a type of regression algorithm also <strong>classifies data.</strong> logistic regression <strong>predicts a continuous variable</strong> and binary classification predicts a set value.</p><p>that’s it, you understand regression</p><h3>5. Classification:</h3><p>There are 3 types of classification:</p><ul><li><strong>Binary Classification</strong>: A type of classification that gives an output between 0 and 1. For example Cat classifier (cat or not = 0 or 1), and heart disease prediction (heart problems or not = 0 or 1).</li><li><strong>Multi-Class classification</strong>: A type of classification that has more than two labels. Data is classified as one among a range of known classes</li><li><strong>- Multi-Label classification:</strong> Multi-Label classification predicts multiple outputs.</li></ul><p>Classification is pretty easy to explain now that you know quite a bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*cUrt2j7conXrpaPv" /><figcaption><a href="https://machinelearningmastery.com/perceptron-algorithm-for-classification-in-python/">https://machinelearningmastery.com/perceptron-algorithm-for-classification-in-python/</a></figcaption></figure><p>This is it:</p><p>For clarity, we are talking about a binary classification algorithm and not multi-class or multi-label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*eTiFnrjWNH0w4306.jpeg" /><figcaption><a href="https://machinelearningmastery.com/a-gentle-introduction-to-sigmoid-function/">https://machinelearningmastery.com/a-gentle-introduction-to-sigmoid-function/</a></figcaption></figure><p>We use a sigmoid activation function and gradient descent to update its parameters.</p><h3>6. Optimizers:</h3><p>An optimizer is used to <strong>adjust the parameters</strong> of a model to minimize the difference between the predicted output and the true output.</p><p>Optimizers are a crucial component of training a neural network as they <strong>determine how quickly and efficiently the model can learn from the training data.</strong></p><p>There are several types of optimizers available in machine learning, each with its own set of advantages and disadvantages. The most commonly used optimizers are:</p><ul><li><strong>Stochastic Gradient Descent (SGD)</strong>: One of the most basic and widely used optimizers. It updates the model’s parameters by<strong> taking the negative of the gradient of the loss function concerning the parameters.</strong> The learning rate determines the step size of the update.</li><li><strong>Momentum</strong>: A variant of SGD that adds a <strong>momentum term to the update rule.</strong> This helps the optimizer to overcome the problem of <strong>oscillation and converge faster.</strong></li><li><strong>Adagrad</strong>: This optimizer <strong>adapts the learning rate for each parameter</strong> individually, based on the historical gradient of that parameter.</li><li><strong>Adadelta</strong>: Similar to Adagrad, but the <strong>learning rate is determined by a moving average of the historical gradients</strong>, rather than their accumulation.</li><li><strong>Adam</strong>: Adaptive Moment Estimation (Adam) is a <strong>combination of the above two optimizers, </strong>it uses both the gradient and the historical gradient to determine the learning rate for each parameter.</li><li><strong>RMSprop</strong>: This optimizer is similar to Adadelta, but it uses the <strong>RMS of the historical gradient</strong> to determine the learning rate for each parameter.</li></ul><p>The choice of optimizer depends on the specific problem and the type of neural network.</p><p>In general, <strong>Adam is a good choice</strong> as it has been shown to work well in many cases.</p><p>However, it’s always good practice to try multiple optimizers on your specific problem and see which one works best.</p><h3>7. Loss:</h3><p>In machine learning, the loss function is used to <strong>evaluate the performance</strong> of a model by comparing its predicted output to the true output.</p><p>The loss function c<strong>alculates the difference between the predicted output and the true output</strong>, and the goal of training a model is to minimize this difference, also known as the error or cost.</p><p>There are several types of loss functions available in machine learning, depending on the specific problem and the type of neural network. The most commonly used loss functions are:</p><ul><li><strong>Mean Squared Error (MSE)</strong>: This loss function calculates the a<strong>verage squared difference</strong> between the predicted and true output. It is commonly used for <strong>regression</strong> problems where the output is a continuous value.</li><li><strong>Mean Absolute Error (MAE)</strong>: This loss function calculates the <strong>average absolute difference</strong> between the predicted and true output. It is also commonly used for regression problems.</li><li><strong>Binary Cross-Entropy</strong>: This loss function is used for <strong>binary classification problems</strong> where the output is a probability between 0 and 1. It calculates the cross-entropy between the predicted probability and the true output.</li><li><strong>Categorical Cross-Entropy</strong>: This loss function is used for <strong>multi-class classification</strong> problems where the output is a probability distribution over multiple classes. It calculates the cross-entropy between the predicted probability distribution and the true output.</li><li><strong>Hinge Loss</strong>: This loss function is used for support vector machines <strong>(SVMs)</strong> and is commonly used for binary classification problems where the goal is to separate the two classes by a large margin.</li><li><strong>log-likelihood</strong>: This loss function is used for <strong>probabilistic models</strong> such as Gaussian Mixture Model (GMM)</li></ul><p>The choice of loss function depends on the specific problem and the type of neural network. For example, for a binary classification problem, it’s common to use binary cross-entropy as the loss function, and for a multi-class classification problem, it’s common to use categorical cross-entropy.</p><h3>8. Python Libraries:</h3><p>Now we are going to be going into a lot of code in the article, so it is important to understand some of this:</p><p>Python libraries are collections of <strong>pre-written code</strong> that can be used to perform a wide variety of tasks. These libraries are designed to make it easier for programmers to perform common or complex tasks by providing a set of pre-built functions, classes, and other tools.</p><h4>8.1 NumPy:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*zmVRP4WF1tXisF__" /><figcaption>NumPy logo</figcaption></figure><p>NumPy is a Python library that is widely used in scientific computing and data analysis. It provides a powerful and efficient way to work with<strong> large arrays and matrices of numerical data</strong>. Some of the key features of NumPy include:</p><ul><li><strong>N-dimensional arrays:</strong> NumPy provides a powerful and efficient array object, called an array, that can be used to<strong> store and manipulate large arrays of homogeneous data</strong> (i.e., data of the same type, such as integers or floating-point values).</li><li><strong>Mathematical functions:</strong> NumPy provides a wide range of mathematical functions that can be applied to arrays and matrices, such as <strong>trigonometric functions, logarithms, exponentials</strong>, and more. These functions are implemented in C or Fortran for speed and are much faster than equivalent functions in Python’s built-in math module.</li><li><strong>Linear algebra:</strong> NumPy provides a set of functions and tools for linear algebra, such as <strong>matrix multiplication, inverse, determinant, eigenvalues, and more.</strong></li><li><strong>Broadcasting:</strong> NumPy allows you to <strong>perform mathematical operations on arrays of different shapes,</strong> by automatically broadcasting the smaller array to the shape of the larger array.</li></ul><p>NumPy is widely used in many areas of scientific computing and data analysis, such as <strong>machine learning, signal processing, image processing, and more.</strong> It is also used as the <strong>foundation of many other libraries</strong>, such as SciPy, Matplotlib, and Pandas, which build on the capabilities of NumPy to provide more advanced functionality.</p><p>To use NumPy, you need to first install the library and then import it into your Python script or Jupyter notebook using the import statement.</p><pre>import numpy as np</pre><p>Once imported, you can create arrays, perform mathematical operations and linear algebra, and use broadcasting.</p><p><strong>8.2 Pandas:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*cJ6LfRe5PIA_iXpe" /><figcaption>Pandas logo</figcaption></figure><p>Pandas is a popular Python library that provides powerful data structures and data analysis tools. It is widely used in data science and machine learning projects for data preprocessing and cleaning tasks.</p><p>Some of the key features of Pandas include:</p><ul><li><strong>Data structures</strong>: Pandas provides two main data structures, <strong>Series</strong> (1-dimensional) and <strong>DataFrame </strong>(2-dimensional). Series is similar to a column in a spreadsheet and DataFrame is similar to a table in a spreadsheet.</li><li><strong>Indexing and selecting data</strong>: Pandas provides a variety of ways to index and select data from a DataFrame, including <strong>label-based indexing</strong> and <strong>boolean indexing</strong>. This allows you to easily select and <strong>filter subsets of the data</strong> based on certain conditions.</li><li><strong>Handling missing data</strong>: Pandas provides several ways to handle missing data, including <strong>filling in missing values</strong> with a specific value or using a <strong>statistic (such as the mean) from the non-missing values.</strong></li><li><strong>Merging and joining</strong>: Pandas allows you to easily <strong>combine multiple data sets</strong> by merging or joining them on one or more columns.</li><li><strong>Grouping and aggregation</strong>: Pandas provides a variety of ways to <strong>group and summarize data</strong>, such as grouping by one or more columns and applying a statistical function (such as mean or sum) to each group.</li><li><strong>Data manipulation</strong>: Pandas provides a wide range of <strong>data manipulation and data transformation</strong> functions, such as pivot, melt, stack, unstack, etc.</li></ul><p>Pandas is <strong>built on top of NumPy</strong>, and it utilizes its powerful array and mathematical operations to provide a fast and efficient way to work with large amounts of data.</p><p>It also integrates well with other libraries like Matplotlib and Scikit-learn for data visualization and machine learning tasks. To use Pandas, you need to first install the library and then import it into your Python script or Jupyter notebook using the import statement:</p><pre>import pandas as pd</pre><p>Once imported, you can create DataFrames, perform data manipulation and data analysis operations, and use the functions provided by pandas.</p><h4>8.3 Matplotlib</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*NeMxLsGmlwS2f3RY" /><figcaption>matplotlib logo</figcaption></figure><p>Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for <strong>embedding plots</strong> into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK. It was originally developed by John D. Hunter in 2003 and is now maintained by a large team of developers.</p><p>Matplotlib provides a wide range of plotting functionality, from <strong>simple line plots to more complex types of visualizations such as scatter plots,</strong> histograms, bar plots, and 3D plots. It also provides several tools for customizing the appearance of the plots, such as <strong>changing colors, adding labels and legends, and adjusting the axis limits.</strong></p><p>One of the most powerful features of Matplotlib is its ability to create subplots, which allows you to create multiple plots in a single figure. This is useful when you want to compare multiple datasets or when you want to display different aspects of the same data in different ways.</p><p>In addition to its plotting capabilities, Matplotlib also provides tools for <strong>working with images, such as reading and writing image files, and for creating animations.</strong></p><p>To use Matplotlib in a Python script or Jupyter notebook, you need to first install the library and then import it using the import statement:</p><pre>import matplotlib.pyplot as plt</pre><p>Once imported, you can use the various functions provided by Matplotlib to create plots, customize their appearance, and display them.</p><p>Matplotlib also has several add-on libraries that provide additional functionality, such as Seaborn and Plotly which are widely used for data visualization and provides more interactive and attractive plots.</p><h4>8.4 Tensorflow:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/0*REnwphjo1WuxnfLT" /><figcaption>Tensorflow logo</figcaption></figure><p>TensorFlow is an open-source library for <strong>dataflow and differentiable programming </strong>across a range of tasks. It is a <strong>symbolic math</strong> library and is also used for machine learning applications such as neural networks. It was developed by the Google Brain Team and released under the Apache 2.0 open-source license in 2015.</p><p>TensorFlow is designed to work with large-scale machine learning models, and it can run on a variety of platforms, including <strong>CPUs, GPUs, and TPUs</strong> (Tensor Processing Units). It is particularly useful for deep learning tasks such as<strong> image and speech recognition, natural language processing, and time series forecasting.</strong></p><p>One of the key features of TensorFlow is its ability to <em>define computations as a directed acyclic graph (DAG</em>) of operations, called a computational graph. This allows TensorFlow to perform efficient symbolic differentiation on the graph, and automatically <strong>compute the gradients</strong> of a model concerning its parameters. This is particularly useful for training machine learning models using <strong>gradient-based optimization algorithms.</strong></p><p>TensorFlow also provides several tools for building, training, and deploying machine learning models, including:</p><ul><li><strong>Flexible architecture</strong> for building and deploying machine learning models</li><li>A wide range of <strong>pre-built and pre-trained models</strong> for common tasks</li><li>Tools for <strong>data loading, preprocessing</strong>, and <strong>input pipelines</strong></li><li>A variety of <strong>optimization algorithm</strong>s for training models</li><li>Tools for <strong>monitoring and visualizing</strong> the training process</li><li>Support for <strong>deploying models</strong> to a variety of platforms, including mobile devices and web services</li></ul><p>To use TensorFlow in a Python script or Jupyter notebook, you need to first install the library and then import it using the import statement:</p><pre>import tensorflow as tf</pre><p>Once imported, you can use the various functions provided by TensorFlow to define and train machine learning models. TensorFlow 2. x has made it more user-friendly and reduced the complexity of creating and managing the computational graph.</p><p>WOW THAT Wt AS A LOT OF LIBRARIES… and there are more but you don’t need them explained that much.</p><p>Before we jump into types of Neural Networks, I am going to need to take a breath so that we can get into some good code and maths!</p><h3>9. Types of Neural Networks:</h3><p>After all of this understanding, let’s go into the good stuff:</p><p>Types of Neural Networks…</p><h4>9.1 Feed Forward Neural Network</h4><p>This is the simplest type of Neural Network, so the perfect one to start with.</p><p>A Feed Forward Neural Network is one where the connections between the nodes <strong>do not form a cycle</strong>, as you can see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/0*usfKBOzN--oFwQzv.png" /><figcaption><a href="https://deepai.org/machine-learning-glossary-and-terms/feed-forward-neural-network">https://deepai.org/machine-learning-glossary-and-terms/feed-forward-neural-network</a></figcaption></figure><p>In this neural network information only <strong>flows forward</strong> and never backward.</p><p>When looking at a Feed Forward Neural Network you normally see it as a <strong>single-layer perceptron.</strong></p><p><strong>Inputs enter the layer and are multiplied by the weights. Each value is then added together to get a sum of the weighted input values.</strong></p><p>Normally the threshold for Feed Forward Neural Networks is set at 0. If we have something <strong>above the threshold it’s 1, and below the threshold is -1</strong>.</p><p>Single Layer perceptrons are normally good for <strong>classification</strong> tasks, this would use the <strong>step function</strong>. However, this can only be used when the data is <strong>linearly separable</strong>. It can also compare the outputs of its nodes with the intended value so that it can later <strong>adjust its weights</strong> to be more accurate, this is known as the <strong>delta rule.</strong></p><p>The learning rate controls <strong>how much we are adjusting the weights</strong> of our network</p><p>A multi-layer perceptron can be used to <strong>classify data that is not linearly separable</strong>, it would be trained using <strong>backpropagation</strong> (this is the process of updating our parameters to have a more accurate output). This means that it would need a <strong>differentiable activation function</strong> because back propagation uses gradient descent to update the network weights.</p><p>This step function is <strong>non-differentiable at x = 0</strong> and its <strong>derivative is 0</strong> elsewhere, so backpropagation would not work, which is why we use a <strong>sigmoid function</strong> a lot in this field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*byXLuTCgVux56Hrg.png" /><figcaption><a href="https://towardsdatascience.com/what-the-hell-is-perceptron-626217814f53">https://towardsdatascience.com/what-the-hell-is-perceptron-626217814f53</a></figcaption></figure><h4>Python for perceptrons</h4><p>Let’s have a go at applying python to this. Firstly, why is python good for AI?</p><blockquote>Python for machine learning is a great choice, as this language is very flexible: 1 It offers an option to choose either to use OOPs or scripting. 2 There’s also no need to recompile the source code, developers can implement any changes and quickly see the results. 3 Programmers can combine Python and other languages to reach their goals.</blockquote><p>I would suggest getting to grips with basic python, this will be a valuable skill if you want to pursue machine learning.</p><p>Here are some good videos(you do not have to watch all of them):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FkqtD5dpn9C8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DkqtD5dpn9C8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkqtD5dpn9C8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/046f748c26c67aee2312a92dcc9ad0dc/href">https://medium.com/media/046f748c26c67aee2312a92dcc9ad0dc/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FrfscVS0vtbw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrfscVS0vtbw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FrfscVS0vtbw%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/aeb151fea7f32e8dabde9e13e410205e/href">https://medium.com/media/aeb151fea7f32e8dabde9e13e410205e/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FI2wURDqiXdM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DI2wURDqiXdM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FI2wURDqiXdM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/38db44840309f78a60dd7bae3c76b0e4/href">https://medium.com/media/38db44840309f78a60dd7bae3c76b0e4/href</a></iframe><p>This is the python illustration for perceptrons:</p><pre>#import our libraries<br>import numpy as np <br>import random as rd <br>import os <br><br>#set bias <br>bias = 1<br><br># learning rate <br>lr = 1 <br><br>#generate weights in a list <br>weights = [random.random(), random.random(), random.random(), random.random()]<br><br>#the inputs and outputs <br>def perceptron(input1, input2, input3, output):<br>   Predicted_output = bias*weights[0] + input1*weights[1] + input2*weights[2] + input3*weights[3]<br><br>#activation function <br>if Predicted_output &gt; 0:<br>   Predicted_output = 1<br>else: <br>   Predicted_output = 0 <br><br>#calculating the errors and adjusting weights <br><br>error = output - predicted outputs <br><br>weights[0] = bias * error * lr <br>weights[1] = input1 * error * lr<br>weights[2] = input2 * error * lr<br>weights[3] = input3 * error * lr<br><br>#printing our results <br>print(&quot;new adjusted weights:&quot;, weights)<br>print(&quot;step function_prediction:&quot;, Predicted output)<br><br>#sigmoid function <br>outputP = 1/(1 + numpy.exp (- Predicted_output))<br><br>#print function prediction <br>print(&quot;sigmoid function prediction&quot;, Predicted_output)<br><br>x1 = int(input())<br>x2 = int(input())<br>x3 = int(input())<br><br>print(&quot;randomly assigned weights&quot;, weights)<br>Perceptron(x1, x2, x3)</pre><h4>9.2 Radial Basis Function (RBF)</h4><p>Most neural networks have many layers and introduce nonlinearity by using <strong>nonlinear activation functions.</strong></p><p>RBFs work with <strong>sequential data</strong>:</p><p>eg: time</p><p>In simple RBFs, you have an <strong>input layer, a single hidden layer, and an output layer.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/0*RoWyldHeSDA1hVcI.png" /></figure><p><strong>The input layer</strong></p><p>The input layer of RBFs is very simple. <strong>No computation</strong> happens in this layer.</p><p>The input neurons are<strong> fully connected </strong>to the hidden neurons and feed their input forward.</p><p>The number of neurons in this layer is equal to the dimensionality of this data</p><p><strong>The hidden layer</strong></p><p>This layer takes the input and makes it more linearly separable.</p><blockquote><strong>Cover’s theorem on the separability of patterns</strong>, states that a pattern that is transformed into a higher-dimensional space with nonlinear transformation is more likely to be linearly separable, therefore the number of neurons in the hidden layer should be greater than the number of the input neuron.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/0*tvx3CPQOIvKhW-bS.png" /></figure><p>Each neuron in the hidden layer has a<strong> prototype vector and a bandwidth</strong> denoted by μ and σ</p><p>The computation in this layer can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/0*NZlXRIwC76NQ3tDa.png" /></figure><ul><li>X bar as the input vector</li><li>μ bar as the iᵗʰ neuron’s prototype vector</li><li>σ as the iᵗʰ neuron’s bandwidth</li><li>phi as the iᵗʰ neuron’s output</li></ul><p><strong>The output layer:</strong></p><p>This layer uses a linear activation function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/0*sZL6Iz-x4wFt1JJV.png" /></figure><p>The computations in the output layer are performed just like <strong>a standard artificial neural network</strong></p><p>This is good for regression and classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/0*XvTTU4ijC_KxRMD_.png" /></figure><ul><li>wᵢ is the weight connection</li><li>phi is the iᵗʰ neuron’s output from the hidden layer</li><li>y is the prediction result</li></ul><p>Now that you have a basic understanding of an RBF Neural Network, what does it look like in python???</p><h4>Python for RBF NN:</h4><pre>#after you process your data, to build your neural network you use this code:<br><br>model = Sequential()<br>#this is becuase RBFs work with sequential data<br><br>rbflayer = RBFLayer(34,<br>                        initializer=InitCentersKMeans(X_train),<br>                        betas=3.0,<br>                        input_shape=(568,))<br>#these are the details for our RBF layer, our neural net will uss multiple layers<br><br>model.add(rbflayer)<br>#this is going to add out RBF ;ayer with the specifications above <br><br>model.add(Dense(4))<br>#this is adding another layyer if we want to, we will go into dense later on <br><br>model.add(Activation(&#39;linear&#39;))<br>#adding our activation function <br><br>#and the rest doesn&#39;t matter at this point in the article</pre><h4>9.3 GANs</h4><p>Generative Adversarial Networks (GANs) are a type of neural network architecture designed for <strong>generative tasks, such as image synthesis, text generation, and audio synthesis.</strong> They consist of two main components: a <strong>generator and a discriminator.</strong></p><p>The generator is responsible for<strong> creating new data</strong> that is similar to the training data. It takes a random input (known as a “noise vector”) and maps it to a sample from the target distribution (e.g., an image).</p><p>The discriminator is responsible for <strong>determining whether a given sample is real </strong>(from the training data) or fake (generated by the generator). It takes a sample as input and produces a<strong> scalar value </strong>indicating the <strong>probability</strong> that the sample is real.</p><p>The two networks are <em>trained together</em> in an adversarial manner: the generator tries to create samples that the discriminator cannot distinguish from real ones, while the discriminator tries to correctly identify fake samples. This process continues until the generator produces samples that are indistinguishable from real ones.</p><p>One of the most popular applications for GANs is <strong>image generation.</strong> GANs can generate new images that are similar to a training set of images, this could be used in various applications such as <strong>creating images of faces that look like real people</strong>, creating new images of animals, or even creating new images of landscapes.</p><p>One important thing to note is that GANs are <strong>difficult to train</strong> and their stability is hard to guarantee, so many tricks and techniques have been proposed to stabilize the training process and improve the quality of the generated data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*BOggGaQ2cyQ2ilM5" /><figcaption><a href="https://developers.google.com/machine-learning/gan/gan_structure">https://developers.google.com/machine-learning/gan/gan_structure</a></figcaption></figure><p><strong>Python for GANs:</strong></p><p>Here is an example of a simple GAN implemented in Python</p><pre>import numpy as np<br>from keras.layers import Input, Dense, LeakyReLU, Dropout<br>from keras.models import Model<br># Define the dimensions of the input and output data<br>latent_dim = 100<br>input_shape = (784,)<br># Define the generator<br>generator_input = Input(shape=(latent_dim,))<br>x = Dense(256, activation=LeakyReLU(alpha=0.01))(generator_input)<br>x = Dense(512, activation=LeakyReLU(alpha=0.01))(x)<br>x = Dense(1024, activation=LeakyReLU(alpha=0.01))(x)<br>generator_output = Dense(784, activation=&#39;tanh&#39;)(x)<br>generator = Model(generator_input, generator_output)<br># Define the discriminator<br>discriminator_input = Input(shape=input_shape)<br>x = Dense(512, activation=LeakyReLU(alpha=0.01))(discriminator_input)<br>x = Dropout(0.4)(x)<br>x = Dense(256, activation=LeakyReLU(alpha=0.01))(x)<br>x = Dropout(0.4)(x)<br>x = Dense(1, activation=&#39;sigmoid&#39;)(x)<br>discriminator = Model(discriminator_input, x)<br># Compile the discriminator<br>discriminator.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br># Freeze the discriminator weights<br>discriminator.trainable = False<br># Connect the generator and discriminator to create the GAN<br>gan_input = Input(shape=(latent_dim,))<br>gan_output = discriminator(generator(gan_input))<br>gan = Model(gan_input, gan_output)<br># Compile the GAN<br>gan.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;)</pre><p>This is a very basic example of a GAN that can be used to generate images of digits <strong>(MNIST dataset).</strong></p><p>In this example, the generator is a simple <strong>feed-forward neural network</strong> that takes a random input (latent_dim-dimensional noise vector) and maps it to an output with the same dimensions as the input data (28x28 = 784 pixels for MNIST images). The discriminator is also a simple feed-forward neural network that takes an image as input and produces a <strong>scalar value indicating the probability that the image is real.</strong></p><p>You can train this GAN by<strong> repeatedly sampling from the generator</strong> and concatenating it with real images from the dataset, then using the resulting data to train the discriminator. Once the discriminator is trained, you can <strong>use its weights to train the generator by using the generator to produce fake images and using the discriminator’s output to compute the loss.</strong></p><h4>9.4 Recurrent Neural Networks (RNNs)</h4><p>Recurrent Neural Networks are known for their<strong> “memory”</strong>. Now let me explain. RNNS take information from previous inputs into account to influence their current output.</p><p>The output of recurrent neural networks <strong>depends on the prior elements within the sequence</strong>, this makes them very different from what we have seen so far.</p><p>Unlike what we have seen in other NNS, RNNs have the <strong>same weight</strong> for every layer of the Neural Network, Weights are still adjusted with backpropagation however instead of how we see it in feedforward neural networks, here we use <strong>BPTT</strong> which sums errors at each time step.</p><p><strong>Exploding and Vanishing Gradients</strong></p><p>Exploding gradients happen when the weights’ gradients become too big, causing the model to <strong>diverge during training</strong>. Vanishing gradients happen when the weights’ gradients become too small, causing the model to <strong>converge too slowly.</strong></p><p><strong>Gradient clipping</strong></p><p>A way to deal with this is gradient clipping.</p><p>It is done by setting a <strong>threshold or limit on the size of the gradients</strong> and then scaling down (clipping) any gradients that exceed this limit. This helps to keep the gradients in a <strong>stable range</strong> and prevent them from causing the model to diverge or converge too slowly.</p><p>Gradient clipping can be done in different ways :</p><ul><li>Element-wise</li><li>Norm-based</li></ul><p><strong>Element-wise </strong>clipping is done by setting a threshold for each weight gradient and scaling down any gradients that exceed this threshold.</p><p><strong>Norm-based</strong> clipping is done by computing the norm (or length) of the gradient vector and then scaling down the entire vector if the norm exceeds a certain threshold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*36IGO9EU_otCMoGP" /></figure><p><strong>Weight initialization methods.</strong></p><p>Weight initialization is the process of <strong>setting the initial values for the weights</strong> of a neural network’s layers before training. The choice of the initialization method can have a significant impact on the network’s performance, as it can <strong>affect the speed and stability of the training process.</strong></p><p>There are several commonly used weight initialization methods:</p><h4>LSTM</h4><p>LSTM stands for <strong>Long Short-Term Memory.</strong></p><p>It is a type of recurrent neural network (RNN) designed to handle the problem of vanishing gradients in traditional RNNs.</p><p>LSTMs can <strong>remember</strong> information for long periods and can selectively choose to forget previous information, which allows them to be more effective in tasks such as<strong> language modeling, speech recognition, and natural language processing.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*3kstBKZ8ObCtrmyo" /><figcaption><a href="https://stats.stackexchange.com/questions/241985/understanding-lstm-units-vs-cells">https://stats.stackexchange.com/questions/241985/understanding-lstm-units-vs-cells</a></figcaption></figure><p>An LSTM cell has three gates: <strong>an input gate, an output gate, and a forget gate</strong>, which controls the flow of information into, out of, and within the cell.</p><p>These gates are controlled by <strong>learned weights and biases</strong>, and allow the LSTM to effectively store and retrieve information over long periods.</p><p><strong>Random initialization:</strong></p><p>Random initialization is a method of<strong> initializing the weights of a neural network’s layers before training</strong>, by assigning random values to the weights. This method is simple and easy to implement, as it only requires generating random numbers for the weights.</p><p>The random initialization method can be implemented in different ways, such as:</p><ul><li>Initializing the weights with <strong>small random numbers</strong>, such as values between 0 and 1 or between -1 and 1.</li><li>Initializing the weights with<strong> random values following a specific probability distribution</strong>, such as a normal distribution or a uniform distribution.</li></ul><p>Random initialization can make the training process <strong>more robust</strong>, as it ensures that the network starts with different starting points, and it can help to avoid getting stuck in local optima. However, it is <strong>not always optimal</strong> and it may require fine-tuning the hyperparameters (such as the learning rate) to achieve good performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/0*O8NFv9v_5MjG7NJz" /><figcaption><a href="https://brunch.co.kr/@linecard/530">https://brunch.co.kr/@linecard/530</a></figcaption></figure><p><strong>Xavier initialisation</strong></p><p>Xavier initialization is a method of initializing the weights of a neural network’s layers before training, to ensure that the variance of the weights’ gradients is the same for all layers. It is named after Xavier Glorot, who first introduced it in a 2010 paper.</p><p>The Xavier initialization method is based on the idea that the variance of the weights should be <strong>inversely proportional </strong>to the number of input neurons. This is because the gradients of the weights can change significantly depending on the number of input neurons, and<strong> by adjusting the variance of the weights</strong>, we can ensure that the gradients are in a stable range.</p><p>The Xavier initialization can be implemented by using the following formula:</p><h4>w = np. random.randn(n_in, n_out) * np.sqrt(2 / (n_in + n_out))</h4><p><strong>Where “n_in” is the number of input neurons and “n_out” is the number of output neurons, this formula generates random numbers following a normal distribution with zero mean and a variance of 2 / (n_in + n_out).</strong></p><p>Xavier initialization is commonly used in feed-forward neural networks, and it helps to<strong> improve the stability and speed</strong> of the training process by keeping the gradients in a stable range.</p><p>It has been shown to work well with <strong>sigmoid and tanh activation functions</strong>, but it can also be used with other activation functions.</p><p><strong>He initialization</strong></p><p>He initialization is a method of initializing the weights of a neural network’s layers before training, similar to Xavier initialization but designed to be used with <strong>ReLU activation functions.</strong> It is named after He Kaiming, who first introduced it in a 2015 paper.</p><p>The He initialization method is based on the idea that the <strong>variance of the weights should be inversely proportional to the square root of the number of input neurons.</strong></p><p>This is because the gradients of the weights can change significantly depending on the number of input neurons, and by adjusting the variance of the weights, we can ensure that the gradients are in a stable range.</p><p>The He initialization can be implemented by using the following formula:</p><p>familiar right?</p><h4>w = np. random.randn(n_in, n_out) * np.sqrt(2 / (n_in))</h4><p>He initialization is commonly used in<strong> feed-forward neural networks </strong>that use the ReLU activation function, and it helps to improve the stability and speed of the training process by keeping the gradients in a stable range.</p><p>It is more effective than Xavier initialization when used with the ReLU activation function, as the ReLU activation function can introduce a <strong>sparsity in the gradients</strong> and the He initialization corrects the variance of the gradients for this sparsity.</p><p><strong>LeCun initialization</strong></p><p>LeCun initialization is a method of initializing the weights of a neural network’s layers before training, similar to Xavier initialization but it is specifically designed to be used with <strong>tanh activation functions</strong>. It is named after Yann LeCun, who first introduced it in a 1998 paper.</p><p>The LeCun initialization method is based on the idea that the variance of the weights should be <strong>inversely proportional to the number of input neurons. </strong>This is because the gradients of the weights can change significantly depending on the number of input neurons, and by adjusting the variance of the weights, we can ensure that the gradients are in a stable range.</p><p>The LeCun initialization can be implemented by using the following formula:</p><h4>w = np. random.randn(n_in, n_out) * np.sqrt(1 / (n_in))</h4><p>familiar?</p><p>LeCun initialization is commonly used in feed-forward neural networks that use tanh activation function, and it helps to <strong>improve the stability and speed of the training process by keeping the gradients in a stable range.</strong></p><p>It is suited for the tanh activation function as it helps to keep the variance of the output of the tanh function close to 1, this allows the network to explore a larger range of the function.</p><p><strong>Orthogonal initialization:</strong></p><p>Orthogonal initialization is a method of initializing the weights of a neural network’s layers before training, which is different from the previously mentioned methods. The main idea behind this initialization is that the <strong>weight matrix is initialized to be orthogonal</strong>, which means that it is a matrix whose columns and rows are perpendicular to each other.</p><p>The main advantage of this initialization is that it ensures t<strong>hat the gradients of the weights are not affected by the correlation between the weights of the same layer.</strong> This helps to avoid the problem of “symmetry breaking” during training, which can cause the gradients to become unstable and the training process to slow down.</p><p>The Orthogonal initialization can be implemented by using the following formula:</p><h4>w = np. random.normal(0,1,(n_in,n_out))</h4><h4>u, s, vh = np.linalg.sid(w, full_matrices=False)</h4><h4>w = u @ vh</h4><p><strong>Where “n_in” is the number of input neurons and “n_out” is the number of output neurons</strong>, this formula generates a random matrix, which is then factorized into its singular values, after that, the matrix is reconstructed from the singular values, this way the matrix is guaranteed to be orthogonal.</p><p>Orthogonal initialization is <strong>not as widely used</strong> as the previously mentioned initialization methods, but it is gaining popularity and is found to be useful in certain types of architectures and problems, for example, it has been shown to work well with recurrent neural networks.</p><p><strong>Python for RNN:</strong></p><p>Here is an example of an RNN code:</p><pre>from keras.layers import SimpleRNN<br>from keras.models import Sequential<br><br># define the RNN model<br>model = Sequential()<br>model.add(SimpleRNN(units=32, input_shape=(None, 1)))<br><br># compile the model<br>model.compile(optimizer=&#39;adam&#39;, loss=&#39;mean_squared_error&#39;)</pre><p>This example defines a simple RNN with 32 units and an input shape of (None, 1), where None represents the number of time steps in the input sequence and 1 represents the number of features in each time step. The model is then compiled using the Adam optimizer and the mean squared error loss function.</p><p>You can then use the model to fit your data and make predictions.</p><pre># train the model on your data<br>model.fit(x_train, y_train, epochs=10)<br><br># make predictions<br>y_pred = model.predict(x_test)</pre><p>This is a basic example and you may want to add more layers, change the number of units, or use different optimizers or loss functions depending on your specific problem.</p><h3>9.5 Convolutional Neural Networks(CNNS):</h3><p>CNNs are neural networks that mimic the brain&#39;s way of classifying images, such as single-digit numbers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*5x37rUK5D7VrS-9-" /><figcaption><a href="https://www.itm-conferences.org/articles/itmconf/pdf/2022/04/itmconf_icacc2022_03049.pdf">https://www.itm-conferences.org/articles/itmconf/pdf/2022/04/itmconf_icacc2022_03049.pdf</a></figcaption></figure><p>What does the image above mean? Let’s go through it.</p><h4>STEP 1: Convolution</h4><p>In convolution, we <strong>multiply the input image by the kernel/filter creating an output matrix.</strong></p><p>We can get the values in the output matrix by sliding the kernel on the input matrix.</p><p>When this process is repeated with many different areas, it creates the first layer in the CNN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*W-1RKJ12QsyCHxrA" /><figcaption><a href="https://medium.com/s-a-a-s/dl-basic-concept-of-cnn-2ef4fc9b039b">https://medium.com/s-a-a-s/dl-basic-concept-of-cnn-2ef4fc9b039b</a></figcaption></figure><h4>STEP 2: Pooling</h4><p>Since the matrix is very big, when we perform step 1 it is <strong>computationally expensive</strong>. So we take the <strong>most important parts </strong>of our convolved matrix or the average by pooling to reduce the dimensions of the feature maps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*9ZbQ5mi0a1Fe5mdl" /><figcaption><a href="https://www.medrxiv.org/content/10.1101/2020.11.08.20228080v4.full?versioned=true">https://www.medrxiv.org/content/10.1101/2020.11.08.20228080v4.full?versioned=true</a></figcaption></figure><p>This makes it less computationally expensive</p><h4>STEP 3: ReLU</h4><p>Rectified linear units <strong>return 0 if it receives a negative input, and if it receives a positive value they will return the same positive value</strong></p><p>The function is understood as:</p><p>f(x)=max(0,x)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*xsAVKuYpiY8_z9d0.jpg" /><figcaption><a href="https://www.quora.com/How-does-Zeta-function-regularization-remove-infinities-from-a-physics-solution-e-g-Casimir-force-computation-Is-it-limiting-the-domain-and-or-range-of-a-function-in-some-manner?ch=1&amp;oid=151124682&amp;share=277b8c51&amp;target_type=question">https://www.quora.com/How-does-Zeta-function-regularization-remove-infinities-from-a-physics-solution-e-g-Casimir-force-computation-Is-it-limiting-the-domain-and-or-range-of-a-function-in-some-manner?ch=1&amp;oid=151124682&amp;share=277b8c51&amp;target_type=question</a></figcaption></figure><p>graphic representation of the ReLU function</p><p>ReLUs can be applied to <strong>minimize interaction effects.</strong> For example, if A=1 and B=2, and both have the respectively associated weights of 2 and 3, the function would be, f(2A+3B). If A increases, the output will increase as well. However, if B is a large negative value, the output will be 0.</p><h4>STEP 4: Dropout</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*KGqYi_MFtuEObAaK.png" /><figcaption><a href="https://towardsdatascience.com/12-main-dropout-methods-mathematical-and-visual-explanation-58cdc2112293">https://towardsdatascience.com/12-main-dropout-methods-mathematical-and-visual-explanation-58cdc2112293</a></figcaption></figure><p>In deep neural networks, a major problem is co-adaptation. When all the weights are learned together some of the connections end up having a larger predictive capability than others so you’ve only really trained part of your neurons.</p><p>This means that the neural network is fine with this set of data but it hasn’t learned anything so with similar but new data it&#39;s lowkey useless. This is caused by the model overfitting the data —<strong> IT HAS 0 FLEXIBILITY</strong></p><p>So that’s why dropout neurons are <strong>randomly selected in a neural net and “dropped out”</strong> so that the network learns a fraction of the weights at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/0*GsbCMUNEk9YZHEjm" /><figcaption><a href="https://www.semanticscholar.org/paper/Advanced-property-valuation-techniques-and-the-Chan-Abidoye/821137c881703e0bb1ddaf951825b34f195d1e35">https://www.semanticscholar.org/paper/Advanced-property-valuation-techniques-and-the-Chan-Abidoye/821137c881703e0bb1ddaf951825b34f195d1e35</a></figcaption></figure><p>To use this in your neural network you need a <strong>dropout ratio</strong>, which is a hyperparameter that the human sets for the machine. So if it were 0.5, half would be dropped out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*1JZbz_rRpYDk4ISl.png" /></figure><h4>STEP 5: SoftMax</h4><p>This is the <strong>activation function</strong> for CNN. once it receives the outputs given by the neural network it flattens and converts them to a set of <strong>probability values we are attempting to predict.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*rQdIN5-lAuYzdW60" /><figcaption><a href="https://machinelearningmastery.com/softmax-activation-function-with-python/">https://machinelearningmastery.com/softmax-activation-function-with-python/</a></figcaption></figure><p><strong>Afterward, we use argmax — this takes the largest number of the probability values out of the vector.</strong></p><p>We pick the biggest probability value which outputs some sort of digit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*B0fJsFXcVpoeMiQ7.png" /></figure><h4>STEP 6:Backpropagation:</h4><p>This is just using whatever we have learned to <strong>update the weights </strong>so that we can make better predictions, we do this again and again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/0*nHFfskqvgbRJT2cU" /><figcaption><a href="https://www.instagram.com/pastoralfamiliarmoc/">https://www.instagram.com/pastoralfamiliarmoc/</a></figcaption></figure><p>AND WE&#39;RE DONE!!!!</p><p><strong>But let’s code it:</strong></p><pre>from keras.models import Sequential<br>from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense<br><br># Create a sequential model<br>model = Sequential()<br><br># Add a convolutional layer with 32 filters and a kernel size of 3x3<br>model.add(Conv2D(32, kernel_size=(3, 3), activation=&#39;relu&#39;, input_shape=(28, 28, 1)))<br><br># Add a max pooling layer with a pool size of 2x2<br>model.add(MaxPooling2D(pool_size=(2, 2)))<br><br># Add another convolutional layer with 64 filters and a kernel size of 3x3<br>model.add(Conv2D(64, kernel_size=(3, 3), activation=&#39;relu&#39;))<br><br># Add another max pooling layer with a pool size of 2x2<br>model.add(MaxPooling2D(pool_size=(2, 2)))<br><br># Flatten the data for the fully connected layers<br>model.add(Flatten())<br><br># Add a dense layer with 128 neurons and ReLU activation<br>model.add(Dense(128, activation=&#39;relu&#39;))<br><br># Add the output layer with 10 neurons (for 10 classes) and softmax activation<br>model.add(Dense(10, activation=&#39;softmax&#39;))<br><br># Compile the model with categorical crossentropy loss and Adam optimizer<br>model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])</pre><p>This is a simple example of a CNN, it is not optimized for any specific task, you need to add more layers, tune the hyperparameters, etc. Also, you need to add the data preprocessing, data augmentation, and training for the model to be complete.</p><h3>10. Federated Learning Models:</h3><p>Federated Learning is a machine learning technique that<strong> allows multiple parties to train a shared model without exchanging sensitive data</strong>. It enables distributed data sources to pool their data and collaboratively train a model while keeping their data private and secure.</p><p>In federated learning, a central server acts as a coordinator, sending the model to multiple clients or devices (known as “nodes”) for local training. Each node trains the model on its data, and the updated parameters are sent back to the central server, where they are averaged to create a global model. This process is repeated several times until the model converges.</p><p>The key advantage of federated learning is that it<strong> enables data to be analyzed in a secure and privacy-preserving manner </strong>since data never leaves the client&#39;s devices. This is particularly useful in scenarios where data is sensitive or subject to privacy regulations.</p><p>There are several types of federated learning models, including:</p><ol><li><strong>Vertical Federated Learning:</strong> Where data samples have the same features but belong to different classes.</li><li><strong>Horizontal Federated Learning:</strong> Where data samples have the same features and belong to the same class but have different characteristics.</li><li><strong>Federated Transfer Learning:</strong> Where models are first trained on central data and then fine-tuned on local data.</li><li><strong>Federated Meta-Learning:</strong> Where models are trained on multiple federated datasets to achieve improved performance on a target dataset.</li></ol><p>Federated learning has been applied in various domains such as <strong>mobile devices, healthcare, and finance </strong>to name a few. It has the potential to democratize access to AI technologies and enable organizations to use advanced analytics without compromising privacy or security.</p><h3>11. QML</h3><p>Quantum Machine Learning (QML) refers to the intersection of quantum computing and machine learning, where<strong> quantum algorithms are used to enhance and speed up the training and prediction of machine learning models.</strong></p><p>Quantum computing has the potential to solve problems that are <strong>intractable with classical computers</strong>, and machine learning can leverage these capabilities to improve its performance. QML combines the strengths of these two fields to create new algorithms and models that can tackle large and complex data problems.</p><p>Quantum algorithms can be used in various stages of the machine learning pipeline, including<strong> feature extraction, dimensionality reduction, and model training.</strong> Some of the popular quantum algorithms used in QML include:</p><ol><li><strong>Quantum Principal Component Analysis (QPCA)</strong>: A quantum algorithm for finding the principal components of a data set, which is used for dimensionality reduction and feature extraction.</li><li><strong>Quantum Support Vector Machines (QSVM)</strong>: A quantum algorithm for training support vector machines, which are a type of linear classifier used for binary classification problems.</li><li><strong>Quantum Neural Networks (QNN)</strong>: A quantum algorithm for training neural networks, which are a type of deep learning model used for various machine learning tasks, including image classification and natural language processing.</li><li><strong>Quantum Boltzmann Machines (QBM)</strong>: A quantum algorithm for training restricted Boltzmann machines, which are a type of generative model used for unsupervised learning tasks.</li></ol><p>Quantum computing has the potential to significantly speed up the training and prediction of machine learning models, especially for large and complex data sets. However, quantum computing is still in its infancy and the development of QML algorithms and models is an active area of research.</p><p>In conclusion, QML has the potential to revolutionize the field of machine learning and lead to breakthroughs in areas such as computer vision, natural language processing, and drug discovery.</p><h3>12. Diffusion Models:</h3><p>Diffusion models are mathematical models used to <strong>describe the spread of information, ideas, diseases, or any other phenomenon through a population over time.</strong> These models simulate the flow of information or influence from one individual to another and predict the growth of the spread over time.</p><p>There are several types of diffusion models, including:</p><ol><li><strong>Susceptible-Infected-Recovered (SIR) models:</strong> These models describe the spread of diseases through a population and track the number of individuals who are susceptible, infected, and recovered over time.</li><li><strong>Susceptible-Infected-Susceptible (SIS) models:</strong> These models are similar to SIR models, but individuals can become infected again after recovering.</li><li><strong>Epidemiological models:</strong> These models describe the spread of diseases through populations and consider various factors such as vaccination, quarantine, and treatment.</li><li>Cascade models: These models describe the spread of information or influence through a network and consider the structure of the network, the influence of individuals, and the timing of events.</li><li><strong>Opinion dynamics models:</strong> These models describe the spread of opinions or attitudes through a population and consider factors such as social influence and peer pressure.</li></ol><p>Diffusion models are widely used in various fields such as epidemiology, marketing, and sociology. They can help to understand the dynamics of the spread and make predictions growth of the spread. However, diffusion models are often complex and can be challenging to fit into real-world data. In addition, they may not accurately reflect real-world behavior and may not account for all the relevant factors.</p><h3>13. Neural Network Layers:</h3><p>There are several types of neural network layers, each with its specific properties and uses. Some of the most commonly used types of layers are:</p><p><strong>13.1 Input Layer:</strong></p><p>The first layer of a neural network is where the input data is fed into the network. It does not perform any computation and it’s mainly used for reshaping the input data.</p><p><strong>13.2 Fully Connected Layer (also called Dense Layer):</strong></p><p>Each neuron in this layer is connected to every neuron in the previous layer. This layer is used to learn non-linear relationships between the input and output data.</p><p><strong>13.3 Convolutional Layer:</strong></p><p>A type of layer commonly used in image and video recognition. It applies a convolution operation to the input data, which helps to extract features from the data.</p><p><strong>13.4 Pooling Layer:</strong></p><p>A type of layer commonly used in image and video recognition. It reduces the spatial dimensions of the data by applying a pooling operation such as max pooling or average pooling.</p><p><strong>13.5 Recurrent Layer (RNN):</strong></p><p>A type of layer is used for sequential data, such as time series or text. It allows the network to maintain a “memory” of past inputs, allowing it to understand relationships between inputs over time.</p><p><strong>13.6 LSTM layer:</strong></p><p>A specific type of Recurrent layer is designed to handle the problem of vanishing gradients in traditional RNNs. LSTMs can remember information for long periods and can selectively choose to forget previous information, which allows them to be more effective in tasks such as language modeling, speech recognition, and natural language processing.</p><p><strong>13.7 Output Layer:</strong></p><p>The last layer of a neural network is where the final output of the network is produced. The output layer can have different forms based on the problem, for example, it could be a softmax layer for classification problems or a linear layer for regression problems.</p><p><strong>13.8 Embedding layer:</strong></p><p>It’s mainly used in NLP problems where it’s converting words into a dense vector that can be used as an input for the neural network.</p><p><strong>13.9 Batch Normalization layer:</strong></p><p>It’s used for normalizing the inputs of a layer, it can help in speeding up the training process and also reduce the variance of the weight updates.</p><p><strong>13.10 Dropout Layer:</strong></p><p>A regularization technique for reducing overfitting in neural networks by randomly setting a fraction of input units to 0 during the forward pass.</p><p>These are some examples of different types of neural network layers, other specific layers could be used depending on the problem and the architecture of the network.</p><h3>14. Revisiting how machines learn in more detail</h3><p>Near the start of this article, I told you how machines learned, but then you didn’t know as much…</p><p>So now, let’s revisit that and go deeper!</p><h4>14.1 The Bellman equation:</h4><p>The Bellman equation is a fundamental concept in <strong>dynamic programming and reinforcement learning</strong>. It is a recursive relationship that defines the optimal value of a decision-making process at each time step, given the optimal value of the next time step.</p><p>The Bellman equation is used to model the value of a decision-making process, represented by a function V(s), where s is the current state of the process. The function V(s) represents the expected cumulative reward of the decision-making process, starting from state s and following the optimal policy.</p><p>The Bellman equation can be defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*zMliz_EcgvpmkA3x" /></figure><ul><li><strong>V(s) is the value of the current state s</strong></li><li><strong>R(s, a) is the immediate reward for taking action on an in-state s</strong></li><li><strong>γ (gamma) is the discount factor, which determines the importance of future rewards</strong></li><li><strong>V(s’) is the value of the next state, s’, that results from taking action on an in-state s</strong></li><li><strong>max[a] represents the maximum value over all possible actions a</strong></li></ul><p>The Bellman equation can be used to find the <strong>optimal policy</strong>, which is the sequence of actions that maximizes the expected cumulative reward of the decision-making process. In practice, the Bellman equation is typically used in an iterative algorithm called dynamic programming, which is used to find the optimal value function and the optimal policy.</p><p>The Bellman equation is a fundamental concept in reinforcement learning and has been used to develop many different algorithms, such as Q-learning, SARSA, and Monte Carlo methods.</p><h4>14.2 Types of Supervised Learning:</h4><p>There are many types of supervised learning, so let’s get into them:</p><p>1. <strong>Transfer learning</strong>: pre-train on general, labeled dataset. Then fine-tune on target dataset.</p><p>2. <strong>Self-supervised learning:</strong> pre-train on unlabeled data, then fine-tune on target dataset.</p><p>3. <strong>Semi-supervised:</strong> train on a dataset that is partially labeled and partially unlabeled.</p><p>4. <strong>Few-shot learning:</strong> learn from a very small number of examples/classes (e.g., 1 or 5) using meta-learning, transfer learning, or metric-based methods.</p><p>5. <strong>Meta-learning:</strong> two definitions, a) either learn from meta-features, b) train a meta-learner in few-shot contexts</p><p>6. <strong>Active learning:</strong> actively select the most informative examples to be labeled by a human</p><p>7. <strong>Weakly supervised learning:</strong> create noisy, limited, or imprecise labels for a supervised learner</p><p>8. <strong>Multi-task learning:</strong> train with multiple losses to perform well on multiple tasks</p><h4>14.3 Unsupervised Learning</h4><p>Unsupervised learning is a type of machine learning where <strong>the system is not provided with labeled data</strong> and is instead asked to find patterns or relationships within the input data. The goal of unsupervised learning is to discover the underlying structure of the data, rather than to make predictions about the output.</p><p>There are several types of unsupervised learning, including:</p><ul><li><strong>Clustering:</strong> The goal of clustering is to group similar data points and identify patterns within the data. Clustering algorithms such as k-means and hierarchical clustering are used to classify data into different groups based on their similarities.</li><li><strong>Dimensionality reduction:</strong> The goal of dimensionality reduction is to simplify the data by reducing the number of features or attributes. This can be done by projecting the data onto a lower-dimensional space, or by removing redundant or irrelevant features. Common techniques include principal component analysis (PCA) and linear discriminant analysis (LDA).</li><li><strong>Association rule learning:</strong> The goal of association rule learning is to find relationships between variables in large datasets. This can be used to discover hidden patterns such as customer buying habits. The Apriori algorithm and Eclat algorithm are popular algorithms for this task.</li><li><strong>Anomaly detection:</strong> The goal of anomaly detection is to identify data points that are unusual or different from the majority of the data. This can be used to detect fraud, network intrusions, or other unusual events. Algorithms such as One-class SVM, Isolation Forest, and Local Outlier Factor (LOF) are used to detect anomalies.</li><li><strong>Generative models: </strong>These models are used to generate new data samples that are similar to the original data, such as Deep Belief Networks (DBN) and Generative Adversarial Networks (GANs).</li></ul><p>Unsupervised learning is a useful technique when the desired output is not known, or when the data is not labeled. It can also be used as a preprocessing step for supervised learning, where the discovered patterns can be used to improve the performance of a supervised learning algorithm.</p><p>It’s important to note that unsupervised learning is more complex than supervised learning as the model is not provided with labeled data to learn from, and this can make it more difficult to evaluate the performance of the model. Additionally, in unsupervised learning, the model does not have a clear criterion for success, so it is more difficult to know when to stop training the model.</p><h4>14.4 Clustering:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QikWjwXU35Qnr7-t.png" /></figure><p>Clustering is a method of unsupervised learning in machine learning, where the goal is to<strong> group a set of objects in such a way that objects in the same group (called a cluster) are more similar to each other </strong>than to those in other groups (clusters). It is used for exploratory data analysis, customer segmentation, pattern recognition, and anomaly detection.</p><p>There are different clustering algorithms, but some of the most common ones are:</p><ol><li><strong>K-Means</strong>: The algorithm partitions the data into K clusters based on their mean values.</li><li><strong>Hierarchical Clustering</strong>: The algorithm builds a hierarchy of clusters by successively merging or splitting existing clusters.</li><li><strong>DBSCAN (Density-Based Spatial Clustering of Applications with Noise)</strong>: The algorithm clusters together dense regions of points and separates sparse regions.</li></ol><p>The choice of the clustering algorithm and the number of clusters depends on the dataset, the problem, and the desired outcome. Clustering results can be evaluated using metrics such as silhouette score, the within-cluster sum of squares, and the Calinski-Harabasz index.</p><p>It is important to note that clustering is an unsupervised learning method, so the algorithm does not have access to labeled data and the cluster assignments have to be interpreted by the analyst.</p><h4>14.5 Dimensionality reduction</h4><p>Dimensionality reduction is the process of r<strong>educing the number of features (dimensions) in a dataset while retaining important information.</strong> It helps to reduce the computational cost and complexity of data analysis and visualization, and can also remove noise and irrelevant features in the data. This is achieved through techniques such as feature selection, feature extraction, and feature projection.</p><p>Dimensionality reduction can be approached in two main ways:<strong> feature selection and feature extraction.</strong></p><p>Feature selection involves <strong>choosing a subset</strong> of the original features to use in further analysis.</p><p>Feature extraction<strong> creates new features</strong> that are a combination of the original features, where the new features are typically a lower-dimensional representation of the original data. Some popular techniques for feature extraction include:</p><ol><li><strong>Principal Component Analysis (PCA):</strong> a linear technique that finds the most important directions in the data, called principal components and projects the data onto these components.</li><li><strong>Singular Value Decomposition (SVD):</strong> a linear technique that decomposes the data matrix into its singular values and vectors.</li><li><strong>t-Distributed Stochastic Neighbor Embedding (t-SNE):</strong> a non-linear technique that maps the data into a lower-dimensional space while preserving the structure of the data.</li><li><strong>Autoencoders:</strong> a neural network architecture that is trained to compress the input data into a lower-dimensional representation, and then reconstruct the original data from this lower-dimensional representation.</li></ol><p>Dimensionality reduction is commonly used in many applications such as image compression, pattern recognition, and feature selection in machine learning.</p><h3>15. Types of ML Models:</h3><p>You may have not known but there are types of ML models! So I am just going to explain those here…</p><h3>15.1 KNN</h3><p>KNN’s purpose is to <strong>use a database in which the data points are separated into several classes to predict the classification of a new sample point.</strong></p><p>KNN falls under lazy learning, this means that there is no proper training phase before classification. This is quite similar to the real world as most of the data does not match up with the assumptions made — in other models for instance.</p><p>CNN is a popular choice for a classification study when little is known about the distribution of a data set.</p><p><strong>How does it work?</strong></p><p>KNN has 3 main steps</p><p><strong>1. Compute a distance value between the item to be classified with every item in the training data set</strong></p><p><strong>2. Pick the k-closest data point/ item</strong></p><p><strong>3. Conduct a “majority vote” among the data points. The dominating classification in that pool is decided as the final classification.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*tFjjj0HMnKo3snYS" /></figure><p>The test sample (inside a circle) should be classified either to the first class of blue squares or to the second class of red triangles. If k = 3 (outside circle) it is assigned to the second class because there are 2 red triangles and only 1 blue square inside the inner circle. If k = 1, for example, it would be classified as class 1 as there is 1 blue square and 0 red triangles.</p><p>2 questions arise:</p><p><strong>How do you compute the distance?</strong></p><p>There are multiple ways to compute the difference but the 2 main ones are:</p><p><strong>euclidian distance</strong></p><p>This is the <strong>magnitude of the vector</strong>, we get this by taking away the training data point from the point to be classified.</p><p>this can be determined by the equation below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/0*tpZmWDgWqA1KV41r.gif" /></figure><p>x and y are the coordinates of a given data point (assuming the data lie nicely on a 2D plane — if the data lies in a higher dimensional space, there would just be more coordinates).</p><p><strong>cosine similarity</strong></p><p>cosine similarity uses the <strong>difference in directions of 2 vectors using the equation bellow</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/0*WIZnxVU-_11AevGf.png" /></figure><p><strong>How do you find the value of k?</strong></p><p>A small value of k will mean that <strong>noise will have a higher influence on the result</strong> and a large value will make it computationally expensive</p><p>Normally data scientists choose an odd number if the number of classes is 2 and another simple approach to select k is to set <strong>k=sqrt(n).</strong></p><p>Another method is to use<strong> cross-validation</strong>, we chose a value of k and compare their corresponding accuracy to find the most optimal value for k</p><p>After doing all of the above and deciding on a metric, the result of the kNN algorithm is a<strong> decision boundary that partitions the space of the feature vectors that represent our data set into sections</strong>. Then, we can<strong> calculate the most likely class for a hypothetical data point in that region</strong>, and we thus color that chunk as being in the region for that class.</p><h4>15.2 Logistic Regression(which has been mentioned)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*yes4gEH9fFcnB-eB.png" /></figure><p>The linear equation for the above curve can be represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/0*y8gp41uO6Bi9zWxV.png" /></figure><p>depending on the value of x, <strong>the output can be anything.</strong> It can be from -infinity to +infinity. However we have a problem, 1 means that the cancer is malignant, and 0 means that the cancer is benign. This means our output can only take values of 0 and 1.</p><p>so to make sure that it only takes those values, we can <strong>squeeze this function into a sigmoid function.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/0*qy2qzLOKpdGyw4HQ.png" /></figure><p>commonly, we take the probability cutoff as 0.5. If the probability of Y is &gt; 0.5, then it can be classified as an event.</p><h4>15.3 Naïve Bayes</h4><p>This is based on <a href="https://corporatefinanceinstitute.com/resources/data-science/bayes-theorem/">Bayes’ theorem</a> and assumes independence among predictors. It assumes the presence of a particular feature in a class unrelated to the presence of any other feature.</p><p>Bayes’ theorem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*hdhd4GOf4X9TTHSN.png" /></figure><ul><li><strong>P(A|B) — the probability of event A occurring, given event B has occurred</strong></li><li><strong>P(B|A) — the probability of event B occurring, given event A has occurred</strong></li><li><strong>P(A) — the probability of event A</strong></li><li><strong>P(B) — the probability of event B</strong></li></ul><h4>15.4 Random forest classification</h4><p>firstly, let&#39;s look at a decision tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*o-LuRDH9b5LytsHb" /></figure><p>a decision tree is upside down with its root at the top and looks something like the image above</p><p>now let&#39;s look at this data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/0*lCfRfNep6Eq1AS9E.png" /></figure><p>A simple decision tree built on this data will it<strong>eratively split the data along one or the other axis according to some quantitative criteria.</strong> At each level, the label of a new region would be assigned according to the majority of votes of points within it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*ircMUYZIBKImrLTD.png" /></figure><p>However, we have a slight problem if we continue splitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/0*BB920rI7dU7RHO6m.png" /></figure><p>As you can see, there is a purple region between the yellow and blue regions, this means that we are overfitting our data.</p><p>In some places, the <strong>two trees produce consistent results</strong>, while in other places, the two trees give very different classifications.</p><p>so by using the info from both trees we come up with a better result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*aBVxRVrq50ML3HtB.png" /></figure><p>The higher the number of trees in the forest gives the high the accuracy results.</p><h4>15.5 SVM</h4><p>So we need to <strong>draw a line</strong> to separate the circles and the squares, pretty simple right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*uTxdPDPzXZlBUsxq.png" /><figcaption><a href="https://medium.datadriveninvestor.com/machine-learning-basics-support-vector-machines-358235afb523">https://medium.datadriveninvestor.com/machine-learning-basics-support-vector-machines-358235afb523</a></figcaption></figure><p>But what do we do with complex data like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*7p1Ynm-LNH6TZfmF.png" /><figcaption><a href="https://medium.datadriveninvestor.com/machine-learning-basics-support-vector-machines-358235afb523">https://medium.datadriveninvestor.com/machine-learning-basics-support-vector-machines-358235afb523</a></figcaption></figure><p>Instead of looking at our data from an XY plane perspective, we can <strong>flip</strong> the plot around. now we are on the YZ plane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*gkJfW9rOrf3XxLY1.png" /><figcaption><a href="https://medium.datadriveninvestor.com/machine-learning-basics-support-vector-machines-358235afb523">https://medium.datadriveninvestor.com/machine-learning-basics-support-vector-machines-358235afb523</a></figcaption></figure><p>When we flip it back, it creates a <strong>circle boundary</strong>, these transformations are called kernels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*210jIzb7L3_5rX4N.png" /><figcaption><a href="https://medium.datadriveninvestor.com/machine-learning-basics-support-vector-machines-358235afb523">https://medium.datadriveninvestor.com/machine-learning-basics-support-vector-machines-358235afb523</a></figcaption></figure><p>So basically we want to find a<strong> hyperplane in N-dimensional space</strong> (N — the number of features) that distinctly classifies the data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*PdtbeV6cU2kK8kWx.png" /><figcaption><a href="https://medium.datadriveninvestor.com/machine-learning-basics-support-vector-machines-358235afb523">https://medium.datadriveninvestor.com/machine-learning-basics-support-vector-machines-358235afb523</a></figcaption></figure><p>We want to find a plane that <strong>has the maximum margin</strong>, maximizing the margin distance provides some reinforcement so that future data points can be classified with more confidence.</p><p>And that&#39;s it! For today…</p><p>But that is it for today!</p><p>There is ALWAYS more to learn. But you have learned A LOT</p><p>AI is a topic that many people fear</p><p>It is also one which many people do not understand and I hope that you are not one of those people</p><p>There has been a lot of info in this article, so I hope you loved reading it as much as I loved writing it!</p><p>Hi, here is a note from the writer of this article: Hi readers, I am a 13-year-old girl in the UK and would love your support. Thank you for reading this and I would love it if you checked out some of my other articles as well!</p><p>Please check out my monthly newsletter: <a href="https://substack.com/profile/106867284-vidushi-valli-surendran">https://substack.com/profile/106867284-vidushi-valli-surendran</a></p><p>Also here is my LinkedIn:</p><p><a href="https://www.linkedin.com/in/vidushi-valli-surendran-075a06250/">https://www.linkedin.com/in/vidushi-valli-surendran-075a06250/</a></p><p>And my personal website:</p><p><a href="http://vidushivs.com/">vidushivs.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b626c1f29085" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The maths behind CNNs]]></title>
            <link>https://vidushi-valli-surendran.medium.com/the-maths-behind-cnns-67f05d34d0fe?source=rss-1c2ea4bc3f60------2</link>
            <guid isPermaLink="false">https://medium.com/p/67f05d34d0fe</guid>
            <dc:creator><![CDATA[Vidushi Valli Surendran]]></dc:creator>
            <pubDate>Mon, 26 Dec 2022 18:40:26 GMT</pubDate>
            <atom:updated>2022-12-26T18:40:26.876Z</atom:updated>
            <content:encoded><![CDATA[<p>The human brain can do all kinds of crazy stuff that we don’t think is all that amazing. We can tell if a number is a 3 or 2 and we can tell the difference between a Christmas tree and a normal tree. Most importantly to this article we can group red circles together and yellow circles together, our brain can easily tell the difference.</p><p>CNNs are neural networks that mimic the brains way of classifying images, such as single digit numbers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*jd0NmZUzDzBTlseB" /></figure><p>What does the image above mean? Let’s go through it.</p><h4>STEP 1: Convolution</h4><p>In convolution we multiply the input image by the kernel/filter creating an output matrix.</p><p>We can get the values in the output matrix by sliding the kernel on the input matrix.</p><p>When this process is repeated with many different areas, it creates the first layer in the CNN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*nOySfg5otzJnmDgx" /></figure><h4>STEP 2: Pooling</h4><p>Since the matrix is very big, when we perform step 1 it is computationally expensive. So we take the most important parts of our convolved matrix or the average by pooling to reduce the dimensions of the feature maps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*-DgE2clqWSL-woFZ" /></figure><p>This makes it less computationally expensive</p><h4>STEP 3: ReLU</h4><p>Rectified linear units return 0 if it receives a negative input, and if it receives a positive value they will return back the same positive value</p><p>The function is understood as:</p><p>f(x)=max(0,x)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*2YJQ3pxuva4BjXrM.jpg" /></figure><p>graphic representation of the ReLU function</p><p>ReLUs can be applied to minimize interaction effects. For example, if A=1 and B=2, and both have the respectively associated weights of 2 and 3, the function would be, f(2A+3B). If A increases, the output will increase as well. However, if B is a large negative value, the output will be 0.</p><p><strong>PReLU Function, a Variation on the ReLU</strong></p><p>Because of the zero gradient problem faced by the ReLU, we can use an adjusted ReLU function called the parametric rectified linear unit, or PReLU: This has the advantage that the gradient is nonzero at all points (except 0 where it is undefined). The PReLU function with α set to 0.1 avoids the zero gradient problem.</p><h4>STEP 4: Dropout</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OTYCg9FohDu_9MOk.png" /></figure><p>In deep neural networks a major problem is co-adaptation. When all the weights are learned together some of the connections end up having a larger predictive capability than others so you’ve only really trained part of your neurons.</p><p>This means that the neural network is fine with this set of data but it hasn’t learned anything so with similar but new data its lowkey useless. This is caused by the model overfitting the data — IT HAS 0 FLEXIBILITY</p><p>So that’s why in dropout neurons are randomly selected in a neural net and “dropped out” so that the network learns a fraction of the weights at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/0*J91obaBtgVQ89L-t" /></figure><p>To use this in your neural network you need a dropout ratio, which is a hyperparameter that the human sets for the machine. So if it were 0.5, half would be dropped out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*7BySdW5eDgxVhJnX.png" /></figure><h4>STEP 5: SoftMax</h4><p>This is the activation function for the CNN. once it receives the outputs given by the neural network it flattens and converts them to a set of probability values we are attempting to predict.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*zDytX1bMsDq2LY_-" /></figure><p>Afterwards we use argmax — this takes the largest number of the probability values out of the vector.</p><p>We pick the biggest probability value which outputs some sort of digit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*nfCJ2h-5Co1lDOTX.png" /></figure><h4>STEP 6:Backpropagation:</h4><p>This is basically just using whatever we have learned to update the weights so that we can make better predictions, we do this again and again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/0*uhTQE_MrM78dlcqm" /></figure><p>AND WERE DONE!!!!</p><p>Thank you guys for reading, I have explained more about neural networks in the past so feel free to check those out!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67f05d34d0fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting breast cancer using ML models]]></title>
            <link>https://vidushi-valli-surendran.medium.com/detecting-breast-cancer-using-ml-models-d5354c8deab2?source=rss-1c2ea4bc3f60------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5354c8deab2</guid>
            <dc:creator><![CDATA[Vidushi Valli Surendran]]></dc:creator>
            <pubDate>Sun, 25 Dec 2022 16:13:58 GMT</pubDate>
            <atom:updated>2022-12-25T16:14:14.009Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Cancer: the deadliest disease in the world right now.</strong></p><p>What are we trying to do? We are merging the power of AI and our intelligence to optimize the diagnosis process in breast cancer. The American Cancer Society’s estimates for breast cancer in the United States for 2022 are: About <strong>287,850 new cases of invasive breast cancer</strong> will be diagnosed in women.</p><p>Today I will discuss how we can use different ML models to detect breast cancer</p><h3>STEP 1: download the dataset</h3><p>I downloaded <a href="http://archive.ics.uci.edu/ml/datasets/breast+cancer+wisconsin+%28diagnostic%29">this dataset</a>, this is our learning data. This dataset was created by Dr. William H. Wolberg. He analyzed the cancer cell samples using Xcyt(a computer program) to perform analysis on the cell features based on the scan. The program returned 10 features of each of the cell within each sample and computed mean value, extreme value and standard error of each feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_CzIiEByhLvWrFnm.jpg" /></figure><h3>STEP 2: explore the data</h3><p>now we import out libraries (I imported them into VScode). Pandas is one of the Python packages that makes importing and analyzing data much easier.</p><p>If you do not have the libraries, in the terminal type:</p><pre>pip3 instal numpy <br>pip3 instal matplotlib<br>pip3 instal pandas</pre><p>now to import the libraries:</p><pre>#libraries<br><br>import pandas as pd <br>import numpy as np <br>import matplotlib.pyplot as plt </pre><p>now we import the dataset</p><pre>#import the dataset<br><br>dataset = pd.read_csv (&#39;c: wpbc.data&#39;)<br>x = dataset.shape (1,31).values <br>y = dataset.shape(0,31).values</pre><p>the dataset.shape() attribute helps us find the dimensions of the dataset.</p><p>finally…</p><pre>dataset.head()</pre><p>this runs the top 5 rows of data by default</p><p>There is a total of 569 rows and 32 columns. In the column that represents diagnosis, we can observe that 357 of the sample is benign, and 212 of the sample is malignant.</p><h3>STEP 3: categorize the data</h3><p>As we are dealing with categorical data, we have labelled values, we use label encoder to label our data.</p><pre>dataframe = pd.DataFrame(y)<br><br>#encoding categorical data values <br>from sklearn.preprocessing import LabelEncoder<br>LabelEncoder_y = LabelEncoder()<br>y = LabelEncoder_y.fit_transform(y)</pre><p>here we have imported the <strong><em>Sci-Kit Learn Library </em></strong>and used the label encoder to convert text data to numerical data so our models can understand it more easily.</p><p>Sci-kit Learn Library also allows us to split our data set into <em>training set </em>and <em>test set. </em>The purpose of this is to later validate the accuracy of our machine learning model.</p><p>to do this we use the train_test_split method:</p><pre>from sklearn.model_selection import train_test_split<br>x_train, x_test, y_train, y_test = train_test_split(x, y, test_size= 0.25, random_state= 0)</pre><h3>PHASE 4: selecting the model</h3><p>since we are classifying 2 different classes of cancer, I tried out many different types of algorithms in ML:</p><h3>KNN</h3><p>KNN’s purpose is to use a database in which the data points are separated into several classes to predict the classification of a new sample point.</p><p>KNN falls under lazy learning, this means that there is no proper training phase before classification. This is quite similar to the real world as most of the data does not match up with the assumptions made — in other models for instance.</p><p>kNN is a popular choice for a classification study when little is known as the distribution of a data set.</p><h4><strong>How does it work?</strong></h4><p>KNN has 3 main steps</p><p>1.Compute a distance value between the item to be classified with every item in the training data set</p><p>2. Pick the k closest data point/ item</p><p>3. Conduct a “majority vote” among the data points. The dominating classification in that pool is decided as the final classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*Ol5Y1nr1OX9XB_ih" /><figcaption>The test sample (inside circle) should be classified either to the first class of blue squares or to the second class of red triangles. If k = 3 (outside circle) it is assigned to the second class because there are 2 red triangles and only 1 blue square inside the inner circle. If k = 1, for example, it would be classified as class 1 as there is 1 blue square and 0 red triangle.</figcaption></figure><p>2 questions arise:</p><h4><strong>How do you compute the distance?</strong></h4><p>There are multiple ways to compute the difference but the 2 main ones are:</p><p><strong>euclidian distance</strong></p><p>This is the magnitude of the vector, we get this by taking away the training data point from the point to be classified.</p><p>this can be determined by the equation below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/0*yi5dTPG_BGOBM7mM.gif" /></figure><p>x and y are the coordinates of a given data point (assuming the data lie nicely on a 2D plane — if the data lies in a higher dimensional space, there would just be more coordinates).</p><p><strong>cosine similarity</strong></p><p>cosine similarity uses the difference in directions of 2 vectors using the equation bellow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/0*cmMYAUlCeXRA30XA.png" /></figure><h4><strong>How do you find the value of k?</strong></h4><p>a small value of k will mean that noise will have a higher influence on the result and a large value will make it computationally expensive</p><p>Normally data scientists choose as an odd number if the number of classes is 2 and another simple approach to select k is set k=sqrt(n).</p><p>Another method is to use cross validation, we chose a value of k and compare their corresponding accuracy to find the most optimal value for k</p><p>After doing all of the above and deciding on a metric, the result of the kNN algorithm is a decision boundary that partitions the space of the feature vectors that represents our data set into sections. Then, we can calculate the most likely class for a hypothetical data-point in that region, and we thus<strong> color </strong>that chunk as being in the region for that class.</p><pre># fitting K-NN algorithm <br>from sklearn.neighbors import KNeighborsClassifier<br>classifer = KNeighborsClassifier(n_neighbors=5, metric=&#39;minkowski&#39;, p=2)<br>classifer.fit(x_train, y_train)</pre><p>95.1% accuracy</p><h3>Logistic Regression</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YSEWpPHc2xn605ty.png" /></figure><p>The linear equation for the above curve can be represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/0*-v2bpdWXYz4le2fz.png" /></figure><p>depending on the value of x, the output can be literally anything. It can be from -infinity to +infinity. However we have a problem, 1 means that the cancer is malignant, and 0 means that the cancer is benign. This means out output can only take values of 0 and 1.</p><p>so to make sure that it only takes those values, we can squeeze this function into a sigmoid function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/0*-8b9G6uNggOlZqJQ.png" /></figure><p>commonly, we take the probability cutoff as 0.5. If the probability of Y is &gt; 0.5, then it can be classified an event (malignant).</p><p>we use the Sci-kit Learn Library to import all algorithms and we use the logistic regression method</p><pre>#fitting logistic regression<br>from sklearn.linear_model import LogisticRegression<br>classifier = LogisticRegression(random_state = 0)<br>classifier.fit(x_train, y_train)</pre><p>The accuracy was 95.8%</p><h3>Naïve Bayes</h3><p>This is based on <a href="https://corporatefinanceinstitute.com/resources/data-science/bayes-theorem/">Bayes’ theorem</a> and assumes independence among predictors. It assumes the presence of a particular feature in a class unrelated to the presence of any other feature.</p><p>Bayes’ theorem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*FEa_KMNAknQmKFHq.png" /></figure><ul><li>P(A|B) — the probability of event A occurring, given event B has occurred</li><li>P(B|A) — the probability of event B occurring, given event A has occurred</li><li>P(A) — the probability of event A</li><li>P(B) — the probability of event B</li></ul><p><strong>How does this apply to our problem?</strong></p><p>Naive Bayes will calculate the probability for the features of the cell that contribute to cancer. Then it will select either malignant or benign based on which has the highest probability.</p><pre>#fitting Naive_bayes<br>from sklearn.naive_bayes import GaussianNB<br>classifer = GaussianNB()<br>classifer.fit(x_train, y_train)</pre><p>91.6% accuracy</p><h3>Random forest classification</h3><p>firstly, lets look at a decision tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*xZSzup04O6RYCTbN" /></figure><p>a decision tree is upside down with its root at the top, and looks something like the image above</p><p>now lets look at this data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/0*vOW2VEPqxAuj6nA9.png" /></figure><p>A simple decision tree built on this data will iteratively split the data along one or the other axis according to some quantitative criteria. At each level, the label of a new region would be assigned according to the majority of vote of points within it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s2iGpZ639giCC1Dh.png" /></figure><p>However, we have a slight problem is we continue splitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/0*4c-oJd8SDGRwLk6P.png" /></figure><p>As you can see, there is a purple region between the yellow and blue regions, this means that we are overfitting our data.</p><p>In some places, the two trees produce consistent results, while in other places, the two trees give very different classifications.</p><p>so by using the info from both trees we come up with a better result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z0lXCH7hIOztH-ki.png" /></figure><p>The higher the number of trees in the forest gives the high accuracy results.</p><pre>#fitting random forest classification algorithm <br>from sklearn.ensemble import RandomForestClassifier<br>classifer = RandomForestClassifier(n_estimators= 10, criterion=&#39;entropy&#39;, random_state= 0)<br>classifer.fit(x_train,y_train)</pre><p>this gave us 98.6% accuracy</p><h3>SVM</h3><p>So we need to draw a line to separate the circles and the squares, pretty simple right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*NHfE4VCMyGsw3OTg.png" /></figure><p>But what do we do with complex data like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*qGQXlYHLY0ROYMOG.png" /></figure><p>Instead of looking at our data from a XY plane perspective, we can flip the plot around. now we are on the YZ plane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*EI1phcnge47F8xIk.png" /></figure><p>When we flip it back, it creates a circle boundary, these transformations are called kernels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*uhmnaf-USm7Ly3KN.png" /></figure><p>So basically we want to find a hyperplane in an N-dimensional space (N — the number of features) that distinctly classifies the data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*viu8RKIABukx0sMP.png" /></figure><p>We want to find a plane that has the maximum margin, maximizing the margin distance provides some reinforcement so that future data points can be classified with more confidence.</p><pre>#fitting SVM<br>from sklearn.svm import SVC<br>classifier = SVC(kernel = &#39;linear&#39;, random_state = 0)<br>classifer.fit(x_train, y_train)<br>#97.2% accuracy <br><br>#fitting K-SVM<br>from sklearn.svm import SVC <br>classifier = SVC(kernel = &#39;rbf&#39;, random_state = 0)<br>classifer.fit(x_train, y_train)<br>#96.5% accuracy</pre><p>so in conclusion, random forest classification provides the most accurate results!</p><p>hope you enjoyed this article, thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5354c8deab2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>