<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Haoli Yin</title>
    <description>The latest articles on DEV Community by Haoli Yin (@haoliyin).</description>
    <link>https://dev.to/haoliyin</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F904164%2F0af88a81-2ef9-4c20-97ae-c3e0f74c37a4.jpg</url>
      <title>DEV Community: Haoli Yin</title>
      <link>https://dev.to/haoliyin</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/haoliyin"/>
    <language>en</language>
    <item>
      <title>Show Off Your Computer Vision Model with Gradio</title>
      <dc:creator>Haoli Yin</dc:creator>
      <pubDate>Fri, 12 Aug 2022 14:52:00 +0000</pubDate>
      <link>https://dev.to/haoliyin/show-off-your-computer-vision-model-with-gradio-1k3o</link>
      <guid>https://dev.to/haoliyin/show-off-your-computer-vision-model-with-gradio-1k3o</guid>
      <description>&lt;p&gt;Most of machine learning development originates from academia, which is often very technical and hard to understand for the layperson. Personally, I enjoy being able to interact with the end result with my own inputs without having to understand the technicalities of the model until later. Another motivation to write this piece is that I haven't seen many public articles or examples using Gradio and HuggingFace hosting to demo computer vision models with image input and output as HuggingFace is traditionally a hub for natural language processing (NLP) knowledge (but they're shifting to incorporate more of other ML domains like computer vision). &lt;/p&gt;

&lt;h2&gt;
  
  
  What is HuggingFace and Gradio
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1u64v34tov7a3tdqitrz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1u64v34tov7a3tdqitrz.png" alt="Gradio and HuggingFace Logos"&gt;&lt;/a&gt; &lt;br&gt;
No, HuggingFace is not those face grabbers from the movie &lt;a href="https://en.wikipedia.org/wiki/Aliens_(film)" rel="noopener noreferrer"&gt;Aliens&lt;/a&gt; (although that's what I first thought it was). It's actually the hugging emoji that's now at the top of my most-used emoji keyboard list! HuggingFace is not only a hub for ML models and demos but also a Python library that allows anyone to create and train select model architectures without having to write it all from scratch (e.g. transformers). For our case, HuggingFace Spaces allows us to freely host our model for public deployment without any extra fees, full-stack development knowledge, or headaches using other platforms. Note that demoing using GPU does cost extra, so I will be showing a CPU-only example. &lt;/p&gt;

&lt;p&gt;Gradio, on the other hand, is the Python library that allows for user-friendly functions and front-end development using a single line of code. This interface can be used to create simple visual demos like mine (link in next paragraph) to complex interfaces like &lt;a href="https://huggingface.co/spaces/skytnt/full-body-anime-gan" rel="noopener noreferrer"&gt;this one&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;
  
  
  Demoing my Research Project
&lt;/h2&gt;

&lt;p&gt;In this tutorial, I'll show you how to quickly deploy a demo of a model that takes an image input and outputs an instance segmentation map overlayed onto the image. This demo is related to a portion of my research project to detect &lt;a href="https://en.wikipedia.org/wiki/Specular_reflection" rel="noopener noreferrer"&gt;specular reflection&lt;/a&gt; regions created from light reflected off wet organ surfaces and blinds the camera to the true colors and features in that region. The generated segmentation map is later used to restore the region using information from adjacent frames of the endoscopy video. &lt;strong&gt;Trigger Warning&lt;/strong&gt;: Blood, Biological Tissue. EDIT: the public demo is taken down until further notice. Please &lt;a href="https://haoliyin.me" rel="noopener noreferrer"&gt;contact me&lt;/a&gt; if you want a demo. &lt;/p&gt;
&lt;h2&gt;
  
  
  Creating a Skeleton of the Code
&lt;/h2&gt;

&lt;p&gt;For any code I work on, I like to first write comments and create a version control system to use such as Github (HuggingFace has their own version of Git in this case that's hosted on their platform). To get started, create an account on HuggingFace and make a &lt;a href="https://huggingface.co/spaces" rel="noopener noreferrer"&gt;Spaces&lt;/a&gt;. From there, you can specify a repository name and license type and select Gradio as the display option. &lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fceb1zszkjcg3wii6hdxb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fceb1zszkjcg3wii6hdxb.png" alt="Making spaces"&gt;&lt;/a&gt;&lt;br&gt;
Then, you can either clone the repo to your local storage using git bash or directly modify your code on HuggingFace. Next, there are two important files to create: requirements.txt and app.py. The requirements text file will store all the pip library dependencies that need to be installed in the HuggingFace hosting environment to run all the Python libraries you use in your code. The app.py file will define how you want your interface to look like and function. The most basic app you can first make is kind of like a "hello world" program using Gradio, which they show you after you make the repository.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import gradio as gr

def greet(name):
    return "Hello " + name + "!!"

iface = gr.Interface(fn=greet, inputs="text", outputs="text")
iface.launch()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's dissect this code a bit. The import statement is telling Python that you want to use all of Gradio's functionality (assuming that you have put this into requirements.txt). The function "greet" is where you will put all the machine learning model logic to process an input and return a prediction or output from your model to be displayed. The Interface is the main function that defines how you want your demo to look - we will dive more into the options later in this post. Then, all you need to do is to launch the demo and HuggingFace will deploy all this code for you automatically. It's as easy as that!&lt;/p&gt;

&lt;h2&gt;
  
  
  Defining model behavior
&lt;/h2&gt;

&lt;p&gt;Now that we have a skeleton of the code we want to write, we will fill it in with the desired functionality. Instead of using the greet function, we want to create a function that will accept an image (read by Gradio as a NumPy or PIL image), preprocess it to be fed into the model, run it through the model with a forward pass for prediction, and output a segmentation map overlayed onto the original image.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def speclab(img):

    # initialize the model
    model = torch.hub.load('Nano1337/SpecLab', 'srdetect', force_reload=True) # for some reasons loads the model in src rather than demo
    model.eval()

    # preprocess image to be used as input
    transforms = A.Compose([
        A.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)),
        ToTensorV2()
    ])
    input = transforms(image=img)['image']
    input = input.unsqueeze(0)

    # model prediction
    output = model(input)

    # overlay output onto original image
    img[output==255] = [0, 255, 0]

    return img
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A small detail that you may notice is that I used torch.hub to load my model from a saved location in my personal Github account. You can see how I made a &lt;a href="https://github.com/Nano1337/SpecLab/blob/main/hubconf.py" rel="noopener noreferrer"&gt;hubconf.py file&lt;/a&gt; there to specify how I wanted to load my model for external usage. &lt;/p&gt;

