<?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 Noah Vandal on Medium]]></title>
        <description><![CDATA[Stories by Noah Vandal on Medium]]></description>
        <link>https://medium.com/@noah.vandal?source=rss-64a433a25b6c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CCO1Yfmmj82GJCxYhIiNqg.jpeg</url>
            <title>Stories by Noah Vandal on Medium</title>
            <link>https://medium.com/@noah.vandal?source=rss-64a433a25b6c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:16:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@noah.vandal/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[Why do I want a Voice Assistant?]]></title>
            <link>https://medium.com/@noah.vandal/why-do-i-want-a-voice-assistant-d13fccd9bd25?source=rss-64a433a25b6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d13fccd9bd25</guid>
            <category><![CDATA[healthcare-technology]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[customer-success]]></category>
            <category><![CDATA[customer-experience]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Noah Vandal]]></dc:creator>
            <pubDate>Wed, 18 Jun 2025 16:55:55 GMT</pubDate>
            <atom:updated>2025-10-01T20:10:48.941Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wEE0fTdIhgs5_S5p" /><figcaption>A clinician speaking to his voice assistant. Created using GPT-4o-ImageGen.</figcaption></figure><p>The AI industry churns with hype, and I mean <em>a lot</em> of hype. Some observers compare today’s AI fervor to the early-2000s dot-com bubble, and we all remember what followed: a five-year period of relative stagnation for website and software companies. Will history repeat itself with the current AI hype train? Time will tell, and it’s certainly within the realm of possibility. However, entirely discounting AI’s potential impact would be unwise, given the vast untapped opportunities that remain unexplored.</p><p>This article focuses on healthcare as our target market for voice AI adoption. Healthcare has already begun integrating voice AI through automated dictation assistants, essentially low-error-rate devices that transcribe what physicians and other healthcare staff say, eliminating the need for dedicated dictation specialists. This proves especially valuable in high-demand situations, where the pressure to find additional staff is reduced since these devices can transcribe accurately and reliably.</p><p>When we say “voice AI,” we’re referring specifically to AI accessed through speech alone. While there’s a text element operating in the background, users don’t need to see or interact with it directly.</p><p>Why is this approach helpful? Many tasks naturally lend themselves to voice-based information transfer. For humans, speech is our default communication mode; for computers, it’s not. Until recently, we couldn’t effectively use voice AI because it required understanding language nuances, something we couldn’t accomplish correctly until just a few years ago.</p><p>What are some practical healthcare applications? The possibilities are nearly endless, but key applications include:</p><ul><li>Intelligent triage systems</li><li>Self-service scheduling and receptionist duties (like SpeechSage!)</li><li>Insurance verification and billing calls</li><li>Direct note-taking into Electronic Health Records (EHR)</li><li>Loneliness support for elderly patients</li></ul><p>These concepts sound promising, but are they actually practical? According to a 2024 survey, absolutely. Over 70% of patients surveyed expressed comfort with using voice AI, and a majority of physicians believe it can positively impact their workflow. Current trends suggest that the overwhelming majority of healthcare interactions will eventually integrate some form of voice AI technology. [1, 2]</p><p>Consider the pure cost-savings perspective: if you’re paying a human to staff the front desk for incoming calls, they’re likely earning around $20 per hour, approximately $0.33 per minute, most of which isn’t spent actually answering calls. By contrast, voice AI typically operates on a pay-per-use model at much lower rates.</p><p>The customer interaction aspect presents another compelling advantage. With a single person handling calls, when two calls arrive simultaneously, the second caller gets put on hold, or if it’s after hours, nobody answers at all. Additionally, when a receptionist is helping someone in the waiting room, they must interrupt that task to answer the phone. This creates a reduction in service quality that’s far from ideal. Voice AI handles these scenarios in a more customer-centric manner, leading to better outcomes across the board.</p><p>Built-in voice AI integrations can also enable HIPAA-compliant data monitoring that extracts valuable insights, resulting in improved future call outcomes. By continuously monitoring calls, identifying which interactions succeeded and which didn’t, healthcare providers can log and track performance, leading to iterative improvements that create happier customers and better results.</p><p>Voice AI represents a powerful tool for the future, with numerous integration opportunities waiting to be explored.</p><p><em>Note: The author is writing this document with the SpeechSage platform audience in mind; however, it may be used as a reference for anyone desiring to understand what a voice assistant is and how it works.</em></p><h3>References</h3><p>[1] <a href="https://augnito.ai/resources/stats-on-voice-ai-in-healthcare/">https://augnito.ai/resources/stats-on-voice-ai-in-healthcare/</a><br> [2] <a href="https://www.grandviewresearch.com/industry-analysis/ai-voice-agents-healthcare-market-report">https://www.grandviewresearch.com/industry-analysis/ai-voice-agents-healthcare-market-report</a></p><p><a href="https://speechsage.ai/">SpeechSage - AI-Powered Healthcare Phone Call Automation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d13fccd9bd25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI has too much hype]]></title>
            <link>https://medium.com/@noah.vandal/ai-has-too-much-hype-430a1a4ae8f3?source=rss-64a433a25b6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/430a1a4ae8f3</guid>
            <category><![CDATA[humanity]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[interpretability]]></category>
            <category><![CDATA[hype]]></category>
            <dc:creator><![CDATA[Noah Vandal]]></dc:creator>
            <pubDate>Sat, 17 May 2025 14:43:55 GMT</pubDate>
            <atom:updated>2025-05-17T14:43:55.712Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YdCj14F71SQo7aDUYq9Glg.png" /><figcaption>An image of a robot failing to do a simple task, such as watering a plant. Created using OpenAI ChatGPT-4o ImageGen.</figcaption></figure><p>Sometimes society goes through these phases where only a few niches dominate every conversation, to the point where it gets exhausting. I remember the first time I noticed this was when the “selfie” became a thing. All my friends were talking about this new way to take photos, and it was being mentioned constantly across every news and media outlet.</p><p>More recently, it was the NFT and crypto wave. Cryptocurrencies had been around for almost a decade at that point, but it wasn’t until 2018 that they really started to gain traction. Between 2019 and 2021, terms like NFTs and crypto were thrown around so much it felt like overload.</p><p>Now, I feel like we’re in that same kind of phase again, only this time, it’s with “AI” and “agents.” And yeah, it can definitely feel like too much.</p><p>So what’s the common thread in all of these trends? The common denominator is that they all eventually cool down. The hype fades. The actual use cases stay intact, but the obsession dies off. Some people might say, “Well, this time it’s different,” and they’d be right. It <em>is</em> different. But so were NFTs. So was the selfie. These are new ways of doing things that eventually get absorbed into the flow of society, and then we all move on. It’s not some massive shift in the human story. Like most things, it’s just a gradual change — something that makes life a bit easier in some narrow area.</p><p>That being said, AI really does have a lot going for it. But like anything new, it needs to go through real evaluation, mainly whether people can trust it.</p><p>Right now, in the AI space, we’ve been promised by the zealots and optimists that a superintelligence is on its way. One that can do everything. And sure, we already have models that can pass the MENSA test, but they still fail to follow instructions reliably. Maybe they match the uncooperative vibe of some PhDs? Either way, most people don’t want a professor in their pocket. They want a dumb little robot that can just do the dishes, every time, without fail.</p><p>Getting AI and agents to actually work in day-to-day life — whether in workflows, businesses, or at home - means two things: interpretability and trust. Interpretability in the sense that we can understand <em>why</em> the robot did something. We want to see a line of reasoning. This is where having some trace or log of what it tried to do becomes valuable. What actions it took, what tools it used, and what it was aiming to achieve.</p><p>And trust? That comes from repeating the same or similar instructions and getting predictable results. When a person can see how the AI operates, when they can witness it fail and still understand what happened, only then can they know how much trust to place in it.</p><p>It’s kind of like going to a doctor. You want them to be accurate, even perfect. But you also know they’re human and mistakes happen. Whether those mistakes are acceptable depends on how bad it was and whether their logic made sense. AI will be the same. It’s going to mess up sometimes. But if its performance matches or beats what a person could do on that task, it becomes worth using.</p><p>That’s where the real alpha in AI shows up. Not in the hype that it can do everything. But in building it for specific tasks that are interpretable and can build trust. That’s what will let us, over time, figure out how it works — and if we can rely on it.</p><p>Hype is overrated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=430a1a4ae8f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Voice Assistants]]></title>
            <link>https://medium.com/@noah.vandal/understanding-voice-assistants-0301d598bf64?source=rss-64a433a25b6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0301d598bf64</guid>
            <category><![CDATA[conversations]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[society]]></category>
            <category><![CDATA[humans]]></category>
            <dc:creator><![CDATA[Noah Vandal]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 05:30:48 GMT</pubDate>
            <atom:updated>2025-10-01T20:11:45.150Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A human conversing with an AI assistant" src="https://cdn-images-1.medium.com/max/1024/1*jxdqrfk9CenSpUFqsfnTZw.png" /></figure><h3>What is a voice assistant? And how does one work?</h3><p>You probably are familiar with older versions of voice assistants such as Apple’s Siri or Amazon’s Alexa. These assistants are pieces of software that allow the user to talk to the computer and get a response back, although not with perfect accuracy.</p><p>However, when we are talking about a new generation of voice assistants, the technology behind how they work and operate is fundamentally changed from regular Siri or Alexa assistants, in a way that may not be intuitive to the average person. We will try to understand these differences better so that you can have a good grasp of what these differences mean.</p><h3>The Basics of Human Language</h3><p>Humans have a complex language system. The way we express ourselves through language is by basic sounds, which are what we call ‘phonemes’; specifically, patterns of sound that when combined together mean something, for each particular language. When you add multiple phonemes together in a predetermined structure, you get a word, and if you keep adding, you get a sentence, and then a logical thought. All languages share this particular trait, even if the phonemes and combinations that represent particular thoughts differ between languages.</p><p>But what is a phoneme? In the physical world, a phoneme is a specific set of sound frequencies arranged in a particular pattern. These sound frequencies, when passed from one human to another, convey information that can be understood by both participants of the conversation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*8hiHgJU9kDQxRmT_" /><figcaption>Example of phonemes and their representations. From <a href="http://stackoverflow.com/questions/33111685/convert-arpabet-to-ipa-with-stress">http://stackoverflow.com/questions/33111685/convert-arpabet-to-ipa-with-stress</a></figcaption></figure><h3>Traditional Voice Assistants</h3><p>The early assistants such as Siri and Alexa had the capabilities of understanding many basic phonemes in human language, then performing what is called a ‘mapping’ from specific phonemes to the actual words those phonemes represent in the intended language. That is how speech-to-text works (we’ll call that STT from now on).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*F5TYNDnwzPlzlHSd" /><figcaption>Spectrogram of speech recording. Different speech signals can be recorded over time, and the patterns that are found in them can be analzyed to be interpreted as different phonemes. From <a href="http://stackoverflow.com/questions/35169706/audio-feature-for-deep-learning">http://stackoverflow.com/questions/35169706/audio-feature-for-deep-learning</a></figcaption></figure><p>In these early voice assistants, the specific phrases or text spoken by the user was processed using what is called ‘fixed responses. This is why you could ask Siri specific commands, such as “text my wife,” but not other commands like “what happened on this day in 1986?” (that would probably just return a Google search and that was it).</p><p>Siri would also generate predetermined text responses, inserting text in placeholder sections corresponding to the output of your question. For example, if you asked what 12 + 2 was, that calculation came from a predetermined compute module so it could respond with the right answer and speak it back. The module that would then take that text and convert it to speech, in a Siri accent, is called the text-to-speech module, or TTS.</p><h3>Modern Voice Assistants: The Leap Forward</h3><p>How is this different nowadays? Why are these new voice assistant models better? The key is in how data is processed in all the different modules, from the STT module, to the data processing module, to the TTS module.</p><p>The main change comes in the data processing module. As mentioned, previous versions used more fixed responses. The assistant could not respond outside of its simple capabilities. However, since fall of 2022 with ChatGPT, we’ve gained the ability to have models that better understand the actual text. Instead of simply looking for keywords in user text, these models can understand what the user is asking, and based on pre-trained data, generate better responses. As time has gone on, the ability to generate truthful, accurate, and human-sounding responses has only improved, making interactions more natural.</p><h3>Machine Learning: The Foundation</h3><p>The ability of this technology comes from machine learning. This involves taking data in a specific format and feeding it to an algorithm. This algorithm creates what we call a model and evaluates the output quality. If the output isn’t good enough, more data is added and the model is updated. This process is repeated billions of times, gradually improving our ability to generate logical text. This has allowed these models to generate language similar to what a human would produce.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4no_KbEfMbRQf0y_" /><figcaption>A crude schematic of a machine learning model. Instead of using preprogrammed ‘links’ between our network, a series of algorithms are used to allow the machine learning model to ‘learn’ from the data, to do the task at hand, whether trying to understand speech, understand text, or generate speech from text. From <a href="http://stackoverflow.com/questions/34725495/can-i-use-a-neural-network-for-regression-when-input-has-multiple-output-values">http://stackoverflow.com/questions/34725495/can-i-use-a-neural-network-for-regression-when-input-has-multiple-output-values</a></figcaption></figure><p>But the text processing module (called large language models, or LLMs) is not the only part that can use machine learning. The TTS module, for converting text back into phonemes, also benefits from these models. By understanding nuances in the text and seeing where words are in a sentence, the pronunciation can be adjusted to properly reflect the intended meaning. Similarly, if a sentence should evoke a specific emotion, the TTS module can be trained using machine learning to match that emotion better, creating more human-like speech.</p><h3>Beyond Just Better Responses</h3><p>Are these new voice assistants simply slightly better versions of Siri and Alexa with smarter responses and more human-sounding voices? Not quite. They also have a capability called ‘tool calling’ or ‘function calling’ that allows them to do more than just respond to voice questions.</p><p>In computer programming, functions are sections of code that perform specific tasks. If we want our voice assistant to do something specific, such as add an event to our calendar, traditional assistants would need specific keyword patterns. However, with LLMs, they can understand what we’re trying to say even if we don’t phrase it exactly the same way each time.</p><p>This means instead of needing to memorize key phrases and exact intonations for specific commands, the LLM can understand what we’re trying to do and execute it. While Siri and Alexa can understand a few key phrases like “Hey Siri” or “Hey Alexa,” modern assistants go much further. The ability to properly understand and decipher user intent is a key building block of how these assistants operate. Instead of just responding in predetermined ways to specific queries, they can adapt to a variety of inputs and respond gracefully, just as a human might.</p><p>And that is what makes them special.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U9zCMD2XNrV2dYCS" /><figcaption>A man looking over the water, with any human knowledge desired, at his disposal. Use of Voice Assistants is something that can help with that, in constrained settings.</figcaption></figure><blockquote>Note: The author is writing this document with the SpeechSage platform audience in mind; however, it may be used as a reference for anyone desiring to understand what a voice assistant is and how it works.</blockquote><p><a href="https://speechsage.ai/">SpeechSage - AI-Powered Healthcare Phone Call Automation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0301d598bf64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Christians in the age of AI]]></title>
            <link>https://medium.com/@noah.vandal/christians-in-the-age-of-ai-5b88aa563271?source=rss-64a433a25b6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b88aa563271</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[morality]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[spirituality]]></category>
            <category><![CDATA[christianity]]></category>
            <dc:creator><![CDATA[Noah Vandal]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 01:15:54 GMT</pubDate>
            <atom:updated>2024-11-05T01:15:54.618Z</atom:updated>
            <content:encoded><![CDATA[<h4>Every day it seems like there is something in the news about artificial intelligence. Some of these reports are positive, like giving a paralyzed man the ability to partially control his own body again, via the use of implanted neurons, or giving sight to their eyes. Other reports are not so hopeful. With many reports claiming for a loss of jobs in the near future from the advent of the robots, or increased tracking and manipulation, it sometimes seems like ai could cause more harms than good. What is an appropriate response to this new technology? How should I think about these things if I am a Christian?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xl0atqw4K7yapGVf" /><figcaption>Christian family reading bible with AI Bot watching. Generated using Dall-E on ChatGPT.</figcaption></figure><p>With any new technology there arises a form of inherent resistance on the part of the established norms. When the motor vehicle was first released, there were reports of people saying it would be the death of many, as traveling over the speed of 5 miles per hour would snap your neck. While these fine folk were correct in their assessment on vehicles killing many people, it was not a result of people getting their necks snapped due to traveling at excessive speeds. The status quo is something that is hard to change; it seems to be an innate aspect of the human psychology, we like things to stay ‘as they are’. And so, with a new technology we should expect some suspicions and apprehensions, and rightfully so.</p><p>“To what extent are the suspicions unfounded?” You may ask. And that is a great question many of us are asking. First off, we must put on our worldview glasses. These glasses help us see the world in a special way. All of us have a pair of worldview glasses; some of us put on the atheistic worldview; others, the agnostic worldview; and many, many others put on the apathetic worldview, where they haven’t even thought about what they believe, instead are content and willing to believe whatever their circumstances in life and those around them have told them to believe. There are many other types of ‘worldview glasses’, but in the case of the glasses we will use, the lenses are ground to the shape of Sola Scriptura, that is, the Bible is Gods word and it explains the purpose of life, and it is our responsibility to understand it and apply it as applicable. The word Christian means “Christ follower”, and Christ states that the Bible is the book for living life (John 17:17, John 1:1–3); as such, to call yourself a Christian would indicate sola scriptura from this premise.</p><p>Now that we have our glasses on, let us look at this AI thing.</p><p>Let’s first get some grounding of our purpose on Earth. As Christians, our duty is to serve God (Micah 6:8, Matthew 22:37), love others (Matthew 22:39), and to fulfill the great commission (Mark 16:15). But wrapped in these commands are the supposed nuances of life. As we go throughout life, many decisions and questions will crop up that don’t have an explicit answer based on the Bible. A good grounding for making choices or for evaluating a situation is found in Philippians 4:8, where it mentions for us to think on things that are true, honest, just, pure, lovely and of good report. In the arena of making decisions it is generally helpful to ask, “will this ultimately bring greater good to my life or the lives of those around me? Will this bring glory to God, or will it detract?”</p><p>With all this being said, we do have many real world issues that aren’t necessarily black and white. A good example of this could be that of social media. There are many well thought out arguments that can be made supporting the decline of societies directly or indirectly due to the influence social media has had on them. However, to label the entire class of social media as entirely wrong is not the correct approach either, as there still has been good things that have come out of social media. As you can see, the broad category of social media can’t easily be relegated to the class of “bad” vs. “good”. It is dependent on how you use and interact with it in the moment. If an individual is spending excess amounts of time consuming media to the denigration of responsibilities in their life, it would be a net “bad”, as would the use of media for deriving primal sensual pleasure, among other things. On the contrary, connecting with old friends that you otherwise wouldn’t have contact with, or even providing public discourse to a particular idea can possibly be a rewarding and positive use of your time.</p><p>Like with any technology, the use of artificial intelligence is not explicitly a “good” or “bad” issue. There have been many technologies created over the course of human civilization that have at certain times been used for good, while at other times been used for evil. Does a technology that has some ‘good’ aspects ever get to a point where all the bad aspects outweigh the good aspects, where the use of that technology should be entirely prohibited? Is AI more bad than good?</p><p>But I digress.</p><p><strong>CAN AN AI BE SENTIENT??</strong></p><p>Before we discuss some thought about what to think about AI, the commonly brought up topic of the ‘Singularity” and “Sentient AI” should be mentioned. This seems to be a very touchy topic between the two fields of “AI doomers” and “AI accelerationists”, with the doomers generally believing that AI has the possibility to take over the world to some extent or less, with the accelerationists generally believing that the only problem with AI in the future is having <em>no </em>AI in the future.</p><p>Concerns about AI safety and regulation are not unfounded, but they are not of topic here. Instead, lets ask the question, “Can an AI ever become sentient?”</p><p>Of course, with our worldview lenses on.</p><p><em>In the beginning, GOD made the heaven and the earth…and God created man in his own image.</em></p><p>So starts the Bible, in the first chapter of Genesis. We see here the description of man’s embodiment from the Biblical perspective; in the image of God. According to the Bible, the human has three parts to their being; the body, the soul and the spirit. (1 Thessalonians 5:23, Matthew 10:28) No other created being was made in this image, with those three parts intact.</p><p>We see a few different examples of a non-human created being having a form of non-biological influence, as in the case of Baalam and the donkey (Numbers 22), or a herd of pigs (Mark 5); however these are short lived anomalies, and not an essence of the lives of these creatures, as the case of the human soul.</p><p>Humans are special. And it would be foolish to say otherwise. We have an inherent form of understanding of the world around us that other creatures don’t possess to our capacity. We thirst for knowledge. We are creative beings. We are willing to suppress or even sacrifice our biological urges for a higher calling, whatever that calling may be. All of these things are unnatural in the biological world, yet we are biological beings. Why do we do this?</p><p>I would surmise it is because we have a soul.</p><p><strong>WHAT SHOULD I, A CHRISTIAN, THINK ABOUT AI??</strong></p><p>With all of that being said, what is a appropriate posture to take as a believer with respect to intelligence from artificial sources? Is it really a demonic being, or does it have the potential capacity to possess a spiritual aspect?</p><p>I am not going to make that decision for you, but I hope some context can be provided that makes that decision easier for you to conclude.</p><p>Much of what we call artificial intelligence at this point in human history (A.D. 2024) is calculated through a mathematical procedure called matrix multiplication. Essentially what the AI is, is a large grid of numbers that have correlations between the inputs and the outputs. The AI is very dumb in the sense that it doesn’t “know” what these numbers mean, or even what they are trying to predict. But human researchers change the values of these numbers in such a way so that a particular input will produce a particular output, with some randomness (the randomness is added by the humans, to match how humans are also somewhat random with decisions).</p><p>Think of it this way; if you grew up in an English speaking household, you were taught from a young age that the specific set of phonemes that produce the word “app-le” are correlated to a red fruit that has a sweet/tart taste. Those specific phonemes don’t NEED to mean “apple”, the English language has just evolved to associate the meaning with that fruit; if you were raised in a Spanish speaking household, the phoneme combination of “man-za-na” would be associated with that fruit. Similarly are these AI models trained. By using large grids of numbers the correlations from the inputs can produce logical output. And we found out that if you make the count of the numbers in the grid on the order of billions, the perceived intelligence that can be produced from these grids are comparable to that of an adult humans memorization skills.</p><p>As of now, these AI models have no agency: they do not have the free will to create, to train themselves to learn more, to conquer, to appreciate beauty. They are relegated to the control of the human running them, and it doesn’t seem like that arrangement will change anytime soon.</p><p>Some believers may ask, “but can demonic influences control these AI models?” And I do not have enough knowledge to say a definitive no. But I would surmise that the potential capability of spiritual influences on a matrix of numbers stored in a memory unit in a computer is no greater than the potential capability of a spiritual influence on a hammer, or a fly. Some may say that if AI moves its way from the silicon based realm to the biological based realm there will be more repercussions, more spiritual aspects to consider. While I would not agree with that conclusion, I cannot definitively say they would be wrong. But the understanding of how the engineering works would not lead me to that conclusion. Any technology can be used for good or for evil. To bring that thought further one may even infer that MOST technologies have been used for good and for evil. We know that as the time grows closer to the second coming of Jesus Christ the evilness of humanity will become more and more apparent (2 Timothy 3). The technology to produce evil will exist. It is up to us to use this technology in the best way possible, if our situation warrants it.</p><h3>Conclusion</h3><p>We are all individuals with a free will, within the realm of providence, with a certain amount of agency. The time we spend on this earth is finite, and how we make use of it has eternal ramifications. It is wise to be informed of new technologies and how we are to interact with it; however, God is not one to give us the spirit of fear regarding progress in civilization. (2Timothy 1:7) It is up to us to make good use of opportunities as they come along, using our time wisely, and for Gods glory, to the best of our abilities. Remember Ecclesiastes 9:10.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b88aa563271" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crusty Rusty and the search for the fastest ML compute (Python vs Rust in Neural Networks)]]></title>
            <link>https://medium.com/@noah.vandal/crusty-rusty-and-the-search-for-the-fastest-ml-compute-python-vs-rust-in-neural-networks-4c3f0d0f5698?source=rss-64a433a25b6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c3f0d0f5698</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Noah Vandal]]></dc:creator>
            <pubDate>Fri, 10 Nov 2023 01:39:45 GMT</pubDate>
            <atom:updated>2023-11-10T01:50:24.286Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BENcLXFWQcoA27gumSPcCA.png" /><figcaption>A rusty, crusty crab adjusting those weights (Author via Dall-E 3)</figcaption></figure><p>Rust has recently been touted as the newest, bestest and greatest computer language in recent times, and with plenty of good reason. With secure variable typing and memory control, helpful error verbosity on the command line, and no global interpreter lock to tie up those threads it is no wonder that plenty of folks have been voting this paradigm as the one of their choice often in the past few years.</p><p>One thing that has not been as prevalent, however, is the use of Rust for machine learning applications. The field of ML is anything but dying, and the language of choice has proven to be Python, for a wide variety of reasons. It is well known that Python is not the fastest language, especially when it comes to intensive compute operations; oftentimes, however Python is build on top of C++ or C hooks, which brings its performance to almost state of the art. I was curious to see how Rust stacks up in the ML domain, how it competes against the top dog, Python.</p><p>The “Hello, World!” of ML is the use of the MNIST dataset for classifying handwritten digits. Created by Yann Lecun in the 90’s for use by convolutional networks, it is now a good way to learn the basics of ML and how to incorporate different functions on a test dataset. It is comprised of a number of handwritten numbers, represented as a 28x28 grayscale image. This dataset is what we will use for our analysis, trying our best to keep an apples to apples comparison when implementing both the Rust code and the Python code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*0DjE4pZvVaM9G0KxbfhtQA.png" /><figcaption>Examples from the MNIST dataset</figcaption></figure><p>The first step of any ML model is getting the data. For Rust, we were able to use the MnistBuilder struct to properly acquire and load our train and test image and label datasets, respectively.</p><pre>fn load_mnist_data() -&gt; (Tensor, Tensor, Tensor, Tensor) {<br>    let Mnist { trn_img, trn_lbl, tst_img, tst_lbl, .. } = MnistBuilder::new()<br>        .label_format_digit()<br>        .training_set_length(50_000)<br>        .validation_set_length(10_000)<br>        .test_set_length(10_000)<br>        .finalize();<br>    <br>    let train_images_tensor: Tensor = Tensor::of_slice(&amp;trn_img.into_iter().map(|x| x as f32 / 255.0).collect::&lt;Vec&lt;f32&gt;&gt;()).view([-1, 28, 28]);<br>    let train_labels_tensor: Tensor = Tensor::of_slice(&amp;trn_lbl.into_iter().map(|x| x as i64).collect::&lt;Vec&lt;i64&gt;&gt;());<br>    let test_images_tensor: Tensor = Tensor::of_slice(&amp;tst_img.into_iter().map(|x| x as f32 / 255.0).collect::&lt;Vec&lt;f32&gt;&gt;()).view([-1, 28, 28]);<br>    let test_labels_tensor: Tensor = Tensor::of_slice(&amp;tst_lbl.into_iter().map(|x| x as i64).collect::&lt;Vec&lt;i64&gt;&gt;());<br><br>    (train_images_tensor, train_labels_tensor, test_images_tensor, test_labels_tensor)<br>}</pre><p>While in Python I used the DataLoader feature from Pytorch.</p><pre>def load_mnist_data():<br>    transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])<br>    <br>    train_dataset = MNIST(root=&#39;./data&#39;, train=True, download=True, transform=transform)<br>    test_dataset = MNIST(root=&#39;./data&#39;, train=False, download=True, transform=transform)<br>    <br>    train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=64, shuffle=True)<br>    test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=64, shuffle=False)<br>    <br>    return train_loader, test_loader</pre><p>The next step is to define the model. In our case, we will stick to the basics of the usual implementation of MNIST (non-convolutional).</p><p>For Rust:</p><pre>fn create_network(vs: &amp;nn::Path) -&gt; nn::Sequential {<br>    let input_size: i64 = 784;<br>    let hidden_size: i64 = 128;<br>    let output_size: i64 = 10;<br>    let cfg: nn::LinearConfig = nn::LinearConfig::default();<br><br>    nn::seq()<br>        .add(nn::linear(vs / &quot;layer1&quot;, input_size, hidden_size, cfg))<br>        .add_fn(|xs| xs.relu())<br>        .add(nn::linear(vs / &quot;layer2&quot;, hidden_size, output_size, cfg))<br>}</pre><p>while for Python:</p><pre>class NeuralNetwork(nn.Module):<br>    def __init__(self):<br>        super(NeuralNetwork, self).__init__()<br>        self.flatten = nn.Flatten()<br>        self.linear_relu_stack = nn.Sequential(<br>            nn.Linear(28*28, 128),<br>            nn.ReLU(),<br>            nn.Linear(128, 10),<br>        )<br><br>    def forward(self, x):<br>        x = self.flatten(x)<br>        logits = self.linear_relu_stack(x)<br>        return logits</pre><p>Now, time to create the training loop;</p><p>for Rust:</p><pre>fn train_network(net: &amp;mut nn::Sequential, optimizer: &amp;mut nn::Optimizer, train_images_tensor: &amp;Tensor, train_labels_tensor: &amp;Tensor, num_epochs: i32, batch_size: i64) {<br>    let num_batches = train_images_tensor.size()[0] / batch_size;<br>    let mut epoch_loss = 0.0;<br>    for epoch in tqdm(1..=num_epochs) {<br>        let mut total_correct = 0;<br>        let mut total = 0;<br>        for batch_index in tqdm(0..num_batches) {<br>            let batch = train_images_tensor.narrow(0, batch_index * batch_size, batch_size).view([-1, 28 * 28]);<br>            let labels = train_labels_tensor.narrow(0, batch_index * batch_size, batch_size);<br>            let predictions = net.forward(&amp;batch);<br>            let loss = predictions.cross_entropy_for_logits(&amp;labels);<br>            optimizer.zero_grad();<br>            loss.backward();<br>            optimizer.step();<br><br>            total_correct += label_accuracy(&amp;predictions, &amp;labels) as i64;<br>            total += batch_size;<br>            epoch_loss = loss.double_value(&amp;[]);<br>        }<br>        println!(&quot;Epoch: {}, Loss: {}&quot;, epoch, epoch_loss);<br>        println!(&quot;Train accuracy: {}&quot;, total_correct as f64 / total as f64)<br>    }<br>}</pre><p>we have a few different hyperparameters here that we are sending to the train loop; these are the dataloaders that we defined previously, the network we are training, the optimizer we are using, and data for the number of epochs and batch size desired.</p><p>For Python:</p><pre>def trainNetwork(net, optimizer, trainLoader, numEpochs, device):<br>    for epoch in tqdm(range(numEpochs)):<br>        net.train()<br>        total_correct = 0<br>        total = 0<br>        for batch_idx, (data, target) in enumerate(trainLoader):<br>            optimizer.zero_grad()<br>            data.to(device)<br>            output = net(data)<br>            output.to(&#39;cpu&#39;)<br>            loss = nn.CrossEntropyLoss()(output, target)<br>            loss.backward()<br>            optimizer.step()<br><br>            total_correct += (output.argmax(1) == target).type(torch.float).sum().item()<br>            total += data.size(0)<br>        <br>        print(f&quot;Epoch: {epoch}, Loss: {loss.item()}&quot;)<br>        print(f&quot;Train accuracy: {total_correct / total}&quot;)</pre><p>And then finally, our evaluation function;</p><p>for Rust:</p><pre>fn evaluate_network(net: &amp;mut nn::Sequential, test_images_tensor: &amp;Tensor, test_labels_tensor: &amp;Tensor, test_batch_size: i64) -&gt; f64 {<br>    let num_test_batches = test_images_tensor.size()[0] / test_batch_size;<br>    let mut total_correct = 0;<br>    let mut total = 0;<br><br>    for batch_index in tqdm(0..num_test_batches) {<br>        let batch = test_images_tensor.narrow(0, batch_index * test_batch_size, test_batch_size).view([-1, 28 * 28]);<br>        let labels = test_labels_tensor.narrow(0, batch_index * test_batch_size, test_batch_size);<br>        let logits = net.forward(&amp;batch);<br>        total_correct += label_accuracy(&amp;logits, &amp;labels) as i64;<br>        total += test_batch_size;<br>    }<br><br>    total_correct as f64 / total as f64<br>}</pre><p>while for Python:</p><pre>def evaluateNetwork(net, testLoader, device):<br>    net.eval()<br>    totalCorrect = 0<br>    total = 0<br>    with torch.no_grad():<br>        for data, target in testLoader:<br>            data.to(device)<br>            output = net(data)<br>            output.to(&#39;cpu&#39;)<br>            totalCorrect += (output.argmax(1) == target).type(torch.float).sum().item()<br>            total += data.size(0)<br><br>    return totalCorrect / total</pre><p>For both models the loss used was cross entropy with logits, and for the optimizer Adam was implemented, with an initial learning rate of 0.001.</p><p>Keep in mind that this entire time, I want as much of an apples to apples comparison if possible. With that being said, we have the following for results, comparing running on Python vs Rust. I am using only the CPU (i7–12650H), and while there are other programs running on my machine, the programs that were running for the Python execution are the same as that of the Rust execution. So without further ado, and assuming as much has been kept constant as possible, lets compare our results.</p><p>For the loss, since the implementations are similar we shouldn’t expect too much of a difference. And as we find out that there isn’t too much of a large divergence, with both Python and Rust code settling on a similar loss value in the 10th epoch. An abnormal spike in the loss for the Python code is an indication that AGI is just around the corner (latent sentience, one may say).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*sj4akwUpUXYmtppvs1PElg.png" /><figcaption>Loss values over 10 train epochs</figcaption></figure><p>The accuracy is much of the same story, with the Python code only slightly behind the Rust code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*sowdyetRBS3HnmPx3JIN9Q.png" /><figcaption>Accuracy values over 10 epochs</figcaption></figure><p>The time taken to execute each epoch, however, is a point of much difference. If you will look carefully, you can see that the Python takes an order of magnitude greater time to execute than the Rust code, per epoch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*mz-re1QyD5Re9RkcXo4NPA.png" /><figcaption>Time taken per epoch, in seconds.</figcaption></figure><p>I was very surprised from these results. I had hoped that Rust would be faster, but I didn’t think it would be this much faster. I may have implementation inefficiencies that could be checked out (if so, let me know!). But the fact that even while training the Rust had a better grasp on the loss and the accuracy shows that it is able to hold its own, at least for this problem.</p><p>I realize I did not implement any convolutional networks in this exercise. (Next time?!?). But this was a good proof of concept for me, that Rust may be a good language to use for ML purposes. With the number of packages in Rust in the domain of machine learning being somewhat sparse, we may have an interesting next few years, trying to build packages that could benefit us (us as in me, other ML engineers, and all who utilize AI and have to pay for AWS credits (crying face)).</p><p>Github repos with source code;</p><p>Python code:</p><p><a href="https://github.com/noahvandal/rust_convolution_project">https://github.com/noahvandal/python_convolution_project</a></p><p>Rust code:</p><p><a href="https://github.com/noahvandal/python_convolution_project">https://github.com/noahvandal/rust_convolution_project</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c3f0d0f5698" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using a Raspberry Pi 3 as an Edge Device]]></title>
            <link>https://medium.com/@noah.vandal/using-a-raspberry-pi-3-as-an-edge-device-a58447935751?source=rss-64a433a25b6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a58447935751</guid>
            <category><![CDATA[philosophy]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[squirrels]]></category>
            <dc:creator><![CDATA[Noah Vandal]]></dc:creator>
            <pubDate>Thu, 21 Sep 2023 20:58:11 GMT</pubDate>
            <atom:updated>2023-09-21T20:58:11.066Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ATYP_1P9ACntJgXp" /><figcaption>Photo by <a href="https://unsplash.com/@jainath?utm_source=medium&amp;utm_medium=referral">Jainath Ponnala</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I had a raspberry pi 3 sitting around. Not in a very productive state. And I wanted to put it to use! I have some squirrels running around in my backyard, and I wanted to track their movements throughout the day, so I thought running an object detection on a raspberry pi would work well! However, I also wanted to allow myself to view the data from anywhere, along with not needing to store detection data on my device. With these thoughts in mind, I decided on also utilizing a remote database that I can push my data to. I will detail my object detection model, along with how I pushed my data to a database (for FREE!) in this article.</p><p>STEPS: <br>We needed to:<br>1) Acquire image<br>2) Perform object detection on image<br>3) Get relevant results from detection<br>4) Push results to database<br>5) Repeat!!</p><p>For (1), I opted to buy a Raspberry Pi camera with built in IR detection form amazon.</p><p><a href="https://www.amazon.com/Aokin-Raspberry-Automatic-Switching-Adjustable/dp/B07JQ1L8XW/ref=sr_1_3?crid=1YQ1CKTQ7EF0P&amp;keywords=raspberry+pi+3+camera+with+ir&amp;qid=1695326621&amp;sprefix=raspberry+pi+3+camerawith+ir%2Caps%2C242&amp;sr=8-3">for Raspberry Pi 3 Model B+ Camera Module Automatic IR-Cut Switching Day/Night Vision Video Webcam Adjustable Focus 5MP OV5647 Sensor 1080p HD for Raspberry Pi 2/3 Model B Model A A+ Zero/Zero W</a></p><p>For actually acquiring the frame from the camera feed, I used the OpenCV “VideoCapture” function for acquiring each frame.</p><pre>    # initialize frame source<br>    src = cv2.VideoCapture(0)</pre><p>Continuing on. How did we perform object detection? I was able to utilize a pretrained model from tensorflow hub; this provides a folder with ‘detect.tflite’ and ‘labelmap.txt’ pretrained embeddings.</p><p><a href="https://tfhub.dev/">TensorFlow Hub</a></p><p>I like the use of modular code; so I will create a class that instantiates the model, which can then be called for initialization. The only package dependencies required for this project is ‘cv2’, ‘numpy’, ‘tflite_interpreter’, and ‘firebase_admin’.</p><pre><br>class LoadModel():<br>    def __init__(self, <br>        modelName=&#39;ModelDir&#39;,<br>        weights=&#39;detect.tflite&#39;,<br>        labels=&#39;labelmap.txt&#39;,<br>        imW = 640,<br>        imH = 480,<br>        ):<br>        self.modelName = modelName<br>        self.weightPath = weights<br>        self.labelPath = labels<br>        self.imgWidth = imW<br>        self.imgHeight = imH<br><br>        ## run load<br>        self.load()<br><br>    def load(self):<br>        global isFloatingModel<br>        # Get path to current working directory<br>        CWD_PATH = os.getcwd()<br><br>        # Path to .tflite file, which contains the model that is used for object detection<br>        PATH_TO_CKPT = os.path.join(CWD_PATH,self.modelName,self.weightPath)<br><br>        # Path to label map file<br>        PATH_TO_LABELS = os.path.join(CWD_PATH,self.modelName,self.labelPath)<br><br>        # Load the label map<br>        with open(PATH_TO_LABELS, &#39;r&#39;) as f:<br>            labels = [line.strip() for line in f.readlines()]<br><br>        ## fix for labels from coco training<br>        if labels[0] == &#39;???&#39;:<br>            del(labels[0])<br><br>        interpreter = Interpreter(model_path=PATH_TO_CKPT)<br><br>        interpreter.allocate_tensors()<br><br>        # Get model details<br>        input_details = interpreter.get_input_details()<br>        output_details = interpreter.get_output_details()<br>        height = input_details[0][&#39;shape&#39;][1]<br>        width = input_details[0][&#39;shape&#39;][2]<br><br>        isFloatingModel = (input_details[0][&#39;dtype&#39;] == np.float32)<br><br>        return interpreter, input_details, output_details, labels, height, width</pre><p>Now when model.load() is called in our main code, it will return all necessary variables. Okay, so now we’ve got our model. We still need to perform object detection. How does this work? In our main() function (the function that is executed as the parent when running the script), we have the following loop:</p><pre><br>    while True:<br>        ret, frame = src.read() ## grab frame<br>        inputData = augmentImageBeforeInference(frame, height, width)<br><br>        ## inference frame<br>        interpreter.set_tensor(input_details[0][&#39;index&#39;],inputData)<br>        interpreter.invoke()<br><br>        ## put data on image<br>        outputFrame, frameData = processImage(frame, interpreter, output_details, labels, imH, imW)<br><br>        ## display image<br>        cv2.imshow(&#39;Object detector&#39;, outputFrame)<br><br><br>        # Press &#39;q&#39; to quit<br>        if cv2.waitKey(1) == ord(&#39;q&#39;):<br>            break<br><br>   <br>    ## when terminated, release from memory<br>    src.release()<br>    cv2.destroyAllWindows()</pre><p>Before inferencing the image, we need to ensure it is in the correct format and shape. That is what the “augmentImageBeforeInference” function does here.</p><pre>def augmentImageBeforeInference(frame, height, width):<br>    global isFloatingModel # is model float32?<br>    frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)<br>    frame_resized = cv2.resize(frame_rgb, (width, height))<br>    # frame_resized = resize_aspect_fit(frame_rgb, (width, height))<br><br>    input_data = np.expand_dims(frame_resized, axis=0)<br>    # print(frame_rgb.shape, frame_resized.shape)<br><br>    # Normalize pixel values if using a floating model (i.e. if model is non-quantized)<br>    if isFloatingModel:<br>        input_data = (np.float32(input_data) - input_mean) / input_std<br>    <br>    return input_data</pre><p>What is the “processImage” function here doing? This image is grabbing bounding boxes from the output of the network prediction, putting them on the frame in question, and also returning the values of those bounding boxes “frameData”. This is step 3. Like I said, I like modular coding. Here is the processImage function:</p><pre><br>def processImage(frame,interpreter, output_details,labels, imH, imW):<br>    # Retrieve detection results<br>    boxes = interpreter.get_tensor(output_details[0][&#39;index&#39;])[0] # Bounding box coordinates of detected objects<br>    classes = interpreter.get_tensor(output_details[1][&#39;index&#39;])[0] # Class index of detected objects<br>    scores = interpreter.get_tensor(output_details[2][&#39;index&#39;])[0] # Confidence of detected objects<br>    #num = interpreter.get_tensor(output_details[3][&#39;index&#39;])[0]  # Total number of detected objects (inaccurate and not needed)<br><br>    # Loop over all detections and draw detection box if confidence is above minimum threshold<br>    objects= {}<br>    for i in range(len(scores)):<br>        if ((scores[i] &gt; 0.5) and (scores[i] &lt;= 1.0)):<br><br>            # Get bounding box coordinates and draw box<br>            # Interpreter can return coordinates that are outside of image dimensions, need to force them to be within image using max() and min()<br>            ymin = int(max(1,(boxes[i][0] * imH)))<br>            xmin = int(max(1,(boxes[i][1] * imW)))<br>            ymax = int(min(imH,(boxes[i][2] * imH)))<br>            xmax = int(min(imW,(boxes[i][3] * imW)))<br>            <br>            cv2.rectangle(frame, (xmin,ymin), (xmax,ymax), (10, 255, 0), 2)<br>            <br>            # Draw label<br>            object_name = labels[int(classes[i])] # Look up object name from &quot;labels&quot; array using class index<br>            label = &#39;%s: %d%%&#39; % (object_name, int(scores[i]*100)) # Example: &#39;person: 72%&#39;<br>            labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2) # Get font size<br>            label_ymin = max(ymin, labelSize[1] + 10) # Make sure not to draw label too close to top of window<br>            cv2.rectangle(frame, (xmin, label_ymin-labelSize[1]-10), (xmin+labelSize[0], label_ymin+baseLine-10), (255, 255, 255), cv2.FILLED) # Draw white box to put label text in<br>            cv2.putText(frame, label, (xmin, label_ymin-7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2) # Draw label text<br><br>            # Draw circle in center<br>            xcenter = xmin + (int(round((xmax - xmin) / 2)))<br>            ycenter = ymin + (int(round((ymax - ymin) / 2)))<br>            cv2.circle(frame, (xcenter, ycenter), 5, (0,0,255), thickness=-1)<br><br>            objectDetected = {<br>                &#39;name&#39;: labels[int(classes[i])],<br>                &#39;location&#39;: (xcenter,ycenter),<br>                &#39;upperLeft&#39;: (xmin, ymin),<br>                &#39;time&#39;: datetime.now().isoformat()<br>            }<br>            objects[f&#39;object_{i}&#39;] = objectDetected # dictionary of dictionaries<br>    <br>    return frame, objects</pre><p>Great!!! We now have step 2 and 3 done, getting detections from our model and processing the results. Now onto the final step, step 4, putting those images onto a database while the inferencing is occurring, in as close to real-time as possible.</p><p>Google has a really nice, free storage system called Firebase. If you have a Google account, you have access to Firebase. To make a database that a Raspberry Pi can push data to, you have to create a Firestore Database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*VZiWXLDhO5Nm_9MWyR4SVA.png" /><figcaption>Firestore Database</figcaption></figure><p>Once you are in the database, create a new project. Follow the steps to get it initialized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*VseI8kB19Kmn_4cShGKZ2w.png" /><figcaption>Adding a project to Firestore</figcaption></figure><p>Once the new project has been created, ensure it is selected as the project using in the Firebase webapp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*QiDIy_yBN0ulBTaPeldYjA.png" /><figcaption>Ensure correct project is selected</figcaption></figure><p>Then click the ‘create database’ button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*n6xP5JCNJApoxUENh4Sgow.png" /><figcaption>Create Database</figcaption></figure><p>Click ‘next’ unless you have good reason to change the mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aaXuQmknVMIb4BWDSwh6-g.png" /></figure><p>Click ‘enable’</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*WB-MYycfBB-QrQuL86M8Vg.png" /></figure><p>Once you have the database initialized, you need to give your Raspberry Pi access to it. We are going to generate a secret key that will be stored on your RPi device.</p><p>Click on ‘Project Settings’ from the settings button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*5EYrujlYysgFmqp7PdHDWg.png" /><figcaption>Project Settings</figcaption></figure><p>Click on ‘Service Accounts”, and then ensure that the correct language (python) is selected. Then click on the “Generate new private key” button, and a Json will be downloaded onto your computer. All these steps for creating database can be done either on a local computer or your Raspberry Pi, from a browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0rRH8798vhwL1Mb1bpsFA.png" /><figcaption>Getting a new private key for use on the RPi</figcaption></figure><p>Now, back to our RPi python code. Lets initialize our Firebase account in the code:</p><pre>class SendToFirestoreDB():<br>    def __init__(self):<br>        cred = credentials.Certificate(&quot;path/to/secret/key/we/got/from/firebase.json&quot;)<br>        initialize_app(cred)<br><br>        self.loadDb()<br><br>    def loadDb(self):<br>        db = firestore.client()<br><br>        return db</pre><p>In our main() function:</p><pre>    ## initialize database origin<br>    database = SendToFirestoreDB()<br>    db = database.loadDb()</pre><p>Now, when we get data we want to be saved on our database, we can update our while loop to reflect the fact; here is the entire main() code with updates to reflect our pushes to our database:</p><pre><br>def main():<br>    ## initialize model<br>    model = LoadModel()<br>    interpreter, input_details, output_details, labels, height, width = model.load()<br><br>    ## initialize database origin<br>    database = SendToFirestoreDB()<br>    db = database.loadDb()<br><br>    # Initialize frame rate calculation<br>    frame_rate_calc = 1<br>    freq = cv2.getTickFrequency()<br><br>    # initialize frame source<br>    src = cv2.VideoCapture(0)<br><br>    # for storing tracking data<br>    classPaths = {}<br><br>    # size of cam dims<br>    imH, imW = 480, 640<br><br>    startTime = str(datetime.now())<br>    frameNumber = 0<br>    while True:<br>        print(&#39;Frame&#39;, frameNumber)<br>        t1 = cv2.getTickCount()<br>        ret, frame = src.read() ## grab frame<br>        inputData = augmentImageBeforeInference(frame, height, width)<br><br>        ## inference frame<br>        interpreter.set_tensor(input_details[0][&#39;index&#39;],inputData)<br>        interpreter.invoke()<br><br>        ## put data on image<br>        outputFrame, frameData = processImage(frame, interpreter, output_details, labels, imH, imW)<br><br>        ## push data to db; new document for each frame<br>        db_push = db.collection(startTime).document(f&quot;Frame_{frameNumber}&quot;)<br>        db_push.set(frameData)<br><br>        # Draw framerate in corner of frame<br>        cv2.putText(outputFrame,&#39;FPS: {0:.2f}&#39;.format(frame_rate_calc),(30,50),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,0),2,cv2.LINE_AA)<br>        outputFrame = plot_paths(outputFrame, classPaths)<br><br>        ## display image<br>        cv2.imshow(&#39;Object detector&#39;, outputFrame)<br><br>        # Calculate framerate<br>        t2 = cv2.getTickCount()<br>        time1 = (t2-t1)/freq<br>        frame_rate_calc= 1/time1<br><br>        # Press &#39;q&#39; to quit<br>        if cv2.waitKey(1) == ord(&#39;q&#39;):<br>            break<br><br>        # update framecount<br>        frameNumber += 1<br>    <br>    ## when terminated, release from memory<br>    src.release()<br>    cv2.destroyAllWindows()</pre><p>In this code, I opted for a new collections file to be created for each inference session, with a new document in each session created for each image. Feel free to change this as desired. I also added some analytics for understanding the performance (time) of my algorithm.</p><p>The last step, step 5, occurs <em>here</em> unless there are bugs in the code (there always are).</p><p>And that’s it! This is one way you can utilize object detection on a raspberry pi and push it to a database, for free. Unfortunately this did not work too well for squirrel detection; however I intend on training a custom dataset for better performance in the future!</p><p>Credit given where credit is due: some of the code for the object detection portion of the model is from here:</p><p><a href="https://github.com/ShawnHymel/tensorflow-object-detection/tree/master/04-object-detection">tensorflow-object-detection/04-object-detection at master · ShawnHymel/tensorflow-object-detection</a></p><p>My source code and model:</p><p><a href="https://github.com/noahvandal/TFLiteObjectDetection/tree/master">GitHub - noahvandal/TFLiteObjectDetection</a></p><p>Thank you for reading!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a58447935751" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Label Class Matrix from an RGB mask for Segmentation Training in Python]]></title>
            <link>https://medium.com/@noah.vandal/creating-a-label-class-matrix-from-an-rgb-mask-for-segmentation-training-in-python-2ddceba459cb?source=rss-64a433a25b6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ddceba459cb</guid>
            <category><![CDATA[unet]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Noah Vandal]]></dc:creator>
            <pubDate>Fri, 06 Jan 2023 23:56:18 GMT</pubDate>
            <atom:updated>2023-01-06T23:56:18.566Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Oranges on matte background; representative of extracting objects of interest from entire scene." src="https://cdn-images-1.medium.com/max/1024/0*myckgWUgHctkyB3z" /><figcaption>Photo by <a href="https://unsplash.com/@charlesdeluvio?utm_source=medium&amp;utm_medium=referral">charlesdeluvio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article as a brief summary for how to create a matrix with label values from an RGB segmentation mask. I am writing this article in the hope that it can be useful for someone else, as I found the documentation regarding this topic to be sparse.</p><p>Goal: create a 2-D matrix of integers, with each integer representing a different class from a dictionary of pre-defined classes. The input for creating this matrix is a RGB image with a defined set of pixel colors; namely, the number of distinct colors is the same amount as the number of different classes. The 2-D matrix of integers can then be used for the ‘y’ label on a loss function, such as <a href="https://pytorch.org/docs/master/generated/torch.nn.CrossEntropyLoss.html">PyTorch’s CrossEntrop</a>y, during model training.</p><p>Components fed to function: Source image (RGB scheme), Color Dictionary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hb4ZeHudmIaovwZVpw770Q.png" /><figcaption>Segmentation image from CITYSCAPES dataset. 33 Classes are present.</figcaption></figure><p>The color dictionary should have a logical indexing scheme, that way the ID of a specific color (such as 0,255,255, cyan), can be correlated to an index number within the dictionary. I implemented this dictionary in the following way: I initialized a <a href="https://docs.python.org/3/library/collections.html#collections.namedtuple">namedtupule from the collections</a> class called ‘Labels’; then I set a variety of labels to their associated ID values, RGB color, etc. This idea was from a UNet-Multiclass repository found here: <a href="https://github.com/hamdaan19/UNet-Multiclass/tree/main/scripts">https://github.com/hamdaan19/UNet-Multiclass/tree/main/scripts</a>. However, a regular dictionary setup would work also.</p><pre>Label = namedtuple(&#39;Label&#39;, <br>[&#39;name&#39;,&#39;id&#39;,&#39;trainId&#39;,&#39;category&#39;,<br>&#39;categoryId&#39;,&#39;hasInstances&#39;,<br>&#39;ignoreInEval&#39;,&#39;color&#39;,])<br>labels = [<br>    Label(&#39;unlabeled&#39;,  0,      255, &#39;void&#39;, 0, False, True, (0,  0,  0)),<br>    Label(&#39;ego vehicle&#39;,  1,      255, &#39;void&#39;, 0, False, True, (0,  0,  0)),<br>    Label(&#39;rectification border&#39;,  2,      255,<br>          &#39;void&#39;, 0, False, True, (0,  0,  0)),<br>    Label(&#39;out of roi&#39;,  3,      255, &#39;void&#39;, 0, False, True, (0,  0,  0)),<br>    Label(&#39;static&#39;,  4,      255, &#39;void&#39;, 0, False, True, (0,  0,  0)),<br>    Label(&#39;dynamic&#39;,  5,      255, &#39;void&#39;, 0, False, True, (111, 74,  0)),<br>    Label(&#39;ground&#39;,  6,      255, &#39;void&#39;, 0, False, True, (81,  0, 81)),<br>    Label(&#39;road&#39;,  7,        0, &#39;flat&#39;, 1, False, False, (128, 64, 128)),<br>    Label(&#39;sidewalk&#39;,  8,        1, &#39;flat&#39;, 1, False, False, (244, 35, 232)),</pre><p>These labels correspond to the <a href="https://www.cityscapes-dataset.com/">CITYSCAPES </a>dataset that the test model was trained on. Once the label dictionary was created, a dictionary of only color values was made. This maxes for easier parsing by the function, as the only data that we need for a particular class is the data regarding the color of the pixel.</p><pre>color2label = {label.color: label for label in labels}</pre><p>And now for our function. It is a straightforward function; what it does is it goes through each class in the list of classes provided, and extracts the color value from that class. It then compares that color to each pixel in the image, and sees if it matches; if it does match, it replaces that index in a placeholder array with the index value, and moves onto the next pixel. This process occurs until every class has been analyzed. The naïve approach would accomplish this using for loops in Python, as the following code shows:</p><pre>def RGBtoOneHot(rgb, colorDict): ## rgb is the image, colorDict is dictionary of label colors<br>  arr = np.zeros(rgb.shape[:2]) ## rgb shape: (h,w,3); arr shape: (h,w)<br>  <br>  for label, color in enumerate(colorDict.keys()): ## keys function will get just rgb color scheme, while &#39;i&#39; preserves index location corresponding to id value<br>    color= np.array(color) ## ensuring that types of arrays are the same<br>    if label &lt; len(colorDict.keys()):## ensuring we don&#39;t calculate classes that aren&#39;t present<br>      for _x, x in enumerate(rgb):<br>        for _y, y in enumerate(x):<br>          pixel = np.array(rgb[_x][_y])<br>          if np.all(pixel == color):<br>            arr[_x][_y] = label<br>   <br>  return arr</pre><p>However, as you may have heard by now, using for loops is something to best be avoided when coding; this is due to the time complexity it adds. Matrix operations are much more desirable. So, there is a better solution to the above function:</p><pre>def RGBtoOneHot(rgb, colorDict):<br>  arr = np.zeros(rgb.shape[:2]) ## rgb shape: (h,w,3); arr shape: (h,w)<br>  <br>  for label, color in enumerate(colorDict.keys()):<br>    color = np.array(color)<br>    if label &lt; len(colorDict.keys()):<br>      arr[np.all(rgb == color, axis=-1)] = label<br>  <br>  return arr</pre><p>Look at that! The <a href="https://numpy.org/doc/stable/reference/generated/numpy.all.html">np.all</a> function will search through the rgb image in the space of [:,:,3] (a 1x3 vector) and see if it is equivalent to the color association with a label; if the result returns <em>True</em>, then another array <em>arr</em>, has that index updated with the index value of the class label; since numpy works well in matrix mode, this operation can be executed much faster than iterating over every pixel using for loops.</p><p>And there you have it. RGB image to matrix of class labels.</p><p><strong>BONUS!!!!!!! Convert one-hot encoded output to RGB Image.</strong></p><p>Lets say I have a one-hot encoded output that I want to convert to an RGB image. What is a straightforward process of going about this?</p><p>Generally the output from a segmentation model is of the shape [batch_size, number_of_classes, height, width]; when performing inference, the batch_size should be 1. The number_of_classes should be thought of as a one-hot vector; for a given pixel index (height, width), there should be a n-long vector corresponding to the number of classes that are being analyzed. Due to the way in which the machine learning model is generally trained, taking the index of the largest value from the one-hot vector should correspond to the class present at that pixel, in a well trained model.</p><p>For example, lets say I have a one-hot matrix of size [1, 5, 256, 256]; it is apparent that there are 5 classes to look for in this output. Since there is a batch size of 1, we can get rid of this dimension to produce a matrix of size [5, 256, 256]. If I take the pixel at location [ :, 100, 100], it may look like this: vector = [[[0.04, 0.25, 0.46, 0.17, 0.08]]]. If I apply argmax(vector), we get the following: vector = [[[0,0,1,0,0]]]. The index of the value corresponding to the output is then 2 (not 3, since in computer coding we start counting from 0). The RGB color scheme that corresponds to Class 2 can then be placed in that location of a new array that has dimensions (height, width, color).</p><p>This process can then be applied to an entire image, creating an RGB image from a multi-class output from a segmentation model. The code I used to implement this is listed below.</p><pre>def onehot_to_rgb(oneHot, colorDict):<br>    oneHot = np.array(oneHot) ## ensuring numpy array; should be dims: (1, classes, height, width)<br>    oneHot = np.argmax(oneHot, axis=1) ## argmax along second dimension; reduces size to (1, height, width)<br>    output = np.zeros(oneHot.shape[1:3]+(3,)) ## size of height, width channel, + 3 for the rgb color space<br>    oneHot= np.transpose(oneHot, [1, 2, 0]) ## ensuring correct dimensions are compared <br><br>    for index, color in enumerate(colorDict.keys()):<br>        if index &lt; len(colorDict.keys():<br>            output[np.all(oneHot== index, axis=-1)] = color<br><br>    return np.uint8(output)</pre><p>And that’s it! I hope this was helpful for you. It would have been for me when I started learning multi-class segmentation!</p><p>Github Reference (code ideas):</p><p><a href="https://github.com/hamdaan19/UNet-Multiclass/tree/main/scripts">https://github.com/hamdaan19/UNet-Multiclass/tree/main/scripts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ddceba459cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I learned from a year working with ML]]></title>
            <link>https://medium.com/@noah.vandal/what-i-learned-from-a-year-working-with-ml-444ecb9ffe81?source=rss-64a433a25b6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/444ecb9ffe81</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[progress]]></category>
            <category><![CDATA[first-post]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[storytelling]]></category>
            <dc:creator><![CDATA[Noah Vandal]]></dc:creator>
            <pubDate>Wed, 03 Aug 2022 23:30:03 GMT</pubDate>
            <atom:updated>2022-08-03T23:30:03.440Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c7naalr8cIgN97U6" /><figcaption>Photo by <a href="https://unsplash.com/@rachaelgorjestani?utm_source=medium&amp;utm_medium=referral">Rachael Gorjestani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I have always been an inquisitive person, trying to learn about things that I currently don’t understand. The thought of not knowing something often bugs the heck out of me. And so, in pursuit of attaining that Shangri-La of technical knowledge, I often spend time researching and reading various scientific and historical topics, oftentimes topics that add little value to my life, other than the pure satiation of knowledge.</p><p>This is how my machine learning (ML) journey began. ML had caught my eye specifically from seeing a demo video of Tesla’s autopilot enabled. This video had nobody touching the wheel, and I was fascinated that a string of one’s and zero’s could do something like that. I remember replaying the video that they showed, showing multiple bounding boxes that would (generally) properly classify objects within the frame in a manner similar to Yolo v5. (I didn’t know about Yolo then, but hindsight is 20/20 as they say).</p><p>I started to read about ML networks, and started with the basic perceptron. From there I moved onto learning about a fully connected layer, and from there I immersed myself into the world of backpropagation and convolutional neural networks (CNN’s). Once I found myself in the world of CNN’s, the entire realm of possibilities opened up, as I found myself surrounded by multitudes of network types such as ResNET, UNET, Yolo and it’s children, etc. It seemed to me like there was no end to learning.</p><p>Dipping your toes into ML can be compared to dipping your toes into a really deep lake. The water near the edge of the lake is shallow and the bottom of the lake is easily visible. However, the further out you go (corollary: the more technical you get), the more you realize you are wayyy in over your head. I did not realize this as I got started in ML, but I have learned and grown over the past year or so into my journey. I have a few key takeaways that I have learned over this year, and that I wish I knew as I started.</p><p>Takeaways:</p><ol><li>You will never stop learning if you are to successfully master ML. The ML domain is rapidly evolving, and new networks and architectures are being released daily. It can seem overwhelming to stay up to date on everything, so choose new modifications and methods wisely. With that being said, being informed of recent developments can be helpful for implementation of new ideas. A good resource is arXiv, which houses many of the state-of-the art papers published daily regarding ML. <em>Link: </em><a href="https://arxiv.org/">https://arxiv.org</a></li><li>To properly learn, properly create. There is nothing that reinforces a new concept more than actual implementation. I remember struggling to understand the concept of backpropagation. It wasn’t until I created a simple fully connected layer, with created backpropagation layers, that I understood what was going on. I am not necessarily recommending that you build an entire network from scratch to understand everything, but I will say that one needs to actually try out ideas in order to get a more comprehensive understanding of them. Google Colaboratory has a number of good tutorials to get started, while also hosting a decent ML coding platform. <em>Link: </em><a href="https://colab.research.google.com/">https://colab.research.google.com</a></li><li>Document, document, DOCUMENT!!! I have learned this lesson the hard way. Even though you are trying to learn about ML and troubleshooting and taking notes, writing down what you are doing and what you are trying to accomplish is highly valuable in a few regards. For one, it helps with memory consolidation (<em>see: </em><a href="https://www.researchgate.net/publication/332301647_Writing_to_Learn_Increases_Long-term_Memory_Consolidation_A_Mental-_chronometry_and_Computational-modeling_Study_of_Epistemic_Writing">https://www.researchgate.net/publication/332301647_Writing_to_Learn_Increases_Long-term_Memory_Consolidation_A_Mental-_chronometry_and_Computational-modeling_Study_of_Epistemic_Writing</a>) <br>For two, it helps to serve as later reference, to understand what you were doing. Not only for the code that you write, but also for the random thoughts that you had as you were learning about your perceptron. It takes effort to learn at first, but pays off in the end.</li></ol><p>I wish I would have known these three things as I got started with my ML path, but my wish is that you can take these tips and get a little bit of a head start on diving into the world of machine learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=444ecb9ffe81" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>