<?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 Alexander Yevchenko on Medium]]></title>
        <description><![CDATA[Stories by Alexander Yevchenko on Medium]]></description>
        <link>https://medium.com/@alexanderyevchenko?source=rss-fc132341b04d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mUbHEBlPmsy-5d-5CQKmcw.png</url>
            <title>Stories by Alexander Yevchenko on Medium</title>
            <link>https://medium.com/@alexanderyevchenko?source=rss-fc132341b04d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 18:38:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexanderyevchenko/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[The Global Food Crisis: Addressing Corn Disease with Computer Vision]]></title>
            <link>https://medium.com/@alexanderyevchenko/the-global-food-crisis-addressing-corn-disease-with-computer-vision-74edc76e949?source=rss-fc132341b04d------2</link>
            <guid isPermaLink="false">https://medium.com/p/74edc76e949</guid>
            <category><![CDATA[food]]></category>
            <category><![CDATA[crops]]></category>
            <category><![CDATA[farming]]></category>
            <category><![CDATA[hunger]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Alexander Yevchenko]]></dc:creator>
            <pubDate>Sat, 17 Dec 2022 01:49:37 GMT</pubDate>
            <atom:updated>2022-12-31T16:21:58.440Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Global Food Crisis: Addressing Disease with Computer Vision</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*8V83xKTBvtGKBcOO" /><figcaption><a href="https://unsplash.com/photos/JYU14tnbfOA">Unsplash</a></figcaption></figure><blockquote>If we’re going to feed the 10 billion people roaming the Earth by the 2080’s, we need better ways of growing food efficiently.</blockquote><p><strong>The Needs of a Growing World</strong></p><p>You’ve probably heard the stat that more than 40% of food gets wasted — whether consumers throw it out after cooking their meals or it rots in the 18-wheeler headed towards your local Walmart. It’s true, the way we store and transport our food is extremely wasteful and deserves a closer examination. This renewed interest in the topic is especially warranted in the face of the hunger crises purging countries like the US, with one in five Americans relying on a food bank for their weekly calorie intake. After all, how can it make sense that we have food expire while not meeting the needs of a nation?</p><p>Taking on a global scope, we understand that the planet produces more than enough food to provide everyone on the planet with sufficient calories, yet there are more than a billion people globally who suffer from malnourishment. For a large part of these consumers, this is a problem of access. They can’t grow enough food for their families and they can’t buy food because they lack adequate disposable income. Malnourishment drives fatigue, which reduces ability to work and earn money, thus perpetuating a cycle of poverty at the individual, familial, and societal levels.</p><p>But that’s just it — one of the main reasons people struggle to put food on the table is because it’s too expensive. Whether due to rising inflation or trade wars, the tiniest fluctuations in the price of food determine whether or not a family is able to eat. The invasion of Ukraine is also having a major effect on some of the world’s poorest economies, which were already struggling with rising food costs. Ukraine exported more than 36% of the world’s wheat, mostly to African nations. With 40% of consumer spending already being allocated to food across sub-Saharan Africa and an 85% reliance on imported wheat, it’s clear to understand that there will be major price hikes, cutting out millions who were already barely scraping by.</p><p>What if, somehow, we could make food <em>cheaper</em>? It seems like quite a daunting task given the state of the world we’re in, but it’s a valid question that we should consider.</p><p>Going back to my economics homework, price is dictated by supply and demand. Clearly, demand is very high — people are dying of starvation, so there’s clearly a need to be met. The problem is that supply is low, especially in low income countries across sub-Saharan Africa and Asia. Naturally, this means that prices will skyrocket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*Za9QqBoId3aPih1pFrSpJQ.png" /><figcaption><a href="https://www.ers.usda.gov/data-products/chart-gallery/gallery/chart-detail/?chartId=105209">USDA ERS</a></figcaption></figure><p>For example, the prices of staple foods in sub-Saharan Africa surged by an average of 23.9% between 2020–2022, leaving 140 million people on the continent acutely hungry.</p><p>Assuming that we can’t decrease demand for food (in fact, demand will continue to increase as we progress to over 10 billion people on the planet), the only factor that we can control is supply. How do we grow more food that can reach more people, which would hypothetically bring down global prices?</p><p>To me, it sounds like a win-win. More food being grown makes global commodity markets more competitive, with producers looking to undercut one other and sign deals on exports. As a result of further competition, importing nations will benefit from lower prices, which in turn lowers food acquisition costs for their citizens and allows them to increase imports to adequately support the needs of burgeoning populations.</p><p>To understand how we could go about approaching an answer to this question, we first need to understand the methods we currently use to produce crops and build solutions for gaps that could plausibly boost yields in the years to come.</p><p><strong>Current Production Methods</strong></p><p>Food, like just about everything in our modern economy, has become industrialized. From the first domestication of plants and animals, humans have been looking for ways to make farming more efficient. We’ve been incorporating technology into our food production since the Middle Ages, when inventions like the plough, wind and water powered mills and a decline in feudalism allowed food production to rise by over 250% to meet the growing demands of urban populations.</p><p>Many of the world’s most produced crops, including rice, maize and wheat, were promoted into world markets by the Green Revolution. This was an initiative started in the mid-20th century to combat starvation worldwide by planting high-calorie staple crops and introducing modern farming techniques. As a result, the production of the aforementioned staple crops topped 2.68 billion metric tons in 2020.</p><p>In many developed nations, there’s an established cycle of what the farming year looks like. The winter is reserved for planning the upcoming season, including field planning, purchasing seeds, fertilizers and pesticides, as well as sorting out financial situations. As spring rolls around, farmers prepare the land using specialized equipment, planting seeds in ideal conditions for growth. Summer may include harvesting of some types of crops, but mainly consists of monitoring fields for diseases and making any decisions necessary on treatment options. Finally, as the season concludes in the fall, farmers harvest their crop, till fields and take measurements of field health to understand what types of crops to plant in the upcoming season.</p><p>One of the questions I had during my research asked how farming differed in the developing world, the understanding of which might lead to relevant gaps in the system that needed to be addressed to get nations up to speed. Like many other symptoms, the root cause of the difference was poverty.</p><p>The Democratic Republic of the Congo (DRC) is a great example of this problem. It’s the second largest country by land mass in Africa and ranks fourth in population on the continent. Its material wealth is vast, with large reserves of precious metals like gold and cobalt, as well as large diamond mines. Unlike many of the Gulf countries that derived their wealth from oil and prospered, the DRC also has over 80 million hectares of arable land. To put this into perspective, this is over <strong>half of the total arable land in the US.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*cnsA8VaIaFe4XADx" /><figcaption>Children at a WFP camp, awaiting a meal. <a href="https://www.wfp.org/countries/democratic-republic-congo">World Food Program</a></figcaption></figure><p>Despite all of these advantages, the country still struggles to feed itself. The majority of the population lives under severe food insecurity, and child malnourishment is rampant. People rely on international aid organizations for their only meals of the day.</p><p>Surprisingly, over 70% of the population is employed in the agricultural sector, which mountains over the US’ measly 1.4% in 2020. This is due to the fact that most of the population engages in subsistence farming, planting crops like bananas, peanuts and cassava to feed their own families. The little food they’re able to produce without knowledge of modern farming techniques and a lack of adequate fertilizers and pesticides isn’t enough to feed their families, and must therefore look to imported foods to supplement their diets, which is often too expensive to afford. In addition, only about 10 million of the 80 million arable hectares in the DRC are used for food production. There’s much room for the expansion of agricultural fields into previously unused lands to provide sustenance for both the population of the country and to bolster the economy off of exports, rather than being reliant on costly imports.</p><p>It’s important to note that there is very little commercial farming in the DRC, with the most important export being coffee. Most plantations are owned by foreign organizations or elites within the nation, providing a few jobs but keeping money in the hands of the already wealthy. The country lacks access to tools like farming grants and loans, fertilizers and pesticides, and infrastructure like silos and tractors that have transformed the way farming exists in most of the world.</p><p>The solution isn’t as easy as giving people microloans, training, and access to foreign resources to get them back on their feet. The principal root cause for the lack of development in the country is the brutal civil war that continues on to this day, which is estimated to have claimed upwards of 6 million lives. More than 5.5 million people around the country are internally displaced, putting strain on families that were already short on food before lending a helping hand.</p><p>International aid organizations have played a major role in the response to the hunger crisis. The World Food Programme alone has helped more than 700,000 people facing acute hunger with cash and food supplies, and is estimated to require over $108 million USD in funding to sustain its mission through 2022. The UN Humanitarian Response Plan allocated more than $1.88 billion USD in the same year. While these programs have helped countless people and their families survive through hunger, they haven’t led to any real change in the lives of the people. Over 40 years of providing humanitarian support to the country, the Human Development Index has only risen by 0.15.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*rFt2KS4gnLdccXRc" /><figcaption>HDI of the DRC 1980–2020. <a href="https://www.theglobaleconomy.com/Democratic-Republic-of-the-Congo/human_development/">The Global Economy</a></figcaption></figure><p>Moreover, the country can’t be dependent on foreign aid to sustain its existence. At some point, there needs to be a transition from receiving to buying foreign food, as well as a shift from largely small-scale, sustenance farming to commercial operations that have the capacity to feed larger swaths of people.</p><p>When considering how to go about this, the second point seems more intensive and would require scale and capital to achieve. This is the approach that many aid organizations are taking — training farmers in better growing techniques and encouraging local markets to boost internal production and purchasing. Of course, there are a variety of challenges when solving for this problem, mainly the issues of internal displacement and civil war destroying output. Given that the UN has had peacekeepers in the country for over 20 years, it doesn’t seem as if this aspect of the fold is going to go away anytime soon, making it difficult to implement long-term solutions.</p><p>The first perspective makes more sense. Given that the country currently imports more than 80% of its total domestic food consumption, lowering the price of imports would make food more accessible to people right away, rather than waiting for agricultural development that could take decades to implement. Moreover, lowering the cost of imports would reduce the strain on foreign aid programs, allowing them to focus on the poorest areas in need of the greatest assistance.</p><p>This case is mirrored across developing nations around the world — they’re working on becoming agriculturally independent, but in the meantime require imports to support their people. To me, this is the most obvious and immediate solution to their hunger problem while they build resilient agricultural systems.</p><p>How would one lower the price of imports? A variety of propositions are possible, from negotiating better trade agreements to lowering tariffs and optimizing shipping costs, but the one that appears most blatant to me is simply lowering the cost of production.</p><p>Optimizing for production of staple crops makes the most sense, as they make up the largest percentage of food eaten around the world. Production type, capacity, and methods vary from region to region, thus it is particularly useful to focus on one geography to dive into root causes, and scale a solution to a larger market after having solved for one segment.</p><p><strong>Zoom into Corn Production in the U.S.</strong></p><p>Why address the US? The reason is quite simple — it’s the world leader in both corn production and corn exports, with a 346 million metric ton yield being produced during the 2019–2020 season.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/0*Ouy4uzAH2-2kHIJp.png" /><figcaption>The United States Corn Belt. <a href="https://www.nass.usda.gov/Charts_and_Maps/Crops_County/cr-pr.php">NASS USDA</a></figcaption></figure><p>The US’ productive capacity of corn is due to the agricultural richness of the Corn Belt, and area that spans over 200,000 km² across the Midwest. The land is rich in organic material and nitrogen, is flat, and experiences warm temperatures day and night with moderate rainfall, perfectly suited for the production of corn.</p><p>Production levels aren’t solely due to the fertility of the land. Corn is the most heavily subsidized crop in the US, with annual payments to farmers averaging $16 billion USD over the past decade. These subsidies were first used to levelize the price of corn during the Great Depression, and have been in place ever since. Farmers use these subsidies to purchase farming necessities and improve farming techniques without having to pass the additional cost down to the consumer.</p><p>Around 60% of the corn produced in the US and used domestically goes toward food, seed and industrial (FSI) uses. The largest portion of this usage is utilized in the production of ethanol, an alcohol that is included in more than 98% of commercial US gasoline. The remaining 40% is used for livestock feed, although this number varies based on the price competitiveness of corn with other feed.</p><p>Land allocation for corn production has steadily risen over the years, and now makes up over 3.7% of America’s total land mass. Corn yields risen from an average of 26 bushels per acre in the late 1800s to 174 bushels per acre between 2016 and 2021, a sixfold increase. This is all thanks to modern farming techniques, specialized labour and advanced science and engineering that have emerged over the years to put food on the tables of growing populations.</p><p>While this miracle of human genius has fundamentally redefined the potential human population on Earth, it still faces its drawbacks. As farmland is repeatedly used, it loses its efficacy in crop production as its natural nitrogen content degrades. This causes farm to expand their fields into grasslands, forests, and wetlands that were previously untouched. Many have raised concerns about naturally sequestered CO₂ being released back into the atmosphere, natural habitat destruction and soil erosion — an unsustainable cocktail of natural repercussions. We can’t continue expanding farmland forever.</p><p>With this line of approach, we need to figure out how to maximize output with the land we already have instead of demonically tearing down everything in our paths. Investigating the major causes of yield loss in each years corn crops, I found a huge gap in the process: we’re not adequately treating disease.</p><p><strong>The Effects of Disease on Corn Crops</strong></p><p>The 20th century brought with it a variety of great developments: the automobile, the airplane, the Haber-Bosch process, the Beatles … The what?</p><p>Haber-Bosch is a process invented in 1905 that catalyzed the commercial production of fertilizers around the world. It’s what allowed the world population to quadruple over the course of the twentieth century, and is responsible for producing the fertilizers of the food we have on our tables today. Various other innovations including pesticides and GMOs have all served to boost yields, but dealing with disease has largely been neglected.</p><p>Of course, technologies like disease resistant hybrids of corn have had some impact on preventing the complete failure of crops in recent years, but the burden caused by disease has not been properly solved for. The average value of yield loss caused by diseases is $55.90 USD / acre, which translates to over $5 billion in lost corn yield across the US alone.</p><p>For example, Gray Leaf Spot (GLS) is a fungal disease that spreads in spores from previous years’ corn crops, and is the most prolific disease affecting corn crops in the US. It spreads from leaf-to-leaf up the plant and causes streaks of dead cells to form, which limit a plant’s ability to photosynthesize and produce carbohydrates essential for plant and kernel growth. Annually, it causes a loss of 6.6 million metric tons of corn, which translates to a net loss of over $2.8 billion USD in lost revenue for farmers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yZ20Afv4oWOiE88Wu1f_fA.png" /><figcaption>Yearly corn yield losses incurred by disease in the Northern US and Ontario. <a href="https://apsjournals.apsnet.org/doi/epdf/10.1094/PHP-05-20-0038-RS">Mueller et al.</a></figcaption></figure><p>GLS, like many other corn diseases, only has treatment options rather than a solution. Farmers follow a variety of guidelines to minimize risk, including field tillage, crop rotation and planting at different points in the season, but there’s often little they can actively do to prevent the disease. Some strains of GLS-resistant corn have made their way into the market, but so far none of these hybrids have proven to be immune. If GLS starts to spread in a field, they’re left with little options for treatment. Fungicides are expensive to purchase and deploy, making them suitable only for extreme cases where disease threatens a majority of their yield. Even whne they’re applied, fungicides act to limit further spread rather than to heal plants already afflicted.</p><p>I’ve addressed a possible solution to GLS in particular in a previous <a href="https://www.notion.so/ayevchenko/Gene-Engineering-Thick-Corn-Cuticles-to-Eliminate-Gray-Leaf-Spot-Disease-d47d4e796bd642fb9943c819189c714d">memo</a>, but a larger commonality between corn diseases is the fact that early identification and treatment plans can significantly improve yield outcomes during farming. Due to the fact that many diseases have an onset period of two weeks between infection and the first symptoms, getting warning as soon as possible is critical to limiting the spread of disease with fungicide application and warning agronomists and other farmers in the area of potential risk factors before a larger pandemic breaks out.</p><p>The process of scouting for disease is intensive and requires farmers to comb through all of their fields multiple times per year. They do this to get a good understanding of what diseases, pests and weeds are present in their field, and how they’ll go about treating their fields for the rest of the year. This work takes hundreds of hours to complete, and is often the reason why farmers employ teenagers and college students throughout the summer months to sift through their fields. This type of work requires precision and expertise in disease identification, but has exponential payoff if its performed correctly, which is why farmers are willing to devote so much effort and financial resources to this task.</p><p>Despite the rapid mechanization of a large portion of the farm, field scouting remains a primarily manual and labour-intensive task — one which I believe can be automated to reduce scouting costs to farmers and give them precise, live data of field health and treatment options.</p><p><strong>A Solution to Early Diagnosis</strong></p><p>Machine learning has already played an important part in the way farms operate, and holds exciting potential when looking to the future. Companies like Monarch Tractor and InnerPlant are already leveraging the technology to help build better outcomes for farmers, whether it be through autonomous farm equipment or monitoring nutritional needs of genetically modified hybrids.</p><p>Progressing into the future, live data feeds of crops will become more widespread and accessible through tractor-mounted cameras, drones, crop dusters and satellite surveillance. The generation of terabytes of images and video feeds will allow algorithms to pinpoint the exact risk factors a crop is prone to, giving farmers advance notice that’s much more effective than manual methods at fractions of the cost.</p><p>Moreover, combining positive hits for crop disease with geo-located data gives farmers a live look at how quickly a disease spreads, and exactly which fields need attention. Such an approach would direct farmers’ fungicide allocations to be carefully evaluated and utilized, improving yields where it makes financial sense to do so.</p><p>A general trend that I’ve noticed while researching the space is the fact that farmers want solutions that integrate with their current farming systems, rather than having to adapt a system. This is why IoT devices implanted in fields have failed to take hold in many jurisdictions, as they require more work than what they’re worth in the eyes of growers. A machine learning algorithm would require very little investment both in time and financial resources — if farmers are already using tractors and combines around their fields, it’s as simple as attaching a video-camera to them and setting up a link to a cloud-based platform for processing. Additional screening tools could require a drone with a camera, which are widely commercially available at low cost. For manual review of positive crop disease hits and targeted treatment plans, a web or mobile app could be linked to their cloud account, allowing user friendly interaction.</p><p>With this understanding, let’s take a look at how we could go about making this solution a reality.</p><p><strong>Building the Model</strong></p><p>We first need to understand what kind of approach would be ideal to solving this problem. It’s definitely a task of computer vision, and more concretely, image classification. I’ve considered segmenting the images, but I don’t think that’s necessary as farmers would be able to look at positively pinged images and immediately tell whether or not that disease is present within an image, which would extend to the surrounding crop area.</p><p>To build an MVP of the product, I started the hunt for a good dataset on Kaggle, and found this <a href="https://www.kaggle.com/datasets/abdallahalidev/plantvillage-dataset">one</a>. It has images of various healthy and diseased plant leaves, classified by plant type and the type of disease, with color, black and white, and segmented data available for use.</p><p>I built the model in Colab, as it has good GPU acceleration for faster training. For a full version of the code, check out my GitHub repository <a href="https://colab.research.google.com/drive/1q0wEnUrQiE-565Cap-SnGAOPVan5wsCS#scrollTo=tfZQc8gwC5Jx">here</a>. I’ll highlight some of the main components in this section.</p><p>After pip installing Kaggle and linking my Kaggle account to Colab, I download the dataset and unzip it to get workable images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eGOhdwJVFuBotr-dzKkW0w.png" /></figure><p>Next, we split the data into test, training and validation sets using splitfolders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*nlsqspavqZhGwUFUBSbu5w.png" /></figure><p>Check that the folders have been correctly split using this loop. As a return, you should see a listing of directories containing image files that we’ll use to train the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uyXSg9mINAeuHbxBOfdsow.png" /></figure><p>To get a better understanding of what the images look like, let’s plot them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*N-AUmWWZVoWD4k7IabxfnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mRqP-RxlsZKZG2EYqyMYcw.png" /></figure><p>This code returns an image of every type of corn disease within the dataset, and we can check to make sure that they’re in the right places.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*hE8uTvSu6wV_CABDWwEogw.png" /></figure><p>Surely enough, they’re in the right folders. The characteristic lesions Gray Leaf Spot and Northern Leaf Blight are evident, while the sprinkling pattern of common rust is clear.</p><p>Skipping forward after extracting the corn files from the dataset and preparing them, we print the length of each array of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*2foJ5HhWV5EqFsOKpcmy8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*xLXf82_hijjJLGc0Hhv9Dw.png" /></figure><p>Next, we must normalize the files to get rid of any discrepancies they may have. We first find the mean file size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*tyfydPdRyvCk1QhT4anobg.png" /></figure><p>and then find the mean and standard deviation of the images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*wEFFP0NY1W__6gTe1L1D-A.png" /></figure><p>Now that we have the mean and standard deviation of all of the images, we can apply torchvision’s transforms to the all of the images through a function, where the transform is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*1P0i9zrCVXtQ9Q2rN8s30g.png" /></figure><p>We make sure that all of our data is of the shape [3, 128, 128] and that our label arrays are the same length as the image arrays. We then cut down our arrays to make sure that the number of images and labels is divisible by the batch size of 32, and then zip them together to load onto the train, validation and test loaders.</p><p>Checking the size of each loader:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*KAu4OhBL2Pan9DYSc6LRqg.png" /></figure><p>Visualizing some of the normalized images, the diseases become more obvious to the average viewer, being highlighted in blue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*PFVUdPlXTmElSalaG9gZrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*KlPXDbsFF79jeO4a5thSaw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*O3sunLJ6K7aAcFMnxnimng.png" /></figure><p>The model we construct is fairly simple, following the basic pattern of convolution, ReLU activation, batch normalization and max pooling. At the end of the model, some dropout is added to prevent overfitting as this image set is small and the model is likely to learn the images rather than the features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wEgjAa3ESDA0SkcoQq7aUQ.png" /></figure><p>After defining a standard training loop and letting the model train, the training and validation loss graph is produced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*Ob7oFLFgBe7LG9as-YaAQQ.png" /></figure><p>Defining a testing loop and letting the model train, we get the final accuracies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*ArAubg063YerU1VOivUZMg.png" /></figure><p>Accuracy is relatively high as the dataset is fairly small and the images are taken at the same angle, making identification an easier task. The accuracy on the Common Rust and Healthy examples is likely due to their unique appearance, making them easier to distinguish. The lower accuracies in Gray Leaf Spot and Northern Leaf Blight are likely due to the fact that the two diseases look fairly similar to each other, and that GLS had significantly less training examples than the other types of diseases.</p><p><strong>Next Steps</strong></p><p>We’ve now seen that it is possible to build accurate models to identify corn disease using computer vision. The plausible next steps would be to find larger datasets with more compute to train on, leading to better accuracies on a variety of different diseases, rather than just three. Additionally, experimenting with live video feed and capturing images from live footage where disease is detected would prove to be useful in building out a next phase of the product.</p><p>There are still a few areas that I’m concerned about. The first being the fact that drones and tractors won’t be able to see to the bottom-most leaves of corn plants in the field, which is usually where the first traces of disease take root. Corn can range anywhere between 5 and 12 feet tall, meaning that getting accurate, bright video from the roots of the crop could prove challenging as the plants reach maturity.</p><p>In addition, the model has to be resilient to variations in lighting, angle, distance and other metrics as the quality of the data would be very difficult to control. In this case, all of the images were taken against a white background with leaves exposed flat against the surface, but this type of image would rarely occur in a natural environment. There also smaller technical challenges of camera mounting, drone flight paths and recharging, etc. that would likely need to be addressed, but this would likely happen further on in the R&amp;D cycle.</p><p><strong>The Big Picture</strong></p><p>Overall, I’m very excited about the potential future machine learning could bring to the farming world, and this is just one of many applications in the optimization of agriculture. I strongly believe that we can’t continue ruining our shared environment through destructive practices like agricultural expansion, and I think that disease diagnosis and treatment will play a large role in the improvement of the efficiency of the farmland we already have.</p><p>In my view, this is also one of the easiest and most impactful solutions that the world could implement to reduce the amount of hunger globally, despite it not being an on-the-ground solution. More production would lead to lower, levelized prices of food around the world, increasing access to those most vulnerable.</p><p>If you’ve found this article useful and would like to chat more about tech, reach out!</p><p>Find me <a href="https://twitter.com/alex_yevchenko">Twitter</a>, or shoot me an email: <em>alexanderyevchenko@gmail.com</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74edc76e949" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Virtual Ruler]]></title>
            <link>https://medium.com/@alexanderyevchenko/building-a-virtual-ruler-82694d821d61?source=rss-fc132341b04d------2</link>
            <guid isPermaLink="false">https://medium.com/p/82694d821d61</guid>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Alexander Yevchenko]]></dc:creator>
            <pubDate>Thu, 24 Nov 2022 02:15:56 GMT</pubDate>
            <atom:updated>2022-11-24T21:21:42.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*j7NYOtE0LaJaGmpu" /><figcaption><a href="https://unsplash.com/photos/pwpVGQ-A5qI">Markus Spikse on Unsplash</a></figcaption></figure><p>Length seems like an elementary concept — pull out a ruler or tape measure and find whatever you’re looking for. Something a 3-year-old could do. For computers, however, this isn’t such a menial task, especially when they don’t have the guidance or direct input from a human.</p><p>Despite seeming basic, lengths play a critical role in the way computers perceive the world around them. When put into the context of self-driving cars, information like distance from the car ahead, lane position, and object tracking is the basis of such technologies. Without basic understanding of length, we wouldn’t be able to tell apart dogs from cats, let alone diagnose tumors.</p><p>To get a better understanding as to how computers go about interpreting the world around them, we must first understand the notion of computer vision.</p><h4>The Basics</h4><p>One critical understanding is that images are incredibly easy for humans to comprehend. Look at this image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*QQBVDh3WJsehKSpz" /><figcaption><a href="https://unsplash.com/photos/kjdCOj2zLrY">Reuben Mcfeeters on Unsplash</a></figcaption></figure><p>Within a split second, you’re able to recognize that this is a dog. Why? It’s because you’ve had generations of experience passed down to you in identifying what a dog looks like, in addition to your own. It’s so easy to classify this image that you almost don’t think about it.</p><p>Here’s what that same image looks like to a computer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*CKqn3QSFN7bqEU6Fsdg_Ww.png" /></figure><p>A computer can only interpret images as arrays of values. In this case, each individual pixel in the image is converted to components of red, green, and blue, and passed on to the computer. From this perspective, it’s now impossibly difficult to decipher what the image contains without prior knowledge of what is passed in.</p><p>Luckily, machine learning developers have discovered various methods of interpreting this data. The most popular method in computer vision models has been the Convolutional Neural Network (CNN).</p><p>In essence, CNNs function by repeatedly passing filters over the pixel values of an image. Early filters pick up basic patterns including lines and curves, while later filters learn what entire objects look like. In our dog example, early layers maybe be able to pick up the rounded edges of the eyes and the tongue, as well as the lines along its ears and back. Middle stages might be able to pick out body components such as eyes and the snout, while final stages will be able to identify the dog as a whole.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/0*podjpszDa5wdCexV.png" /><figcaption>A good example of the edges an early convolutional filter might pick up. <a href="https://developer.nvidia.com/discover/convolution">NVIDIA</a></figcaption></figure><p>Now that we’ve understood some of the basics of how CNNs function, let’s take a look at how they might be applied in a virtual ruler application.</p><h4>Building Out the Ruler</h4><p>One of the first elements that we need to measure an object is a sense of scale. This problem is a vital one — without proper context, we couldn’t tell whether an object was a few meters or a few kilometers long. For the purposes of this experiment, I’ll use letter paper. The standard format of the letter paper will allow a consistent relative scale of the objects we’re measuring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pmFIhN1mq4wQVDwg0T3Gpg.jpeg" /></figure><p>In this image, for example, the letter paper will serve as a ‘calibration’, and any objects placed onto its surface will be detected and measured.</p><p>Now that we have some standardization, we can use computer vision packages like CV2 to help determine where each element is on the page. This can be done using a specific convolutional kernel that detects edges on an image. With these edges, we can define where the paper is as well as where the item being measured is.</p><h4>Finding the Contours</h4><p>Let’s build out a function called <em>getCountours </em>to get a better understanding.</p><pre>def getContours(img, cThr=[100, 100], showCanny=False, minArea=1000, filter=0, draw=False):<br>    imgGrey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)</pre><p>We pass in several arguments into the function, the first of which is the image we would like to process. The other arguments will be explained in a bit. In the first line of the function, we greyscale the image, since it makes computation in real time faster by getting rid of the extra RGB channels.</p><pre>imgBlur = cv2.GaussianBlur(imgGrey, (5, 5), 1)</pre><p>Next, we apply a Gaussian blur to the image to prevent any overfitting from occurring and to make the model robust when there is noise from live input data. When we’re applying Gaussian noise, we’re sampling noise from a normal distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LKMbLQkohl8LqQFY.png" /><figcaption><a href="https://www.scribbr.com/statistics/standard-normal-distribution/">Scribbr</a></figcaption></figure><p>We then apply the outcome of that sample to each individual pixel value. What this means is that most pixels will stay the same or very close to their initial brightness, but some will be vastly different than what they were originally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_gh7mO912uV_L_3W.jpeg" /><figcaption>Unnoised and Gaussian Noised Image of the Brain. <a href="https://medium.com/@shafayet.islam.61/image-noise-basic-of-computer-vision-part-02-93898eda0698">Shafayet Islam</a></figcaption></figure><p>As you can see, applying some noise maintains image coherence while adding some variation into a ‘perfect’ image.</p><h4>Finding Edges using Canny Edge Detection</h4><p>Next, we’ll apply Canny edge detection:</p><pre>imgCanny = cv2.Canny(imgBlur, cThr[0], cThr[1])</pre><p>The Canny edge detection algorithm was first proposed by John F. Canny in 1986 and is a four-step process:</p><ol><li>De-noise the input image using Gaussian Smoothing.</li><li>Find the Edge Gradient using Sobel filters.</li><li>Apply Non-Maximum Suppression to preserve only local maxima.</li><li>Hysteresis Thresholding.</li></ol><blockquote>It sounds like a lot but walking through it will provide much more clarity.</blockquote><p>De-noising the image using Gaussian smoothing reverses the effect that we created in the initial noising step, using the same process as outlined above.</p><p>Finding the edge gradient using the Sobel filter is how the first estimates for an adequate edge are created. The algorithm applies the Sobel X and Sobel Y filters, outlined below. These filters are useful in identifying edges as they magnify the differences between adjoining columns and rows, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/0*rl1b-e6KuYnzI-Fa" /></figure><p>The problem with this type of filter is that it is biased toward either positive or negative, meaning that depending on the filter used, you’ll end up with different edge detections, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*brfENFwMNQqkrh_InSk9hg.png" /><figcaption>In these images, black edges represent negative values and white edges represent positive values. <a href="https://www.youtube.com/watch?v=uihBwtPIBxM">Computerphile</a></figcaption></figure><p>What we ideally want to compute is the magnitude of both of these filters, along with the gradient of the edges — the direction they’re going. Luckily, this can be achieved with some elementary math: Pythagoras’ theorem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*C638xnho2ChMr2Xvvg8jfQ.png" /><figcaption><a href="https://docs.opencv.org/4.x/da/d22/tutorial_py_canny.html">OpenCV</a></figcaption></figure><p>By computing the edge gradient, we remove the sign that is attached to each individual component and end up with an absolute magnitude, as well as an angle. With this information, we can plot the result that answers the question: <em>‘How big is the gradient at this point?’</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oAkNadV0VGu9wS8TpQDXMA.png" /><figcaption>Black tones have near zero values, whereas white values have high gradients. <a href="https://www.youtube.com/watch?v=uihBwtPIBxM">Computerphile</a></figcaption></figure><p>Now that we’ve computed the edge gradients, we can move on to the next step in the Canny process: Non-Maximum Suppression. All that this step entails is checking that values along an edge are the local maxima along their gradient direction. To put this in another way, this method checks whether a pixel actually <em>makes up</em> and edge or whether it is simply <em>near</em> an edge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*_RuOv7MT0o_Lg1DdZCBREA.png" /><figcaption><a href="https://docs.opencv.org/4.x/da/d22/tutorial_py_canny.html">OpenCV</a></figcaption></figure><p>In this image, point <strong>A</strong> lies on a vertical edge, as well as in the gradient direction with points <strong>C</strong> and <strong>B</strong>. Non-Maximum Suppression checks whether or not <strong>A</strong> is the maximum among these three points. If it is not, its value is dropped to zero <em>(suppression)</em>, but if it is, it is included as part of the edge shown in the image above.</p><p>The last part of the Canny filter is Hysteresis Thresholding, which serves as a discriminator to determine whether or not a set of pixels is really an edge or not. Two threshold values, <em>minVal</em> and <em>maxVal</em>, are selected. Any edges above the <em>maxVal</em> threshold will be classified as edges, while any values below <em>minVal</em> are discarded. Values between the two thresholds are tested, according to their connectedness to ‘sure’ edges, which are the edges above maxVal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*Z707mtcwlWbNEopdPpGS5Q.png" /><figcaption><a href="https://docs.opencv.org/4.x/da/d22/tutorial_py_canny.html">OpenCV</a></figcaption></figure><p>In this example, both edge <strong>C</strong> and edge <strong>B</strong> are between the <em>maxVal</em> and <em>minVal</em> thresholds. Since <strong>C</strong> is connected to edge <strong>A</strong>, a ‘sure’ edge above the <em>maxVal</em> threshold, edge <strong>C</strong> is included in the final edge output. Conversely, because edge <strong>B</strong> is not connected to any ‘sure’ edges, it is discarded.</p><pre>kernel = np.ones((5, 5))<br>imgDial = cv2.dilate(imgCanny, kernel, iterations=3)<br>imgThreshold = cv2.erode(imgDial, kernel, iterations=2)</pre><p>These lines of code apply a ‘morphological closing’ of an image. Dilation of an image consists of a filter passed over each pixel, and that pixel taking on the highest pixel value present within the area of a kernel. This has the effect of thickening thin lines, as well as making edges and shapes more visible. Conversely, erosion is the process of passing a filter over each pixel and find the minimum value within the area of the kernel. As you may have guessed, this results in the thinning of thick lines, as well as the removal of extremely thin edges and shapes.</p><p>When these two methods are applied in unison, the morphological closing of an image has the effect of filling small gaps in an image while preserving the shape and size of larger holes and objects in the image, as seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*3wC8U3nl2KVDMRuy6ixHvQ.png" /><figcaption>Image before and after morphological closing. <a href="https://www.mathworks.com/help/images/morphological-dilation-and-erosion.html">Mathworks</a></figcaption></figure><p>We’ve now finished the main processing of the function! Let’s take a look at the before and after of the image passed into the function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*_ZIuGpV7HmKCktXkWY9QqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*FB8W9wktkRXMiGHus7SNqg.png" /></figure><p>Now that we have an image with edges clearly defined, we can leverage the cv2.findContours method to find the contours in the image and return them in the form of an array.</p><h4>Finding the Contours</h4><pre>contours, hierarchy = cv2.findContours(<br>        imgThreshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)</pre><p>The <em>findContours</em> method returns both a list of contours and a hierarchy, which is an array describing the parent-child relationship between each contour in the image. We pass in the <em>imgThreshold</em> that we’ve calculated above. The second argument specifies that we only want to find external contours in the image, ignoring nested contours that may appear within the objects we’re analyzing. The third argument specifies the manner in which we want to receive our contours — in this case, we simply want the <em>(x,y) </em>coordinates of the four corners of the shape.</p><p>The findContours method works on the <a href="https://www.sciencedirect.com/science/article/abs/pii/0734189X85900167?via%3Dihub">algorithm</a> implemented by Suzuki and Abe, in which pixels are compared to neighbouring binary pixels to understand the relative change. In this case, since our image is in black and white, it detects the appearance of white edges on a black background.</p><pre>finalContours = []<br><br>    for i in contours:<br>        area = cv2.contourArea(i)<br>        if area &gt; minArea:<br>            perimeter = cv2.arcLength(i, True)<br>            approx = cv2.approxPolyDP(i, 0.02*perimeter, True)<br>            bbox = cv2.boundingRect(approx)<br>            if filter &gt; 0:<br>                if len(approx) == filter:<br>                    finalContours.append([len(approx), area, approx, bbox, i])<br>            else:<br>                finalContours.append([len(approx), area, approx, bbox, i])</pre><p>This code is semantically simple to understand. In the contours that are detected, we find the area of each contour using the <em>contourArea</em> method. This method uses the Green formula to calculate the area of complex 2D images, which involves vector calculus. If the area of the contour is greater than the minimum area we want to detect, then we find the perimeter using the <em>arcLength </em>method, as well as an array of the approximated points of a contour. This is achieved using the Douglas-Peucker algorithm (hence <em>approxPolyDP</em>), which reduces the number of points necessary to get a good approximation of a complex edge contour. We can also find the bounding rectangle of the contours using the <em>boundingRect</em> method. With the filter <em>if</em> statements, we’re checking if the length of number of points in the edge contour is equal to a filter value set in the function declaration. For example, if we wanted to find only rectangles, filter would only match to 4 as the minimum points needed to the contour points of a rectangle is 4.</p><pre>finalContours = sorted(finalContours, key=lambda x: x[1], reverse=True)<br><br>    if draw:<br>        for con in finalContours:<br>            cv2.drawContours(img, con[4], -1, (0, 0, 255), 3)<br><br>    return img, finalContours</pre><p>We sort the final contours array from largest to smallest, and conditional draw the contours to the original image. Just like that out <em>getContours</em> function is finished!</p><h4>Perspective Transform</h4><p>But there’s still one more critical function to build, <em>warpImage</em>. This function will find a particular set of contours and get a bird’s eye view of that shape, cutting out and background that is not relevant.</p><pre>def warpImage(img, points, w, h, pad=20):<br>    points = reorder(points)<br>    pts1 = np.float32(points)<br>    pts2 = np.float32([[0, 0], [w, 0], [0, h], [w, h]])</pre><p>We pass in the original image and a set of points, as well as a set width and height. We reorder the points in a specific manner using the <em>reorder</em> function, which can be found on <a href="https://github.com/alexyev/ObjectSizeEstimation">GitHub</a>. The order of the points will make sense after this next section.</p><pre>matrix = cv2.getPerspectiveTransform(pts1, pts2)<br>imgWarp = cv2.warpPerspective(img, matrix, (w, h))<br>imgWarp = imgWarp[pad:imgWarp.shape[0]-pad, pad:imgWarp.shape[1]-pad]<br><br>    return imgWarp</pre><p>The <em>matrix </em>variable finds an appropriate transform matrix that takes the points of an area of interest and maps them to take up the entire image, as seen in the <em>pts2</em> variable. Essentially, it’s asking: How do I take the points of an area of interest and transform them to take up the entire output screen? The order of the pts1 variable now makes sense, because the mapping operation of each input point to each output point must come in a specific sequence, otherwise the image will not be transformed correctly. This can be understood through the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqziE0qJ15KgIp5RA06CnQ.jpeg" /></figure><p>The image transformation is completed using the warpPerspective method, and some padding is used to get rid of unwanted side pixels. When this is run on our example image, the output looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*wUxbgJKwzG5nPsAPtp1pDg.png" /></figure><p>As we can see, when passing in the image of the paper as the desired image to be transformed, we end up with an image that contains only the paper and the items on it.</p><p>Now that helper functions are done, we can move on to the logic.</p><h4>The Finished System</h4><pre>imgContours, conts = utils.getContours(<br>            img, showCanny=True, minArea=50000, filter=4)<br><br>        if len(conts) != 0:<br>            # pre-sorted so that first is largest, and find it&#39;s approx points<br>            biggestCont = conts[0][2]<br>            imgWarp = utils.warpImage(<br>                img, biggestCont, widthPaper, heightPaper)<br>            cv2.imshow(&#39;Letter Paper&#39;, imgWarp)</pre><p>Call the <em>getContours</em> function to get the contours from the original image. Find the biggest contour, which will be the paper, and run the <em>imgWarp</em> function so that it is isolated from the rest of the image. Show the warped image in a new window called Letter Paper — this was the code responsible for the image above.</p><pre>imgContours2, conts2 = utils.getContours(<br>            imgWarp, minArea=400, filter=4, cThr=[50, 50], draw=False)<br><br># skipped some lines that plot lines and measurements onto the image<br><br>cv2.imshow(&#39;cont2&#39;, imgContours2)<br>        cv2.waitKey(400)  </pre><p>We run the getContours function on the warped image, which will yield the contours of any items present on the paper, depending on the <em>minArea</em> and <em>filter</em> set. Show the image final product using the <em>imshow</em> method, which looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*vUZpqQmXYADo8dzEpNjyIg.png" /></figure><p>This final output highlights an important point — shadow and perspective play a large part in the way computers perceive image data. Thus it is important to minimize shadow as much as possible, or find possible workarounds. Let’s take a look at what happens when we pass in an image that has little shadow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*G2fuDtIcrcynnTADGofWiQ.png" /></figure><p>A much more accurate result. What’s cool about this example is the fact that you can use a webcam to get live measurements of items placed on the paper. Just check out this <a href="https://github.com/alexyev/ObjectSizeEstimation">Github</a>, copy over the code, and make the changes required in the comments, and you should get a live stream of data coming through!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2oTUd2cN37k%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2oTUd2cN37k&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2oTUd2cN37k%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/d107633acaaf981114d9a091116a6c96/href">https://medium.com/media/d107633acaaf981114d9a091116a6c96/href</a></iframe><h4>The Big Picture</h4><p>As society moves toward an automated future, applications of computer vision will have unprecedented demand. By building out this ruler project, we can already see the relevance of image processing in fields from medical tumor segmentation to AgriTech. By building out this project, we’ve also seen some of the many challenges that engineers have to overcome when building out models — a sense of scale, the best ways to process and identify objects, and dealing with natural features such as shadows, to name a few. By building out a knowledge in computer vision, you’re setting yourself up for one of the most in-demand jobs of the next ten years.</p><h3>TL;DR</h3><ul><li>Computer Vision has applications across a variety of industries including Medical, Automation, Agriculture, Waste Reduction and a variety of other WBPs.</li><li>We can build out useful tools with CV right now, using our own data.</li><li>Using processes such as Canny edge detection, morphological closings and perspective transforms, we can build a practical ruler application using live video and image input.</li></ul><p>If you’ve found this article useful and would like to chat more about tech, reach out!</p><p>Find me <a href="https://twitter.com/alex_yevchenko">Twitter</a>, or shoot me an email: <em>alexanderyevchenko@gmail.com</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82694d821d61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding ResNet]]></title>
            <link>https://medium.com/@alexanderyevchenko/understanding-resnet-775fa911332d?source=rss-fc132341b04d------2</link>
            <guid isPermaLink="false">https://medium.com/p/775fa911332d</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[resnet]]></category>
            <dc:creator><![CDATA[Alexander Yevchenko]]></dc:creator>
            <pubDate>Sun, 13 Nov 2022 03:23:23 GMT</pubDate>
            <atom:updated>2022-11-13T03:23:23.999Z</atom:updated>
            <content:encoded><![CDATA[<p>In 2015, machine learning researchers were facing a critical problem: as they added more layers to their models, they began to underperform.</p><p>Training error and testing error for a plain neural network are visualized in the graph below, on the left and right respectively. Interestingly, the deeper 56-layer models had higher training and test error. This was puzzling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLpXp-I4RoziC0Hq19g6xg.png" /><figcaption>Figure from <a href="https://arxiv.org/pdf/1512.03385.pdf">Deep Residual Learning for Image Recognition</a></figcaption></figure><p><em>Theoretically</em>, the deeper models should have performed better. It would make sense, since the deeper layers can detect additional features, which would lead to a higher test and validation accuracy. This was not the case, as can be seen above.</p><p><em>Interestingly, this example was not a case of overfitting. </em>Overfitting occurs when the training accuracy is the same or better than a shallower model, but testing accuracy is much lower. On an intuitive level, this can be understood as the model learning the very specific features of one dataset but being unable to accurately identify features when presented with new data.</p><p><strong><em>So, what’s the problem?</em></strong></p><p>It turns out that deep models are especially hard to train. As you add more parameters to the model, you’re adding additional complication to your backpropagation processes, and you’re often stuck in local minima due to the scale of the model. Creating a better model is not a matter of adding more layers.</p><p>It’s worth a moment to stop and ponder this problem. The facts are:</p><ul><li>The 20-layer model achieves better performance in both training and validation.</li><li>The 56-layer model largely follows the same learning pattern as the shallower model yet does not achieve the same levels of performance.</li><li>The 20-layer model is a subset of the 56-layer model.</li></ul><p>Hold on. That last point of information is crucial. How can the 56-layer model underperform the 20-layer model, if the 20-layer model is present within its larger counterpart? At worst, their accuracies should be the same, with the first 20 layers being a carbon-copy, and the last 36 learning the identity matrix (<em>i.e., not changing any weights</em>).</p><p>This is exactly the insight that the authors of <a href="https://arxiv.org/pdf/1512.03385.pdf"><em>Deep Residual Learning for Image Recognition</em></a>, otherwise known as ResNet, had.</p><h4><strong>The ResNet Hypothesis</strong></h4><p>If this thinking is correct, then why doesn’t the deep network correctly learn the first shallow layers, while learning the identity for the rest?</p><p>It all has to do with the way that the weights of the model are initialized. Previous initializations featured a log-normal distribution around zero, which looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*TqEgePvH9-NeTdaIPKnzMQ.png" /></figure><p>Due to this standard deviation around 0, as well as other normalization layers present in previous models, weights often tended towards a value of 0.</p><p>This fact made learning the identity function as difficult as learning any other function, since the weights were biased to be far from a value of 1. This led to a thought: <strong><em>why not initialize all of the weights on a normal distribution around 1 instead?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*rL9swSao4KGpE2rn0XE0QA.png" /></figure><p>To implement this idea, the authors came up with an ingenious solution, what we now call the <strong>Residual Block</strong>.</p><p>Instead of passing in a variable <em>x and</em> attempting to train a neural network to return some very similar output <em>x̅</em>, we can model <em>x̅ </em>as <em>x, </em>with some neural trained weights added on. This is best understood when visualized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*LYInNwOVf0Sh9kh3d_txSw.png" /><figcaption>Figure from <a href="https://arxiv.org/pdf/1512.03385.pdf">Deep Residual Learning for Image Recognition</a></figcaption></figure><p>As can be observed, the <em>x </em>input is mapped directly into the output, where an <em>f(x)</em> is added on. Considering what we know about weight layers, particularly that they tend towards a value of zero, it’s clear to see that <em>f(x) </em>will result in a value very near zero. When the sum of <em>f(x)</em> and <em>x</em> is considered, the result is very near the identity function. The output of this building block now results in small changes to the identity, which reflect the features the model is learning.</p><p>This approach differs from the traditional methods of creating deep neural nets in the fact that in no longer relies on each individual node trying to learn the perfect weight. As you might imagine, getting each parameter to learn on optimal configuration is already hard, and when scaled to millions, this solution becomes intractable and stuck in local minima.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/0*tCngeVXddba7N71y" /><figcaption>More parameters lead to more local minima, thus increasing difficulty in learning. <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fbrilliant.org%2Fwiki%2Fextrema%2F&amp;psig=AOvVaw04fFpwywL894QYLj923X4C&amp;ust=1668211426860000&amp;source=images&amp;cd=vfe&amp;ved=0CAMQjB1qFwoTCMDL1f7ppPsCFQAAAAAdAAAAABAJ">Brilliant</a></figcaption></figure><p>By implementing ResNet, the model only has to learn optimal configurations for <em>F(x), </em>not placing as much importance on the configuration of individual neurons, but rather outputs of entire sets of neurons.</p><p>Looking at the model structure proposed in the paper, ResNet-34 is made up of 34 of these residual blocks and includes standard layers such as max pooling and average pooling, where necessary.</p><p>One import exception to note is the existence of layers where the residual connection <em>has parameters</em>. Take a look at this diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*3Ij5tV585LJ3eyXt-3NIhQ.png" /></figure><p>The output after the 3x3 conv layer has 64 channels, whereas the final output of the residual block after it has 128 channels. To perform addition between the two outputs, we must have the same channel size. As such, the residual connection is modeled as a 1x1 convolutional layer, and upscales the channels from 64 to 128, allowing the addition to occur.</p><p>Another challenge the authors faced was the number of parameters requiring training as the model grew deeper. To maximize computing efficiency, they constructed the <strong>Bottleneck Block</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fIHcpdZqahGcoDgYk9wbHQ.png" /></figure><p>The trick here is ingenious. Instead of conducting two expensive 3x3, 64-channel convolutions, the authors manage to get away with computing just one. The Bottleneck Block, pictured on the right, first downscales a 256-channel input to just 64 channels through a computationally inexpensive 1x1 convolutional layer, performs the 3x3 convolutional layer, and upscales back to 256 channels to perform the addition.</p><p>To put this into perspective, let’s take a look at how this saves computing power. Since each output pixel channel is a 3x3x3 filter, there are 27 Fused-Multiply-Add (FMA) operations that are implemented (FMA is the basis for modern computing calculation). The number of output pixels is 64 channels by 62x62 pixels (assuming an initial 64x64 image is used) because the 3x3 filter shaves off a pixel on each edge. This means that there are 64x62x62 = 246016 outputs channels, each requiring 27 FMAs, or 6,642,432 calculations in total.</p><p>Compare this with 1x1x3 filter, which results in 3 FMA operations. With a 1x1 convolutional filter, there are 64x64x64 = 262,144 output channels, each requiring 3 FMAs, or 786,432 calculations in total. With 256 channels, this scales to 256x64x64 by 3 FMAs, or 3,145,728 calculations in total.</p><p>For the layer on the right, there are 6,642,432 x 2 = 13,284,864 calculations in total. For the one on the left, there are 786,432 + 6,642,432 + 3,145,728 = 10,574,592 calculations, which is a 25% reduction in compute power. With deeper models, this 25% is a great help in reducing calculations and therefore compute time on the same hardware.</p><h4><strong>Constructing the Model</strong></h4><p>Now that we have understood the mechanics behind ResNet, we’re able to build models of a variety of depths to solve image classification challenges.</p><p>It’s useful to understand how the building blocks are created, which we can then leverage as layers to build more complex models. First up, the Residual Block. <em>(Note that I’m using Python and PyTorch for these examples).</em></p><pre>class BasicBlock(nn.Module):<br>  expansion: int = 1<br><br>  def __init__(self, inplanes, planes, stride=1, downsample=None,<br>               groups=1, base_width=64, dilation=1, norm_layer=None):<br>    <br>    super().__init__()<br>    if norm_layer is None:<br>      norm_layer = nn.BatchNorm2d<br>    if groups != 1 or base_width != 64:<br>      raise ValueError(&#39;BasicBlock only supports groups=1 and base_width=64&#39;)<br>    if dilation &gt; 1:<br>      raise NotImplementedError(&#39;Dilation &gt; 1 not supported by BasicBlock&#39;)</pre><p>Basing the Basic (Residual) Block off of the pre-built nn.Module class, I’m able to create a layer with trainable parameters with ease. In this code, I’ve created an initialization function with all required parameters, and implemented some errors when extraneous values are passed in.</p><pre>self.conv1 = conv3x3(inplanes, planes, stride)<br>self.bn1 = norm_layer(planes)<br>self.relu = nn.ReLU(inplace=True) <br>self.conv2 = conv3x3(planes, planes)<br>self.bn2 = norm_layer(planes)<br>self.downsample = downsample<br>self.stride = stride</pre><p>Here, the model layers are defined. Note that the conv3x3 function is just a nn.conv2d layer that has been predefined with a kernel size of 3x3. The rest follows the regular conventions of the Residual Block as defined above, which includes convolutional layers, ReLU activations, and downsampling.</p><pre>def forward(self, x):<br>    identity = x # preserving the identity<br><br>    # defining layers in the model<br><br>    # weight layer<br>    out = self.conv1(x)<br>    out = self.bn1(out)<br><br>    # relu<br>    out = self.relu(out)<br>  <br>    # weight layer<br>    out = self.conv2(out)<br>    out = self.bn2(out)<br><br>    # optional downsample<br>    if self.downsample is not None:<br>      identity = self.downsample(x)<br><br>    # summation<br>    out += identity<br><br>    # final relu<br>    out = self.relu(out) <br><br>    return out</pre><p>Here, we’ve defined the forward pass of the layer. We can observe the initial value passed in being added back to the output, very clearly following the outline of the diagrams. Intuitively, this looks exactly like the initial graphic of the Residual Block, pictured below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*LYInNwOVf0Sh9kh3d_txSw.png" /></figure><p>Next is the Bottleneck Block. Here, we need to take into account the downscaling, convolution, and upscaling layers as mentioned previously.</p><pre>class Bottleneck(torch.nn.Module):<br>    expansion = 4  # will be used in determining in upsampling<br><br>    def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,<br>                 base_width=64, dilation=1, norm_layer=None):<br><br>      super.__init__()<br>      if norm_layer is None:<br>        norm_layer = nn.BatchNorm2d</pre><p>Once again, we use nn.Module to create a layer with trainable parameters. We define a basic initialization function with all necessary parameters for the model and set a standard normalization layer.</p><pre># calculated downscaled layer output<br>width = int(planes * (base_width / 64.)) * groups <br><br><br># define model layers<br>self.conv1 = conv1x1(inplanes, width)<br>self.bn1 = norm_layer(width)<br>self.conv2 = conv3x3(width, width, stride, groups, dilation)<br>self.bn2 = norm_layer(width)<br>self.conv3 = conv1x1(width, planes * self.expansion)<br>self.bn3 = norm_layer(planes * self.expansion)<br>self.relu = nn.ReLU(inplace=True)<br>self.downsample = downsample<br>self.stride = stride</pre><p>Here, we’re once again defining each layer of our neural net. Notice that by setting the width variable, we’re downscaling our initial image. In the 3rd convolution and batch normalization layers, we upscale back to the initial image size, just like the Bottleneck Block above. This can be a bit confusing, just as it was to me, so I’ll do an example.</p><p>Let’s say we had the 256-dimensional input and wanted to scale down to 64. Our planes argument would be 64, since that’s the number of output channels. Since our <em>base_width</em> is set to 64 and we only have 1 group, we see that width is 64. As such, we run convolutions normally up to the third layer, where we see our output channels set to a product of <em>planes</em> and <em>self.expansion</em>. We know that <em>planes</em> is set to 64 and <em>expansion</em> was defined earlier as 4, so our output will have 256 channels.</p><pre>def forward(self, x):<br>      identity = x # preserving the identity <br><br>      # 1x1, downscaled convolution<br>      out = self.conv1(x)<br>      out = self.bn1(out)<br><br>      # relu<br>      out = self.relu(out)<br><br>      # 3x3, downscaled convolutio<br>      out = self.conv2(out)<br>      out = self.bn2(out)<br><br>      # relu<br>      out = self.relu(out)<br>      <br>      # 1x1, upscaled convolution<br>      out = self.conv3(out)<br>      out = self.bn3(out)<br><br>`     # optional downsample<br>      if self.downsample is not None:<br>        identity = self.downsample(x)<br><br>      # summation<br>      out += identity<br><br>      # final relu<br>      out = self.relu(out)<br><br>      return out</pre><p>Once again, we construct a forward pass in which the addition of the original identity is very clear, emulating the visualization of the Bottleneck Block from the paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*fIHcpdZqahGcoDgYk9wbHQ.png" /></figure><p><strong><em>With these layers, we’re now able to build image recognition models that aren’t restricted in depth, allowing for deeper models to be trained to greater degrees of accuracy than ever before.</em></strong></p><h4><strong>How Does ResNet Perform?</strong></h4><p>In case you weren’t in tune with the computer vision world back in 2015, the ResNet paper made shock waves, to say the least. Taking a look at its performance against previous State-of-the-Art models, the difference is glaring.</p><p>For context, the best model at the time was named VGG. The hypothesis of its construction was the abstraction of features through downscaling. Put another way, machine learning engineers would add more channels, while downscaling original image pixel values as the model progressed deeper. The intuition was the fact that the model would begin to learn more abstract features as it progressed in depth, no matter where the particular object was placed in the frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*Bk_GSvUNYb7OyK8INGobgQ.png" /><figcaption>Figure from <a href="https://arxiv.org/pdf/1512.03385.pdf">Deep Residual Learning for Image Recognition</a></figcaption></figure><p>ResNet blew the competition out of the water, winning the ImageNet Large Scale Visual Recognition Challenge by well over a percentage point error. This model set the standard for the future of machine learning architectures after these successes.</p><p>Another reason ResNet was so impactful was its relative slightness. The VGG model was a sequence of convolutional layers gradually increasing in channel number, along with max pooling built in between convolutions. While this may not seem initially obvious, the number of trainable parameters increased unsustainably as model depth increased, meaning a 19-layer VGG network contained 19.6 billion Floating Points Operations (FLOPs) per forward pass.</p><p>ResNet, meanwhile, remained relatively agile due to the fact that its learning per layer tended toward 0. Thus, the number of FLOPs required per forward pass was just 3.6 billion. <strong>This means that VGG required more than 5x more computing power, to train to a worse outcome.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*8kJGTJ-OYp65vH2JksUOLw.png" /><figcaption>Relative computing power put into perspective.</figcaption></figure><h4>Implications of ResNet</h4><p>It’s difficult to understate the importance the ResNet paper has had on the field. ResNet was the first instance that proved the general hypothesis in the machine learning industry — that deeper was better. It went on to form the basis for the many state-of-the-art (SOTA) models that dominated machine learning challenges for years to come.</p><p>It also continues to form the basis of emerging deep learning, including diffusion models. These models have peaked in popularity with the emergence of tools like Dall-E and Stable Diffusion, which are able to generate art pieces based on a prompt input by the user, allowing them to express artistic expression without the need for formal training.</p><p>They’re also extensively used in more practical applications, including processing image and video data in self-driving cars, feature identification, medical imaging, and a variety of other tasks. As the world progresses towards further automation, ResNet architecture will continue to play a tremendously important role in achieving this reality.</p><p>In case you’re interested in running your own version of ResNet, check out the code that I’ve built on my <a href="https://github.com/alexyev/Resnets/blob/main/Resnet18_Classification.ipynb">GitHub</a>. This a slightly shallower version of ResNet, but it should take a shorter amount of time to train.</p><p>If you’ve found this article useful and would like to chat more about tech, reach out!</p><p>Find me <a href="https://twitter.com/alex_yevchenko">Twitter</a>, or shoot me an email: <em>alexanderyevchenko@gmail.com</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=775fa911332d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arrogance, Obviousness, and People: Lessons from WebSummit 2022]]></title>
            <link>https://medium.com/@alexanderyevchenko/arrogance-obviousness-and-people-lessons-from-websummit-2022-ba6b95f19e39?source=rss-fc132341b04d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba6b95f19e39</guid>
            <category><![CDATA[growth]]></category>
            <dc:creator><![CDATA[Alexander Yevchenko]]></dc:creator>
            <pubDate>Fri, 11 Nov 2022 21:05:27 GMT</pubDate>
            <atom:updated>2022-11-11T21:05:27.841Z</atom:updated>
            <content:encoded><![CDATA[<p>People — including my former self — have the wrong impression of what a conference actually is. It’s easy to focus on the ‘sexy’ side — speaking in front of hundreds of people and attending talks from industry-leading experts. But that’s not the point of being there.</p><p><strong><em>You derive the most value from the people you meet</em></strong>, and your talks are only there to inform other attendees that you exist and that you’re someone interesting enough to invest the time to talk to.</p><p>In case you’re interested in what that ‘exposure’ looked like for me, here’s one of the talks that happened to be recorded:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FvShQhBSgw0k%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DvShQhBSgw0k&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FvShQhBSgw0k%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/0b354b987600c394ae26739878f0dbf6/href">https://medium.com/media/0b354b987600c394ae26739878f0dbf6/href</a></iframe><p>This was my ‘Oh, he’s pretty interesting moment’. It catalyzed some of the most meaningful conversations that I had at WebSummit, purely because people found my talk interesting enough to come up to me and ask a question. It also got me featured in <a href="https://forbes.es/opinion/192870/un-web-summit-entre-berners-lee-y-rania-de-jordania-se-apunta-al-nuevo-orden/">Spanish Forbes</a> — serendipity.</p><p>Over the course of my week in Lisbon, I had a variety of discussions that catalyzed introspective thinking. Once you realize something, you sit back and wonder: ‘Why hadn’t I thought of that before?’ Someone makes a point that is so blatantly obvious it bothers you that you hadn’t come to that conclusion before. Here’s a good one:</p><blockquote><strong><em>All successful people are arrogant.</em></strong></blockquote><p><em>Surely that can’t be true, right? That’s a gross misrepresentation of pooling ‘successful people’ into one bucket. Sure, there are some that come off as pretentious, but that’s far from the mainstream.</em></p><p>This thought process makes sense — that’s what I thought when I first heard this. But then I realized that the way we use the word ‘arrogant’ matters, <em>a lot</em>.</p><h4>Arrogance vs. Perceived Arrogance</h4><p>If I were to walk up to someone on the street and ask them how they defined arrogance, their answers may differ slightly, but they will have a clear negative connotation. It makes sense — nobody likes the arrogant guy strutting around the office with his new watch pretending he’s the king of the world, telling others how great he is and what they should do to get on his level. But not the way that I used arrogant incorrectly. This situation is one of <strong><em>perceived arrogance</em></strong>, in other words, one where others perceive you to be an arrogant person.</p><p>Perceived arrogance requires a clear delineation from arrogance, because the former has little upside, whereas the latter is a prerequisite for growth.</p><p>But how does arrogance lead to growth? Think about it this way — if you’re not arrogant, you have no internal drive to do harder things. If you’ve mastered quadratics, it would take a little bit of arrogance to make the leap to calculus, because it’s something substantially more difficult. If you didn’t have that spark of arrogance within you, you would have remained solving quadratics your entire life. This is an analogy for career growth. If you’re never pushing yourself to do harder things, you’ll never grow.</p><p>In this sense, arrogance is good thing. You can view it as that little voice in your head that tells you <em>‘You can do better!’ </em>As you do the hard things, you prove to yourself that you’re capable of building great things, which builds a level of self-esteem and trust in one-self that successful people possess.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lsxsRmKpWCd5-aNETQ2gnA.jpeg" /><figcaption>Catching up with Cathie Wood</figcaption></figure><p>Speaking with the people who found success, I understood that their stories all had one thing that was very similar — they always knew that they could do better. Cathie Wood was especially inspiring, because she continues to function at an extremely high level despite market conditions and external criticism. She trusts herself with her decisions, because she has already proven to herself and to others what she is capable of. The level of trust she has in herself, and by extension the amount of trust others have in her, has gotten her to the position she’s in today.</p><h4>Retrospective Obviousness</h4><p>Whenever we look at a successful person and what they did over the course of their life, we often ask what habits got them to the position they’re in today. This makes sense, as we want to replicate their habits in our own lives, ideally to achieve similar outcomes.</p><p>When we turn back the clock on their lives and discover the habits, mindsets, and biases toward action that successful people had in their lives, it seems obvious to us that they were destined to succeed.</p><p>One funny example of this came up in conversation with Brad Smith, who recounted the story of his first job at a law firm. He would accept his position only if he were to have access to a personal computer at his desk. When the lawyers challenged him and said that the secretaries did all the typing, he insisted on having one regardless. All these years later, it makes sense why he’s the President of Microsoft — it’s obvious that he would make it there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i7XbqiFKIDQdnJTkLGiDVg.jpeg" /><figcaption>Learning from the best</figcaption></figure><p>That’s exactly the question that we want to be asking ourselves: What habits, mindsets and biases am I creating in my life right now? Looking back to this time in my life 20 years down the road, will my success be ‘obvious’, being directly attributable to the actions I’m cultivating right now?</p><p>This is a very useful mental framework to have, as it forces you to consider the compounding effects of different habits you instill in your life. Conversely, it forces you to consider the negative outcome of your life in the next 20 years and evaluate what negative habits that negative outcome might be attributed to. I’ve found this extremely useful when thinking about the habits that cause the most harm to my development.</p><h4>Serendipity</h4><p>If there’s one thing young people need to accept as rapidly as possible, it’s the notion that they’re the function of the people they know. Why is this true? Most opportunities, investments, and even love interests come from the people the tangled web of your contacts. Even the opportunities you hustle are results of backing from a person that believes you’d be a good fit.</p><p>The obvious answer to increasing serendipity? Meeting more people. You have to obsess over this. Go out of your way to start conversations, whether that be in the line at your local Starbucks or as you walk into your office. It’s about switching the default mindset from being the quiet person that stares at their phone on the elevator to the master of words who can befriend anyone over the course of a 10-minute conversation. The default setting is to be talking.</p><p>It goes way beyond just meeting people. You have to invest time in your relationships. Notice the intentional use of invest vs. spend, talking to people is never a waste. Put the time into understanding the person you’re talking to beyond a transactional relationship — most of your contacts will take years to bear fruit that you might benefit from, if they ever do so. Might as well make your relationship a solid one in the meantime.</p><p>Don’t pay attention to titles or your monkey-mind trying to play status games. It’s too easy for us to dismiss people based on their role or their seniority, because it’s what’s programmed into us since the time, we were young. After all, who wanted to be at an entry-level position when you could be CEO. The important part is to not talk to people based on where they are now, but where they’re going. Speaking from personal experience, I’ve talked with CEOs who are extremely dull and offer little in the way of insightful conversation, and some of my best discussions came from unexpected positions.</p><p>None of this is to put down executives, but to encourage serendipity with everyone you meet. One core tenet that humans often don’t understand is the fact that opportunity comes from everywhere, and most often from where we least expect it. If I were to tell you that I had an amazing conversation with a South African student on the Queen’s University campus, you wouldn’t think much of it. Yet, some years down the line, he’s one of the greatest inventors of our era.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KevxOw5f8DhjnQjbTuIlGg.jpeg" /><figcaption>Behind the scenes</figcaption></figure><p>This was understanding reigned supreme at WebSummit. I was surrounded by hundreds of people in the room, and somehow had to choose just one person to have a conversation with. Some conversations weren’t the best, but that was the cost that I had to pay for the true gems. By continuously talking to all sorts of people, I found people that were working on the exact problems that interested me, and I learned a lot from them. They’ll remain valuable mentors as I progress down the path of building with emerging tech.</p><h4>You’re a Function of the Five Closest People Around You</h4><blockquote><strong><em>The bar that is set is the bar that is attained. Set high bars.</em></strong></blockquote><p>Despite the popularity of this quote, maintaining high-quality people around you is still a very underrated factor in success. However consciously or unconsciously, you’ll start to pick up the habits and mannerisms the people you spend most of your time with. Even if you do your absolute best to remain an independent actor, the amount of brainpower and effort you dedicate to this task is put to better use elsewhere.</p><p>This goes to say that you want to surround yourself with high-functioning people whose habits set them up for success. Being surrounded by these people, you begin to adapt their strategies into your own life, as well as being held accountable to a much higher standard than what you’re used to. Through spending time with the five, you’re building an unshakeable foundation of trust, out of which a high standards mentality for oneself and for each other is created. Their success is your success, and their failure is your failure. By creating such a tight environment, you know that the group isn’t afraid to call anyone out for not performing to a high level — they know you can do better, and they’ll make sure you do.</p><p>In considering this, we need to be extremely vigilant about the people we let into our lives. Allowing them to get near you means that they will directly influence your outcomes, meaning that you only want them there if you’re absolutely sure they’ll be a positive influence. Constantly question: ‘Is this person helping create a better me?’ If not, you know what to do.</p><p>These were just a few of my takeaways from WebSummit. If you’d like to see more, let me know by sending me a message (alexanderyevchenko@gmail.com) or on Twitter: @alex_yevchenko</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba6b95f19e39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feeding the World: AI’s Role in the Food Economy]]></title>
            <link>https://medium.com/@alexanderyevchenko/feeding-the-world-ais-role-in-food-economy-d04c2582e5c8?source=rss-fc132341b04d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d04c2582e5c8</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[food-waste]]></category>
            <category><![CDATA[food-production]]></category>
            <dc:creator><![CDATA[Alexander Yevchenko]]></dc:creator>
            <pubDate>Fri, 14 Oct 2022 18:41:00 GMT</pubDate>
            <atom:updated>2022-10-14T18:41:15.526Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*--qabLl0M8Xkiq_5" /><figcaption>Drone shot of farms in the Netherlands. <a href="https://unsplash.com/photos/-ey_a6WrfX0">Unsplash</a></figcaption></figure><p>When you think of the things a human needs to survive, food is one of the first answers that pops into your head. Despite being such a necessity, we don’t spend enough time thinking about where our food <em>comes from.</em> If I were to ask you when you last visited a grocery store or had food delivered to you, you’d probably answer within the last week. If I asked you about the last time you’ve intentionally checked the provenance of your bananas or your milk, you’d likely give a very different answer.</p><p>In developed nations, we’ve become accustomed to food magically appearing in grocery store aisles, as if delivered by the Walmart fairy every night. To many, this still isn’t a reality. In fact, I believe we’ve lost track of the magnitude of our growing need for food.</p><p>To feed the <strong><em>9.3 billion</em></strong> people on the Earth by 2050, the UN’s Food and Agriculture Organization (FAO) has estimated that the world needs to produce <strong>60%</strong> more food than we do today.</p><p>This seems like a daunting challenge, and in some respects, it is. The positive side of the puzzle is that humanity knows what it’s doing wrong. We understand that our current methods aren’t sustainable, and that the problem trickles down the value chain. As such, it’s useful to analyze the root causes before attempting a solution.</p><p><strong>Current farming techniques are extremely wasteful.</strong></p><p><strong><em>Worldwide, irrigating crops takes up 70% of human freshwater consumption, half of which is lost due to wind, evaporation and runoff.</em></strong> Diverting freshwater from natural routes causes imbalances in soil moisture, destroys local ecosystems, and changes weather patterns across the world. Take the Colorado River, for example. Seven states rely on the river for freshwater, leading to rapid declines in water levels. As a result, droughts and elevated air temperatures have reached new peaks, threatening the livelihoods of over 40 million people who rely on the river as their main source of water.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bGbOeY6yqYsA0ilu.jpg" /><figcaption>The drop in water levels in the Colorado River can be clearly observed. <a href="https://www.politico.com/news/2022/07/06/colorado-river-drought-california-arizona-00044121">Politico</a></figcaption></figure><p>The invention of the Haber-Bosch process in the early 20th century revolutionized farmers’ crop output but came with an enormous environmental price. <strong><em>Considering nitrogen fertilizers alone, over 65% of the 115 million tonnes applied each year end up in watersheds and ecosystems. </em></strong>Wasted fertilizers harm the local ecosystem, disturb the Earth’s natural nitrogen cycle, and create losses for small-holder farmers.<strong><em> </em></strong>Rich nations use much more fertilizer than necessary to increase their crop yields, and developing nations end up with tiny fractions of the pie. Their crop yields suffer as a consequence, prolonging the cycle of poverty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJHeXWg3h59PWQtzgYF93w.png" /><figcaption>Developed nations have the highest incidence of fertilizer usage, while developing nations, especially in sub-Saharan Africa, lag behind. <a href="https://ourworldindata.org/fertilizers">Our World in Data</a></figcaption></figure><p>Moreover, <strong><em>1/3 of all food produced is wasted</em></strong>. This results in roughly <strong>US $1 trillion</strong> worth of lost produce, not accounting for the energy and resource costs that went into production. Food perishes at various points in the value chain, with poorer countries dealing with losses during processing and storage, while richer countries let food go to waste during meal preparation and not consuming leftovers. What’s more, uneaten food produces 6% of the world’s annual greenhouse gas emissions — warming our planet with no tangible return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZudlBJ2jLEz40QHDee7yQ.png" /><figcaption><a href="https://ourworldindata.org/food-waste-emissions#:~:text=Almost%20two%2Dthirds%20of%20this,away%20by%20retailers%20and%20consumers.">Our World in Data</a></figcaption></figure><p>These are just a few examples of malpractices in human food production, and it’s clear that we need a radical change to meet our 2050 Food and Climate Goals. Technology, from the AI to robotics, are already being leveraged to tackle the biggest problems farmers are facing. Based on outcomes we intend to achieve by 2050, we can analyze what applications of these technologies will take us there.</p><p><strong>Farming will become more resource-efficient, producing more with less.</strong></p><p><strong>Roughly half of the world’s habitable land is used for agriculture.</strong> With a growing population, housing requirements and new development will limit the expansion of farmland, meaning we must grow more crop in the same amount of space.</p><p>This can be done in a variety of methods, including genetically modifying seeds to become more resistant to weather, or to yield more fruit. Other ideas include drastically reducing the amount of meat in the average diet, the production of which takes up nearly 80% of the world’s agricultural land yet produces only 20% of the world’s calories.</p><p>AI algorithms will play a significant role in creating resource-efficient farms due to their prediction capability. AI models take in a variety of variables about their environment, and based on previous experiences and outcomes, they predict how the situation they are presented with might evolve. This is fundamentally similar to the way humans learn, using their previous experiences to make a decision about the current situation.</p><p>Farmers are leveraging in-field sensors to provide massive amounts of data for AI models to train on. When training, the model is discovering some sort of connection between the input variables, which may include precipitation, temperature or wind speed, and the end outcome, which may be an increased or decreased need for fertilizer distribution. At the high-level overview, models are <em>‘learning’</em> the connections between input and output. During their training process, the amount of data they’re exposed to allows them to make precise decisions, finding patterns that can only be understood by filtering through millions of examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZCYMeawn_RG5vRHI.jpg" /><figcaption>Sensor providing raw data, feeding AI algorithms.</figcaption></figure><p>From a farmer’s perspective, leveraging this technology is a <strong><em>no-brainer</em></strong>. With its ability to provide unique insights, farmers are able to apply <strong><em>only the fertilizers and water their crops need</em></strong>. Given that nitrogen-based fertilizers are sitting at all-time price highs, the generated cost savings could be the deciding factor of a profitable season. Additionally, farmers’ environmental impact is greatly reduced, as their fertilizers are absorbed by the soil instead of leaking off into nature.</p><p>Beyond predictive analytics, AI can be leveraged with drones to give farmers insights on how their crops are performing. There are a variety of startups leveraging computer vision <em>(AI algorithms adapted to recognizing objects in images)</em> to give farmers insights on crop health, eliminating the time intensive task of looking through rows one-by-one. Using this technology, they’re able to diagnose and support crops, cutting out otherwise unforeseen losses.</p><p><strong>Food waste will be eliminated by 2050.</strong></p><p>This sounds more daunting than the last outcome but is quite achievable. Taking a look at the problem, most of the addressable problem lies within the domain of <strong><em>processing</em></strong>, <strong><em>storage</em></strong> and <strong><em>transport</em></strong>. These problems are perfectly adapted to the use of AI, and we’re already seeing major results.</p><p>American grocery stores produce 16 billion pounds of food waste every year, by leaving food to sit on shelves through their expiry dates. That’s 16 billion pounds of food that could have gone to feeding the world’s hungriest people. Afresh Technologies is leveraging AI to solve grocery stores’ fresh food supply chain concerns. Their models are able to measure customer demand and factor in irregularities like ripening and fruit size to assess and deliver the amount of produce a store actually needs, minimizing wastage.</p><p>Likewise, transportation logistics have leveraged AI for quite some time now, optimizing transportation routes and delivery times for perishable foods, ensuring maximal freshness on arrival. Consumer trends models are leveraged to understand ever-changing customer demand, making important decisions on which items to send to long-term storage and which items make it to shelves.</p><p><strong>An Ideal Future</strong></p><p>This article provides only a cursory glance at AI’s potential in transforming the food industry, as well as its necessity in feeding a growing global population. There are hundreds more problems plaguing the industry today, and it’s vital that the best and brightest minds are working on first-principles solutions to create real change.</p><p>If you found this article useful in inspiring new insight, please reach out to me to discuss further. I’d love getting your point of view and reaching new understandings.</p><p>Contact me at <em>alexanderyevchenko@gmail.com</em>,<em> </em>or on Twitter at<em> @alex_yevchenko.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d04c2582e5c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On Happiness]]></title>
            <link>https://medium.com/@alexanderyevchenko/on-happiness-b2f2f806678d?source=rss-fc132341b04d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2f2f806678d</guid>
            <category><![CDATA[eudaimonia]]></category>
            <category><![CDATA[mindset]]></category>
            <category><![CDATA[grow]]></category>
            <dc:creator><![CDATA[Alexander Yevchenko]]></dc:creator>
            <pubDate>Fri, 02 Sep 2022 02:54:02 GMT</pubDate>
            <atom:updated>2022-09-02T02:54:02.075Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FixXpz8aQeUR2y2pYrwSuA.png" /><figcaption>Aristotle</figcaption></figure><p>The word happiness is thrown around a lot, perhaps too much so. The key here being that a lot of our definitions don’t match up. The definition commonly accepted in society is a feeling: a sudden experience of emotion usually caused by some external stimulation. But to <a href="https://www.pursuit-of-happiness.org/history-of-happiness/aristotle/#:~:text=According%20to%20Aristotle%2C%20happiness%20consists,which%20may%20be%20very%20difficult.">Aristotle</a>, it’s something much more than that. <strong><em>Eudaimonia</em></strong>, the word often translated from Greek as ‘happiness’, is not a <em>feeling</em>, but a state of <em>being</em>.</p><p>I’ve heard countless people prioritizing <em>‘feeling happy’</em> about themselves or their lives. A lot of people <em>‘feel happy’</em> due to external circumstances, like celebrating a birthday or going out with their friends. These are fleeting feelings of joy that leave you over the course of a few hours, a day, or perhaps even a week or a month. They always fall away, no matter how hard you try to retain them, because that’s the nature of feelings — they come and go. Therefore, you can’t prioritize <em>‘feeling’</em> happy, because you’re optimizing for something temporary and something external, both of which lead down the wrong path.</p><p>Eudaimonia can be translated as ‘happiness’, but it’s really much more than that. It’s a state of being in which your happiness is not tied to any external event or temporary experiences of feeling, but rather stems from <em>virtue</em> and <em>fulfillment</em>. Virtue guides us through our lives on the basis of rational thought and empathy towards others, and fulfillment is the knowledge of a greater goal or outcome you work towards, whether that be personal or as a community.</p><p>As I’ve explored life, I’ve found that virtues can be adapted. We are inherently social creatures, and we consciously and subconsciously observe the behaviours of others and adapt them into our own lives. Positive virtues have a calling, as if inviting the soul to act in a way that benefits us, society, and the world around us. This is not to say that adapting virtue is easy — some take a lifetime to achieve. But the satisfaction they bring to everyday living is worth the journey.</p><p>An underappreciated aspect to the achievement of Eudaimonia is the fulfillment you experience in your day. No matter how virtuously you act towards others, there will always be a missing link. For the majority of us, the work we do takes up a large part of our day. In fact, it takes up a majority of our waking hours. If we’re interested in fulfillment and achieving Eudaimonia, our work has to be meaningful to us. Likewise, if you hate what you’re doing everyday, there’s no way you’re going to find fulfillment. It doesn’t matter what you like to do or what you find meaningful. From teaching middle schoolers to managing a company, the passion you have for your work directly translates into your overall state of being.</p><p>Of course, there are going to be roadblocks to this. You may be strapped for money and need to take on a job at a fast food place. You may find yourself in a position doing pointless work to appease your boss. It’s all part of the process, but the goal is to get out of that position as fast as you can.</p><p>You’ll find fulfillment in other areas of your life as well. Whether that be going to the gym or eating healthy or writing, all of these outlets contribute to your level of fulfillment. I’ve noticed that as I focus on getting the basics right, my productivity and passion for my work increases, which then increases my feeling of fulfillment.</p><p>Here’s the twist. <strong><em>You’ll never achieve Eudaimonia</em></strong>. Have you ever sat down to think about why Elon never sells his shares, leaves everything behind and sails away into the sunset? It’s because he loves the game. He loves every single one of his companies so much that nothing could ever bring him greater fulfillment than working on them. He could lift off and coast and say he’s reached his goals, but he never does. It’s the <em>process </em>that brings you fulfillment. No matter how much you achieve, you’ll always set higher and higher targets for yourself. This cycle of process, progress and achievement is the core tenet of Eudaimonia in the modern world.</p><p><strong><em>Live virtuously, find fulfillment, and chase Eudaimonia as hard as you can.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2f2f806678d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Quantum Computers to Price Options]]></title>
            <link>https://medium.com/geekculture/using-quantum-computers-to-price-options-5bd92ab5fe5c?source=rss-fc132341b04d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bd92ab5fe5c</guid>
            <category><![CDATA[options]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <dc:creator><![CDATA[Alexander Yevchenko]]></dc:creator>
            <pubDate>Mon, 20 Jun 2022 01:03:11 GMT</pubDate>
            <atom:updated>2022-06-20T01:03:11.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*DuIbB6XyQ-kakhpn" /><figcaption><a href="https://unsplash.com/photos/mHdATQY9fIU">Unsplash</a></figcaption></figure><p>While still in its infancy, quantum computing is already showing promising speedups to classically expensive computational problems. And while the industry still faces its fair share of criticism, many financial institutions are realizing the importance of this technology moving into the future and have made significant investments to beat their competitors to market.</p><p>With developments in classical computing, a market simulation that would have taken days on a state-of-the-art computer in the 70’s now takes only a few minutes on your home laptop. Quantum computing is seen as the next catalyst for improvement on computation. Bankers might see a massive speedup on computationally complex problems like market simulations and they’re willing to take a bet in early investment in the tech. The earliest adopters, or better put the first to get the tech to market, are sitting on a goldmine.</p><p>How might a quantum computer be put to use in the hands of a bank? There are, obviously, many different answers to that question. Some might say credit risk evaluations, others might point to insurance premium calculations, but here I would like to point in the direction of pricing options.</p><p><strong>What is an Option?</strong></p><p>In essence, an option is a financial contract that gives the holder the right, but not an obligation, to buy <em>(call option)</em> or sell <em>(put option) </em>a financial asset at an established price <em>(strike) </em>in a given timeframe <em>(exercise window)</em>.</p><p>In the case an investor buys a call option, they believe that the trend of a stock in the exercise window will trend upwards beyond their strike price. For example, if an investor purchased a call option at the $30 strike, and a week later the underlying stock is trading at $40, they can exercise their call option and net the difference between the current price of the stock and the strike. More explicitly, the investor is able to exercise their call option and buy the underlying for $30, and immediately sell for the current $40 market price. Of course, there is a fee <em>(the premium) </em>associated with buying the call option which one must take into account when calculating returns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yTl5mI0QVYFQHJHK.jpg" /><figcaption>Profit and Loss (P/L) graph for a call option with the $102.5 strike price. As the price of the underlying moves above the strike, an investor nets a profit. As the price of the underlying moves downwards, an investor nets a loss. The most an investor risks to lose is the price of the option (the premium). <a href="https://www.investopedia.com/terms/c/calloption.asp">Investopedia</a></figcaption></figure><p>Put options have the same intuition, but in reverse. These options are betting that the price of a stock will fall below a strike price in a given exercise window. In this vein, an investor may purchase a put option and when the stock falls below a given strike, the investor may sell at a higher price than the current market price, netting them the difference between their strike and the market.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cBBKxR7GGeRtqQhQ.png" /><figcaption>P/L graph for a put option. As the underlying stock trades below our strike, an investor stands to make money. However, as the underlying stock trades near and above the strike, the investor stands to lose money, up to the cost of the premium on the put. <a href="https://www.investopedia.com/articles/optioninvestor/120401.asp">Investopedia</a></figcaption></figure><p><strong>Why Options?</strong></p><p>An intuition or question you may have is this:</p><blockquote>Why not just purchase or short the shares I’m interested in? Why do I need an option?</blockquote><p>Options provide several advantages that buying equities does not offer. First of all, options give higher leveraging power. An investor can purchase a position in a security at a much lower cost that what if would have cost them to buy an equal position in stock. As such, they give investors more freedom in terms of capital allocation.</p><p>Options offer another way to mitigate risk in portfolios, as they are often used as a hedging mechanism. As a hedge, options work to minimize the downside if an investor’s trade goes sour. A put option <em>(where we’re guaranteed to sell at a set price) </em>would help offset any losses an investor might incur in the case that a security’s price went tumbling down.</p><p>They also help increase returns when used wisely. Due to the fact that options oftentimes are more receptive to changes in the underlying stock’s movement, they offer higher returns on investment than equity purchases. For example, if the price of the underlying ticks up 1%, my call option may bounce up 10% in value. Of course the inverse, where an investor may lose 10%, is a possibility and a major motivator for due diligence.</p><p>Options give investors the option of not only taking positions in equity markets, but also allowing them to make bets on a market’s volatility and the passage of time, no matter what the general movement of the market is. They offer an effective alternative to those seeking additional opportunities to generate returns outside of stocks and bonds.</p><p>Financial derivatives, especially options, make up a large part of global markets. In 2021, there were over <strong>33 billion</strong> options contracts traded worldwide, up from over 21 billion from the year prior. Ensuring that options are priced correctly is a huge concern for financial institutions to make sure they have validly assessed risk and are maximizing profits on the contracts they offer and trade.</p><p><strong>Pricing the Premium</strong></p><p>Any attempt at option pricing has to be based in an attempt to price the underlying into the future. Since the option derives its value from the price of the underlying, we must understand how the underlying security will develop to accurately assess how the option will develop.</p><p>Pricing the underlying, and thereby the option, relies on three main factors: the price of the underlying, the time value of the option, and the implied volatility of the underlying.</p><p>As may be inferred, the price of the underlying is the main factor behind the premium of the option. To have the right to buy or sell a stock that is currently trading at $1000, the premium paid must be higher than to have the same rights on a $10 stock. Otherwise, there would be no incentive for investors to buy options on the cheaper stock as there would be more opportunity in the more expensive one.</p><p>The time value of an option refers to the amount of time between the time of purchase and the expiry of the option. The more time there is until the expiration of the option, the more opportunity there is for the underlying asset to reach the designated strike. As such, an option expiring 6 months from the time of purchase is more expensive than an option expiring in 3 months at the same strike.</p><p>Another factor that must be considered is the implied volatility of the underlying asset. The price of an option increases as the seller’s perception of the volatility of the underlying increases. The price increases because the the buyer stands to make more money on an asset that fluctuates 10% in comparison to a more established security that may fluctuate 1%. The seller stands to lose more money in a more volatile security, and the risk they take on in selling an option on that security is priced into the premium.</p><p><strong>The Bottom Line</strong></p><p>When considering whether or not to purchase an option, the essential question can be boiled down to:</p><blockquote>Do I make money by buying this option?</blockquote><p>Of course, this is a very difficult question to answer. A concrete answer would entail knowing the future price action of the market, a fairytale to most bankers. But, how do they currently try to answer this question?</p><p>One valid approach to answer this question is an analytical approach, taking advantage of the stochastic nature of markets to boil down their evolution into a formula which we can solve. I’m of course making reference to the Black-Scholes-Merton Formula, which is perhaps the most famous formula of modern finance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/0*vPkqFS9GHYmJ_pPK.png" /><figcaption>BSM model, which encapsulates options into a concrete mathematical formula, taking into account cost of the underlying, time value, and the implied volatility of an underlying to predict the profitability of an option. <a href="https://medium.com/swlh/calculating-option-premiums-using-the-black-scholes-model-in-python-e9ed227afbee">Suhail Saqan</a></figcaption></figure><p>The BSM model was revolutionary because it was the first mathematical grounding of pricing options, despite the basic intuitions driving derivative markets decades beforehand. It incorporated Brownian Motion into the movement of markets, which was a powerful realization that acknowledged that markets acted like a random walk as they progressed through time.</p><p>Various limitations exists in the formula, including assuming a constant risk-free rate over time, a constant volatility over time, and stocks not paying dividends, to name a few. Despite these setbacks, bankers have adapted the formula to help accurately price options over time using partial derivatives, referred to as the Greeks.</p><p><strong>Monte Carlo</strong></p><p>Another approach is simulating the market many times over until convergence on a good estimate for an option’s payoff. This method is referred to as a Monte Carlo simulation, and is especially useful in pricing options that would be difficult or impossible to price using an analytical method like BSM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cYWs0UN1pglX12fx" /><figcaption>Monte Carlo simulation of a commodity. Each path represents a different simulation of a random walk in the price of a security. As we continue adding paths, they begin to converge, giving investors a estimate of the future price dynamics. <a href="https://www.supplychaindataanalytics.com/animated-monte-carlo-simulation-with-gganimate-in-r/">Supply Chain Data Analytics</a></figcaption></figure><p>Monte Carlo remains the most effective <em>(classical)</em> way to price complex, path-dependent options. These options, as the name implies, derive their value at various points throughout the option contract’s exercise window, and thus complete knowledge of the market dynamics of the underlying are often required to price them. Path-dependent options include barrier options, lookback options, and Asian options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s86iCKueWYWu-boG.png" /><figcaption>Example of a path-dependent barrier option, where the option contract is only exercisable when the price of the underlying has crossed a ‘barrier’. <a href="https://www.investopedia.com/terms/u/up-and-inoption.asp">Investopedia</a></figcaption></figure><p>Running a simulation of the option’s payoff to a point where an investor feels confident enough to make an investment is a computationally expensive task. With modern advances in computer technology, the time it takes to run all of these paths has been drastically reduced, but nonetheless, pricing a portfolio of millions of options often takes several hours to complete, and thus is used to analyze portfolios overnight.</p><p><strong>Quantum Amplitude Estimation</strong></p><p>Quantum computing holds significant promise in options pricing, using the Quantum Amplitude Estimation algorithm to propose a quadratic speedup when compared to classical Monte Carlo methods of pricing options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*GD5gA20_YdrbMb1y48eUng.png" /><figcaption>Quadratic speedup achieved when using Quantum Amplitude Estimation to price options, where M is the number of quantum samples used.</figcaption></figure><p>Since this speedup can be applied to classically hard-to-price options, quantum computers may very well be the future of efficient options pricing.</p><p><strong>Laying Out the Groundwork</strong></p><p>There are 3 steps outlined to achieve option pricing on a quantum computer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*nzqY8kiA4EtteEN18oZQFg.png" /><figcaption>We capture the random walk evolution of a set of underlyings in set X. We compute the payoff of this set in the second step. In the third step, we compute the expectation value of the probability distribution of the payoff function to find a fair price for the option.</figcaption></figure><p>To achieve these steps, we may take advantage of pre-existing quantum algorithms to implement in our circuit.</p><ol><li><strong>Loading the Probability Distribution</strong></li></ol><p>In the first step, we may take advantage of various quantum machine learning algorithms to efficiently load probability distribution onto a quantum register. Various approaches exist, including Artificial Neural Networks (ANN) and quantum Generative Adversarial Networks (QGAN).</p><p>ANNs are generally more computationally expensive to conduct on quantum registers, but are still of use in overnight options risk calculations, especially across larger models and portfolios. The computational cost mainly comes from training the ANN models, which requires both high processing power and relatively large periods of time.</p><p>QGANs are also useful when considering options pricing. This is because of their ability to learn the random distribution <strong>X </strong>by observing price paths and directly loading that probability distribution onto a quantum register.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*Gmvc53MNPBugIOEB.png" /><figcaption>Visualization of a QGAN. The generator does its best to create a perfect replica of the real data, while the discriminator determines which data is fake (generator created) and which is real. The general idea is that the generator will create high-quality fake data, which will reach the exact representation of the random distribution of the underlyings on a quantum computer. <a href="https://pennylane.ai/qml/demos/tutorial_QGAN.html">Pennylane</a></figcaption></figure><p>QGANs are useful when considering time- and hardware-constrained problems, particularly on NISQ-era computers with low fidelities. This is due to the fact that we can leverage their form to construct short-depth (ie. low gate-count) circuits to minimize the amount of error introduced into the system.</p><p>In addition, the business usefulness of QGANs can’t be discounted. As new market data comes as the business day closes, QGANs don’t need to be completely retrained. The previous day’s training is used as an initial distribution for the most current model, which allows for quicker convergence of the model.</p><p>For experimental purposes, we can still use the simplified price mechanics of Black-Scholes, which require relatively few gates and offers more options when considering loading options.</p><p>Loading isn’t the main focus of this article, but I refer you to the various resources that exist on <a href="https://pennylane.ai/qml/demos/tutorial_quantum_gans.html">qGANs </a>and <a href="https://www.sciencedirect.com/topics/earth-and-planetary-sciences/artificial-neural-network">ANNs</a>.</p><p>2. <strong>Circuits that Compute the Payoff</strong></p><p>In the second step, computing the payoff, most of the work consists of quantum logic gates and comparator circuits. We encode the strike value of the option in binary and compare each digit to the qubits encoding the probability distributions of the underlying to find the fair price. We’ve covered how to encode the probability distribution of a set of options already, so the only component still needed is a way to compute the payoff function of the option on a quantum computer.</p><p>While considering this problem, it’s necessary to remember that an operator compatible with Amplitude Estimation (AE) is required, since that is the final tool used to calculate the expectation value and thus the fair value of the option. An operator <em>A</em> is constructed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*pcLb37q8fdDVh-arDVnqBg.png" /><figcaption>By acting on a register of n + 1 qubits in the zero state, the A operator creates a superposition over the n qubits, controlled on the last qubit (the +1). As can be seen from the equation, little a is isolated in the right term, allowing for perfect integration with AE.</figcaption></figure><p>To be able to use AE to deduce a fair value, we encode <em>a </em>to be the expectation value of the linear function of a random variable,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*I2Gvp8_scejgmTzLAYwiVg.png" /></figure><p>where <strong>X </strong>is our set of random price paths from the previous section.</p><p>You might remember that from earlier in the article we found a lot of the options observed had a piece-wise linear payoff — that is to say the payoff is 0 when the market moves to the opposite direction of our prediction, and increases the payoff linearly as the difference between strike and spot price increases.</p><p>The payoff for the option can be encoded as a piecewise linear function, which maps to [0, 1]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*MDRBYAG1LM3cAy2eHN421g.png" /><figcaption>Where f₀ represents the constant term.</figcaption></figure><p>The result of this function can be encoded on a single qubit on a quantum computer. This is visualized as a quantum register <em>i</em> encoding the probability distribution and a single qubit onto which we will encode the linear function, with this qubit initialized to the state 0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*ucruVHJ2U0g1aBRx9-VWBg.png" /><figcaption>The final qubit in a superposition representing the result of the linear function over each qubit (represented by i) in the quantum register.</figcaption></figure><p>To create this state, one can take advantage of controlled-Y rotations. We will use these gates to encode the linear part of the payoff function. Each qubit encoding in the <em>i </em>register <em>(the one encoding the probability distribution)</em> will be used as a control for the Controlled-Y, encoding a rotation of</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/96/1*z97ttLjf_oPTtiz9j-WNpw.png" /></figure><p>onto the ancilla qubit. That is, if there’s a controlled-Y rotation being controlled on a qubit with index 3, the ancilla qubit is rotated</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/132/1*nxSw9nxQhplfzJhiifP-mQ.png" /></figure><p>This may seem rather arbitrary, but this is just converting the binary representation of the strike represented by the <em>i</em> register back into base-10 to ensure accurate rotations. As an example, a quantum state with three qubits in the |111⟩ state corresponds to the base-10 value of 7 after applying the controlled-Y rotations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*0kv6ft5h9nAPWuIunsf7Rw.png" /></figure><p>Looking back at the original linear function <em>f(i)</em>, there is still a constant term to implement. This can be easily achieved by using a Y-rotation on the ancilla qubit, without a control.</p><p>After implementing both of these steps, the output circuit might look something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*7nq6eak-4w_6K6HN5c8Gmw.png" /><figcaption>The constant term is implemented by the first RY, and the subsequent CRYs implement the linear rotation onto the qubit at index 3, the ancilla.</figcaption></figure><p>For a more concrete example, we can examine how to obtain the expectation value of a linear function of a set of random variables. To achieve this, we use the controlled-Y procedure above to implement an operator that maps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*2n8-V_sMk--N8mZSKyDQ1g.png" /></figure><p>In the above equation, a few changes are made, namely:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*asz16aJEGe8NGEblwYRA6A.png" /></figure><p>This may seem like a rather arbitrary change to make, but it becomes useful in practice. When taking probabilities in quantum mechanics, the Born rule comes into play. Thus, during the measurement of the amplitude of the |1⟩ state, the entire function is squared. This square creates an anti-symmetric function around <em>f(i) = 0. </em>In this case, an anti-symmetric function can be understood as a function in which the exchange of our two variables results in a change in the sign, as can be seen in change 1.</p><p>Our measurement probability of finding our final ancilla qubit in the |1⟩ state is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*JBPzZtHLBrars32kW28WcQ.png" /></figure><p>Based off of the structuring of our problem and other approximations that don’t tie into the purposes of this article, the probability is well estimated by the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*9vtAfQdUIEgpNGjN4emF-g.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*u7A3rgxoQGhgoaNrtbX87A.png" /></figure><p>With first-order approximation, the convergence of Amplitude Estimation is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/1*S2BXgbEQjUCYQam4ma8zUw.png" /></figure><p>To recover the full <em>(1/M)</em> convergence, more circuit depth is needed. It must be noted that to achieve these speed-ups accurate values of <em>c</em> are required, which turns into a matter of minimizing the number of gates for a set error in the estimation of the expectation value.</p><p>The expectation value <strong><em>E</em></strong><em>[f(x)]</em> can be recovered from probability measurement above because we know the values of <strong><em>f</em></strong><em>max, </em><strong><em>f</em></strong><em>min, </em>and<em> c.</em></p><p>3. <strong>Amplitude Estimation</strong></p><p>Referring back to some of our earlier clarifications, our use of Amplitude Estimation serves to find the <em>a</em> value in the amplitude of the |1⟩ state of the ancilla qubit after application of the <strong><em>A</em></strong> operator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*pcLb37q8fdDVh-arDVnqBg.png" /></figure><p>While traditional approaches to Quantum Amplitude Estimation could be used, NISQ era quantum computers are still limited in their qubit counts, interconnectivity, fidelity and coherence. As such, a simplification of AE can be used to lower circuit depth and make results more accurate. This simplification of AE comes from the work of <em>Suzuki et al.</em>, who have proven that AE can be performed without Quantum Phase Estimation, which contributed additional gates and sampling qubits.</p><p>AE is represented by the quantum operator <strong><em>Q</em></strong>, which acts as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*M8oiclBhOJF-LijM3Mv6Ig.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*e6gZ3nuzVtkGLGGFZ6aJ7w.png" /></figure><p>This entire equation corresponds to a rotation of angle <strong><em>2θₐ </em></strong>in the two-dimensional vector space spanned by |Ψ₀⟩ and |Ψ₁⟩. For a more visual and intuitive approach, make sure to read my <a href="https://medium.com/visionary-hub/what-exactly-is-grovers-algorithm-a8f5dce1e1b3">article</a> on Grover’s Algorithm for added learning.</p><p>Using the trick outlined by <em>Suzuki et al.</em>, namely that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*L15QjN7lBngMo4DhAHJNLw.png" /></figure><p>and by measuring</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*-NbNgLDwDGyD4WxepXD_wA.png" /></figure><p>for a given number of additional sampling qubits <em>m</em>, applying maximum likelihood approximation will lead to a good estimate for <strong><em>θₐ </em></strong>and therefore a good estimate for <strong><em>a, </em></strong>which encodes the fair, undiscounted value of the option in the amplitude of |1⟩ in the ancilla qubit!</p><p><strong>Practical Applications</strong></p><p>With various free-to-use quantum computing SDKs available to use right now, it’s easier than ever to run quantum algorithms and visualize the results. It’s useful to program these circuits to understand how they work in practice. I’ll be using Qiskit’s Finance module to visualize some of these quantum circuits. Their website has great tutorials on all of these types of options, which I highly encourage you to explore.</p><p><strong>Pricing European Call Options</strong></p><p>As mentioned earlier, these are some of the easiest options to price, since they have a set exercise date and have a linear payoff. They do not require any knowledge of the entire price movement of the underlying, just the price at the expiry. Call options are constructed so that if the price of the underlying is higher than the strike price, the option pays the difference between the strike and the spot <em>(current trading)</em> price. Else, the options pays nothing.</p><p>Putting this intuition into mathematical notation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*0iBJ-LteIWyZqgxIaegBrQ.png" /><figcaption>Where f꜀ is the call option, S is spot price at time T, and K is the strike.</figcaption></figure><p>Looking back, we know how to compute the payoff at a given spot price using piece-wise linear functions, but we still need to check whether the spot price is greater than the strike. This will determine whether to apply just the constant term of the function if the spot is lower than the strike, or to apply both the constant and linear terms in the case that the spot is greater than or equal to the strike. The first thing that pops into mind is using a qubit as a comparator to check which of the two conditions is true.</p><p>A comparator qubit |<em>c</em>⟩ is initialized to state|0⟩. It is converted to state |1⟩ if the spot price is greater than the strike, and stays in |0⟩ otherwise. The transformation looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*2GbVy_l8A2bObgo7Cgct9w.png" /></figure><p>To implement this circuit, we can use Toffoli and CNOT gates to complete bitwise addition over the qubits. A classical array of the binary bitstring of the strike price is created, which is used to compute the carries in the quantum circuit. A quantum register with an equal number of qubits is added to the circuit to help with the bitwise addition, and a final comparator qubit is added to the circuit to store the end result.</p><p>As we pass through each qubit in the circuit, we compute whether or not there is a carry from qubit |<em>i</em>⟩ and corresponding binary digit t[<em>i</em>] in the classical array, the result of which is then stored in the ancilla qubit |<em>aᵢ</em>⟩.</p><p>As you may imagine, there are a variety of cases that could occur, with carries from previous qubits, states of current qubits and the binary from the classical array needing to be taken into account. Each case requires a different quantum gate, which can be adjusted depending on the classical bit string.</p><p>After computing all of the carries the final qubit, |Ψ⟩ₙ, will only be greater than or equal to the strike if there is a carry in the last and most significant qubit.</p><p>Let’s take a look at an example. Assume we have a strike price of $5, which converted to binary corresponds to [101]. 3 qubits encoding the probability distribution are required, as well as 3 ancilla qubits and 1 comparator to hold the end result, meaning that a quantum circuit containing 7 qubits is required.</p><p>The 0th index of the classical array is a 1, which results in a CNOT on the 0th ancilla qubit controlled by the 0th register qubit.</p><p>The 1st index of the classical array is a 0, which results in a Toffoli gate on the 1st index ancilla controlled by the 1st index qubit on the register and the 0th ancilla.</p><p>The 2nd index in the array is a 1, which result in a logical OR applied to the 2nd index ancilla qubit, controlled by the 2nd index register qubit and the 1st index ancilla qubit. The logical OR can be implemented using X and Toffoli gates.</p><p>Finally, the result of the computation is stored on the comparator qubit using a CNOT.</p><p>The final circuit looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-DwztssaFFxKcIpYsS2jmQ.png" /><figcaption>Note that the X gate on the second register appears early.</figcaption></figure><p>We now have a comparator circuit that is able to check whether the spot price is greater than or equal to the strike. To actually implement the linear payoff function, a second ancilla qubit is added to Φ₁. This extra qubit corresponds to the last qubit in the transformation function defined above. The piece-wise linear payoff function of the option can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*AH3X4SF30bzFvW1M9Zu4OA.png" /></figure><p>For a European call option, the variables would take the values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/1*oDTz3vmba-qeA8c1-66cSg.png" /></figure><p>Referring back to the section on computing the payoff for use with AE, the payoff is tailored as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*DIGoBi6V_DLmg6cPOpkLFQ.png" /><figcaption>Where g(i) is a linear function of i and g₀ is an angle to be selected.</figcaption></figure><p>A payoff in the form of the aforementioned equation can be created from the state |Φ₁⟩|0⟩ by rotating implementing <em>cos(g₀)</em>|0⟩ + <em>sin(g₀)</em>|1⟩ on the last ancilla qubit, and then adding a rotation of <em>g(i) </em>controlled by both the comparator qubit and qubits in the probability register. This means that the rotation by that angle only occurs if <em>i ≥ K</em>.</p><p>The above can be implemented with this quantum circuit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*f7vGbAJC74_lqSKJHs0n8w.png" /></figure><p>The state of the qubits after this transformation becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*JzKbVy5N7ybcQN4lqYXgBw.png" /></figure><p>As can be observed, the probability for finding the second ancilla in state |1⟩ is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*1O6coE3xr2vaeBdjaTo3LQ.png" /></figure><p>All that is left to do is figure out which values of <em>g₀</em> and <em>g(i) </em>to use. We’ve already defined a P₁ approximation earlier in the section on computing the payoff, and we’ll use that as a reference point to recover the payoff <strong>E</strong>[<em>f(</em><strong><em>X</em></strong><em>)</em>].</p><p>To satisfy both of the following conditions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*pj_grvxaJoVgROzhfPsUFA.png" /></figure><p><em>g(i)</em> must be set to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*tvV1dPDRXzjBac-5Ep3tLA.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*1ysZRZpXqMINYW2QOQIQCQ.png" /></figure><p>Following this selection for <em>g(i), g</em>₀ takes on</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*tmXX1jbUHVcgvCR9_0tr1w.png" /></figure><p>From these definitions, <strong>E</strong>[<em>max(0, i-K)</em>] can be recovered from P₁ up to a scaling factor and a constant, from which it’s then possible to recover the expectation value <strong>E</strong>[<em>f(i)</em>].</p><p>Of course, this process yields the undiscounted price of the option. To know the option’s present value, discounting by future interest rates would be required, but this can be easily done on classical hardware.</p><p>Loading the probability distribution of an option with spot price of $3, 20% volatility, and 100 days until expiry on onto a quantum register with the help of the Qiskit Finance module, the probability distribution is visualized as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*JnjNgyVgse0M-VGXC1RzEQ.png" /></figure><p>Buying a call for the underlying at a $3.40 strike price, the payoff function has the following form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*1mcVSvbR86WjTA9eHrRNxQ.png" /></figure><p>As calls are easy to price on classical hardware, we obtain an ‘exact value’ of the option computed classically, as well as a quantum estimate and confidence interval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*pshWbETsVzaNKNEkEPiwLw.png" /></figure><p>Note that the accuracy is relatively low due to the fact that the ‘estimated value’ was computed on just 3 qubits, which can be increased for a higher degree of accuracy.</p><p><strong>Pricing European Put Options</strong></p><p>Pricing European puts can be achieved in the same way as outlined above, just changing a few equations to properly represent the payoff of the put. The payoff of a put can be modelled as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*T4SVfnibCswm8J1IuW3ZpA.png" /></figure><p>This payoff denoted in the piecewise notation shown above corresponds to values of:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*kg-Sy0MSlLfbplbEJudMVQ.png" /></figure><p>Implementing this payoff on the same probability distribution as the previous section with a $3.40 strike price, the payoff function changes to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*ejmdYBnmBmObIPRzcWdkGg.png" /></figure><p>As can be observed, the option makes money when the spot price of the underlying is <em>below</em> the strike, which makes sense as a put is a bet against the stock and predicting a decline in future price.</p><p>Once again computing the payoff classically, and on a quantum register with 3 qubits, we get the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*Lmzmp50tJPOiAgmVZTiv3A.png" /></figure><p><strong>Pricing Basket Options</strong></p><p>A European Basket option is an extension of the previous 2 types of options, with the payoff now depending on a weighted sum of a number of underlyings, opening a combined position on multiple assets.</p><p>This type of option depends on a multivariate distribution of random variables, due to the fact that it relies on the price action of multiple underlyings. This distribution represents the spot prices of a basket of underlying assets at expiry, and can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*ZBAUJQMgSpu2OqKJo2U1RQ.png" /></figure><p>The quantum state of this probability distribution can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*G-iXQc2nDEgf6kRD_nhFDA.png" /><figcaption>Where each pᵢ represents the probability that the underlying has taken values id, with d quantum registers representing each asset in the basket of underlying assets. Each register has nⱼ qubits as a sum over all j.</figcaption></figure><p>In addition to this state, basket options also require finding the sum of the random variables. To implement quantum adder circuit to find the sum of two registers, an extra qubit register with <em>n’ </em>qubits is needed to serve as an accumulator.</p><p>We create a new state through the transformation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*5wCx09v9sdSZEBKoBFeU9Q.png" /></figure><p>Now that we have an established quantum state, we can take a look at the payoff of the basket call option, which is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*3CfGxVBkc-UIk_iSe9_gMA.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*XL2AmXMINJbVTLl_3sMaHA.png" /><figcaption>Where w is a vector of basket weight and S is a vector of spot prices at expiration</figcaption></figure><p>In this example, a multivariate log-normal distribution is used to model the underlying asset prices.</p><p>The quantum circuit for pricing the European basket call option is similar to the standard single-asset circuit, except an additional unitary is added to compute the weighted sum of each of the asset registers. The comparator and payoff circuits are then applied, being controlled by the additional accumulator register added.</p><p>Considering a loaded probability distribution on the <em>i </em>registers, the circuit output would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*F0BzSPtU9rIBmCeXGBQBRg.png" /><figcaption>Where the first operation computes the weighted sum of all of the i registers, and the second operation compares the weighted sum of the basket to the strike. Finally, the linear function is implemented on the last qubit, controlled on both the last i register and the comparator.</figcaption></figure><p>But does this actually provide a speedup when compared to classical Monte Carlo methods?</p><p>Amplitude Estimation uses a classical mapping as an estimation for a given knowledge about a quantum state. At the end of the process of AE, the qubits are measured and their values result in an integer <em>y</em> <em>∈ {0, …, M-1}, </em>where M is the number of qubits. This result is classically mapped to an estimate of amplitude <em>a</em>, which looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*nVal7FWAsewofc5D1iUdIA.png" /></figure><p>The maximum distance between any two of these values is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*CjXO50bSDNzgjAg4hnJkeA.png" /></figure><p>Essentially, this equation gives how many <em>M</em> times we need to apply the operator <em>Q </em>to get sufficiently close to the amplitude that properly encodes the option price.</p><p>Using:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*i764pU1xXtX0wFDrunHqTg.png" /></figure><p>It can be show that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*uSWW7uUYKZ0OrtYxcmXUzg.png" /></figure><p>From the fact that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*jo1LJb34-Qh8DXLVaOWxUA.png" /></figure><p>and the P₁ estimation given for the earlier European call option amplitude estimation, the estimation value will be within the range of</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*VQkEOnAy9JZNxgLgeZ-wuA.png" /></figure><p>with the probability of at least 8/π² .</p><p>Comparing this to classical Monte Carlo with the corresponding 8/π² confidence interval on three assets, AE is shown to have a <strong><em>quadratic speedup</em></strong> over classical Monte Carlo. It exhibits <strong><em>M^(-1) </em></strong>scaling versus classical<strong><em> M^(-1/2), </em></strong>and becomes more efficient at<strong><em> 2⁹ </em></strong>samples.</p><p>Great! We’ve once again observed the quadratic speedup of AE on basket options. Implementing them is much the same as implementing the European call option.</p><p>Using a basket of 2 underlying assets is a great introduction to pricing basket options and is the easiest to visualize, so it makes sense to start with them. Loading the probability distribution of 2 identical underlying assets, with a $2 spot, 20% volatility, and 100 days till expiration results in a 3-dimensional graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*hF0WNpagDaQZX2HX554CRg.png" /></figure><p>The payoff function looks very similar to the European call option, except it is now a function of 2 variables rather than a single asset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*HvTbbG2oIhfZNkxlWT9V9g.png" /></figure><p>The total number of qubits in the circuit is 11, with 5 of the qubits representing the spot price of the underlyings at expiration and 6 qubits being used as ancillas for calculations.</p><p>Luckily for us, this computation is still viable on classical computers, so an exact value is computed alongside the quantum equivalent and a confidence interval:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*xpkW3Y-FkXXnd2Rid4tTFA.png" /></figure><p>Again, the quantum estimated value can be further improved with more qubits and better quantum computers, which will continue to be developed into the NISQ era and beyond.</p><p><strong>Acknowledgements</strong></p><p>This article was written based off of the work of <a href="https://arxiv.org/abs/1905.02666"><em>Stamatopoulos et al.</em></a>, which was critical in providing the math and motivation behind the idea of pricing options using quantum computers.</p><p>The simulations in this article were achieved through Qiskit’s Finance module, which offers plenty of <a href="https://qiskit.org/documentation/finance/tutorials/index.html">tutorials</a>.</p><p><em>If you enjoyed this article or found it helpful, please make sure to leave some claps and share it with a friend!</em></p><p><em>If you spot a mistake or want to talk about anything tech-related, make sure to add me on </em><a href="https://www.linkedin.com/in/alexander-yevchenko-1334291b3/"><em>LinkedIn</em></a><em> and </em><a href="https://twitter.com/alex_yevchenko"><em>Twitter</em></a><em>. For more info about me, here’s my </em><a href="https://alexyev.github.io/landing_page.html"><em>website</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bd92ab5fe5c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/using-quantum-computers-to-price-options-5bd92ab5fe5c">Using Quantum Computers to Price Options</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forget Wires: Why We Need a New Way to Transfer Electricity]]></title>
            <link>https://medium.com/geekculture/f-ck-wires-why-we-need-a-new-way-to-transfer-electricity-72495b4947c?source=rss-fc132341b04d------2</link>
            <guid isPermaLink="false">https://medium.com/p/72495b4947c</guid>
            <category><![CDATA[electricity]]></category>
            <category><![CDATA[wireless-energy]]></category>
            <category><![CDATA[grid]]></category>
            <dc:creator><![CDATA[Alexander Yevchenko]]></dc:creator>
            <pubDate>Thu, 05 May 2022 08:02:50 GMT</pubDate>
            <atom:updated>2023-12-28T02:05:44.537Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*XpYbqQWSh4-4WiUe" /><figcaption>Credit: <a href="https://unsplash.com/photos/U6tYeEhEVTk">Unsplash</a></figcaption></figure><p>Since the advent of electricity, it has been transmitted through electrical wire, powering the world. Since the time of the emergence of the first arc lamps, the world has transitioned power generation from heavy pollutants like coal to environmentally friendly, renewable and sustainable sources like hydro, wind and solar. The question is, if we’ve made so much progress on the generation side of the equation, why hasn’t transmission kept up?</p><p><strong>High Maintenance Costs</strong></p><p>One of the largest problems with wired electricity transmission is the sheer amount of maintenance needed to ensure all pylons and wires are functioning safely and correctly. North America is estimated to have over 150 million utility poles stretching out across the continent, a number which is expected to rise as new infrastructure projects are completed. As can be expected with such sheer volume, utility companies simply do not have the time, capital or manpower to properly inspect and maintain each individual pole, which leads to deadly consequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hWD5nwaJ9Z64cOnI.jpg" /><figcaption>Effects of the Camp Fire. Credit: <a href="https://www.wired.com/story/the-terrifying-science-behind-californias-massive-camp-fire/">Wired</a></figcaption></figure><p>The Camp fire, the deadliest and most destructive wildfire in Californian history, killed 85 civilians, destroyed 18,804 structures, and burned 153,336 acres. The cause? A faulty C-hook, responsible for holding up an electric wire, had ground against its metal holder and snapped in a windstorm. PG&amp;E, the utility company that owned the power line, knew that this was a recurring problem yet failed to respond. They conducted visual inspection from the ground and from the air, yet failed to rectify the problem before it caused this disaster. And these are just the power lines we know about.</p><p>It’s clear to see that despite the negligence of the utility company, wired electricity requires intricate inspection, which is expensive and involves workers scaling towers to inspect individual components. Utilities seek a more cost effective work-around that doesn’t catch the problem, and disaster strikes.</p><p><strong>Susceptible to External Interference</strong></p><p>Another key concern with wired electricity is its susceptibility to weather events and natural interference. Snow, wind, temperature variations, and thunderstorms can all have an immediate effect on the grid. If a power line comes into contact with anything, whether it be a fallen tree or a bunch of balloons, it could lead to entire transmission lines being taken out of commission. Despite best efforts of engineers and city planners to install breakers, substations, and other preventative measures, major outages still occur for many communities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8nlUO09mtrK7ZS6e.jpg" /><figcaption>View of Toronto in the dark. Credit: <a href="https://www.thestar.com/photos/2013/08/13/blackout_2003_the_day_in_photos.html">Toronto Star</a></figcaption></figure><p>Take the August 14th, 2003 blackout. Due to a hot day, many people in the Northeast were running air conditioners to keep themselves cool. This created a huge need for electricity in places like Cleveland, which drew electricity in from surrounding power plants on Lake Erie and further south. Due to a series of trees coming into contact with high-voltage power lines bringing electricity into the area, and a computer malfunction rendering electricity controllers oblivious to this fact, the load placed on the system was unsustainable and breakers across the grid kicked in to stop electricity flow. Within 3 minutes, an electricity island greater than the size of Iran was created. More than 50 million people were left without electricity, ranging from Detroit to Toronto to New York. The blackout caused mass boil-water advisories, knocked out cells service, and created chaos on the streets and highways of the affected municipalities. It contributed to nearly 100 deaths.</p><p><strong>Development Issues</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5YItxXCw1dABoeIo.jpg" /><figcaption>Halted electricity transmission project. Credit: <a href="https://www.wbur.org/news/2021/01/15/avangrid-maine-massachusetts-power-energy-grid">WBUR</a></figcaption></figure><p>Wired electricity transmission projects are also notoriously hard to set up, especially in developed countries where there are various parties to be consulted in the erection of a project. In the United States or Canada, for example, new energy projects would require the permission of local and municipal governments, provincial and state government, private landowners, energy oversight boards, First Nations Band Councils, and various other stakeholders. In the U.S., voters in Maine held a referendum and rejected a new high-voltage line that would usher in clean hydropower from Canada. Mainers just didn’t want more, obstructive power lines. The Portland Press Herald dubbed it as ‘one of the most divisive and expensive environmental battles in Maine history.’ In Kenya, land owners opposed to electricity lines running through their property caused significant construction delays to several 240 kV and 404kV lines.</p><p>In 2011, when President Barack Obama tried to accelerate the construction of seven major power lines to bolster the vision of a national economy, only two succeeded in being built. In fact, over 75% of proposed sustainable energy projects never make it to market. This is due to the cost and impact of new high-voltage infrastructure needed to get renewable energies from the rural areas where they are abundant to major urban centers.</p><p><strong>Case Study: Africa</strong></p><p>Take Africa, for example. As solar and wind technologies experience 60% drops in price over the 2010’s, they become the most logical choice for extra power to fuel the region’s rapidly growing economies. Home to the world’s largest concentrated solar farm, the Noor Ouarzazate Solar Power Station, more than a third of Morocco’s electricity is powered by renewable sources. Significant investment funds are being created by the African Development Bank and the European Investment Bank to inject capital into local economies to encourage the growth of sustainable electricity. These projects work to extend abundant electricity to the over 597,000,000 Africans still living in the dark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kayWckfepa2V4w2R.jpg" /><figcaption>Noor Ouarzazate Solar Power Station in southern Morocco. Credit: <a href="https://www.cnn.com/2016/02/08/africa/ouarzazate-morocco-solar-plant/index.html">CNN</a></figcaption></figure><p>To power everyone, the continent requires and efficient method for transferring power over large distances, ideally one that doesn’t come with many of the drawbacks sustained with wired electricity.</p><p>But do people really require electricity? The answer is a resounding yes. Energy access has long been the most important factor in economic growth of a country. The more electricity was available, the more people could get done. The unprecedented growth in living standards in many Western countries was largely driven by technological innovation made possible through the abundant electricity that flowed through the power grids. Electricity brought about accessible and affordable means of modernizing homes, enabling everything from electric refrigeration to illumination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xNCXT81thSFlDeRcT643dg.png" /><figcaption>Credit: <a href="https://ourworldindata.org/grapher/access-to-electricity-vs-gdp-per-capita">Our World In Data</a></figcaption></figure><p>Currently, sustainable energy models in Africa are often limited in size to small micro-grids and single-home solar systems. The home solar systems only provide power to customers while the sun is up, charging a battery that might power three lightbulbs and a radio through the night. While this is a definite improvement over no electricity access at all, this is still categorized a as energy poverty. There needs to be a significant increase to the amount of electricity available to communities to enable them to adopt the technological innovations introduced over the last century to thrive. Instead of a few lights and a radio, we give people access to electric machinery, refrigeration, and the internet.</p><p>Why don’t we just give them electricity through power lines? As if the reasons mentioned above weren’t enough, power lines are also expensive for developing governments to build and maintain. The reality of the situation is that governments are simply not willing to construct hundreds of kilometers of utility poles just to power a few hundred people in a remote village. There are also geographical challenges when traversing remote areas, meaning dense jungle, deserts, mountains, and lakes must be factored in to the costs of constructing electrical grids. All of these factors combine to make electrical infrastructure prohibitively expensive to construct.</p><p>If power lines are no longer a viable solution, what is there left to do? How do we get people in developing nations adequate amounts of power, while reducing transmission costs and encouraging new renewable electricity growth?</p><p>I’m currently working on this problem, creating a way for people to get electricity access at a fraction of the cost wirelessly at <a href="http://jointungsten.com/">jointungsten.com</a>. Feel free to check it out. If you’re interested, contact me: alexanderyevchenko@gmail.com and <a href="https://twitter.com/alex_yevchenko">@alex_yevchenko</a> on Twitter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72495b4947c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/f-ck-wires-why-we-need-a-new-way-to-transfer-electricity-72495b4947c">Forget Wires: Why We Need a New Way to Transfer Electricity</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I Learned in a Month Working Alongside IKEA, and How You Can Use It]]></title>
            <link>https://studentsxstudents.com/what-i-learned-in-a-month-working-alongside-ikea-and-how-you-can-use-it-8e7cc7836b9b?source=rss-fc132341b04d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e7cc7836b9b</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[growth]]></category>
            <category><![CDATA[enjoy-writing]]></category>
            <category><![CDATA[improvement]]></category>
            <dc:creator><![CDATA[Alexander Yevchenko]]></dc:creator>
            <pubDate>Fri, 18 Mar 2022 16:24:56 GMT</pubDate>
            <atom:updated>2022-03-18T16:24:56.915Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*OXNrF6IXy2zk1uXt" /><figcaption><a href="https://unsplash.com/photos/14KzeKimDyI">Unsplash</a></figcaption></figure><p>Tired but happy. This was the general sentiment among my team and I as we submitted our final deck to IKEA. A month of work went into creating this 25 slide deck, and clicking on a little blue button seemed oddly anticlimactic. But all this work calls for a celebration, and in true TKS fashion, takeaways. Perhaps we can call this a celebratory article?</p><p><strong>The Backstory</strong></p><p>So, how did I end up working alongside IKEA in the first place? Doesn’t seem like the first company you’d think of a 16 year old creating decks for. I’m part of The Knowledge Society, an organization that brands itself as a human accelerator creating ‘unicorn’ people. Think Y Combinator or TechStars but for nerdy teenagers. We got the opportunity to work on a Global Challenge, essentially solving problems for major brands on a global scale. Like McKinsey or BCG, but for free.</p><p>I’ll save myself the explanation of the problem, and I’ll let you read the prompt for yourself: ‘How do we increase our market share as city landscapes are shifting and technologies are evolving by 2030? How can IKEA increase accessibility and sustainability while not compromising on affordability to their customers?’</p><p>First thought: isn’t that solving your entire business plan for you, IKEA? Now that I’m on the far side, yes, seems like it.</p><p>Before I get into lessons learned and skills developed, I’d like to take a paragraph to thank our directors for putting this all together and creating such an awesome learning experience. They put in a serious amount of time in securing the partnerships with Walmart, XPRIZE, the United Nations Environment Programme, and IKEA, as well as providing us with too many feedback sessions and workshops to count. Yes, you read that right. They organized four challenges, and we got a pick. Serious round of applause due.</p><p>Who would’ve thought that 4 teens and a multi-billion dollar Swedish furniture retailer were a reciprocal relationship? Surprised myself with that one, too.</p><p><strong>Attitude is Altitude</strong></p><p>To give credit where credit is due, I may or may not have borrowed this one from one of TKS’ founders, Navid.</p><p>Attitude — team dynamics, work ethic, outlook — is everything when you’re working in a team. If you’re not excited to solve a problem, what makes you think that the rest of your team is?</p><p>I can personally attest to this, since this is exactly what our team ran into over the course of the Challenge. Nobody was interested in the problem anymore, and were researching quasi-pointless things just to keep ourselves busy and say that we were ‘productive’. This may have been for a variety of reasons, from other projects to school to a simple lack of motivation, but the most important part is knowing how to deal with it.</p><p><strong>Align your goals.</strong> Know what you want to achieve by the end, and make sure your team is on board with the amount of effort you’re going to put into something. If you’re spending ten hours a day doing research and the rest of your team is only putting in one hour, you’re going to feel like you’re pulling more weight, which will impact future decisions you make. Likewise, your team members will start seeing you as a dead weight, a lose-lose outcome. Once you’ve outlined the amount of work everyone expects out of each other, you’re ready to work backwards from that goal, setting up realistic deadlines as you go along. Knowing <em>when</em> things need to get done sets the precedent for <em>actually getting stuff done.</em></p><p><strong>Be honest.</strong> If you have that wake up moment, tell your team what you think. You’ll be surprised to hear that they often agree with you, but were keeping to themselves. Honesty and trust in your team is the first step to a successful team and an implementable solution. I know, it may seem scary at first, but take the chance. Would you rather be miserable and end up with a below-average project or have a fun time with your team and deliver a final project you’re proud of. I’m certainly choosing the latter.</p><p><strong>Communicate. </strong>Working in a team is the best test of your communication skills. It forces you to set yourself responsible to other people, explain your thought and mental processes clearly, and voice concerns over flaws in a solution. Effective communication can make or break a team, and it’s up to you to make sure you’re holding up your end of the bargain and keeping others accountable. Communication ties back in with honesty, too. If you’re having trouble grasping a concept and won’t be able to have research done in time, let people know. If you’re not able to work certain hours due to an obligation, let people know. When you communicate, it’s easier to find solutions to problems that would have otherwise bubbled under the surface until they boiled over with a crash.</p><p><strong>Take a break.</strong> A high-stakes environment takes a mental and physical toll on everyone, and kills motivation in the process. If things are getting rough or if you’ve been typing away for three hours straight, force yourself and your team to relax for a bit. When under stress, our brains tend to blow problems way out of proportion, and limit our inventiveness in finding a solution. Taking a step back and looking at the bigger picture often helps alleviate this. Use 10 minutes to watch a YouTube video, go outside, or appreciate your pet. With a fresh lens, you’re geared for <em>less worrying and more doing</em>.</p><p><strong>A Great Recommendation</strong></p><p>After everything is said and done, you need to know how to set yourself apart from the competition. You need to know that your solution is good — not just in your eyes, but in an exec’s too. Here are a few points of learning so far.</p><p><strong>Numbers are critical. </strong>It’s one thing to say that your solution is going to increase market share, but it’s a completely different thing to say your solution is going to increase market share <em>by 10%. </em>Anyone can say that they’re going to do X and Y because of Z, but when it comes down to it, the pitches based on solid numbers and research are going to win. This may seem very obvious, but in my experience researching, it’s not obvious enough. Papers, investigations, reviews all providing findings and conclusions, but no calculations or numbers as to where they came to them. Show work, it makes you that much more credible.</p><p><strong>Important stuff first.</strong> Reviewing our deck, I realized just how much of it was filler and provided little value for the reader. Paraphrasing <a href="https://www.linkedin.com/in/ahmed-hassan-5826411b0/">Ahmed</a>, important people will only skim through the slides and perhaps read the subheading. Make sure all of your most important information is there, and that all of your numbers are clearly visible. If they’re interested, they’ll pass it down to someone to review before implementing. The key is in getting them to the point of interest. My team and I noticed the importance of this early on in our research — hundred pages reports were filled with a bunch of BS. You really had to dig for any useful info, if there ever was any in the first place.</p><p><strong>Implement.</strong> You’re giving a recommendation to a company, make sure they know what to do with it. When you create a solution, always keep the implementation plan or pilot in the back of your head. By crunching the numbers and giving the company an exact plan of action, like opening 3 stores in Brooklyn by 2023 between 500–1000 sq. ft., makes the turnaround time from deck to reality much quicker. Problems stemming from interpretation of terms such as ‘urban area’ or ‘micro-stores’ are alleviated, and success metrics can be directly measured against estimates for a very specific pilot plan.</p><p><strong>Get feedback (early). </strong>You’re trapped in your own bubble. You’ll cover the most important questions of a problem in your eyes, but as soon as someone outside of your team glances over your solution, there’s a huge gap you’ve never even thought of addressing. That’s why reaching out to industry professionals is so important — they know everything about the problem, and where your solution is likely to fall short. They know what works and what doesn’t because they’ve seen others try and fail. Validation from people who’ll be tasked with implementing a solution is the key to success. Don’t leave such an important step to the last minute. Consult with them as you’re researching the problem, as you’re discussing potential fixes, and when you’ve come to a final recommendation.</p><p><strong>The Experience</strong></p><p>In my case, it’s not so much about the final product as it is about the experience and new skills. Quoting Navid once again: ‘<strong>Don’t judge your success by the end result.</strong> Instead, judge yourself and your team on your process.’ Don’t get me wrong, my team and I were pretty proud of the end product, but as everything, it could use some improvements too. Same goes for our process. We did things right, and we did things wrong, which we need to improve on.</p><p><strong>The Right</strong></p><ul><li>Daily meetings to ensure everyone was on-track and keeping the team up to date with progress.</li><li>20 min. max meetings to discuss findings and direction, with pre-selected outcomes and action items to finish by the next day.</li><li>Centralized Notion workspace where everyone reviewed work and gave feedback on research / ideas.</li></ul><p><strong>The Wrong</strong></p><ul><li>Choosing our meetings. There were a lot of coaching calls and help sessions throughout the Challenge, but they created little value-add. <strong>How to improve:</strong> Allocate time to the most valuable meetings (e.g. 2 / week), spend extra time with industry professionals and on outreach.</li><li>Getting feedback too late. A few of our feedback meetings with TKS Alumni and industry professionals happened too late in the Challenge stage to feasibly make necessary changes. <strong>How to improve: </strong>Get feedback on preliminary ideas and thought processes, even if you don’t have a deck or solid research to back you up yet. Get out there and see what people think and what advice they have.</li><li>Limiting our solution. Given our challenge prompt, we were constantly worrying ourselves about what was within or outside of those bounds that we could fit into our solution. <strong>How to improve: </strong>Do what works. If your solution is viable and addresses the problems that a company has presented, don’t limit yourself. If it has value, people will recognize it.</li></ul><p><strong>Takeaways</strong></p><p>As a recap, here’s all the important stuff.</p><p><strong><em>Attitude is Altitude.</em></strong></p><ul><li>Align your goals.</li><li>Be honest.</li><li>Communicate.</li><li>Take a break.</li></ul><p><strong><em>A Great Recommendation</em></strong></p><ul><li>Numbers are critical.</li><li>Important stuff first</li><li>Implement</li><li>Get feedback (early)</li></ul><p><em>Stay Connected. </em><a href="https://twitter.com/alex_yevchenko"><em>Twitter</em></a><em>. </em><a href="https://www.linkedin.com/in/alexander-yevchenko-1334291b3/"><em>LinkedIn</em></a><em>. alexanderyevchenko@gmail.com.</em></p><p><strong><em>We’re providing opportunities for the next generation of student thinkers, inventors, and learners, to publish their thoughts, ideas, and innovation through writing.</em></strong><br><em>Our writers span from all areas of topics — from </em><a href="https://studentsxstudents.com/"><em>Growth to Tech, all the way to Future and World</em></a><em>.</em><br><em>So if you feel like you’re about to jump into a rabbit hole of reading these incredible articles, don’t worry, we feel the same way. ;)</em><br><em>That’s why </em><a href="https://studentsxstudents.com/"><em>studentsxstudents</em></a><em> is the place for getting your voice heard!</em><br><em>Sounds interesting? </em><a href="https://studentsxstudents.com/for-students-by-students-becoming-a-contributor-and-expanding-your-impact-f6da9189fa78"><em>Why not join us on this epic journey</em></a>?</p><p><a href="https://studentsxstudents.com/">students x students</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e7cc7836b9b" width="1" height="1" alt=""><hr><p><a href="https://studentsxstudents.com/what-i-learned-in-a-month-working-alongside-ikea-and-how-you-can-use-it-8e7cc7836b9b">What I Learned in a Month Working Alongside IKEA, and How You Can Use It</a> was originally published in <a href="https://studentsxstudents.com/">students x students</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Classification Using Quanvolutional Neural Networks (QNN)]]></title>
            <link>https://studentsxstudents.com/image-classification-using-quanvolutional-neural-networks-qnn-cd13b287ceca?source=rss-fc132341b04d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd13b287ceca</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[enjoy-writing]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[quantum-machine-learning]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <dc:creator><![CDATA[Alexander Yevchenko]]></dc:creator>
            <pubDate>Tue, 15 Feb 2022 23:55:40 GMT</pubDate>
            <atom:updated>2022-02-15T23:55:40.427Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*bEaHZyebYCBNc7ys" /></figure><p>Machine Learning is taking over the world around us. In fact, most of your daily tasks are directly impacted by machine learning algorithms. Do you check your email first thing in the morning? A machine learning spam filter has ensured that the Nigerian Prince that’s been emailing you over the past week doesn’t get through. Want to check in on your crypto losses on Robinhood? Don’t worry, a machine learning algorithm has ensured that those pesky fraudsters don’t run away with your bitcoin.</p><p>We’re growing more and more reliant on machine learning every day. Take a Tesla, for example. Have you ever wondered how they’ve been able to engineer a car that’s able to drive on ‘Autopilot’? <em>I think you can guess the answer to that one…</em></p><p>The car uses a <a href="https://www.youtube.com/watch?v=ECmG0nNJE98">combination</a> of video, radar, ultrasound, and GPS information and feeds it to an onboard computer, which processes it to make decisions in the same speed a human can. The onboard computer uses a neural network, which is a subset of machine learning, to accomplish this feat.</p><p><strong>What is a neural network?</strong></p><p>In the simplest terms, a neural network is modeled around the structure of the human brain and have the ability to recognize patterns in data to solve problems. Take number classification in the example below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*tHKYR6pghkLwg9q6.gif" /><figcaption>Input data being fed, passing through ‘hidden layers’, and being classified as a digit. <a href="https://www.youtube.com/watch?v=aircAruvnKk">3Blue1Brown</a></figcaption></figure><p>Each pixel from the image is passed into the input neurons, passes through hidden layers, and light up a final output neuron that represents what digit the network thinks the image should be classified as.</p><p>I know, I know, I haven’t explained what a hidden layer is. It’s a layer of neurons, where each these neurons has a combination of weights and biases, which both provide an outline or rule as to how the output should behave. The weights determine how much significance each input to a neuron should have, while the biases adjust output values based on the use case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/0*JHErCk2Z-BoLWUv0.png" /><figcaption>The output is the x input multiplied by the weight w, and adjusted using the b bias term. <a href="https://becominghuman.ai/an-introduction-to-neural-networks-50adc4029b09">Yash Matharu</a></figcaption></figure><p>For example, we may want to create a model to predict whether a student will get into university. The weight of their GPA input in the model would be much higher than the weight of a non-contributing factor, like the color of their hair. Similarly, if we needed to increase the importance of this neuron in the next layer, we could increase its output value by adding a bias, 2 for example.</p><p>It’s also worth noting that there’s an activation function, which serves to constrict the possible output values of a particular neuron. For example, I may want to have a neuron that fires only above a certain value, for which I may use the <a href="https://en.wikipedia.org/wiki/Rectifier_(neural_networks)">RELU</a> activation function. Conversely, if I wanted to output probabilities, I would likely use the <a href="https://en.wikipedia.org/wiki/Sigmoid_function">sigmoid</a> function, which transforms values into outputs between 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KkIqFVXK4agvKdtS.png" /><figcaption>In this example, each of the inputs is multiplied by a certain weight, and the sum of these products and a bias is computed. They pass through an activation function which sets a threshold as to whether or not a neuron should fire, and finally spits out an output to the next layer. <a href="https://towardsdatascience.com/whats-the-role-of-weights-and-bias-in-a-neural-network-4cf7e9888a0f">Towards Data Science</a></figcaption></figure><p>The model ‘learns’ by checking its output in the final layer <em>(like the neurons labeled 1–10 in the example above)</em> against the label of the image that was passed in, increasing its accuracy by optimizing the values of the weights and biases in each layer of the model. We can test how well our model performs using a cost function.</p><p>A cost function spits out a number to quantify how well our model works. The output value of our cost function remains low if our model is accurate, and spits out a relatively higher number if we’re doing something totally random. Once again, 3Blue1Brown has come to the rescue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/0*T-bYWpTPjJZeWmHD.gif" /><figcaption>We tell the model that it should fire the output neuron of 3, with all of the other outputs not being fired at all. If the model veers away from these instructions, the value of the loss function increases, offering some indication that we can further optimize our weights and biases. <a href="https://www.youtube.com/watch?v=IHZwWFHWa-w&amp;list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi&amp;index=2">3Blue1Brown</a></figcaption></figure><p>We’ve established how a neural network works and how it’s able to assess how well it’s working, but how do we optimize the individual weights and biases of each neuron in each layer to yield maximal accuracy? The answer: backpropagation.</p><p>In essence, all that backpropagation does is compute the gradients <em>(ugh, calculus) </em>of a formula representing how well our network fits the data, with respect to a certain unknown parameter in our network, which could be a weight or bias.</p><p>To optimize this value, we initialize it with a random value and use gradient descent, which looks like a tangent line taking values closer and closer to the optimized value, at the bottom well of the graph. With each step we take through the model, we move closer to the well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yD_Py48DBYSSsHBU.png" /><figcaption>We move closer to the absolute minimum (optimized value) with each iteration. <a href="https://towardsdatascience.com/stochastic-gradient-descent-explained-in-real-life-predicting-your-pizzas-cooking-time-b7639d5e6a32">Carolina Bento</a></figcaption></figure><p>It’s a lot to take in at once, but it’s all just a bunch of math that lets us describe an intuitive system of pattern recognition. If I see an image of a 2, and I label it incorrectly as a 3, I need to reinforce the neurons that lead to the activation of a 2, as well as minimize the activation of a 3, as well as the other 8 digits of the dataset.</p><p>If you’re new to neural networks and would like to dive deeper into the subject, 3Blue1Brown’s <a href="https://www.youtube.com/watch?v=aircAruvnKk&amp;list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi">video-series</a> is an awesome resource to gain an intuitive understanding. Josh Starmer’s <a href="https://www.youtube.com/playlist?list=PLblh5JKOoLUIxGDQs4LFFD--41Vzf-ME1">StatQuest on Machine Learning</a> is awesome as well.</p><p><strong>Convolutional Neural Networks</strong></p><p>One particularly interesting strand of neural networks that has emerged has been Convolutional Neural Networks, or CNNs for short. They’ve proven to be especially useful in the image classification space, including classifying everything from brain tumors to heart diseases.</p><p><em>What’s so unique about a CNN?</em></p><p>It’s it the name — convolution. Yeah, the first time I heard the word, I had no clue what it meant either. Luckily, there’s always a cool GIF to save the day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*iELrT0kNe_H6ivaj.gif" /><figcaption>A 3x3 kernel passes over the 5x5 matrix input data, producing a convolution. <a href="https://medium.datadriveninvestor.com/convolutional-neural-networks-3b241a5da51e">Rijul Vohra.</a></figcaption></figure><p>That’s all a convolution really is. It’s a window that slides over the input data to produce a more compact representation as an output. What’s even more interesting is that we can tweak the kernel <em>(the middle window)</em> to detect patterns like vertical or horizontal lines, which combine to make shapes, then entire objects like planes or stop signs.</p><p>One can then further simplify the output by applying a maxpool, which looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/0*0xIljWyNTCGaaWiG.gif" /><figcaption>Maxpool transforming a 4x4 input into a 2x2 output. <a href="https://developers.google.com/machine-learning/practica/image-classification/convolutional-neural-networks">Google</a></figcaption></figure><p>All it really does is take the maximum value from a particular region of the convolution and transform it into the output.</p><p>One last thing to note is the notion of a channel. If we were to take a 2D matrix of input pixels from an image, we would have them in the form <em>w x h</em>. If we have an image that contains color, it has three channels: blue, green and red. Using this fact, we can represent our image in the form <em>w x h x c</em>, where <em>c</em> is the number of channels and equal to three.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*6yavDJGu_XdbWhfkT_IsAA.png" /><figcaption>In this example, there are four output channels. <a href="https://pennylane.ai/qml/demos/tutorial_quanvolution.html">Pennylane</a></figcaption></figure><p>As you may have already inferred, CNNs have a huge practicality in our everyday lives. For many, image detection is the key to a fully automated era, where robots can navigate freely and your car can take you from A to B without you ever touching the steering wheel.</p><p>As we gather <a href="https://techcrunch.com/2021/10/20/tesla-third-quarter-earnings-safety-score/">larger and larger amounts</a> of data, we need more raw computing power in order to process it. In key areas like self-driving cars and tumor detection, the faster we can get a better model to the consumer, the better.</p><p>With computer chips pushing one nanometer scale and <a href="https://en.wikipedia.org/wiki/Moore%27s_law">Moore’s Law</a> starting to break down, limitations in processing power may not be able to make use of the amount of data pouring in. As such, we’ll need to find alternatives…</p><p><strong>Where does Quantum come into Play?</strong></p><p>One interesting area of research that may be able to solve this problem is Quantum Machine Learning (QML). As you may have inferred, QML leverages the exponentially increased computing power of a quantum computer to integrate into a machine learning model. If you’re looking for a refresher, check out my previous <a href="https://medium.com/studentsxstudents/revolutionizing-finance-1-qubit-at-a-time-5758f82243bb">article</a> where I explain some of the basics behind quantum computing.</p><p>But what does the quantum computer actually do?</p><p>One method of enhancing classical models that has been proposed is replacing a classical layer of a network with a quantum layer. All of the inputs into the layer are converted into a quantum representation of the data, a quantum circuit is run on this input data, and finally, the qubits are measured, converted back into classical values, and mapped to pixel outputs to be passed on to the next layer. This layer can be trained just as any other classical layer can.</p><p>In this vein, you may be wondering what kind of quantum circuits are to be run on the data once it has reached the quantum layer. One experimental circuit is running random gates on each of the qubits, and optimizing the expectation value of the circuit within the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*gFi4J8MuMWyQ7kbToMXwvQ.png" /><figcaption>Random Layers run on Pennylane.</figcaption></figure><p>The expectation value is the expected value of the measurement of the quantum circuit, which is inherently probabilistic. With Dirac Notation, we define the expectation value as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*_MV4wlznPnljAEF4CxJf8Q.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Expectation_value_(quantum_mechanics)">Wikipedia</a></figcaption></figure><p>which yields a single value, exactly how a node in a classical layer would.</p><p>Another method that has been proposed is using a quantum computer to pre-process data, and then pass it into a fully classical model on which to train. The idea behind this process is that the model would converge faster on the pre-processed dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*Oo9cpKr65PFL_qTwVThwDQ.png" /><figcaption>Quantum pre-processing vs. raw images. <a href="https://pennylane.ai/qml/demos/tutorial_quanvolution.html">Xanadu</a></figcaption></figure><p>It’s critical to note that QML has not yet been proven to superior to classical models, but the results from work done so far in the space have been promising.</p><p>At first, interfacing a classical model with quantum hardware mat seem daunting, but thankfully resources such as Xanadu’s <a href="https://pennylane.ai/">Pennylane</a> make this job extremely easy for us. They allow us to insert a quantum layer directly into a classical model in such a way that the quantum layer is indistinguishable from a classical one. The computer carries on training as usual, never needing to know it was training an expectation value of a quantum circuit.</p><p><strong>Coding the QNN</strong></p><p>How do we go about coding such a thing? First off, pick a library to use. Pennylane supports both PyTorch and TensorFlow, so there’s no need to switch if you prefer one over the other. Past that, it’s much the same as any other neural network.</p><p>First, as usual, run all of the necessary imports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*Ud9KibhHrti-n41HtnD8dA.png" /><figcaption>We’ll be using PyTorch in this example.</figcaption></figure><p>Next, we’ll need to initialize a class called QLayer which will act as our quantum layer. This class will have methods for initialization, creating the random circuit from earlier, as well as the forward convolution pass. Note that the full code is on my GitHub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiXiIGJsqAyo-sBZ77elYA.png" /><figcaption>Initialization of the class using many of the same methods</figcaption></figure><p>Then we have the training function, quite standard. We select a loss function and an optimizer, recording our the values of our loss function and accuracies over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*5Zt64lx3C0mqSaQ7nGirKQ.png" /><figcaption>Optimizes parameters through aforementioned classical methods.</figcaption></figure><p>Next up is importing all of our train and test data, creating the model using our QLayer class and a classical linear layer to represent what digit our model thinks an image is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UwTtvopKaUqo3Zq0KV2pmA.png" /><figcaption>This code will let the model train over one epoch, which is one run-through of all the training data.</figcaption></figure><p>And finally, once the model is trained, a test function to test the accuracy of our model on images that it hasn’t seen before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*ks8OkHZ0PiB0bTeLkPzgzw.png" /></figure><p>All in all, the only that really differs from building a classical CNN is the inclusion of a QLayer class and some QML imports!</p><p><strong>A Quantum Future?</strong></p><p>Yes and no. Quantum has a few already proven use cases, including simulation of molecules and drug discovery, but in no means is it a be all end all, especially in the field of machine learning.</p><p>As quantum computers become increasingly relevant, accessible, and error-correctable/error-free, however, there will be an ever-increasing interest in potential use-cases.</p><p>It’s worth keeping an eye out for new research papers harnessing the unique properties of quantum systems <em>(including the exponential </em><a href="https://arxiv.org/abs/2202.00054"><em>substates</em></a><em> of Hilbert Spaces) </em>to lead to superiority in artificial intelligence.</p><p>Extremely excited of what is to come!</p><p><em>If you enjoyed the article, spotted a mistake, or wanted to discuss, feel free to reach out.</em></p><p><em>Stay Connected. </em><a href="https://twitter.com/alex_yevchenko"><em>Twitter</em></a><em>. </em><a href="https://www.linkedin.com/in/alexander-yevchenko-1334291b3/"><em>LinkedIn</em></a><em>. alexanderyevchenko@gmail.com.</em></p><p><strong><em>We’re providing opportunities for the next generation of student thinkers, inventors, and learners, to publish their thoughts, ideas, and innovation through writing.</em></strong><br><em>Our writers span from all areas of topics — from </em><a href="https://studentsxstudents.com/"><em>Growth to Tech, all the way to Future and World</em></a><em>.</em><br><em>So if you feel like you’re about to jump into a rabbit hole of reading these incredible articles, don’t worry, we feel the same way. ;)</em><br><em>That’s why </em><a href="https://studentsxstudents.com/"><em>studentsxstudents</em></a><em> is the place for getting your voice heard!</em><br><em>Sounds interesting? </em><a href="https://studentsxstudents.com/for-students-by-students-becoming-a-contributor-and-expanding-your-impact-f6da9189fa78"><em>Why not join us on this epic journey</em></a>?</p><p><a href="https://studentsxstudents.com/">students x students</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd13b287ceca" width="1" height="1" alt=""><hr><p><a href="https://studentsxstudents.com/image-classification-using-quanvolutional-neural-networks-qnn-cd13b287ceca">Image Classification Using Quanvolutional Neural Networks (QNN)</a> was originally published in <a href="https://studentsxstudents.com/">students x students</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>