&lt;h1&gt;
  
  
  Importing Example Images
&lt;/h1&gt;

&lt;p&gt;Since the subject I'm working on is quite niche, users won't always have the appropriate data to input into the demo. We can define ready-to-be-used examples to be shown. I stored the images in the same personal Github repo as shown here and I imported the raw image address as shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from urllib.request import urlretrieve

# get image examples from github
urlretrieve("https://github.com/Nano1337/SpecLab/blob/main/examples/05829.png?raw=true", "05829.png") # make sure to use "copy image address when copying image from Github"
urlretrieve("https://github.com/Nano1337/SpecLab/blob/main/examples/10384.png?raw=true", "10384.png")
examples = [ # need to manually delete cache everytime new examples are added
    ['05829.png'], 
    ["10384.png"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another small detail you may notice is that I specified later on in the code that I wanted these examples and their outputs to be cached so that users won't have to wait for the example images to be run through the model (which can take significantly more time since the model is run on CPU only). &lt;/p&gt;

&lt;h1&gt;
  
  
  Creating the Interface
&lt;/h1&gt;

&lt;p&gt;Now comes the front-end work, which is thankfully really easy for a noob webdev like me. Below is my code to define the demo's look using the Interface function, but Gradio also has more customizable and advanced functionality if you want more front-end flexibility in their documentation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# define app features and run
title = "SpecLab Demo"
description = "&amp;lt;p style='text-align: center'&amp;gt;Gradio demo for an ASPP model architecture trained on the SpecLab dataset. To use it, simply add your image, or click one of the examples to load them. Since this demo is run on CPU only, please allow additional time for processing. &amp;lt;/p&amp;gt;"
article = "&amp;lt;p style='text-align: center'&amp;gt;&amp;lt;a href='https://github.com/Nano1337/SpecLab'&amp;gt;Github Repo&amp;lt;/a&amp;gt;&amp;lt;/p&amp;gt;"
css = "#0 {object-fit: contain;} #1 {object-fit: contain;}"
demo = gr.Interface(fn=speclab, 
                    title=title, 
                    description=description,
                    article=article,
                    inputs=gr.Image(elem_id=0, show_label=False), 
                    outputs=gr.Image(elem_id=1, show_label=False),
                    css=css, 
                    examples=examples, 
                    cache_examples=True,
                    allow_flagging='never')
demo.launch()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's walk through this code together. The title and description are self-explanatory and the article shows some more text at the bottom of the screen. If you're front-end savvy (which I definitely am not), you can also define custom CSS to pretty up your interface. We specify both the input and output components to be Gradio images, but these can be any one of the &lt;a href="https://gradio.app/docs/#components" rel="noopener noreferrer"&gt;components&lt;/a&gt; that Gradio supports (similar to the diverse components found in React.js components if you're familiar with that framework). Other parameters are just nice-to-haves that can be found in the &lt;a href="https://gradio.app/docs/" rel="noopener noreferrer"&gt;Interface documentation&lt;/a&gt;. &lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8syiqyelvvw9u7qagn4k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8syiqyelvvw9u7qagn4k.png" alt="End Result"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Congrats
&lt;/h2&gt;

&lt;p&gt;There you have it! After about 50 lines of code (or even less), you have a functioning demo that doesn't cost anything to deploy. Feel free to share this article, and if you like this content, let me know what you would like to see next from me! Happy deep learning my friends :))&lt;/p&gt;

</description>
      <category>machinelearning</category>
      <category>datascience</category>
      <category>ai</category>
      <category>computervision</category>
    </item>
    <item>
      <title>Adversarial ML: Making a Turtle Look like a Rifle</title>
      <dc:creator>Haoli Yin</dc:creator>
      <pubDate>Sun, 07 Aug 2022 03:50:02 +0000</pubDate>
      <link>https://dev.to/haoliyin/adversarial-ml-making-a-turtle-look-like-a-rifle-4ba9</link>
      <guid>https://dev.to/haoliyin/adversarial-ml-making-a-turtle-look-like-a-rifle-4ba9</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;The use of machine learning (ML) for image classification is very common today from identifying objects in the original ImageNet dataset to grading levels of cancerous tumors. Machine learning models trained on such datasets, however, aren't resistant to Out-Of-Distribution (OOD) testing samples, in which the models are assessed on their edge cases and commonly result in inaccurate classifications. One particular ongoing &lt;a href="https://www.ood-cv.org/"&gt;challenge&lt;/a&gt; is held by the European Conference on Computer Vision (ECCV) specifically addressing these edge cases. While testing edge cases for these models may seem boring, there is a whole field of ML dedicated to addressing the limitations of classification models that's on the rise called adversarial ML. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--tV5zwb3e--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ahxe156ktd2e77a5v1ps.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--tV5zwb3e--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ahxe156ktd2e77a5v1ps.jpg" alt="Out-of-Distribution examples provided by the ECCV OOD challenge" width="880" height="248"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Beyond just testing models on their edge cases, adversarial ML is important for maintaining the security and safe usage of such ML models. Adversarial attacks from the input data are intentional image patterns generated to fool the classification model based on previous knowledge of its weaknesses. There are several strategies to generate such patterns, but one of the easiest ones to understand is to recognize that deep learning classification models are trained on the principle of gradient descent to minimize their defined loss function. Instead of descending, we want to ascend the gradient so we achieve maximal loss and generate a specific pattern that can be put on the object to be detected to fool the classifier to think that the object is something else. This type of adversarial attack is called an untargeted attack since we simply want to make the model think that the object is something else. On the other hand, a targeted attack is fooling the classifier to think that the object is another specific label, such as making a turtle look like a rifle. &lt;/p&gt;

&lt;h2&gt;
  
  
  Original Paper
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Y0GGPPFB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s17gn1grtwprhojd324e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Y0GGPPFB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s17gn1grtwprhojd324e.png" alt="Fooling a classifier using an adversarial attack. Image from the paper below." width="528" height="299"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;The original &lt;a href="https://arxiv.org/pdf/1707.07397.pdf"&gt;paper&lt;/a&gt; from Google research named "Synthesizing Robust Adversarial Examples" from 2017 brought the field of adversarial ML to the public eye when it showed how a specific image pattern applied to a turtle's back fooled a classifier into thinking that the turtle was a rifle when observed from any angle. While it is a surprising finding that such a targeted attack can make a turtle look like a rifle, the more important question on everyone's minds (especially the US Department of Defense) was: can a rifle be made to look like a turtle?&lt;/p&gt;

&lt;p&gt;With the introduction of machine learning applications to all aspects of our lives, it is not surprising that the defense industry is leveraging this emerging technology in all ways possible. A couple of examples of relevant use today range from image classification of vehicles for targeting to identifying hidden weapons. If the opposing side knows that the defense industry is using such ML models, they can theoretically pose adversarial attacks and fool the models; thus, the topic of adversarial defenses is naturally introduced. &lt;/p&gt;

&lt;p&gt;Much like the parallel evolution of attacks and defenses between bacteria and viruses, adversarial attacks and adversarial defenses are quickly advancing in research to match the development rate of the other. &lt;/p&gt;

&lt;h2&gt;
  
  
  Closing Remarks
&lt;/h2&gt;

&lt;p&gt;Personally, I'm excited to see how this field progresses as it's still in its early stages. One tweet I saw that made me chuckle said that anyone could write a paper on the adversarial attacks or out-of-distribution data samples of a new state-of-the-art model and get it easily published - theoretically pushing out hundreds of papers every year! &lt;/p&gt;

</description>
      <category>machinelearning</category>
    </item>
  </channel>
</rss>
