<?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 Eric on Medium]]></title>
        <description><![CDATA[Stories by Eric on Medium]]></description>
        <link>https://medium.com/@ericy_63269?source=rss-c8111db71de0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7vmTg8BnU_Grx1va.jpg</url>
            <title>Stories by Eric on Medium</title>
            <link>https://medium.com/@ericy_63269?source=rss-c8111db71de0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:08:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ericy_63269/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[Share the spectacular World Cup construction with ChatGPT ⚽️]]></title>
            <link>https://blog.infuseai.io/share-the-spectacular-world-cup-construction-with-chatgpt-%EF%B8%8F-8d8a64c9509?source=rss-c8111db71de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d8a64c9509</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[data-observability]]></category>
            <category><![CDATA[world-cup]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <dc:creator><![CDATA[Eric]]></dc:creator>
            <pubDate>Thu, 15 Dec 2022 14:31:41 GMT</pubDate>
            <atom:updated>2022-12-15T14:31:41.905Z</atom:updated>
            <content:encoded><![CDATA[<p>The <a href="https://www.fifa.com/fifaplus/en/tournaments/mens/worldcup/qatar2022">World Cup</a> and <a href="https://chat.openai.com/chat">ChatGPT</a> have recently been the most popular subjects all across the world. The World Cup is the largest football event conducted every four years, and it is being held in Qatar this year, and ChatGPT is the natural language model for dialogue built by <a href="https://openai.com/">OpenAI</a>.</p><p>On 18 December 2022, the World Cup Final will be held in the <a href="https://www.qatar2022.qa/en/tournament/stadiums/lusail-stadium">Lusail Stadium</a> of Lusail city. Lusail city was still desert in 2010 but the new municipality now includes an urban center and an artificial archipelago.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BW3yDlLiamIiTufRRnXnqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0_RmGxuwVzawfA6NZMncg.png" /><figcaption>Left: Satellite image of Lusail city in 2010; Right: Satellite image of Lusail city in 2022 (Source: <a href="https://www.bloomberg.com/graphics/2022-what-qatar-built-for-the-world-cup">https://www.bloomberg.com/graphics/2022-what-qatar-built-for-the-world-cup</a>)</figcaption></figure><p>As ChatGPT would have limited knowledge of the world after 2021, so I’m curious about how ChatGPT will introduce Lusail city. 🤔</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJ07O2ao5IwX1YNW9x4PgQ.png" /></figure><p>Anyway, let’s try!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*nZ9x5BKkoM5qd5ysh6NNpw.png" /></figure><p>It looks great! However, several World Cup aspects are currently missing.</p><p>Feed the contents of the answers to the Text-to-Image generator <a href="https://huggingface.co/spaces/stabilityai/stable-diffusion">Stable Diffusion</a>. 🎨</p><p>The World Cup element is still missing from the created visualization, as we can see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*V6MPYQQb32fg4LNRBFeR-w.png" /></figure><p>Okay! I would like to collect some latest information about Lusail city toward World Cup and share it with ChatGPT to see if it can gather more exciting news!</p><p>I created the scripts to parse the web contents from the following websites:</p><ul><li><a href="https://www.qatar2022.qa/en/tournament/stadiums/lusail-stadium">https://www.qatar2022.qa/en/tournament/stadiums/lusail-stadium</a></li><li><a href="https://www.bloomberg.com/graphics/2022-what-qatar-built-for-the-world-cup">https://www.bloomberg.com/graphics/2022-what-qatar-built-for-the-world-cup</a></li><li><a href="https://en.wikipedia.org/wiki/Lusail">https://en.wikipedia.org/wiki/Lusail</a></li></ul><p>Stored in a <strong>qatar-worldcup.csv</strong> file with described contents and parsed sources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUS8O8O4m68f1mzEPGprpw.png" /></figure><p>Before we share the raw data with ChatGPT, let’s run the <strong>qatar-worldcup.csv</strong> file through <a href="https://www.piperider.io/">PipeRider</a>, a data reliability tool that can ensure data quality.</p><p>We can examine the data characteristics in PipeRider’s data report and discover that there are some <strong>missing</strong> and <strong>duplicate</strong> contents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QNpfCIY-JB15QiivcN67rg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*DMdbjwV1KHqqRLVofeWSMg.png" /></figure><p>In <strong>qatar-worldcup.csv</strong>, there are numerous missing values as a result of the script’s attempt to parse text from the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*pHJeAm9aNal5dF_bEvRYlg.png" /></figure><p>As for the duplicates, they mainly resulted from the bug of retry logic in our parsing script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tgxBBB3bi3aVTCMkYlmfeA.png" /></figure><p>After fixing the known issues, the new data report now looks promising!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6kUqW8KR-snI1BA8ZzRfKQ.png" /></figure><p>Next, I used another script to automatically communicate parsed contents with ChatGPT. Here are some conversations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*u3vIBrl4Tf2wtLqs5vTc4A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*3jKHhnKEqPsUuCpaS2tiCw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*k0uoKg0xD3hA9BHUMJvD1Q.png" /></figure><p>Cool! At the moment, it seems like our friend ChatGPT knows more about Lusail City in terms of the World Cup.</p><p>Let me ask the same question again!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*Htz32k1TDsFcaeuyhz7mdA.png" /></figure><p>Excellent! The 2022 FIFA World Cup is included in the introduction of Lusail city!</p><p>Again, use the <a href="https://huggingface.co/spaces/stabilityai/stable-diffusion">Stable Diffusion</a> to visualize Lusail city from the new ChatGPT’s perspective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*2Y_yxE1G41ZCrYAugOd-Yw.png" /></figure><p>Fantastic! Despite the fact that it is far from the actual city of Lusail. 😂</p><p>But the visualization shows how much more realistically ChatGPT can explain how a city looks from a sports perspective and how it looks now.</p><p>When it becomes a football expert, which I believe it will, I will ask about its predictions for future World Cup champions. 🏆🏆🏆</p><p>Find out more at the following links:</p><ul><li><a href="https://pse.is/4jvr43">PipeRider on GitHub</a></li><li><a href="https://docs.piperider.io/">PipeRider Documentation</a></li></ul><h3>Join the community or get in touch</h3><ul><li>Twitter: <a href="https://twitter.com/infuseai">@infuseai</a></li><li>Mastodon: <a href="https://fosstodon.org/web/@piperider">@piperider@fosstondon.org</a></li><li>Discord: <a href="https://discord.gg/328QcXnkKD">InfuseAI Community</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d8a64c9509" width="1" height="1" alt=""><hr><p><a href="https://blog.infuseai.io/share-the-spectacular-world-cup-construction-with-chatgpt-%EF%B8%8F-8d8a64c9509">Share the spectacular World Cup construction with ChatGPT ⚽️</a> was originally published in <a href="https://blog.infuseai.io/">InfuseAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What our PrimeHub SDK can do towards MLOps]]></title>
            <link>https://blog.infuseai.io/what-our-primehub-sdk-can-do-towards-mlops-b6592aec96db?source=rss-c8111db71de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6592aec96db</guid>
            <category><![CDATA[sdk]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Eric]]></dc:creator>
            <pubDate>Mon, 25 Oct 2021 23:32:22 GMT</pubDate>
            <atom:updated>2021-10-25T23:32:22.451Z</atom:updated>
            <content:encoded><![CDATA[<h3>What PrimeHub SDK can do towards MLOps</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9AYLuMUIa_mfIzlRW667Mw.jpeg" /></figure><h3><strong>What’s MLOps?</strong></h3><p>Machine Learning Operations, MLOps, is a combination of processes that aims to provide services related to dataset, experiment, model, deployment, monitoring, and so on.</p><p>A scalable and team-centric MLOps means can assist the whole team to be more efficient and reduce the efforts in delivering outcomes to production.</p><h3><strong>What does PrimeHub SDK offer?</strong></h3><p><a href="https://www.infuseai.io/">PrimeHub</a> is an end-to-end platform that allows users to prepare data, train models, review experiments, manage and deploy their trained models to the production environment.</p><p>PrimeHub platform provides users with GUI to achieve the ML end-to-end workflow. Similarly, the <a href="https://github.com/InfuseAI/primehub-python-sdk">PrimeHub SDK</a> can provide the API and CLI manipulations to accomplish the same experiences. In this article, we will focus on how to use API to interact with the PrimeHub platform.</p><p>Let’s install the PrimeHub SDK with pip.</p><pre>$ pip install primehub-python-sdk </pre><p>With the installation, we get a fully-supported API for SDK to be available to work.</p><pre>from primehub import PrimeHub, PrimeHubConfig <br>ph = PrimeHub(PrimeHubConfig())</pre><p>We won’t cover every detail in the current SDK, but it’s worth looking at some of the main operations for fulfilling MLOps needs.</p><h4><strong>Groups</strong></h4><p>PrimeHub adopts the group-centric design. Based on the specified working group, users can access corresponding resources and perform features within the group accordingly.</p><p>List all associated groups.</p><pre>ph.groups.list()</pre><p>We are in Data Team and Model Team, it shows both the user and group resource quotas. Switch to Model Team and proceed to the next step.</p><pre>[{&#39;id&#39;: &#39;927406f6-88b0-490e-8e36-7835224fdf13&#39;,<br>  &#39;name&#39;: &#39;data-team&#39;,<br>  &#39;displayName&#39;: &#39;Data Team&#39;,<br>  &#39;quotaCpu&#39;: 2,<br>  &#39;quotaGpu&#39;: 1,<br>  &#39;quotaMemory&#39;: 8,<br>  &#39;projectQuotaCpu&#39;: 16,<br>  &#39;projectQuotaGpu&#39;: 2,<br>  &#39;projectQuotaMemory&#39;: 128},<br> {&#39;id&#39;: &#39;ac1a2022-c58f-4b54-8213-699cdb5d02bf&#39;,<br>  &#39;name&#39;: &#39;model-team&#39;,<br>  &#39;displayName&#39;: &#39;Model Team&#39;,<br>  &#39;quotaCpu&#39;: 4,<br>  &#39;quotaGpu&#39;: 1,<br>  &#39;quotaMemory&#39;: 64,<br>  &#39;projectQuotaCpu&#39;: 64,<br>  &#39;projectQuotaGpu&#39;: 8,<br>  &#39;projectQuotaMemory&#39;: 256}]</pre><h4><strong>Instance Types</strong></h4><p>Instance Types are preset of resources allocation for environments such as <a href="https://docs.primehub.io/docs/quickstart/launch-project">Notebooks</a>, <a href="https://docs.primehub.io/docs/job-submission-feature">Jobs</a>, <a href="https://docs.primehub.io/docs/model-deployment-feature">Deployments</a>, and <a href="https://docs.primehub.io/docs/primehub-app">Apps</a>. When launching an environment, it tries to find/allocate an instance according to the requested resources.</p><p>List all instance types within the group.</p><pre>ph.instancetypes.list()</pre><p>We have three instance types.</p><pre>[{&#39;id&#39;: &#39;cpu-1&#39;,<br>  &#39;name&#39;: &#39;cpu-1&#39;,<br>  &#39;displayName&#39;: &#39;CPU 1&#39;,<br>  &#39;description&#39;: &#39;1 CPU / 2G / 0 GPU&#39;},<br> {&#39;id&#39;: &#39;cpu-2&#39;,<br>  &#39;name&#39;: &#39;cpu-2&#39;,<br>  &#39;displayName&#39;: &#39;CPU 2&#39;,<br>  &#39;description&#39;: &#39;1 CPU / 16G / 0 GPU&#39;},<br> {&#39;id&#39;: &#39;gpu-1&#39;,<br>  &#39;name&#39;: &#39;gpu-1&#39;,<br>  &#39;displayName&#39;: &#39;GPU 1&#39;,<br>  &#39;description&#39;: &#39;1 CPU / 16G / 1 GPU&#39;}]</pre><h4><strong>Images</strong></h4><p>Images are working environments to Notebooks and Jobs. When launching a Notebook or Job, it needs to know requesting image as the container environment.</p><p>List all images within the group.</p><pre>ph.images.list()</pre><p>We have TensorFlow 2.6 and PyTorch 1.9 images.</p><pre>[{&#39;id&#39;: &#39;tf-2-6&#39;,<br>  &#39;name&#39;: &#39;tf-2-6&#39;,<br>  &#39;displayName&#39;: &#39;TensorFlow 2.6&#39;,<br>  &#39;description&#39;: &#39;TensorFlow 2.6 with OpenCV&#39;,<br>  &#39;useImagePullSecret&#39;: &#39;secret-xxxxx&#39;,<br>  &#39;spec&#39;: {&#39;description&#39;: &#39;TensorFlow 2.6 with OpenCV&#39;,<br>   &#39;displayName&#39;: &#39;TensorFlow 2.6&#39;,<br>   &#39;pullSecret&#39;: &#39;secret-xxxxx&#39;,<br>   &#39;type&#39;: &#39;both&#39;,<br>   &#39;url&#39;: &#39;infuseai/docker-stacks:tensorflow-notebook-v2-6-0-xxxxx&#39;,<br>   &#39;urlForGpu&#39;: &#39;infuseai/docker-stacks:tensorflow-notebook-v2-6-0-gpu-xxxxx&#39;}},<br> {&#39;id&#39;: &#39;pytorch-1-9&#39;,<br>  &#39;name&#39;: &#39;pytorch-1-9&#39;,<br>  &#39;displayName&#39;: &#39;PyTorch 1.9&#39;,<br>  &#39;description&#39;: &#39;Latest build of PyTorch 1.9&#39;,<br>  &#39;useImagePullSecret&#39;: &#39;&#39;,<br>  &#39;spec&#39;: {&#39;description&#39;: &#39;Latest build of PyTorch 1.9&#39;,<br>   &#39;displayName&#39;: &#39;PyTorch 1.9&#39;,<br>   &#39;pullSecret&#39;: &#39;&#39;,<br>   &#39;type&#39;: &#39;cpu&#39;,<br>   &#39;url&#39;: &#39;infuseai/docker-stacks:pytorch-notebook-v1-9-0-xxxxx&#39;,<br>   &#39;urlForGpu&#39;: &#39;infuseai/docker-stacks:pytorch-notebook-v1-9-0-xxxxx&#39;}}]</pre><h4><strong>Files</strong></h4><p>The Files is shorthand for the <a href="https://docs.primehub.io/docs/shared-files">PHFS</a> (PrimeHub File System) that acted as shared storage among group members. We can download content from PHFS that is shared by other members to continue the experiment.</p><p>List all files in the dataset folder. We have mnist.npz that is a well-organized dataset.</p><pre>files = ph.files.list(&#39;/dataset&#39;)<br>print(files)</pre><pre># [{&#39;name&#39;: &#39;mnist.npz&#39;, &#39;size&#39;: 11490434, &#39;lastModified&#39;: &#39;2021-09-27T08:47:15.395Z&#39;}]</pre><p>Now download the dataset file to local. With the prepared dataset, we can feed it into the next step for model training.</p><pre>ph.files.download(&#39;dataset/mnist.npz&#39;, &#39;.&#39;)</pre><pre>$ ls -lh mnist.npz</pre><pre># -rw-r--r-- 1 jovyan users 11M Sep 28 09:29 mnist.npz</pre><h4><strong>Jobs</strong></h4><p>On PrimeHub, we can choose an environment combination (Instance Type, Image) along with the execution content to run the jobs.</p><p>By using jobs, we can turn a workflow into a pipeline of automatic tasks which are time-consuming and we can check the results once jobs are finished.</p><p>Specifying the GPU instance type and TensorFlow 2.6 image, the execution commands are:</p><ul><li>python train.py: feed MNIST dataset to the training code, export model to saved-model folder</li><li>mv saved-model ~/phfs: move the trained model to PHFS for further model deployment</li></ul><pre>config = {<br>    &#39;instanceType&#39;: &#39;gpu-1&#39;,<br>    &#39;image&#39;: &#39;tf-2-6&#39;,<br>    &#39;displayName&#39;: &#39;training-mnist&#39;,<br>    &#39;command&#39;: &#39;python train.py\nmv saved-model ~/phfs&#39;,<br>}<br>training_job = ph.jobs.submit(config)</pre><pre># Wait the job to be done<br>ph.jobs.wait(training_job[&#39;id&#39;])</pre><p>Successfully get the execution results once our job is completed.</p><pre>{&#39;id&#39;: &#39;job-202109280634-ml80u8&#39;,<br> &#39;displayName&#39;: &#39;training-mnist&#39;,<br> &#39;cancel&#39;: None,<br> &#39;command&#39;: &#39;python train.py\nmv saved-model ~/phfs&#39;,<br> &#39;groupId&#39;: &#39;ac1a2022-c58f-4b54-8213-699cdb5d02bf&#39;,<br> &#39;groupName&#39;: &#39;model-team&#39;,<br> &#39;schedule&#39;: None,<br> &#39;image&#39;: &#39;tf-2-6&#39;,<br> &#39;instanceType&#39;: {&#39;id&#39;: &#39;gpu-1&#39;,<br>  &#39;name&#39;: &#39;gpu-1&#39;,<br>  &#39;displayName&#39;: &#39;GPU 1&#39;,<br>  &#39;cpuLimit&#39;: 1,<br>  &#39;memoryLimit&#39;: 16,<br>  &#39;gpuLimit&#39;: 1},<br> &#39;userId&#39;: &#39;d1bb1d50-fa77-4f85-a58b-edf3698d757e&#39;,<br> &#39;userName&#39;: &#39;phadmin&#39;,<br> &#39;phase&#39;: &#39;Succeeded&#39;,<br> &#39;reason&#39;: &#39;PodSucceeded&#39;,<br> &#39;message&#39;: &#39;Job completed&#39;,<br> &#39;createTime&#39;: &#39;2021-09-28T06:34:30Z&#39;,<br> &#39;startTime&#39;: &#39;2021-09-28T06:34:35Z&#39;,<br> &#39;finishTime&#39;: &#39;2021-09-28T06:34:38Z&#39;}</pre><p>Print out the job logs.</p><pre>logs = ph.jobs.logs(training_job[&#39;id&#39;], follow=True)<br><br>for line in logs:<br>    print(line)</pre><p>It is simple training.</p><pre># model.fit(x_train, y_train, epochs=3)<br>...<br>Epoch 1/3<br>1875/1875 [==============================] - 10s 5ms/step - loss: 1.5835 - accuracy: 0.8951<br>Epoch 2/3<br>1875/1875 [==============================] - 10s 5ms/step - loss: 1.5226 - accuracy: 0.9443<br>Epoch 3/3<br>1875/1875 [==============================] - 10s 5ms/step - loss: 1.5096 - accuracy: 0.9553<br>...</pre><pre># model.evaluate(x_test,  y_test, verbose=2)<br>313/313 - 1s - loss: 1.5027 - accuracy: 0.9613</pre><h4><strong>Deployments</strong></h4><p>One of the later stages in the MLOps is model deployments. On PrimeHub, we can use the model image officially hosted by PrimeHub along with our trained model to create a deployment that can retrieve queries and respond with inferences/predictions.</p><p>Specifying the CPU instance type, the deployment configurations are:</p><ul><li>modelImage: a TensorFlow 2 image for model deployment environment</li><li>modelURI: the trained model we kept in PHFS</li></ul><pre>config = {<br>    &quot;id&quot;: &quot;tf2-mnist-deployment&quot;,<br>    &quot;name&quot;: &quot;TF2 MNIST&quot;,<br>    &quot;modelImage&quot;: &quot;infuseai/tensorflow2-prepackaged:latest&quot;,<br>    &quot;modelURI&quot;: &quot;phfs:///saved-model&quot;,<br>    &quot;instanceType&quot;: &quot;cpu-1&quot;,<br>    &quot;replicas&quot;: 1<br>}</pre><pre>deployment = ph.deployments.create(config)<br>ph.deployments.wait(deployment[&#39;id&#39;])</pre><p>Successfully get the deployment results once our model is deployed.</p><pre>{&#39;id&#39;: &#39;tf2-mnist-deployment&#39;,<br> &#39;name&#39;: &#39;TF2 MNIST&#39;,<br> &#39;modelImage&#39;: &#39;infuseai/tensorflow2-prepackaged:latest&#39;,<br> &#39;imagePullSecret&#39;: None,<br> &#39;description&#39;: None,<br> &#39;replicas&#39;: 1,<br> &#39;stop&#39;: False,<br> &#39;endpointAccessType&#39;: &#39;public&#39;,<br> &#39;endpointClients&#39;: [],<br> &#39;status&#39;: &#39;Deployed&#39;,<br> &#39;endpoint&#39;: &#39;&lt;https://hub.xxx.primehub.io/deployment/tf2-mnist-deployment/api/v1.0/predictions&gt;&#39;,<br> &#39;availableReplicas&#39;: 1,<br> &#39;message&#39;: &#39;Deployment is deployed and available now&#39;,<br> &#39;pods&#39;: [{&#39;name&#39;: &#39;deploy-tf2-mnist-deployment-7bcf786974-zwqcs&#39;}]}</pre><p>Print out the deployed endpoint.</p><pre>print(ph.deployments.get(deployment[&quot;id&quot;])[&#39;endpoint&#39;])</pre><pre># &lt;https://hub.xxx.primehub.io/deployment/tf2-mnist-deployment/api/v1.0/predictions&gt;</pre><p>Verify the endpoint by sending a test image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/28/1*kOv8wbKctvYSGIwsJ4dEbA.png" /><figcaption>test_image.jpg</figcaption></figure><pre>$ curl -F &#39;binData=@test_image.jpg&#39; https://hub.xxx.primehub.io/deployment/tf2-mnist-deployment/api/v1.0/predictions | jq</pre><p>It predicts the highest probability in number 7. Great, correct answer!</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;names&quot;: [<br>      &quot;t:0&quot;,<br>      &quot;t:1&quot;,<br>      &quot;t:2&quot;,<br>      &quot;t:3&quot;,<br>      &quot;t:4&quot;,<br>      &quot;t:5&quot;,<br>      &quot;t:6&quot;,<br>      &quot;t:7&quot;,<br>      &quot;t:8&quot;,<br>      &quot;t:9&quot;<br>    ],<br>    &quot;tensor&quot;: {<br>      &quot;shape&quot;: [<br>        1,<br>        10<br>      ],<br>      &quot;values&quot;: [<br>        9.83689130151788e-10,<br>        2.49615646472167e-18,<br>        7.989667816232782e-10,<br>        3.2611246751912404e-06,<br>        2.971394755341638e-16,<br>        4.320067220620061e-11,<br>        8.943934549440304e-23,<br>        0.9999967813491821,<br>        1.1607271567515287e-11,<br>        5.723543861080316e-10<br>      ]<br>    }<br>  },<br>  &quot;meta&quot;: {<br>    &quot;requestPath&quot;: {<br>      &quot;model&quot;: &quot;infuseai/tensorflow2-prepackaged:latest&quot;<br>    }<br>  }<br>}</pre><h4><strong>Schedules</strong></h4><p>Besides the one-time jobs feature, we can create <a href="https://docs.primehub.io/docs/job-scheduling-feature">schedules</a> to regularly execute jobs. For example, we can use schedules to sync the latest dataset, re-train the model, and update the existing deployment. Indeed accomplished the self-activating ML workflow.</p><pre>config = {<br>    &quot;instanceType&quot;: &quot;cpu-1&quot;,<br>    &quot;image&quot;: &quot;tf-2-6&quot;,<br>    &quot;displayName&quot;: &quot;sync data&quot;,<br>    &quot;command&quot;: &quot;python sync-data.py&quot;,<br>    &quot;recurrence&quot;: {<br>        &quot;cron&quot;:&quot;0 4 * * *&quot;<br>    }<br>}</pre><pre>schedule = ph.schedules.create(config)</pre><h3><strong>Conclusion</strong></h3><p>PrimeHub is an enterprise platform designed for groups of data scientists. It aims at being a collaborative machine learning platform to provide seamless MLOps experiences.</p><p>In addition to the PrimeHub platform, we’ve introduced the PrimeHub SDK that can perform API manipulations to achieve a completed ML workflow. Also, we can integrate PrimeHub SDK with some powerful libraries to reach more practical applications.</p><p>We are extending the scope of PrimeHub SDK, such as <a href="https://docs.primehub.io/docs/primehub-app">PrimeHub Apps</a> that assembled third-party applications, and <a href="https://docs.primehub.io/docs/guide_manual/admin-dataset">PrimeHub Datasets</a> that connected data from various sources.</p><p>Wanna play our SDK? YES! Welcome to explore it in <a href="https://colab.research.google.com/github/InfuseAI/primehub-demo-notebooks/blob/main/primehub-sdk-mlops/mlops.ipynb">Colab</a>.</p><ul><li>Interested in PrimeHub? <a href="https://one.primehub.io/">Try PrimeHub</a> on your AWS account now!</li><li>Subscribe to InfuseAI newsletter: <a href="http://eepurl.com/hyI2TD">http://eepurl.com/hyI2TD</a></li><li>Join Discord community: <a href="https://discord.gg/CrAxQznedH">https://discord.gg/CrAxQznedH</a></li></ul><figure><a href="https://discord.gg/CrAxQznedH"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1r4NJL-4j_33yICIu3j-vg.png" /></a></figure><figure><a href="http://eepurl.com/hyI2TD"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5DM8_spjXbLizwmNU7BNnA.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6592aec96db" width="1" height="1" alt=""><hr><p><a href="https://blog.infuseai.io/what-our-primehub-sdk-can-do-towards-mlops-b6592aec96db">What our PrimeHub SDK can do towards MLOps</a> was originally published in <a href="https://blog.infuseai.io/">InfuseAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[在 PrimeHub 中使用 PyTorch Hub 的 YOLOV5 以及 OpenAI 的 CLIP 模型，快速打造行人安全的偵測系統]]></title>
            <link>https://blog.infuseai.io/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-pytorch-hub-%E7%9A%84-yolov5-%E4%BB%A5%E5%8F%8A-openai-%E7%9A%84-clip-%E6%A8%A1%E5%9E%8B-%E5%BF%AB%E9%80%9F%E6%89%93%E9%80%A0%E8%A1%8C%E4%BA%BA%E5%AE%89%E5%85%A8%E7%9A%84%E5%81%B5%E6%B8%AC%E7%B3%BB%E7%B5%B1-bb865921e590?source=rss-c8111db71de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb865921e590</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Eric]]></dc:creator>
            <pubDate>Fri, 11 Jun 2021 02:10:36 GMT</pubDate>
            <atom:updated>2021-06-11T07:38:07.193Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJ8MFkIIK9gdjItEeKiHww.png" /></figure><p>近來，COVID-19 疫情在台灣再次蔓延，雖然未進入封城階段，但許多民眾都會避免非必要的外出，由 Google 的 <a href="https://www.google.com/covid19/mobility/?hl=zh-TW">COVID-19 社區人流趨勢報告</a>中指出，截至 6 月 6 日，許多公共場所的人流變化都有下降的趨勢。</p><p>在室外場所較少人流和車流時，倘若有行人因突發狀況例如中暑、血糖過低而倒地時，極可能因周遭沒有其它民眾，而導致延誤就醫的情況。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*S3bvQVQc8edXNK1SfW7usA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*uUCey0HlMCUkf5uVKnRq8g.png" /></figure><p>今天，我想結合兩個強大的 pre-trained models 並搭配 <a href="https://docs.primehub.io/docs/introduction">PrimeHub v3.6</a> 的眾多功能，實現快速且零基礎上手的物件異常偵測系統。其中，第一個 pre-trained model 為 <a href="https://pytorch.org/hub/">PyTorch Hub</a> 的 <a href="https://github.com/ultralytics/yolov5">YOLOV5</a> 模型，可即時偵測圖片中的各類型物件；第二個 pre-trained model 則為 <a href="https://beta.openai.com/">OpenAI</a> 的 <a href="https://github.com/openai/CLIP">CLIP</a> 模型，其可進行圖片與自然語言類別的分類（我們先前有對 CLIP 做詳細的介紹，歡迎<a href="https://medium.com/infuseai/openai-%E7%9A%84-multimodal-%E7%A5%9E%E7%B6%93%E7%B6%B2%E8%B7%AF-%E4%B8%8B-clip-connecting-text-and-images-2e9962905504">參考</a>）。</p><p>接下來，將以桃園大溪老街的行人為監控目標，確保每位行經大溪老街的行人安全。以下為整個 end-to-end 流程的概述：</p><ol><li>在 PrimeHub 的 <a href="https://docs.primehub.io/docs/quickstart/launch-project">Notebooks</a> 中測試 YOLOV5 和 CLIP 預訓練模型</li><li>將 YOLOV5 和 CLIP 包裝成 model image 並推送至 Docker Hub</li><li>在 PrimeHub 的 <a href="https://docs.primehub.io/docs/model-deployment-feature">Model Deployments</a> 進行模型部署</li><li>在 PrimeHub 的 <a href="https://docs.primehub.io/docs/group-image">Custom Images</a>, <a href="https://docs.primehub.io/docs/job-submission-feature">Jobs</a>, 以及 <a href="https://docs.primehub.io/docs/job-scheduling-feature">Schedules</a> 中構建並優化全自動流程</li><li>整合 PrimeHub 的 <a href="https://grafana.com/">Grafana Monitoring</a> 和 Alert Notification，監控模型部署所發出的警告數值</li></ol><h3>1. 模型測試</h3><p>進入 PrimeHub，選擇 Demo group 作爲本次的實驗環境，其可與其它工作群組的資料和運算做有效區隔，利於團隊的資源管理。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*ZwgpyoSWgT-uuBmOYOfNrA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ieI3P7gpIdfYm2PwTaAhIA.gif" /></figure><p>接著，進入 <a href="https://docs.primehub.io/docs/quickstart/launch-project">Notebooks</a> 的開啟頁面。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*I-NJnzuZydQ1-hU_X1bb6w.gif" /></figure><p>選擇 CPU 為 1 且 Memory 為 2G 的 <a href="https://docs.primehub.io/docs/guide_manual/admin-instancetype">Instance Type</a>，並選擇 PyTorch 1.7 的 <a href="https://docs.primehub.io/docs/guide_manual/admin-image">Image</a> 作為實驗環境，按下 Start Notebook 稍待 Notebook 環境開啟吧！（完整的 Image 列表可<a href="https://docs.primehub.io/docs/guide_manual/images-list">參考</a>）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fkGO6SgQQLPr-Ux0cFkUUw.gif" /></figure><p>成功進入 Notebook 環境後，開啟 <a href="https://gist.github.com/ggosiang/76d8317b49f3205233638807c0c96abf">experiment.ipynb</a> 並執行所有的 cells。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Q3d1YDBs2FATutwvI8fuXQ.gif" /></figure><p>所有 cells 已執行完畢。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*AsiqETlpz3GYHPG6GEWjwg.gif" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0daee7d158e1926c332d81fb95ad2cdc/href">https://medium.com/media/0daee7d158e1926c332d81fb95ad2cdc/href</a></iframe><ul><li>第 4 cell：載入 CLIP 的 pre-trained model</li><li>第 6 cell：載入 YOLOV5 的 pre-trained model</li><li>第 8、9 cell：使用 YOLOV5 對圖片進行物件偵測，得到各物件的 bounding box</li><li>第 10 cell：顯示測試圖片，圖片來源為<a href="https://youtu.be/c1Hwm-vH9mo?t=63">道路事故影片</a>的畫面截圖</li><li>第 11 cell：將物件類別為 person 的 bounding box 取出，送入 CLIP 模型預測各個文字描述的機率</li></ul><p>結果如下面的三張圖所示，站立於人行道的是事故目擊者，其 need help 的機率僅為 36 %，而另外兩位因事故而趴、坐在馬路上的人其 need help 的機率明顯提升至 60 % 和 59 %。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*714HJRFjNSa2NJUzTRImpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*bxcONx7_I4sdZiHIrnPWHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*QvFtiAJHgD6Rlo1z-7WJyg.png" /></figure><h3>2. 準備 Model Image</h3><p>接著，我們將 YOLOV5 和 CLIP 的 pre-trained models 包進 model image，以作為一個可重複運行的服務。打包 model image 須用到的檔案可參考 <a href="https://github.com/InfuseAI/model-deployment-examples/tree/master/object_monitoring">GitHub</a>，其中必須包含以下的檔案：</p><ul><li><a href="https://github.com/InfuseAI/model-deployment-examples/blob/master/object_monitoring/Model.py">Model.py</a></li></ul><pre>class Model():<br>    def __init__():<br>    # 讀取環境變數以設定參數、並載入 yolov5 和 clip 的 pre-trained models</pre><pre>    def predict_yolov5():<br>    # 偵測圖片中的物件，並回傳各物件的 bounding box</pre><pre>    def predict_clip(): <br>    # 預測並回傳圖片在各個文字類別的分類機率</pre><pre>    def predict():<br>    # 將收到的圖片傳入 predict_yolov5() 以獲得 bounding box<br>    # 並將符合條件的 bounding box 傳入 predict_clip() 預測異常的機率<br>    # 若任一 bounding box 的總異常機率大於門檻值，則設 warning_number 為 1</pre><pre>    def metrics():<br>    # 將 metrics 數值 (warning_number) 送至 Grafana</pre><ul><li><a href="https://github.com/InfuseAI/model-deployment-examples/blob/master/object_monitoring/requirements.txt">requirements.txt</a>：執行 model image 所需安裝的套件</li><li><a href="https://github.com/InfuseAI/model-deployment-examples/blob/master/object_monitoring/Dockerfile">Dockerfile</a>：安裝所需套件，並設定環境變數</li></ul><p>檔案都準備好後，可遵循 <a href="https://github.com/InfuseAI/model-deployment-examples/blob/master/object_monitoring/README.md">README</a> 打包 model image 並在本地端測試。目前已先完成下列指令且將 model image 推至 <a href="https://hub.docker.com/r/infuseai/object_monitoring">Docker Hub</a>。</p><pre>$ cd model-deployment-examples/object_monitoring/<br>$ docker build . -t infuseai/object_monitoring:v0.1.0<br>$ docker push infuseai/object_monitoring:v0.1.0</pre><p>因此，後續使用的 model image URL 將為 <a href="https://hub.docker.com/layers/infuseai/object_monitoring/v0.1.0/images/sha256-12aa680589f74842dbd92f80916017a037b581977b63b9942528c8c51eada3dc?context=explore">infuseai/object_monitoring:v0.1.0</a></p><h3>3. 模型部署</h3><p>將 model image 推至 Docker Hub 後，我們來建立 Deployment 吧！回到 PrimeHub，進入 <a href="https://docs.primehub.io/docs/model-deployment-feature">Deployments</a> 頁面並點選 Create Deployment。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*KPCQxooFn95AsUiWETcmFQ.gif" /></figure><p>輸入下列資訊：</p><ul><li>Deployment Name：object-monitoring</li><li>Model Image：infuseai/object_monitoring:v0.1.0</li><li>Environment Variables（此組環境變數已透過實驗調整，可判斷行人的異常狀況，並將結果呈現於回傳的圖片中）：</li></ul><pre># yolov5：預載入的模型<br>YOLO_CKPT： yolov5x6</pre><pre># yolov5：COCO dataset 的 class（0 為 person）<br>MONITOR_OBJECT： 0</pre><pre># yolov5：偵測物件的信心數值<br>OBJECT_PROB： 0.5</pre><pre># clip：正常類別的文字描述<br>CLASS_LIST_NORMAL： [&quot;An image showing a person standing on the ground&quot;, &quot;An image showing a person is safe&quot;]</pre><pre># clip：異常類別的文字描述<br>CLASS_LIST_ABNORMAL： [&quot;An image showing a person falling on the ground&quot;, &quot;An image showing a person is not safe&quot;, &quot;An image showing a person meets with an accident&quot;]</pre><pre># 異常狀態的門檻值<br>ABNORMAL_THRESHOLD： 0.6</pre><pre># 回傳編碼圖片的 bytes<br>RETURN_IMAGE： 1</pre><ul><li>Instance Type：CPU 為 1 且 Memory 為 4 G（開啟 Notebook 時僅使用 2 G 的 Memory，此處多預留空間給 model serving）</li></ul><p>填完 Deployment 所需資訊後，按下 Deploy，先稍待片刻讓模型部署 ☕️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*NmTy3dGPPfCaYf87OVffHg.gif" /></figure><p>成功部署後，可點選 object-monitoring 進入<a href="https://docs.primehub.io/docs/model-deployment-feature#deployment-detail">資訊頁面</a>，並複製 Endpoint 欄位的值（https://hub.a.demo.primehub.io/deployment/object-monitoring-4e518/api/v1.0/predictions），我們可傳送 request 至此 Endpoint 並得到預測結果。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*8mdE_7oeylpKGoazf2PIXQ.gif" /></figure><p>來測試看看，<a href="https://github.com/InfuseAI/model-deployment-examples/blob/master/object_monitoring/test_image.jpg">test_image.jpg</a> 為影片 <a href="https://www.youtube.com/watch?v=BzecMZUZ_3Y">Pedestrian hit by falling ice</a> 的畫面截圖，透過以下指令可將圖片送至部署好的模型，並得到 <a href="https://github.com/InfuseAI/model-deployment-examples/blob/master/object_monitoring/example_output.jpg">output.jpg</a>，其正確預測出，被物體擊倒在地的人正處於不安全的狀態。</p><pre>$ curl -F &#39;binData=@test_image.jpg&#39; https://hub.a.demo.primehub.io/deployment/object-monitoring-4e518/api/v1.0/predictions | jq -r .binData | base64 --decode &gt; output.jpg</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Np_LojjH1mBywDjsyy5z2w.jpeg" /><figcaption>output.jpg</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Oh9GXXo1l8qT-7O7Gm8z6w.gif" /></figure><p>以下亦列出其它成功分類的圖片：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yWtv2ldEsow8Kgq4Fxk76w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNQiPqQiyTJ2grCX7zXtew.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z9yMtAes6VyhDrnCvydyXw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_pVdZNpuC857iDGlAcxjsg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hg7lS4oYIEcTlaNogbugLA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MK9VWYyzEev0pkRFIabVCQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JFiNBzxaba6PoPp2R8D4Yg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AIqZULaoi3KCfbeW4UsrJA.jpeg" /></figure><h3>4. 建構自動化流程</h3><p>確認部署的模型可重複提供服務後，接著我們透過 PrimeHub Jobs 來建立實際的監控和資料流程。回到 PrimeHub，進入 <a href="https://docs.primehub.io/docs/job-submission-feature">Jobs</a> 頁面並點選 New Job。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*yOVP4c-0w5hoKi0mSOO8Fg.gif" /></figure><p>輸入下列資訊：</p><ul><li>Instance Type：CPU 為 1 且 Memory 為 2 G</li><li>Image：<a href="https://docs.primehub.io/docs/guide_manual/images-list#jupyterlab-v2-with-primehub-extension-2">AI notebook</a>（預安裝機器學習套件、CPU 版、Python 3.7）</li><li>Job Name：object-monitoring-test</li><li>Command：</li></ul><pre># 安裝 jq 和 youtube-dl 套件<br>sudo apt-get update<br>sudo apt-get install jq -y<br>pip install youtube-dl</pre><pre># PrimeHub 提供 Job Artifacts 功能，我們只需將檔案產生於 artifacts 目錄下<br># 即可在 job 執行完畢後，透過 UI 檢視檔案<br>mkdir -p artifacts<br>cd artifacts/</pre><pre># 使用 youtube-dl 擷取桃園大溪老街的即時串流，存於 <strong>stream.mp4</strong><br>timeout -s SIGINT 5s youtube-dl -o stream.mp4 <a href="https://www.youtube.com/watch?v=z_mlibCfgFI">https://www.youtube.com/watch?v=z_mlibCfgFI</a></pre><pre># 從即時串流中取出一張 frame，存於 <strong>frame.jpg</strong><br>ffmpeg -i stream.mp4 -ss 00:00:01 -vframes 1 frame.jpg</pre><pre># 將 <strong>frame.jpg </strong>送入部署好的模型，將結果解碼並存於 <strong>result.jpg</strong><br>curl -F &quot;binData=<a href="http://twitter.com/frame">@frame</a>.jpg&quot; <a href="https://hub.a.demo.primehub.io/deployment/object-monitoring-4e518/api/v1.0/predictions">https://hub.a.demo.primehub.io/deployment/object-monitoring-4e518/api/v1.0/predictions</a> | jq -r .binData | base64 --decode &gt; &quot;result.jpg&quot;</pre><p>填完 Job 所需資訊後，按下 Submit，稍待一會兒就能看結果囉！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*QsJQ08C0zd2PHIr9yWUIiA.gif" /></figure><p>Job 成功執行完畢，進入其資訊頁面並點選 <a href="https://docs.primehub.io/docs/job-artifact-feature">Artifacts</a> tab，首先檢視 stream.mp4（大溪老街的即時串流）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*aGpiTVNPM0PHFcQsq54FpQ.gif" /></figure><p>接著是 frame.jpg （即時串流中的單張影像）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*v3PZjJ9NT8EziEvLQYMnaw.gif" /></figure><p>最後是 result.jpg（由於無行人經過，因此暫無預測結果）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*rnu96_sJLXUsI9VfYxoJaA.gif" /></figure><p>目前已可透過 Job 自動抓影像、並自動送入模型預測，而在將 Job 轉換為定時執行的 Schedule 前，我想對 Job 的 Command 做一些優化。目前 Job 每執行一次約需 30~34 秒，而以下 Command 為環境設置的部分，可預先安裝於 image，避免每次執行時重複的安裝。</p><pre># 安裝 jq 和 youtube-dl 套件<br>sudo apt-get update<br>sudo apt-get install jq -y<br>pip install youtube-dl</pre><p>因此，進入 <a href="https://docs.primehub.io/docs/group-image">Images</a> 頁面並點選 New Image。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YdDLtR-diREHuTabi29LCA.gif" /></figure><p>輸入下列資訊：</p><ul><li>Display Name：object-monitoring-custom-image</li><li>選擇 Build Custom Image</li><li>Base Image URL：選擇 AI notebook</li><li>Package — APT：jq</li><li>Package — PIP：youtube-dl</li></ul><p>填完 Image 所需資訊後，按下 Create，稍等一下就能使用我們的客製化 image 了 🍰</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*QAtl_zFUGYjulojFf1viAw.gif" /></figure><p>點選 object-monitoring-custom-image，查看 building logs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vQTOL49MLVkOrle9ZyxvSQ.gif" /></figure><p>image build 完後，即可在 Container Image URL 看到新的客製化 image URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TS9DUxu9Y31pK_SsR32E8Q.png" /></figure><p>回到 Jobs，對剛才執行過的 object-monitoring-test 按下 Clone。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2GDCrYXUY48n1Z6FnHENHw.png" /></figure><p>接著在 Image 改選新的客製化 image — object-monitoring-custom-image，並移除 Command 中安裝套件的指令。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*gDYOxOhEkoUodPBVQF6wtQ.gif" /></figure><p>成功了，新 image 執行的時間明顯減少為 18 秒 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0ja3Pmrr-zB53WH5WInVg.png" /></figure><p>最後，進入 <a href="https://docs.primehub.io/docs/job-scheduling-feature">Schedules</a> 頁面並點選 New Schedule。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fI_7KK8SLMTgHwKS30Tq5A.gif" /></figure><p>輸入下列資訊：</p><ul><li>Instance Type：CPU 為 1 且 Memory 為 2 G</li><li>Image：object-monitoring-custom-image</li><li>Schedule Name：object-monitoring-daxi-old-street</li><li>Command：</li></ul><pre># PrimeHub 提供 Job Artifacts 功能，我們只需將檔案產生於 artifacts 目錄下<br># 即可在 job 執行完畢後，透過 UI 檢視檔案<br>mkdir -p artifacts<br>cd artifacts/</pre><pre># 使用 youtube-dl 擷取桃園大溪老街的即時串流，存於 <strong>stream.mp4</strong><br>timeout -s SIGINT 5s youtube-dl -o stream.mp4 <a href="https://www.youtube.com/watch?v=z_mlibCfgFI">https://www.youtube.com/watch?v=z_mlibCfgFI</a></pre><pre># 從即時串流中取出一張 frame，存於 <strong>frame.jpg</strong><br>ffmpeg -i stream.mp4 -ss 00:00:01 -vframes 1 frame.jpg</pre><pre># 將 <strong>frame.jpg </strong>送入部署好的模型，將結果解碼並存於 <strong>result.jpg</strong><br>curl -F &quot;binData=<a href="http://twitter.com/frame">@frame</a>.jpg&quot; <a href="https://hub.a.demo.primehub.io/deployment/object-monitoring-4e518/api/v1.0/predictions">https://hub.a.demo.primehub.io/deployment/object-monitoring-4e518/api/v1.0/predictions</a> | jq -r .binData | base64 --decode &gt; &quot;result.jpg&quot;</pre><ul><li>Recurrence Options：0 * * * * (每小時的整點執行一次)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*sMyRKLQqzALoHtxXsP7URA.gif" /></figure><p>每隔一小時送出定義好的 Job，其運行於客製化的 image 環境，並將即時影像送入部署好的模型服務，可在短時間內完成場景中的物體異常偵測。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QI5Cg-gtLazP6kYhttDgzg.png" /></figure><p>以下為實際場景的預測結果：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*syLtuUXuj5PcBonjg5c1dw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0rPdB0PpiBgYEg_a6ASYA.jpeg" /></figure><h3>5. 整合 Grafana Alert Notification</h3><p>目前部署好的模型已可定時被 schedule 呼叫，進行即時的異常偵測，但假設真的有行人呈現非安全狀態時，我們該如何得知呢？</p><p>接下來將整合 <a href="https://grafana.com/">Grafana Monitoring</a> 和 Alert Notification，接收已部署的模型在每次預測中發出的回饋數值，而此數值在打包 model image 時，已先定義於 <a href="https://github.com/InfuseAI/model-deployment-examples/blob/master/object_monitoring/Model.py#L102">Model.py</a>。</p><pre>def metrics(self):<br>    return [{&quot;type&quot;: &quot;GAUGE&quot;, &quot;key&quot;: &quot;<strong>object_monitor_warning</strong>&quot;, &quot;value&quot;: self.<strong>warning_number</strong>}]</pre><p>Alert Notification 的其它設定已事先於 Grafana 完成，其提供多種通知方式，我們選用的是 <a href="https://slack.com/intl/en-tw/">Slack</a> 訊息的通知。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*9IS3Dl4IsK3zYRydWDbl0w.png" /></figure><p>讓我們進入 Grafana Dashboard 吧！</p><p>回到 PrimeHub，點選右上方的 <a href="https://docs.primehub.io/docs/quickstart/login-portal-admin">Admin Portal</a>，進入 Admin Portal 後點選左側 menu 中的 Grafana。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*K8YqHS41BC9hqrj67ueZEA.gif" /></figure><p>搜尋欄中會列出可監控的資源，點選 PrimeHub / Model Deployments / List。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GFEr5ybKgds2GD7bHchQ8A.png" /></figure><p>此 List 可列出平台中已部署的模型服務，點選我們的 object-monitoring。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wwXFJHDQVqCgsfDnOAtzQg.png" /></figure><p>成功進入 object-monitoring 的監控畫面，其中 Model Metrics 顯示兩個即時更新的趨勢圖：Predict QPS 可顯示模型於每秒接收到的 query 數；Object Monitoring 則會監控模型送出的 warning_number（0 代表安全、1 代表不安全）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GlIXOY0ee0Zgvx08m3xR2Q.png" /></figure><p>Object Monitoring 趨勢圖的監控規則：</p><ul><li>持續判斷最近的 2 分鐘，若平均值大於門檻值（0.5），會先標示警告（如下圖於 17:53:30 的橘線）</li><li>如果標示警告後 2 分鐘的平均值依然大於門檻值，則會發出 alert 至 Slack（如下圖於 17:55:30 的紅線）</li><li>至於若最近 2 分鐘的平均值小於門檻值，則表示安全狀態（如下圖於 17:59:30 的綠線）</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*beTCNZ-bATsWfivrf6w2Lw.png" /></figure><p>當圖片中的人物較小時，YOLOV5 的偵測和 CLIP 的預測皆可能出現誤差，而導致模型發出錯誤的回饋數值。此外，出現狀況的行人依然有可能自力或接受他人幫助而回到安全狀態。因此，在 Object Monitoring 偵測到警告時，會先短時間（2 分鐘）觀察，再根據最新的回饋數值，決定是否發出 alert。</p><p>如下圖所示，18:30:30 標示警告，而 18:32:30 正式發出 alert。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*qGij6GUWvx2GFam00HHxzg.png" /></figure><p>成功在 Slack 的 object-monitoring 頻道收到 alert 訊息。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RIKjL3odvTs5-yMkRumQGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4uas-ZU9C2M2ifHMOUf-RQ.gif" /></figure><p>而當 18:38:30 回到安全狀態。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*9UWdbjfQIcnS0oteYqLDSA.png" /></figure><p>Slack 亦收到 OK 的訊息通知，表示行人的危急狀態已解除。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hvtWZ4u9akI7mdwqzg5JGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hDGrR83I5-zYQtbZ0U-evw.gif" /></figure><p>成功將模型回饋、Grafana、以及 Slack 串連後，我們再回到 PrimeHub 的 Schedules 頁面，編輯先前的排程 — object-monitoring-daxi-old-street，將執行頻率改為每分鐘執行一次。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*nHdTGkywQJ4hmeHmJAzPJw.png" /></figure><p>最終，我們實現了每分鐘的即時串流擷取、模型預測、回饋監控、以及緊急狀態的回報。當收到 Slack 的 alert 通知時，可連至即時串流查看最新狀況，而每分鐘 Job 的執行檔案亦保留於 <a href="https://docs.primehub.io/docs/job-artifact-feature">Job Artifacts</a> 中，可供日後查閱。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OM6uzv24RLMIQjE5G3DFvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7iTC0GaLgyUjhyA_x-5wNg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPJ3loHPa7b9Ly0yPbdu3w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6rkTGGuLgnyB8DFRMDvHcg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LatMpVqegJnodRR1cfqJTA.jpeg" /></figure><h3>結論</h3><p>我們使用了兩個極具代表性的 model — YOLOV5、CLIP，並搭配 PrimeHub 的 Custom Images、Jobs、Schedule、Model Deployments、以及 Grafana Integration，實現全自動行人安全偵測的系統雛形。</p><p>YOLOV5 和 CLIP 對於較小的物體、或當物體的部分區域被遮蔽時，其預測準度會明顯下降。倘若日後有更佳的預訓練模型、或是我們自己訓練得到模型後，皆可透過 PrimeHub 的 Model Deployments，將模型預測的環節替換為更可靠的服務。</p><p>目前已將模型中的許多設定參數化，以偵測處於異常狀態的某物件，例如本文中偵測不安全 的 人。我們可自由更新 Model Deployments 中的環境變數，延伸至更廣泛的異常監控，例如故障的卡車🚚、或是卡在運河中的船隻🚢。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*j6SRtwFdflSAthDkBXnUCQ.png" /></figure><p>最後，希望疫情早日步入歷史。大家待在家的時候，不妨也玩玩看 <a href="https://www.infuseai.io/products/primhub-ai-platform">PrimeHub</a> 的<a href="https://github.com/InfuseAI/primehub">社群版</a>吧！</p><figure><a href="http://eepurl.com/hyI2TD"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5DM8_spjXbLizwmNU7BNnA.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb865921e590" width="1" height="1" alt=""><hr><p><a href="https://blog.infuseai.io/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-pytorch-hub-%E7%9A%84-yolov5-%E4%BB%A5%E5%8F%8A-openai-%E7%9A%84-clip-%E6%A8%A1%E5%9E%8B-%E5%BF%AB%E9%80%9F%E6%89%93%E9%80%A0%E8%A1%8C%E4%BA%BA%E5%AE%89%E5%85%A8%E7%9A%84%E5%81%B5%E6%B8%AC%E7%B3%BB%E7%B5%B1-bb865921e590">在 PrimeHub 中使用 PyTorch Hub 的 YOLOV5 以及 OpenAI 的 CLIP 模型，快速打造行人安全的偵測系統</a> was originally published in <a href="https://blog.infuseai.io/">InfuseAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[使用 TensorFlow Hub 快速訓練能辨別石虎（Leopard cat）的影像分類模型]]></title>
            <link>https://blog.infuseai.io/%E4%BD%BF%E7%94%A8-tensorflow-hub-%E5%BF%AB%E9%80%9F%E8%A8%93%E7%B7%B4%E8%83%BD%E8%BE%A8%E5%88%A5%E7%9F%B3%E8%99%8E-leopard-cat-%E7%9A%84%E5%BD%B1%E5%83%8F%E5%88%86%E9%A1%9E%E6%A8%A1%E5%9E%8B-f04d2ac67be6?source=rss-c8111db71de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f04d2ac67be6</guid>
            <category><![CDATA[wildlife-conservation]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Eric]]></dc:creator>
            <pubDate>Thu, 18 Jun 2020 01:35:18 GMT</pubDate>
            <atom:updated>2020-06-18T01:46:45.429Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71OYQFQryGLEoUo124l12Q.jpeg" /><figcaption><a href="http://pre10.deviantart.net/ad96/th/pre/i/2015/199/0/5/leopard_cat_20150713_2_by_furlined-d91teyl.jpg">http://pre10.deviantart.net/ad96/th/pre/i/2015/199/0/5/leopard_cat_20150713_2_by_furlined-d91teyl.jpg</a></figcaption></figure><p>在深度學習的訓練方法中，不論是初踏入的新手、亦或是專家級的研究者，想必都對<a href="https://en.wikipedia.org/wiki/Transfer_learning">遷移學習（Transfer Learning）</a>相當熟悉。尤其是當 pre-trained model 已透過大型資料集完成訓練，則將其轉移至較小的資料集時，總能獲得不錯的效果，並能藉此降低訓練成本。</p><p><a href="https://tfhub.dev/">TensorFlow Hub</a> （TF-Hub）是一個模型的整合平台，我們可透過 TF-Hub 直接調用訓練好的模型進行預測、或可利用 TF-Hub 所針對不同領域和不同平台的模型進行遷移學習。</p><p>這次，我在 <a href="https://www.infuseai.io/primehub">PrimeHub</a> 中使用 TF-Hub 載入一預先訓練好的影像分類模型，並以新資料集進行遷移學習。新資料集的類別中，包括了目前台灣的第一級保育類動物 — <a href="https://en.wikipedia.org/wiki/Leopard_cat">石虎（Leopard cat）</a>。以下將整個探索流程概述分為四部分：</p><ol><li>事前準備</li><li>進入 JupyterHub 進行實驗</li><li>準備新資料集</li><li>訓練新資料集</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTYAjmnnNbc1WuL-2Jtd9Q.png" /><figcaption><a href="https://www.ysnp.gov.tw/page.aspx?path=392">https://www.ysnp.gov.tw/page.aspx?path=392</a></figcaption></figure><h3>1. 事前準備</h3><h4>石虎</h4><p><a href="https://www.natgeomedia.com/environment/article/content-4778.html">石虎在外型上的特徵</a>：</p><ol><li>體型跟家貓相似</li><li>石虎耳後為黑底白斑</li><li>眼睛內側有向上延伸的兩條白色線條</li><li>身體、四肢與尾巴都有黑色塊狀斑</li></ol><p>由於石虎在外觀上與其它貓類有著部分差異，因此應可利用 ML 網路架構中的 feature extractor layer 提取有用的分類特徵。</p><h4>TF-Hub</h4><p>TF-Hub 包括了豐富的 Filters 功能，供使用者快速搜尋所需的模型。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*Cbg3Zb1-D02WlmXc0F1yyg.png" /><figcaption><a href="https://tfhub.dev/s?subtype=model-family">https://tfhub.dev/s?subtype=model-family</a></figcaption></figure><p>我們根據 Problem domain 為 Image classification、TF Version 為 TF2、Architecture 為輕量級的 MobileNet V2、以及 Dataset 為擁有高達 1000 個類別的 <a href="http://www.image-net.org/challenges/LSVRC/2012/">Imagenet (ILSVRC-2012-CLS)</a> 來過濾，最後選擇 <a href="https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4">tf2-preview/mobilenet_v2/classification</a> 作為本次的預訓練模型。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXord7Sfk8g_9QmiH2SvgQ.png" /><figcaption><a href="https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4">https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4</a></figcaption></figure><h3>2. 進入 JupyterHub 進行實驗</h3><p>首先，進入 <a href="https://docs.primehub.io/docs/next/guide_manual/primehub-manual#launch-your-project-jupyterhub">JupyterHub</a> 的 Spawner 頁面。</p><p>選擇 Instance Type 為 CPU1 以及 Image 為 TensorFlow 2.1 (Python 3.7) (Universal)，按下 Start Notebook！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iqKtcozswylJUiU_.png" /></figure><pre>更多關於 JupyterHub 的詳細介紹，歡迎參考<a href="https://medium.com/infuseai/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-14cef9f583a9">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (1/4)</a></pre><p>進入 JupyterLab 環境後，執行 pip install tensorflow_hub 以安裝 TF-Hub</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7zIPdAXtSH9VYw_33ErUA.png" /></figure><p>若往後會經常透過 TF-Hub 輔助實驗，不妨可透過 <a href="https://docs.primehub.io/docs/next/guide_manual/admin-build-image#docsNav">Image Builder</a> 將 TF-Hub 預先安裝於環境中，省下每次需重複安裝的時間。</p><pre>更多關於 Image Builder 的詳細介紹，歡迎參考<a href="https://medium.com/infuseai/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-3-4-c94a82e2cb9a">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (3/4)</a></pre><p>接下來，開啟 Jupyter Notebook、以及本次使用的 <a href="https://gist.github.com/ggosiang/ce09808f3faf94e956f06615b8d29f61">notebook 檔案</a>。</p><p>一開始，載入所需的 libraries。本次實驗所用的 tensorflow 為 2.1.0 版、tensorflow_hub 則為 0.8.0 版。</p><pre>import tensorflow as tf<br>import tensorflow_hub as hub<br>from tensorflow.keras import layers<br>import numpy as np<br>import matplotlib.pylab as plt<br>import PIL.Image as Image</pre><p>接著，設定 classifier_url 為剛才在 TF-Hub 中選定的 <a href="https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4&#39;">https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4</a>。</p><p>載入 MobileNet 並包裝於 Keras 的 sequential model 中。</p><pre>classifier_url = &#39;<a href="https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4&#39;">https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4&#39;</a><br>IMAGE_SHAPE = (224, 224)</pre><pre>classifier = tf.keras.Sequential([<br>    hub.KerasLayer(classifier_url, input_shape=IMAGE_SHAPE+(3,))<br>])</pre><p>先下載一張石虎的影像來測試，以 tf.keras.utils.get_file 下載的檔案會保存於 ~/.keras/datasets 中。</p><p>根據 tf2-preview/mobilenet_v2/classification 網頁中的 Usage 說明：</p><blockquote>The input images are expected to have <strong>color values in the range [0,1]</strong>, following the <a href="https://www.tensorflow.org/hub/common_signatures/images#input">common image input</a> conventions. For this module, the size of the input images is fixed to <strong>height x width = 224 x 224 pixels</strong>.</blockquote><p>因此，將載入的影像 resize 為 224x224，並將 pixel value rescale 至 [0, 1]。</p><pre>image_url = &#39;<a href="https://upload.wikimedia.org/wikipedia/commons/9/9c/Stavenn_Felis_bengalensis_00.jpg&#39;">https://upload.wikimedia.org/wikipedia/commons/9/9c/Stavenn_Felis_bengalensis_00.jpg&#39;</a><br>img = tf.keras.utils.get_file(&#39;leopard-cat.jpg&#39;, image_url)<br>img = Image.open(img).resize(IMAGE_SHAPE)<br>img = np.array(img)/255.0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*sySL-bnBJvqKHZ5g.jpg" /><figcaption><a href="https://upload.wikimedia.org/wikipedia/commons/9/9c/Stavenn_Felis_bengalensis_00.jpg">https://upload.wikimedia.org/wikipedia/commons/9/9c/Stavenn_Felis_bengalensis_00.jpg</a></figcaption></figure><p>接下來，將影像的 NDArray 多加入一維的 batch dimension，送入 classifier 進行預測。result.shape 為 (1, 1001)，其包含 Imagenet (ILSVRC-2012-CLS) 的 1000 個類別、再加上 background 類別共 1001 類的分類機率。</p><pre>result = classifier.predict(img[np.newaxis, ...])<br>result.shape # (1, 1001)</pre><p>機率最高的類別為 286 類。</p><pre>predicted_class = np.argmax(result[0], axis=-1)<br>predicted_class # 286</pre><p>下載 <a href="https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt">ImageNetLabels.txt</a> 並顯示第 286 類的類別名稱 — Egyptian cat。由於 ImageNet 中尚無石虎的類別，所以此時會將其誤判為可能相似的動物 — Egyptian cat（埃及貓）。</p><pre>labels_path = tf.keras.utils.get_file(&#39;ImageNetLabels.txt&#39;,&#39;<a href="https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt&#39;">https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt&#39;</a>)<br>imagenet_labels = np.array(open(labels_path).read().splitlines())<br>predicted_class_name = imagenet_labels[predicted_class]<br>predicted_class_name # &#39;Egyptian cat&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/0*K055Dbq__XtkDL3z.jpg" /><figcaption>埃及貓，<a href="https://en.wikipedia.org/wiki/Egyptian_Mau#/media/File:Mau_egyptien_bronze.jpg">https://en.wikipedia.org/wiki/Egyptian_Mau#/media/File:Mau_egyptien_bronze.jpg</a></figcaption></figure><h3>3. 準備新資料集</h3><p>接下來，我們試著分類多張石虎的影像。</p><p>因無法在網路上找到公開的石虎資料集，我們使用 <a href="https://github.com/ultralytics/google-images-download">ultralytics/google-images-download</a> 來從 <a href="https://www.bing.com/?scope=images">Bing 的圖片搜尋</a>中下載圖片。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8oLhJuz_hY7N_lx9v5y93A.png" /></figure><p>執行以下指令：</p><pre>python bing_scraper.py \<br>    --url &#39;https://www.bing.com/images/search?q=leopard-cat&#39; \<br>    --format &#39;jpg&#39; \<br>    --limit 50 \<br>    --download \<br>    --chromedriver /path/to/chromedriver</pre><ul><li>url：query item 為 leopard-cat</li><li>format：下載的圖檔須為 JPG 格式</li><li>limit：下載 50 張影像</li><li>chromedriver：<a href="https://chromedriver.chromium.org/">chrome driver</a> 的存取路徑</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N2VG9wcTzIZiQtCAliJZ-A.png" /></figure><p>稍待片刻，我們即可在 images 目錄檢視下載的 50 張影像。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zh-BhjYwd10cqVS5fYXxaQ.png" /></figure><p>接下來，人工過濾以移除下列情況的影像，並至多保存 30 張作為本次實驗的 test images：</p><ol><li>石虎在影像中的面積過小</li><li>石虎被其它障礙物遮蔽掉過多面積</li><li>影像中不止一隻石虎</li><li>錯誤的影像</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*E0-UL0LVnLM92FSAVf8sWg.jpeg" /><figcaption>需移除的影像：影像中不只一隻石虎，<a href="https://www.bengalcats.co/wp-content/uploads/2012/05/felis-bengalensis-leopard-cat-kittens.jpg">https://www.bengalcats.co/wp-content/uploads/2012/05/felis-bengalensis-leopard-cat-kittens.jpg</a></figcaption></figure><p>人工過濾完後，重新命名該目錄為 leopard-cat 並壓縮至 leopard-cat.zip。</p><p>接著使用 PrimeHub 的 <a href="https://docs.primehub.io/docs/zh-tw/guide_manual/admin-dataset#upload-server">Dataset Upload</a> 功能，將壓縮檔上傳至 leopard-cat dataset。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-kSCH9Z7Nj5kSIAeVTQfw.png" /></figure><p>透過 Upload Server 上傳中。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VPyEeVnCYiVLh1vQPu_qIw.png" /></figure><p>上傳完畢，會自動解壓縮。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zlkOU8wsH4xQTZsIjq1omw.png" /></figure><p>我們可在 JupyterLab 環境中存取 /datasets/leopard-cat 檢視資料集的檔案。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0bAfeRfTUPgUlQ9estUSqQ.png" /></figure><pre>更多關於 Dataset Upload 的詳細介紹，歡迎參考<a href="https://medium.com/infuseai/%E4%BD%BF%E7%94%A8-primehub-%E8%A8%93%E7%B7%B4-yolov4-%E6%A8%A1%E5%9E%8B-%E5%AF%A6%E7%8F%BE%E5%AE%9A%E6%99%82%E5%AE%9A%E9%BB%9E%E7%9A%84%E5%8F%A3%E7%BD%A9%E9%85%8D%E6%88%B4%E6%AF%94%E4%BE%8B%E5%81%B5%E6%B8%AC-9e361f837e49">使用 PrimeHub 訓練 YOLOv4 模型 — 實現定時定點的口罩配戴比例偵測</a>中的 &quot;1. 準備資料集&quot;</pre><p>接下來，回到 notebook 設定 data_root 為剛才上傳資料的 /datasets/leopard-cat 。</p><pre>data_root = &#39;/datasets/leopard-cat&#39;</pre><p>再以 <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator">tf.keras.preprocessing.image.ImageDataGenerator</a> 產生以 batch 為單位的 tensor image data，flow_from_directory 的 batch_size 預設為 32，因此全部的 30 張影像會位於同一 batch 中。</p><pre>image_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1/255)<br>image_data = image_generator.flow_from_directory(data_root, target_size=IMAGE_SHAPE)</pre><p>檢視 class_names，目前只有一個類別 — Leopard-Cat。</p><pre>class_names = sorted(image_data.class_indices.items(), key=lambda pair:pair[1])<br>class_names = np.array([key.title() for key, value in class_names])<br>class_names # array([&#39;Leopard-Cat&#39;], dtype=&#39;&lt;U11&#39;)</pre><p>檢視 image_batch 的 shape 為 (30, 224, 224, 3) -&gt; 30 張 224x224 的 RGB 影像；label_batch 的 shape 為 (30, 1) -&gt; 30 張影像的類別皆為 Leopard-Cat。</p><pre>for image_batch, label_batch in image_data:<br>    print(&quot;Image batch shape: &quot;, image_batch.shape) #(30,224,224,3)<br>    print(&quot;Label batch shape: &quot;, label_batch.shape) #(30,1)<br>    break</pre><p>送入 classifier 進行預測。</p><pre>result_batch = classifier.predict(image_batch)<br>predicted_class_names = imagenet_labels[np.argmax(result_batch, axis=-1)]</pre><p>將影像與預測類別一同顯示出來。</p><pre>plt.figure(figsize=(10,9))<br>plt.subplots_adjust(hspace=0.5)<br>for n in range(30):<br>    plt.subplot(6,5,n+1)<br>    plt.imshow(image_batch[n])<br>    plt.title(predicted_class_names[n])<br>    plt.axis(&#39;off&#39;)<br>_ = plt.suptitle(&quot;ImageNet predictions&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yn8TIKAAdr0LzH1bcGrgNw.png" /></figure><p>由於 ImageNet 中尚無石虎的類別，因此其會被分類至其它較相似的動物。觀察多組資料後，發現 <a href="https://en.wikipedia.org/wiki/Tabby_cat">tabby （虎斑貓）</a>、<a href="https://en.wikipedia.org/wiki/Oncilla">tiger cat（小斑虎貓）</a>、<a href="https://en.wikipedia.org/wiki/Lynx">lynx（猞猁屬）</a>、以及 <a href="https://en.wikipedia.org/wiki/Egyptian_Mau">Egyptian cat（埃及貓）</a>為最常被分到的類別。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*sySL-bnBJvqKHZ5g.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o__qfWnaYz36WG_O.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/0*JFur5YDPJav_cMDs.jpg" /><figcaption>左：石虎、中：虎斑貓、右：小斑虎貓（<a href="https://upload.wikimedia.org/wikipedia/commons/9/9c/Stavenn_Felis_bengalensis_00.jpg">https://upload.wikimedia.org/wikipedia/commons/9/9c/Stavenn_Felis_bengalensis_00.jpg</a>、<a href="https://en.wikipedia.org/wiki/Tabby_cat#/media/File:Cat_November_2010-1a.jpg">https://en.wikipedia.org/wiki/Tabby_cat#/media/File:Cat_November_2010-1a.jpg</a>、<a href="https://zh.wikipedia.org/wiki/%E5%B0%8F%E6%96%91%E8%99%8E%E8%B2%93#/media/File:Tika2009Jan24.jpg">https://zh.wikipedia.org/wiki/%E5%B0%8F%E6%96%91%E8%99%8E%E8%B2%93#/media/File:Tika2009Jan24.jpg</a>）</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/0*GKee5JZgAXnHpXQb.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tp6s-5bEkydkWsLE.jpg" /><figcaption>左：猞猁屬、右：埃及貓（<a href="https://en.wikipedia.org/wiki/Lynx#/media/File:Lynx_lynx_poing.jpg">https://en.wikipedia.org/wiki/Lynx#/media/File:Lynx_lynx_poing.jpg</a>、<a href="https://zh.wikipedia.org/wiki/%E5%9F%83%E5%8F%8A%E8%B2%93#/media/File:Egyptian_Mau_Bronze.jpg">https://zh.wikipedia.org/wiki/%E5%9F%83%E5%8F%8A%E8%B2%93#/media/File:Egyptian_Mau_Bronze.jpg</a>）</figcaption></figure><p>因此，接下來繼續使用 <a href="https://github.com/ultralytics/google-images-download">ultralytics/google-images-download</a> 下載 leopard cat、tabby、tiger cat、lynx、以及 Egyptian cat 的影像：</p><ul><li>額外下載 250 張 leopard-cat，並不與先前的 30 張 test images 重複</li><li>各下載 250 張 tabby、tiger cat、lynx、以及 Egyptian cat</li><li>過濾 1250 張影像並刪除不適合作為 training images 的影像</li></ul><p>影像都確認無誤後，壓縮並使用 Dataset Upload 上傳至 cats dataset 中。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPcM0blJidOiObbDd4tJKA.png" /></figure><p>各個類別的 training images 中，egyptian-cat 有 193 張、leopard-cat 有 190 張、lynx 有 191 張、tabby 有 193 張、而 tiger-cat 則有 191 張，確保了資料的平衡性。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tt1xv87uIdv8LgNK9iWWzw.png" /></figure><p>回到 notebook 設定 data_root 為剛才上傳的 /datasets/cats。</p><pre>data_root = &#39;/datasets/cats&#39;</pre><p>產生以 batch 為單位的 tensor image data。</p><pre>image_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1/255)<br>image_data = image_generator.flow_from_directory(data_root, target_size=IMAGE_SHAPE)</pre><p>檢視 class_names，類別名稱依序為 Egyptian-Cat、Leopard-Cat、Lynx、Tabby、以及 Tiger-Cat。</p><pre>class_names = sorted(image_data.class_indices.items(), key=lambda pair:pair[1])<br>class_names = np.array([key.title() for key, value in class_names])<br>class_names <br># array([&#39;Egyptian-Cat&#39;, &#39;Leopard-Cat&#39;, &#39;Lynx&#39;, &#39;Tabby&#39;, &#39;Tiger-Cat&#39;], dtype=&#39;&lt;U12&#39;)</pre><p>檢視 image_batch 的 shape 為 (32, 224, 224, 3) -&gt; 32 張 224x224 的 RGB 影像；label_batch 的 shape 為 (32, 5) -&gt; 每張影像屬於五類中的其中一類；而 training images 共有 958 張。</p><pre>for image_batch, label_batch in image_data:<br>    print(&quot;Image batch shape: &quot;, image_batch.shape) # (32,224,224,3)<br>    print(&quot;Label batch shape: &quot;, label_batch.shape) # (32,5)<br>    break<br>print(&quot;Totle number of images: &quot;, image_data.samples) # 958</pre><h3>4. 訓練新資料集</h3><p>TF-Hub 不僅提供 classifier 直接預測，其亦提供 feature extractor layer 協助使用者產生客製化資料的 feature vector，我們可將 feature extractor layer 與自定義的 classification layer 結合，快速實現遷移學習。</p><p>設定 feature_extractor_url 為一開始在 TF-Hub 中選定的 <a href="https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4">https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4</a>。</p><pre>feature_extractor_url = &#39;<a href="https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4&#39;">https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4&#39;</a></pre><p>建立 feature_extractor_layer。</p><pre>feature_extractor_layer = hub.KerasLayer(feature_extractor_url,<br>                                         input_shape=(224,224,3))</pre><p>每張影像經 feature_extractor_layer 處理後會產生長度為 1280 的向量。</p><pre>feature_batch = feature_extractor_layer(image_batch)<br>print(feature_batch.shape) # (32, 1280)</pre><p>利用已訓練好的 feature_extractor_layer，來訓練我們疊加上去的 classification_layer，因此設定 feature_extractor_layer 的參數不應在訓練中更改。</p><pre>feature_extractor_layer.trainable = False</pre><p>將 feature_extractor_layer 與新加入的 classification_layer 包裝於 Keras 的 sequential model 中。</p><pre>model = tf.keras.Sequential([<br>  feature_extractor_layer,<br>  layers.Dense(image_data.num_classes)<br>])</pre><pre>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-qrWYlZIk3LcWpnPNngRg.png" /></figure><p>設定 training config。</p><pre>model.compile(<br>  optimizer=tf.keras.optimizers.Adam(),<br>  loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),<br>  metrics=[&#39;acc&#39;])</pre><p>執行 3 個 epochs 的簡單訓練。</p><pre>model.fit(image_data, epochs=3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L-EaKJDJ0AKiZ8pwaUK5lA.png" /></figure><h4>Results (training images)</h4><p>快速訓練後，先測試 training images 中的一個 batch。</p><pre>predicted_batch = model.predict(image_batch)<br>predicted_id = np.argmax(predicted_batch, axis=-1)<br>predicted_label_batch = class_names[predicted_id]<br>label_id = np.argmax(label_batch, axis=-1)</pre><p>將影像與預測類別一同顯示出來。</p><pre>plt.figure(figsize=(10,9))<br>plt.subplots_adjust(hspace=0.5)<br>for n in range(30):<br>    plt.subplot(6,5,n+1)<br>    plt.imshow(image_batch[n])<br>    color = &quot;green&quot; if predicted_id[n] == label_id[n] else &quot;red&quot;<br>    plt.title(predicted_label_batch[n].title(), color=color)<br>    plt.axis(&#39;off&#39;)<br>_ = plt.suptitle(&quot;Model predictions (green: correct, red: incorrect)&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i9e23VvUzmlO17rBod7Wng.png" /></figure><p>其中有 3 張影像分類錯誤。</p><h4>Results (test images)</h4><p>再測試先前的 test images（與 training images 無重複的 30 張 leopard cat）。</p><pre>data_root = &#39;/datasets/leopard-cat&#39;</pre><pre>image_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1/255)<br>image_data = image_generator.flow_from_directory(data_root, target_size=IMAGE_SHAPE)</pre><pre>for image_batch, label_batch in image_data:<br>    print(&quot;Image batch shape: &quot;, image_batch.shape) #(30,224,224,3)<br>    print(&quot;Label batch shape: &quot;, label_batch.shape) #(30,1)<br>    break</pre><pre>predicted_batch = model.predict(image_batch)<br>predicted_id = np.argmax(predicted_batch, axis=-1)<br>predicted_label_batch = class_names[predicted_id]</pre><pre>label_id = np.argmax(label_batch, axis=-1)</pre><p>將影像與預測類別一同顯示出來。</p><pre>plt.figure(figsize=(10,9))<br>plt.subplots_adjust(hspace=0.5)<br>for n in range(30):<br>    plt.subplot(6,5,n+1)<br>    plt.imshow(image_batch[n])<br>    plt.title(predicted_label_batch[n].title())<br>    plt.axis(&#39;off&#39;)<br>_ = plt.suptitle(&quot;Model predictions&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vi-wSCtEu8pLESkX01N-YA.png" /></figure><p>有 2 張預測錯誤，分別被誤判為 Tiger-Cat 和 Tabby。</p><h4>Result (sample image)</h4><p>最後，重新挑戰一開始誤判為 Egyptian cat（埃及貓）的可愛石虎。</p><pre>img = tf.keras.utils.get_file(&#39;leopard-cat.jpg&#39;, image_url)<br>img = Image.open(img).resize(IMAGE_SHAPE)<br>img</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*sySL-bnBJvqKHZ5g.jpg" /><figcaption><a href="https://upload.wikimedia.org/wikipedia/commons/9/9c/Stavenn_Felis_bengalensis_00.jpg">https://upload.wikimedia.org/wikipedia/commons/9/9c/Stavenn_Felis_bengalensis_00.jpg</a></figcaption></figure><p>印出各類別的機率 [-1.3605374 , 2.4656174 , -3.7321572 , -1.9058045 , -0.17406169]，其中 index = 1 的類別最高。</p><pre>img = np.array(img)/255.0<br>result = model.predict(img[np.newaxis, ...])<br>result[0]<br># array([-1.3605374 ,  2.4656174 , -3.7321572 , -1.9058045 , -0.17406169], dtype=float32)</pre><p>太棒了，index = 1 的類別即為 Leopard-Cat！</p><pre>predicted_class = np.argmax(result[0], axis=-1)<br>class_names[predicted_class] # &#39;Leopard-Cat&#39;</pre><p>測試模型的部分，雖然仍有不少的分類錯誤，但已能成功辨識出原本沒有的石虎類別。</p><p>最重要的是，透過 TF-Hub 直接將預訓練好的模型加以利用，即可在極短的時間、以及極低的機器運算成本，產出一個可作為 baseline 的模型成果。</p><h3>結論</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*lztA44qwgVOBAtkfxROdTw.jpeg" /><figcaption><a href="https://i.pinimg.com/736x/c1/e6/5b/c1e65b3f5c95e702f16d955f279467db--leopard-cat-domestic-cat.jpg">https://i.pinimg.com/736x/c1/e6/5b/c1e65b3f5c95e702f16d955f279467db--leopard-cat-domestic-cat.jpg</a></figcaption></figure><p>隨著近年來資料量的擴增，我們很難在短時間內對大部分的資料進行訓練。因此，透過社群的力量將模型共享，並藉助遷移學習讓訓練成果能持續沿用，實為現今機器學習的一大助力。</p><p>TensorFlow Hub 提供豐富的模型資源，供使用者選用。<a href="https://pytorch.org/hub/">PyTorch Hub</a> 亦提供類似的模型服務，不過其目前尚處於 beta release，未來有機會也會向大家介紹 PyTorch Hub。</p><p>這次在蒐集石虎影像時，看了很多石虎的可愛模樣，但也被一些受傷的石虎、或是倒在路上的石虎而感到難過痛心，台灣不是只有自私的人類在生活著，<strong>請給動物們一個良好的環境</strong>。</p><h3>參考</h3><ul><li><a href="https://tfhub.dev/">https://tfhub.dev/</a></li><li><a href="https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4">https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4</a></li><li><a href="https://www.tensorflow.org/tutorials/images/transfer_learning_with_hub">https://www.tensorflow.org/tutorials/images/transfer_learning_with_hub</a></li><li><a href="https://github.com/ultralytics/google-images-download">https://github.com/ultralytics/google-images-download</a></li><li><a href="https://docs.google.com/forms/d/e/1FAIpQLSe_Z8JfIbYnvhOampGN_XXle4d3GVX04E8evnNI_Py3abth-A/viewform">PrimeHub 試用申請表單</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f04d2ac67be6" width="1" height="1" alt=""><hr><p><a href="https://blog.infuseai.io/%E4%BD%BF%E7%94%A8-tensorflow-hub-%E5%BF%AB%E9%80%9F%E8%A8%93%E7%B7%B4%E8%83%BD%E8%BE%A8%E5%88%A5%E7%9F%B3%E8%99%8E-leopard-cat-%E7%9A%84%E5%BD%B1%E5%83%8F%E5%88%86%E9%A1%9E%E6%A8%A1%E5%9E%8B-f04d2ac67be6">使用 TensorFlow Hub 快速訓練能辨別石虎（Leopard cat）的影像分類模型</a> was originally published in <a href="https://blog.infuseai.io/">InfuseAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[使用 PrimeHub 訓練 YOLOv4 模型 — 實現定時定點的口罩配戴比例偵測]]></title>
            <link>https://blog.infuseai.io/%E4%BD%BF%E7%94%A8-primehub-%E8%A8%93%E7%B7%B4-yolov4-%E6%A8%A1%E5%9E%8B-%E5%AF%A6%E7%8F%BE%E5%AE%9A%E6%99%82%E5%AE%9A%E9%BB%9E%E7%9A%84%E5%8F%A3%E7%BD%A9%E9%85%8D%E6%88%B4%E6%AF%94%E4%BE%8B%E5%81%B5%E6%B8%AC-9e361f837e49?source=rss-c8111db71de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e361f837e49</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[yolov4]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Eric]]></dc:creator>
            <pubDate>Tue, 02 Jun 2020 05:20:54 GMT</pubDate>
            <atom:updated>2020-06-02T05:20:54.437Z</atom:updated>
            <content:encoded><![CDATA[<h3>使用 PrimeHub 訓練 YOLOv4 模型 — 實現定時定點的口罩配戴比例偵測</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*10K2YaS5l60SAxzNbgfabg.png" /></figure><p>上回的系列文章中，我在 <a href="https://www.infuseai.io/primehub">PrimeHub</a> v2.6 結合了 <a href="https://github.com/ytdl-org/youtube-dl">youtube-dl</a> 和 <a href="https://github.com/AlexeyAB/darknet">YOLOv4</a> 以提供一定時的景點擁擠度偵測。有興趣的朋友，歡迎至以下連結閱讀！</p><ul><li><a href="https://medium.com/infuseai/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-14cef9f583a9">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (1/4)</a></li><li><a href="https://medium.com/p/1b6f5150fbd">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (2/4)</a></li><li><a href="https://medium.com/p/c94a82e2cb9a">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (3/4)</a></li><li><a href="https://medium.com/p/5cb3f27a1676">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (4/4)</a></li></ul><p>近來，雖然 COVID-19 的疫情逐漸在台灣趨緩，但其影響層面依舊在國際間不容忽視，而台灣在這段期間獲得國際認同的防疫物資 — 口罩，想必不論是國人或是國際朋友都對台灣的口罩讚譽有加！</p><p>由於口罩能適度地降低病毒以飛沫的型式在密閉空間內傳播，因此這陣子許多地方例如車廂、百貨公司皆規範人員需全時配戴口罩。這次，我想嘗試以客製化的資料集在 PrimeHub v2.6 進行 YOLOv4 的模型訓練，偵測空間內未正確配戴口罩的比例。以下將整個 end-to-end 流程概述分為四部分：</p><ol><li>準備口罩資料集，並透過 <a href="https://docs.primehub.io/docs/zh-tw/guide_manual/admin-dataset#upload-server">Dataset Upload</a> 將資料集上傳</li><li>在 <a href="https://docs.primehub.io/docs/next/guide_manual/admin-build-image#docsNav">Image Builder</a> 中建置帶有 C/C++ OpenCV 函式庫的專屬映像檔，以供後續訓練時使用</li><li>在 <a href="https://docs.primehub.io/docs/next/guide_manual/primehub-manual#launch-your-project-jupyterhub">JupyterHub</a> 中運行實驗，包括函式庫編譯、資料集前處理、準備訓練所需的檔案、實際訓練、並透過 Grafana 查看 GPU 資訊</li><li>將訓練結果與先前的景點擁擠度 workflow 整合，實現一定時定點的口罩配戴比例偵測</li></ol><h3>1. 準備資料集</h3><p>為訓練出能辨別有無戴口罩的模型，我使用的資料集是 Kaggle 的 <a href="https://www.kaggle.com/andrewmvd/face-mask-detection">Face Mask Detection Dataset</a>，共有 853 張影像，涵蓋了以下三種類別：</p><ol><li>With mask</li><li>Without mask</li><li>Mask worn incorrectly</li></ol><p>而其檔案結構包含 images 和 annotations 目錄，其中 images/*.png 包含 853 張影像，annotations/*.xml 則是各個影像中物件的標記資料。</p><p>首先，按下 Download 以下載資料集。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-71Aqo5gUicBaQaHtkvkQ.png" /></figure><p>下載完成為 667889_1176415_bundle_archive.zip。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*lHKYB-9y8o3CbFqrkR8tUw.png" /></figure><p>為了讓後續 JupyterHub 可存取該資料集，接著透過 Dataset Management 的 Dataset Upload 功能來上傳資料集！</p><p>進入 User Portal，選擇 Admin Dashboard。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-gUa7eDWZwPmQPZJBegqQ.png" /></figure><p>選擇 Datasets，來到 Datasets list 頁面。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_L1aq4-4g3L5KR69jDc9Qw.png" /></figure><p>點選 Add，進入 Dataset 的創建頁面。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpACCU-yJnR-t7QbEzdQNg.png" /></figure><p>在各個欄位輸入：</p><ul><li>Name：face-mask-detection</li><li>Type：pv</li><li>Readonly Groups：選擇所屬的 The A-Team</li></ul><p>此舉將掛載一個 persistent volume 至 /datasets/face-mask-detection 上，以存放上傳的資料集。PrimeHub 使用 Readonly Groups 和 Writable Groups 分配不同的存取權限予不同的工作群組，達到資料保護和共享。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BX1Y1ZLQXc0ilsQQEG7b-w.png" /></figure><p>設定完畢後，按下 Confirm 。</p><p>face-mask-detection 出現在 Datasets list 中，點選 Actions 中的編輯按鈕。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CkCh4Q3Xr3QkJQMqNTxJrw.png" /></figure><p>將 Enable Upload Server 的 checkbox 打勾，並按下 Confirm 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*6fmJthuzHm-rtnYyo3IUUA.png" /></figure><p>畫面中會顯示提示視窗，其中指出 Upload Server 已成功啟動，將 Username 和 Password 先行紀錄下來，點選 OK。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gFLiNunc-M4MMeW3du5OEQ.png" /></figure><p>回到 Datasets list，點選 face-mask-detection 其 Upload Server 欄位中的 Link。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5RnjzFiFgypL-j6EKelFxA.png" /></figure><p>進入 Upload Server 的登入頁面，登入資訊為先前紀錄的 Username 和 Password。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*n1u824ezDewUrqKZtExywQ.png" /></figure><p>成功登入後，可查看 Dataset 目錄中的內容，先點選 Upload Data。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-QRPt2qYLV-hynXv-lNtg.png" /></figure><p>選擇先前從 Kaggle 下載的 667889_1176415_bundle_archive.zip。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xxBqYkoiWnJ7hUf2HEeSbQ.png" /></figure><p>點選 Upload 1 file。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jAu7oPF9Ty3f6Wo7mOwKHg.png" /></figure><p>上傳中。Dataset Upload 支援暫停、取消、並可於上傳中另外新增上傳的檔案。此外，若網路非預期中斷，亦可於中斷點進行續傳。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ARg6mrgEGenjYSU7-RDVmw.png" /></figure><p>上傳完畢，關閉此視窗。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JW-7t2b4OrrJtCR6V003Gg.png" /></figure><p>回到 Dataset 內容頁面，Dataset Upload 會自動將上傳的檔案解壓縮，因此可直接查看 images 和 annotations 目錄中的檔案。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eTT-lPEKl784ZHJ54Lbe9w.png" /></figure><p>images 目錄中的影像檔。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rvY6g9DxAuoaFNab2XZaRg.png" /></figure><p>annotations 目錄中的標記檔。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wYdoOFvsaG6DazFzx8xWhg.png" /></figure><p>目前，我們已成功將口罩資料集上傳至 Datasets 中。而在後續的章節，我們即可透過 JupyterHub 直接在 /datasets/face-mask-detection 存取 images 和 annotations 目錄中的內容。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*2ocjdu8D9qDfb0S1144mrg.png" /></figure><h3>2. 建置映像檔</h3><p>YOLOv4 使用了一個新的 Data Augmentation 技術 — Mosaic，以提升模型訓練時資料的豐富度。而使用 Mosaic 須先安裝 C/C++ 的 OpenCV 函式庫 — libopencv-dev，就讓我們先透過 Image Builder 將其安裝於映像檔中吧！</p><p>詳細的 Image Builder 使用範例可參考 <a href="https://medium.com/infuseai/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-3-4-c94a82e2cb9a">實戰系列文章 3/4</a>。</p><p>首先，在 Image Builder 的創建頁面輸入所需資訊，記得在 APT 欄位中填入 libopencv-dev。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x0BO7almgsPZC8T-JXb89g.png" /></figure><p>稍待片刻，裝有 libopencv-dev 的 Image 建置完成，並已 pushed 至 Google Container Registry 中存放。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v6NsGH_0GGSzr5jkN_QUqw.png" /></figure><p>最後，將建置好的 Image URL 搭配 Image Pull Secret，建置出一個可供 The A-Team Group 存取的 GPU Image。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVL4_LSMzeMuEkf1BKcA4w.png" /></figure><pre>😉  小分享 😉</pre><pre>在 <a href="https://medium.com/infuseai/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-3-4-c94a82e2cb9a">實戰系列文章 3/4</a> 中，我們使用 Image Builder 將 youtube-dl 預先安裝於映像檔，但當時是為了簡化 Job 在 inference 階段的步驟和時間，因此在實驗階段並未提供太大幫助。</pre><pre>而本次的 C/C++ OpenCV 是模型訓練時即需安裝的 dependency，因此透過 Image Builder 建置出符合當下 project 所需的客製化映像檔，確實減少了每次實驗前的環境建置成本。</pre><h3>3. 運行實驗</h3><h4>Compile Library</h4><p>首先，進入 JupyterHub 的 Spawner 頁面，選擇 GPU 的 Instance Type 以及新加入的 Image — tf-2.1-py3.7-opencv-cpp，按下 Start Notebook！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eSlmCHxloNe4EpNb1ooSBA.png" /></figure><p>進入到 JupyterLab 環境，開啟之前在 <a href="https://medium.com/infuseai/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-14cef9f583a9">實戰系列文章 1/4</a> 編輯過的檔案 — darknet/Makefile，並將 OPENCV 設為 1。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*IcBkpXd5XM2psV8CW2ESxw.png" /></figure><p>於同目錄中開啟 Terminal，執行 make。待編譯完成後，我們即可使用編譯好的 library 進行 Mosaic enabled 的訓練。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6B_8fimfsEPwVeiVZK4vXQ.png" /></figure><p>透過前一步驟先行安裝 libopencv-dev，並在實驗環境中編譯出所需的 shared library，則日後從 JupyterHub 或 Job Submission 進行訓練時都無需再重複編譯。</p><h4>Dataset 前處理</h4><p>由於 Face Mask Detection Dataset 是以 <a href="http://host.robots.ox.ac.uk/pascal/VOC/">PASCAL VOC</a> format 標註資料集，因此先透過 <a href="https://github.com/ssaru/convert2Yolo">Convert2Yolo</a> 轉換至 YOLO 可接受的資料集格式。</p><pre>$ git clone <a href="https://github.com/ssaru/convert2Yolo.git">https://github.com/ssaru/convert2Yolo.git</a><br><br>$ cd convert2Yolo/</pre><pre>$ python example.py \<br>    --datasets VOC \<br>    --img_path /datasets/face-mask-detection/images/ \<br>    --label /datasets/face-mask-detection/annotations/ \<br>    --convert_output_path /project/a-team/darknet/data/face-mask-detection/dataset \<br>    --img_type &quot;.jpg&quot; \<br>    --cls_list_file /project/a-team/darknet/data/face-mask-detection/obj.names</pre><ul><li>其中指名標記檔之原始型態為 VOC</li><li>原始資料集在 /datasets/face-mask-detection/</li><li>會將結果輸出至 /project/a-team/darknet/data/face-mask-detection/dataset</li><li>此處的 /project/a-team/darknet/data/face-mask-detection/obj.names 為訓練目標中每個類別的名稱，會在稍後的內容中介紹</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fzG70_5_b1M5VTKdEQIk9g.png" /></figure><p>處理完標記檔後，接著再透過 Jupyter Notebook 實作一簡單的 script 將 Face Mask Detection Dataset 中的圖片從 PNG 格式轉為 JPG 格式，並按照 90:10 的比例將資料集分配至 train.txt 和 valid.txt 中。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57dfe078138fbf36073caf6d3cce31da/href">https://medium.com/media/57dfe078138fbf36073caf6d3cce31da/href</a></iframe><p>在 Jupyter Notebook 中執行所有的 cells。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E3Dx4f-cb7dujoBWXIjazg.png" /></figure><p>新的 JPG 圖檔會輸出至 /project/a-team/darknet/data/face-mask-detection/dataset。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*wSu3ADAYPdiPbZW0gyYsiQ.png" /></figure><p>train.txt 包含訓練資料的圖片檔路徑，我取 90%（767 張）作為訓練資料。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*Ylsa97kdsKNNHNFl471tCg.png" /></figure><p>valid.txt 包含驗證資料的圖片檔路徑，我取 10%（86 張）作為驗證資料。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*5tS7QP8_PN4EjoZX-R6lHA.png" /></figure><h4>準備訓練所需的檔案</h4><p>遵循 YOLOv4 GitHub 的<a href="https://github.com/AlexeyAB/darknet#how-to-train-to-detect-your-custom-objects">訓練教學</a>，新增以下的檔案：</p><ul><li>darknet/data/face-mask-detection/obj.names：每個類別的名稱。</li></ul><pre>with_mask<br>without_mask<br>mask_weared_incorrect</pre><ul><li>darknet/data/face-mask-detection/obj.data：指定 input 和 output 的設定檔，其中 backup/ 為模型 weights-file 存放的路徑。</li></ul><pre>classes= 3<br>train  = data/face-mask-detection/train.txt<br>valid  = data/face-mask-detection/valid.txt<br>names = data/face-mask-detection/obj.names<br>backup = backup/</pre><ul><li>darknet/cfg/yolo-obj.config：神經網路設定檔，可直接複製 <a href="https://github.com/AlexeyAB/darknet/blob/master/cfg/yolov4-custom.cfg">yolov4-custom.cfg</a>，並做以下三處的修改。</li></ul><ol><li>修改 network size</li></ol><pre>Line    8:  width=416 <br>Line    9:  height=416</pre><p>2. 根據欲訓練的類別數，修改 max_batches 和 steps</p><pre>Line   20:  max_batches=6000 <br>Line   22:  steps=4800,5400</pre><p>3. 根據欲訓練的類別數，修改所有 yolo 層中的 classes、以及所有 yolo 層前一 convolutional 層中的 filters</p><pre>Line  963:  filters=24 <br>Line  970:  classes=3  </pre><pre>Line 1051:  filters=24 <br>Line 1058:  classes=3  </pre><pre>Line 1139:  filters=24 <br>Line 1146:  classes=3</pre><p>相關檔案都設定完畢後，我們還需下載 pre-trained weights-file：yolov4.conv.137。</p><p>yolov4.conv.137 的下載連結： <a href="https://drive.google.com/open?id=1JKF-bdIklxOOVy-2Cr5qdvjgGpmGfcbp">https://drive.google.com/open?id=1JKF-bdIklxOOVy-2Cr5qdvjgGpmGfcbp</a>。</p><h4>開始訓練</h4><p>終於！可以！開始訓練啦！</p><p>開啟 Terminal，執行 ./darknet detector train data/face-mask-detection/obj.data cfg/yolo-obj.cfg yolov4.conv.137 -dont_show。</p><p>其中 obj.data、yolo-obj.cfg、以及 yolov4.conv.137 皆為先前步驟中所準備的檔案，而由於我們在雲端平台上進行訓練，並未與實體顯示器連結，因此使用 -dont_show 以避免 Gtk-WARNING **: cannot open display: 的錯誤發生。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1K-srQ44GFtjsGgflgAJg.png" /></figure><p>我們可查看訓練中的 logs 資訊，隨著訓練時間的增加，每一個 iteration 中的 avg loss value 應可逐漸降低。倘若觀察到 avg loss value 出現 nan 數值，則可能先前步驟中準備的資料有誤，可以再檢查一遍。</p><p>第 211 個 iterations，avg loss 約為 10.3。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eYdH0PHFncrUGEd5pfthag.png" /></figure><p>第 450 個 iterations，avg loss 約為 7.5。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hCJ4mzjmWjfMjBntqCT0Bg.png" /></figure><pre>😉  小分享 😉</pre><pre>曾誤用錯誤的資料進行訓練，當時 bounding-box 的 width 和 height 都直接給成像素寬高，而非影像中的比例。</pre><pre>但當時訓練還是照常運行，沒有提示錯誤，所以大家自己在訓練的時候，可以適時觀察 logs，避免錯誤的訓練持續下去。</pre><p>訓練進行中，會將 weights-file 保存於 backup 目錄。其中每 1000 個 iterations 會保存一次（yolo-obj_1000.weights、yolo-obj_2000.weights、…），每 100 個 iterations 亦會保存於 yolo-obj_last.weights，而最終的 iteration 則會保存於 yolo-obj_final.weights。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*RgTwRUOK0IvjxuTb1XuyMQ.png" /></figure><p>我們可以中途結束訓練，再以</p><p>./darknet detector train data/face-mask-detection/obj.data cfg/yolo-obj.cfg <strong>backup/yolo-obj_xxx.weights</strong> -dont_show</p><p>重啟以 <strong>yolo-obj_xxx.weights</strong> 為起點的接續訓練。</p><h4>透過 Grafana 查看 GPU 資訊</h4><p>隨著資料量的爆炸成長以及現代模型愈趨複雜，監控 GPU 的運行負載將能有效提升團隊在 GPU 資源的控管分配。</p><p>PrimeHub 提供 Grafana 作為資源的監控儀表板，透過可視化介面即可查看即時的 GPU Memory 使用率、Power Usage、Duty Cycle、以及 GPU 溫度等資訊。</p><p>回到 User Portal，點選 Grafana。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQ4G5DuxSL4Z3gz48h7jzg.png" /></figure><p>進入 Grafana 監控後台，我們可於此選擇查看多種 resources 的 dashboard。</p><p>選擇 GPU / Node。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*onmgfN-fIIV4vW7NpNY1zw.png" /></figure><p>GPU Node 的資訊顯示圖表，我們可調整至任意的時間區間，以查看 YOLOv4 模型訓練時，GPU 的即時狀態。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a5kP-5UREzI8z1ptzg-R7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QBU36XUyxU-9Yj3q-HWw3A.png" /></figure><p>在訓練完 6000 個 iterations 之後，avg loss value 約在 0.7 至 0.9 的區間震盪。若加入更多有效的訓練資料、並搭配足夠的訓練時間，則可能將訓練誤差獲得進一步改善。</p><blockquote>you should preferably have 2000 different images for each class or more, and you should train 2000*classes iterations or more</blockquote><blockquote><a href="https://github.com/AlexeyAB/darknet#how-to-improve-object-detection">https://github.com/AlexeyAB/darknet#how-to-improve-object-detection</a></blockquote><pre>😉  小分享 😉</pre><pre>除了單純以 JupyterHub 進行訓練外，我也很推薦使用 Job Submission 執行長時間訓練，使用範例可參考 <a href="https://medium.com/infuseai/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-2-4-1b6f5150fbd">實戰系列文章 2/4</a>。</pre><pre>以本次的 YOLOv4 為例，做完所有前置作業後，訓練的 Job 只需進入指定的 darknet 目錄，並執行 &quot;./darknet … -dont_show&quot; 即可。過程中會自動保存 weights-file，而我們亦可至 Job 的 Logs 頁面查看 loss value 等資訊。</pre><pre>只要我們使用的 Resources（CPU, Memory, GPU） 不超過 User 和 Group 所規範的 Resource Limits，則透過 Job Submission 執行 GPU 的長時間訓練，同時在 JupyterHub 以 CPU 進行其他實驗，可有效提升專案效率。</pre><h3>4. 訓練結果</h3><p>為實現定時定點的口罩配戴比例偵測，我修改了在 <a href="https://medium.com/infuseai/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-14cef9f583a9">實戰系列文章 1/4</a> 中的 darknet_video.py。其中，載入檔案的部分，我使用經口罩資料集訓練得到的 weights-file。</p><pre>configPath = &quot;./cfg/yolo-obj.cfg&quot;<br>weightPath = &quot;./backup/yolo-obj_5000.weights&quot;<br>metaPath = &quot;./data/face-mask-detection/obj.data&quot;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e6297803be5cc025a307e52b6d93354/href">https://medium.com/media/0e6297803be5cc025a307e52b6d93354/href</a></iframe><p>偵測由台中市政府民政局建置的<a href="https://www.youtube.com/watch?v=WHeYEZIUbZQ">台中東區樂成宮即時影像</a>的結果：</p><ul><li>能偵測出部分 with_mask 和 without_mask 的類別</li><li>當物體呈現正面或略為側面，其辨識效果較好</li><li>當物體在畫面中較小時，其辨識效果會明顯較差</li><li>串流的視角是由上而下，但訓練資料集較缺乏這種角度</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*10K2YaS5l60SAxzNbgfabg.png" /></figure><p>使用 <a href="https://docs.primehub.io/docs/next/job-submission-feature">Job Submission</a> 將此 end-to-end 流程以 Job 執行，其中執行的 Commands 依序為：</p><ol><li>切換至 darknet 目錄</li><li>擷取視訊串流</li><li>即時偵測並送出結果</li><li>刪除串流檔</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p9kcpjTOZtj0I2syj1oBbw.png" /></figure><p>檢視發出的 Email。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6j4H6mNikP4AYsVk2hoGsQ.png" /></figure><p>每張 frame 的類別數量圖。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQ0RaAK4Mmgg6Cj9kWn6hA.png" /></figure><p>detection 的結果影片。仍有不少誤差在較小的物體上。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ut9SXgB0BSas4NkzrqlpEQ.png" /></figure><p>目前已成功將訓練完的模型加入原有的 workflow 中，倘若想實現定時的自動偵測，只需再透過 <a href="https://docs.primehub.io/docs/next/job-scheduling-feature">Job Scheduler</a> 為已確立的流程加上時間屬性即可。詳細的 Job Scheduler 使用範例可參考 <a href="https://medium.com/infuseai/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-4-4-5cb3f27a1676">實戰系列文章 4/4</a>。</p><h3>結論</h3><p>相較於上次僅使用 YOLOv4 運行 video inference，本次實際訓練客製化的 dataset 則讓我對 YOLOv4 的模型和訓練有了更多了解。</p><p>未來，我希望能擴增訓練資料集，包括口罩的樣式、與其他配件的搭配、以及嘗試從不同視角蒐集資料。實際分析結果影片中的單張影像時，才發現有些模型的誤判其實以人類也很難判別，因為臉部大小在畫面中的比例較低，因此要準確判斷該區域確實不易，這也是 ML 的迷人之處吧！</p><p>本文透過 PrimeHub v2.6 進行環境映像檔建置、資料集上傳、實際訓練、以及訓練時的硬體資源監控，實現了 ML 流程中相當重要的環節。不久後，PrimeHub 將推出 <a href="https://docs.primehub.io/docs/next/model-deployment-feature">模型部署（Model Deployment）</a>的功能，協助使用者將訓練好的模型打包，上傳至 PrimeHub 中實現不中斷的線上預測服務。</p><p>本文僅介紹 PrimeHub v2.6 的部分功能，若您有興趣探索更多的 PrimeHub，歡迎<a href="https://docs.google.com/forms/d/e/1FAIpQLSe_Z8JfIbYnvhOampGN_XXle4d3GVX04E8evnNI_Py3abth-A/viewform">點選試用申請</a>並開始您的旅程！</p><h3>參考</h3><ul><li>YOLOv4：<a href="https://arxiv.org/abs/2004.10934">https://arxiv.org/abs/2004.10934</a></li><li>YOLOv4 GitHub：<a href="https://github.com/AlexeyAB/darknet">https://github.com/AlexeyAB/darknet</a></li><li>youtube-dl Github：<a href="https://github.com/ytdl-org/youtube-dl">https://github.com/ytdl-org/youtube-dl</a></li><li>台中東區樂成宮的直播串流：<a href="https://www.youtube.com/watch?v=WHeYEZIUbZQ">https://www.youtube.com/watch?v=WHeYEZIUbZQ</a></li><li>Face Mask Detection Dataset：<a href="https://www.kaggle.com/andrewmvd/face-mask-detection">https://www.kaggle.com/andrewmvd/face-mask-detection</a></li><li>convert2Yolo GitHub：<a href="https://github.com/ssaru/convert2Yolo">https://github.com/ssaru/convert2Yolo</a></li><li><a href="https://docs.google.com/forms/d/e/1FAIpQLSe_Z8JfIbYnvhOampGN_XXle4d3GVX04E8evnNI_Py3abth-A/viewform">PrimeHub 體驗申請表單</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e361f837e49" width="1" height="1" alt=""><hr><p><a href="https://blog.infuseai.io/%E4%BD%BF%E7%94%A8-primehub-%E8%A8%93%E7%B7%B4-yolov4-%E6%A8%A1%E5%9E%8B-%E5%AF%A6%E7%8F%BE%E5%AE%9A%E6%99%82%E5%AE%9A%E9%BB%9E%E7%9A%84%E5%8F%A3%E7%BD%A9%E9%85%8D%E6%88%B4%E6%AF%94%E4%BE%8B%E5%81%B5%E6%B8%AC-9e361f837e49">使用 PrimeHub 訓練 YOLOv4 模型 — 實現定時定點的口罩配戴比例偵測</a> was originally published in <a href="https://blog.infuseai.io/">InfuseAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (4/4)]]></title>
            <link>https://blog.infuseai.io/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-4-4-5cb3f27a1676?source=rss-c8111db71de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cb3f27a1676</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[yolov4]]></category>
            <dc:creator><![CDATA[Eric]]></dc:creator>
            <pubDate>Wed, 20 May 2020 06:07:01 GMT</pubDate>
            <atom:updated>2020-05-21T06:13:49.042Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDsAaeBksd_5jQxm7J8hNA.png" /></figure><h3>定時自動偵測</h3><p>目前，我們已建置好執行所需的環境（Image）、以及確認可重複執行的步驟（Job）。接下來，只須再加入排程特性，即可達成定時的景點擁擠度自動偵測，這時我就用 PrimeHub 的 Job Scheduler 功能。</p><p>進入 User Portal &gt; Job Submission (Beta) &gt; Schedule。</p><p>此頁面會顯示 <a href="https://docs.primehub.io/docs/next/job-scheduling-feature">Job Scheduler</a> 的 list。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oG740kLTDqqCG2_XxkftiA.png" /></figure><p>點選 Schedule Job 進入 Schedule 的創建頁面。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-7ps7LoYGxBdvtwdPXDrw.png" /></figure><p>在各個欄位輸入：</p><ul><li>Group：The A-Team</li><li>InstanceTypes：GPU 1</li><li>Images：tf2.1-py3.7-yt-dl</li><li>Schedule name：object-detection</li><li>Command：</li></ul><pre>cd a-team/darknet<br>timeout -s SIGINT 10s youtube-dl -o stream.mp4 <a href="https://www.youtube.com/watch?v=WGLUUH5HEVA">https://www.youtube.com/watch?v=WGLUUH5HEVA</a><br>python darknet_video.py<br>rm stream.mp4</pre><ul><li>Recurrence Options：預設提供 Every Day、Every Week、以及 Every Month 的固定時程，我選擇 Custom 並填入 Cron expression 0 */2 * * * （每 2 小時執行一次）</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*LQmkcEHq_3r1YEllW-yiJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5-_F09lqNe8QyD9uTJSZA.png" /></figure><p>設定完畢後，點選 Submit。</p><p>完成 Job Schedule 的設定，下一次執行為 18 分鐘後。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8eYIKbsxbFL1eSNcasytrA.png" /></figure><p>當到達排定的時程後，Job Scheduler 會自動 submit 預先設定好的 job settings。</p><p>Job list 顯示 scheduled job 處於 Preparing 狀態。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ln299gk4olHGW24YRZvx_w.png" /></figure><p>稍待片刻，scheduled job 執行完畢。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*du18HuYqraB31oGilzEkpg.png" /></figure><p>收到由 scheduled job 寄來的結果。擁擠度依然為中，而且開始降雨了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hjd_04Nmb2W5o6YOq3kPhA.png" /></figure><p>由於我們的 Job Schedule 排定為每 2 小時執行一次，就讓我們隔天再回來看結果！</p><p>過了一個晚上，成功收到由 20:00、22:00、00:00、02:00、04:00、06:00、以及 08:00 所執行的結果。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uiv3uOtp7cM2JD3kCxTMZA.png" /></figure><p>相對應的 Job list。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nc3stNL2UNL_7COkQPExaA.png" /></figure><ul><li>2020/05/18 22:06</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*PNucPTW57eNqt6KjtU8HaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*TZNOQrhC1rfzaDqQMpOHmw.png" /></figure><ul><li>2020/05/19 08:06</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*OJNY_ifXE6vHxd0uCYW15w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*jJtKJCSRzprWJYMhdz7M9A.png" /></figure><h3>結論</h3><p>本文透過 InfuseAI 的機器學習平台 — PrimeHub，串連 youtube-dl 和 YOLOv4（感謝作者的付出！當中有台灣作者！），實現定時的景點擁擠度偵測。相關的直播串流與物件偵測之延伸，例如特定路段的車流預測，亦可以相同流程達到應用目的。</p><p>未來，我們希望能拓展目前的單一時間點至長時間分析，將每次 scheduled job 的影像結果，保存於雲端空間，並導入機器學習，取代目前單純以數量判斷的擁擠度，產出進一步的景點擁擠度趨勢預測。</p><p>此外，目前 InfuseAI 正積極研發 PrimeHub <a href="https://docs.primehub.io/docs/next/model-deployment-feature">模型部署（Model Deployment）</a>的功能，期許之後能將擁擠度預測的模型，部署至線上直接提供服務。</p><p>本文僅介紹 PrimeHub v2.6 的部分功能，若您有興趣探索更多的 PrimeHub，歡迎<a href="https://docs.google.com/forms/d/e/1FAIpQLSe_Z8JfIbYnvhOampGN_XXle4d3GVX04E8evnNI_Py3abth-A/viewform">點選試用申請</a>並開始您的旅程！</p><h3>參考</h3><ul><li>YOLOv4：<a href="https://arxiv.org/abs/2004.10934">https://arxiv.org/abs/2004.10934</a></li><li>YOLOv4 GitHub：<a href="https://github.com/AlexeyAB/darknet">https://github.com/AlexeyAB/darknet</a></li><li>youtube-dl Github：<a href="https://github.com/ytdl-org/youtube-dl">https://github.com/ytdl-org/youtube-dl</a></li><li>公館夜市的直播串流：<a href="https://www.youtube.com/watch?v=WGLUUH5HEVA">https://www.youtube.com/watch?v=WGLUUH5HEVA</a></li></ul><h4>搶先申請體驗⬇ ️</h4><p><a href="https://docs.google.com/forms/d/e/1FAIpQLSe_Z8JfIbYnvhOampGN_XXle4d3GVX04E8evnNI_Py3abth-A/viewform">申請表單</a></p><h4>PrimeHub 實戰系列文章</h4><p><a href="https://medium.com/infuseai/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-14cef9f583a9">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (1/4)</a></p><p><a href="https://medium.com/p/1b6f5150fbd">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (2/4)</a></p><p><a href="https://medium.com/p/c94a82e2cb9a">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (3/4)</a></p><p><a href="https://medium.com/p/5cb3f27a1676">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (4/4)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cb3f27a1676" width="1" height="1" alt=""><hr><p><a href="https://blog.infuseai.io/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-4-4-5cb3f27a1676">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (4/4)</a> was originally published in <a href="https://blog.infuseai.io/">InfuseAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (3/4)]]></title>
            <link>https://blog.infuseai.io/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-3-4-c94a82e2cb9a?source=rss-c8111db71de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c94a82e2cb9a</guid>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[yolov4]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Eric]]></dc:creator>
            <pubDate>Wed, 20 May 2020 06:06:57 GMT</pubDate>
            <atom:updated>2020-05-21T06:12:25.850Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDsAaeBksd_5jQxm7J8hNA.png" /></figure><h3>建置專屬映像檔</h3><p>目前，我們已可藉由單一 Job 的執行，來重現串流擷取與偵測的步驟。</p><p>不過，在每次執行 Job 時，都須先安裝 youtube-dl，帶來部分執行時間的增加。幸運的是，PrimeHub 具有建置專屬映像檔功能 Image Builder。因此，為了縮短 Job 執行時間，我將使用 Image Builder，建置一個具備先決環境 Image，以縮短後續執行時間的花費。</p><p>回到 User Portal，進入 Admin Dashboard。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RHEGeh81XptjsFIdGGe3xA.png" /></figure><p>選擇 Image Builder，此處會顯示所有的 Image Builder list。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*258KD2NeqZXu1XYOECZpjg.png" /></figure><p>點選 Add，進入 Image Builder 的創建頁面。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wu0ZmYmSkkPBFTfYFCBoKQ.png" /></figure><p>在各個欄位輸入：</p><ul><li>Name：tf2.1-py3.7-with-youtube-dl</li><li>Base Image：使用先前 TensorFlow 2.1 (Python 3.7) (Universal) 中 GPU 版本的 image URL</li><li>Package(s) &gt; Pip：youtube-dl</li></ul><p>一切設定完畢後，按下 Confirm。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wgFJ5g8PF9o7_dOVJsswbg.png" /></figure><p>Image Builder list 顯示 tf2.1-py3.7-with-youtube-dl 開始 Running。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EasFCGbg362Ot6YotQCy7g.png" /></figure><p>檢視該 Image Builder，會顯示其 builder job 的歷史紀錄。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dq7O_aC4t5ZrlQB1HzFK1Q.png" /></figure><p>檢視正在執行中的 builder job logs。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0y5lLC-wgxfKf2slK8kJQ.png" /></figure><p>稍待片刻，帶有 youtube-dl 的 Image 建置完成，並已 pushed 至 Google Container Registry 中存放。（Registry 可自定）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JyMJVALq-owEz2ds7kIaKg.png" /></figure><p>Image Builder 的 job 已順利完成。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTkUfaNRR2PuBynpEyEQhg.png" /></figure><p>Image Builder list 亦顯示 tf2.1-py3.7-with-youtube-dl 已建置成功，可直接複製位於 Google Container Registry 的 Image URL。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70_uIyy7ubWzDkGRVtI8ig.png" /></figure><p>由於該 Image 位於 private repo 內，因此須先新增 image pull secret。</p><p>進入 <a href="https://docs.primehub.io/docs/next/guide_manual/admin-secret#docsNav">Secrets</a> 頁面並點選 Add。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OXlBHO8aqcXyGHVS-O3E1Q.png" /></figure><p>在各個欄位輸入：</p><ul><li>Name：gcr-pull-image-secret</li><li>Registry Host：<a href="https://gcr.io/">https://gcr.io</a></li><li>Username</li><li>Password</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KW0pZabj22lyOCakalGWDA.png" /></figure><p>輸入完畢後，按下 Confirm 即可完成新增。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7E83KypcaHdIT9S2rddRw.png" /></figure><p>接下來，進入 <a href="https://docs.primehub.io/docs/next/guide_manual/admin-image#docsNav">Images</a> 頁面，此處紀錄著供 JupyterHub 和 Job Submission 所存取的 images list。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G9X0bfkFSISXcYJPvBZpUA.png" /></figure><p>點選 Add 進入 Image 的創建頁面。</p><p>在各個欄位輸入：</p><ul><li>Name：tf2.1-py3.7-yt-dl</li><li>Type：gpu（僅供 GPU 的 Instance Type 使用）</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*dz5pXcIZ_PaLLQ3vJv6Oaw.png" /></figure><ul><li>Container image url：貼上剛才在 Image Builder 所複製 tf2.1-py3.7-with-youtube-dl 的 URL</li><li>Checked Use Image Pull Secret 並選擇剛才在 Secrets 頁面創建的 gcr-pull-image-secret</li><li>Groups：選擇所屬的 The A-Team。PrimeHub 將使用者以 Group 的方式管理，並可將資源（Instance Types、Images、Datasets）在 Group 之間做有效地共享或獨立。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AQdX2f4upZ6F4oprCwUDsQ.png" /></figure><p>設定完畢後，按下 Confirm 即可完成新增。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sghbILyVo7_6FAch5N7zAA.png" /></figure><p>讓我們測試看看！</p><p>回到 Job Submission (Beta) &gt; Create Job：</p><ul><li>Image 改為使用 tf2.1-py3.7-yt-dl</li><li>Command 的部分，把原先第 1 行的 pip install youtube-dl 移除</li></ul><p>按下 Submit 吧！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fBY5FnMRKkw0A2bqdHLRYw.png" /></figure><p>從 Job logs 可得知，youtube-dl 已預先安裝且可正常運行。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FaaiYjuWZ03o5_amqfteBg.png" /></figure><p>縮短了執行時間，Job 執行完畢！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IRhQaVxKdeub31jTaiaU1A.png" /></figure><p>公館夜市目前的擁擠程度為中。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mlu5uH9LqyA3CCNJzcpmtQ.png" /></figure><p>從影片可看出，接近傍晚的公館夜市，擁擠程度有略微提升。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vkwrwaRvnXU1LYjvUX0hrg.png" /></figure><p>Image Builder 主要的功能，是提供不同專案領域的使用者，能建置符合其需求的映像檔，例如影像、文字、以及生醫等機器學習領域，都有專屬的套件和函式庫可供選用。因此，透過 Image Builder 降低日後重複安裝套件的 efforts，可有效提升整體專案的效率。</p><h3>待續</h3><p>第四篇，我將介紹運用 PrimeHub 的 Job Scheduler 將前述的 Job、專屬映像檔、並搭配運行的排程設定，實現定時的景點擁擠度偵測。</p><h4>搶先申請體驗⬇ ️</h4><p><a href="https://docs.google.com/forms/d/e/1FAIpQLSe_Z8JfIbYnvhOampGN_XXle4d3GVX04E8evnNI_Py3abth-A/viewform">申請表單</a></p><h4>PrimeHub 實戰系列文章</h4><p><a href="https://medium.com/infuseai/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-14cef9f583a9">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (1/4)</a></p><p><a href="https://medium.com/p/1b6f5150fbd">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (2/4)</a></p><p><a href="https://medium.com/p/c94a82e2cb9a">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (3/4)</a></p><p><a href="https://medium.com/p/5cb3f27a1676">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (4/4)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c94a82e2cb9a" width="1" height="1" alt=""><hr><p><a href="https://blog.infuseai.io/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-3-4-c94a82e2cb9a">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (3/4)</a> was originally published in <a href="https://blog.infuseai.io/">InfuseAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (2/4)]]></title>
            <link>https://blog.infuseai.io/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-2-4-1b6f5150fbd?source=rss-c8111db71de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b6f5150fbd</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[yolov4]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[Eric]]></dc:creator>
            <pubDate>Wed, 20 May 2020 06:06:36 GMT</pubDate>
            <atom:updated>2020-05-21T06:11:49.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDsAaeBksd_5jQxm7J8hNA.png" /></figure><h3>包裝成 JOB</h3><p>在<a href="https://medium.com/infuseai/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-14cef9f583a9">前篇的實驗</a>中，我們已可下載直播串流，再透過自定義的 darknet_video.py 產生結果並發送 Email ，且效果可如期地呈現該地擁擠程度。</p><p>接下來，我們來運用 PrimeHub 的 Job Submission 功能，將實驗步驟整理成一個小型的 pipeline，藉此產生出可重複執行的 Job。</p><p>回到 User Portal，選擇 <a href="https://docs.primehub.io/docs/next/job-submission-feature">Job Submission (Beta)</a>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RHEGeh81XptjsFIdGGe3xA.png" /></figure><p>進入 Job list 頁面，使用者可在此頁檢視所屬 Group 中所有 Job 的執行狀況。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6ifQdWukwYUg05bdkeHuA.png" /></figure><p>點選 Create Job。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tlWtHGvLPjOi_DGZqL_nDw.png" /></figure><p>在各個欄位輸入：</p><ul><li>Group：The A-Team</li><li>InstanceTypes：GPU 1</li><li>Images：TensorFlow 2.1 (Python 3.7) (Universal)</li><li>Job name：object-detection</li><li>Command：</li></ul><pre>pip install youtube-dl<br>cd a-team/darknet<br>timeout -s SIGINT 10s youtube-dl -o stream.mp4 <a href="https://www.youtube.com/watch?v=WGLUUH5HEVA">https://www.youtube.com/watch?v=WGLUUH5HEVA</a><br>python darknet_video.py<br>rm stream.mp4</pre><p>1. 先以 pip install youtube-dl 安裝 youtube-dl 套件。</p><p>2. 切換至 a-team/darknet 目錄，這裡的 a-team 是預先 mount 好的 <a href="https://docs.primehub.io/docs/2.1.0/concepts/designs/persistence-storage#group-volume-project-volume">Group Volume</a>， JupyterHub 和 Job Submission 都可存取其中的檔案。我們可在 Job Submission 中載入先前用 JupyterHub 訓練好的模型、亦可在 JupyterHub 中載入用 Job Submission 同步回來的資料。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*5GFpU8ZRXu9g3h9jh-xaXg.png" /></figure><p>3. 下載直播串流檔，使用 timeout -s SIGINT 10s 強制中斷其執行。</p><p>4. 執行自定義的 darknet_video.py。</p><p>5. 執行完畢後，移除下載的串流檔。</p><p>一切設定完畢後，就按下 Submit 吧！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3X5Dt79yXQtvYbljkh99g.png" /></figure><p>Job list 顯示目前 Job 正處於 Pending 狀態。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IhLwCeTo08gcwSxQrNcZyw.png" /></figure><p>點選 Job name — object-detection 進入其詳細頁面。目前狀態已進入 Preparing，而 Message 顯示運算資源不足，不過 Job Submission 同樣有支援 Auto-Scaling，僅需稍待片刻等 node auto scale-up 即可開始後續執行。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1NBo4roSkznyk8c0rCj8cQ.png" /></figure><p>Job 進入 Running 狀態。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*As7g2xqBTP0kKdQZg71r6Q.png" /></figure><p>切換至 Logs tab，目前已開始安裝並執行 youtube-dl。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ln22VbkSj52th0iQv_oU2A.png" /></figure><p>稍待片刻，我們的即時偵測完成囉！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hl1dQLnDkV9hUwVdd_GaNQ.png" /></figure><p>切換回 Information tab，Job 更新至 Succeeded 狀態。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HFQyaRMjk2WzZvZmWm4DrA.png" /></figure><p>而 Job list 亦呈現我們的 Job 順利完成。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vm9HaX7DncVifiq26G5AKQ.png" /></figure><p>檢查 Email，發現由 Job Submission 寄來的偵測結果。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0n5FGV3qZJeOhxGJL1OBQ.png" /></figure><p>公館夜市目前的擁擠程度為低。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2W16CCqigu3lbGVWxAZhw.png" /></figure><p>每張 frame 的數量圖。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ls9Y87C5tr0MXvBNZy8qyw.png" /></figure><p>檢查影片，該地實際擁擠狀況如預期，此影片為 2020/05/18 的下午 14:24 所擷取。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FonnOF7E9NgLW7gQHpFNPg.png" /></figure><h3>待續</h3><p>第三篇，我將介紹運用 PrimeHub 的 Image Builder 來建置專屬映像檔，縮短每次 Job 運行所需的環境建置時間（如：pip install）。</p><h4>搶先申請體驗⬇ ️</h4><p><a href="https://docs.google.com/forms/d/e/1FAIpQLSe_Z8JfIbYnvhOampGN_XXle4d3GVX04E8evnNI_Py3abth-A/viewform">申請表單</a></p><h4>PrimeHub 實戰系列文章</h4><p><a href="https://medium.com/infuseai/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-14cef9f583a9">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (1/4)</a></p><p><a href="https://medium.com/p/1b6f5150fbd">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (2/4)</a></p><p><a href="https://medium.com/p/c94a82e2cb9a">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (3/4)</a></p><p><a href="https://medium.com/p/5cb3f27a1676">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (4/4)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b6f5150fbd" width="1" height="1" alt=""><hr><p><a href="https://blog.infuseai.io/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-2-4-1b6f5150fbd">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (2/4)</a> was originally published in <a href="https://blog.infuseai.io/">InfuseAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度]]></title>
            <link>https://blog.infuseai.io/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-14cef9f583a9?source=rss-c8111db71de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/14cef9f583a9</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[yolov4]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[Eric]]></dc:creator>
            <pubDate>Tue, 19 May 2020 06:26:04 GMT</pubDate>
            <atom:updated>2020-05-21T06:10:38.478Z</atom:updated>
            <content:encoded><![CDATA[<h3>在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (1/4)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDsAaeBksd_5jQxm7J8hNA.png" /></figure><p>近來，由於 COVID-19 疫情的影響，許多知名景點都相繼限制人潮的數量，希望藉此達到人與人之間社交距離的規範。而網路上，我們亦可觀看各個景點的即時直播串流，快速了解該地目前的擁擠程度，實為防疫的一大助力。</p><p>數週前，<a href="https://github.com/AlexeyAB/darknet">YOLOv4</a> 的釋出，無疑是電腦視覺（Computer Vision，CV）領域的一大突破與社群樂見之事，第四版的 YOLO 相較於前版，不僅維持 real-time 的辨識速度，其 Average Precision 亦有顯著的提升。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*amE9ci4MRvUXk0x1V13TMA.png" /><figcaption><a href="https://arxiv.org/abs/2004.10934">https://arxiv.org/abs/2004.10934</a></figcaption></figure><p>今天，我想在 <a href="https://www.infuseai.io/primehub">PrimeHub</a> v2.6 上整合幾個方便易用的 API，試圖去產出一個自動定時的服務，其可偵測景點中的人流和車流，並判斷目前的擁擠程度，作為防疫生態系中的小幫手。以下將整個 end-to-end 流程概述分為四篇：</p><ol><li>在 JupyterHub 中運行實驗，以 youtube-dl 獲得直播串流，並以 YOLOv4 偵測，再將結果透過 Email 傳送。</li><li>在 Job Submission 中將實驗流程包裝成一個可重複運行的 Job，並以 GPU 運行確保即時性。</li><li>在 Image Builder 中建置專屬映像檔，降低每次 Job 運行所需的環境建置時間。</li><li>在 Job Scheduler 中將前述的 Job、專屬映像檔、並搭配運行的時間設定，實現定時的景點擁擠度偵測。</li></ol><h3>1. 運行實驗</h3><p>一開始，先登入 PrimeHub 吧！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3zaBD-9ZUmA1isE_UshhJA.png" /></figure><p>首先進入 <a href="https://docs.primehub.io/docs/next/quickstart/login-portal-user">User Portal</a>，此為系統平台的 overview 頁面，我們可於此自由切換至許多功能。</p><p>選擇 <a href="https://docs.primehub.io/docs/next/guide_manual/primehub-manual#launch-your-project-jupyterhub">JupyterHub</a>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RHEGeh81XptjsFIdGGe3xA.png" /></figure><p>我們會先進入 Spawner 頁面，可依據專案開設出所需的 JupyterLab 環境，並在裡面開發、測試我們的程式。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OuTJKE0iaUjTUv-Mc8AW3w.png" /></figure><p>由於 The A-Team 這個 <a href="https://docs.primehub.io/docs/guide_manual/admin-group#docsNav">Group</a> 允許使用較多的運算資源，因此先切換至該 Group。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*v7hehbJ_g0YmUJLGb5HD_g.png" /></figure><p>選擇 <a href="https://docs.primehub.io/docs/next/guide_manual/admin-instancetype#docsNav">Instance Type</a> 為 CPU 1，初期的實驗先選擇較低配額的硬體即可。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KTvLJMBInSDGBB661JRL5Q.png" /></figure><p>選擇 <a href="https://docs.primehub.io/docs/zh-tw/guide_manual/admin-image-cht#docsNav">Image</a> 為 TensorFlow 2.1 (Python 3.7) (Universal)，雖然本次實驗不會用到 TensorFlow 或 PyTorch 等機器學習框架，但由於每個 Image 都預先安裝了機器學習常使用到的函式庫（例如 NumPy、OpenCV等），因此選擇較新的 Image，有機會獲得較佳且較廣的 API 支援。完整的可用 Image 列表可<a href="https://docs.primehub.io/docs/next/guide_manual/images-list">參考此</a>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nAZRsSWtkEyBxdw6rkmuaw.png" /></figure><p>在 Spawner 頁面的右側，顯示了目前所屬 Group 中每位 User 運算資源的配置上限、以及整個 Group 運算資源的使用資訊。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*sEk5GXsFFC6LZPg1wLEKDw.png" /></figure><p>上述 Group 資源的配置，都可在 Admin Dashboard &gt; Groups 中設定。藉由每個 Group 對資源配置的獨立規範，可以讓每個部門，在運算資源上做到最好的平衡配置，相當適合團隊協作。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jwrrz09zDYmcB8WMsLWRw.png" /></figure><p>一切設定完成後，按下 Start Notebook 吧！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-EiHFE_1SHqRFG58QDpJQ.png" /></figure><p>環境建立中，在 Event log 裡可發現這個資訊：[Normal] pod triggered scale-up。</p><p>這是因為 Auto-Scaling 的功能，當我們需要運算資源時，才自動 scale-up pool 中的資源，而當我們使用完畢後，也會自動 scale-down pool 中的資源。如此一來，就不用擔心忘記開導致錯誤、亦或是忘記關導致花費過高之情形發生。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uzvZvzKHkzru0xyIhg2u-w.png" /></figure><p>稍待片刻，當環境建立完畢後，即可進入到 JupyterLab 囉！</p><p>（筆者偏好暗色主題，使用者可依據自身喜好自由切換）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Taaj3oHESmQ7v8iLo1UYyg.png" /></figure><p>為了下載直播的視訊串流，先安裝 <a href="https://github.com/ytdl-org/youtube-dl">youtube-dl</a>。</p><p>在 Launcher 中選擇 Terminal，並輸入 pip install youtube-dl。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*7p9hXHT3Il0MKx19aTYnJw.png" /></figure><p>試著執行以下指令以擷取由台北市政府提供的公館夜市直播串流，並輸出至同目錄的 stream.mp4。</p><pre>youtube-dl -o stream.mp4 <a href="https://www.youtube.com/watch?v=WGLUUH5HEVA">https://www.youtube.com/watch?v=WGLUUH5HEVA</a></pre><p>（由於擷取目標是無間斷的直播，因此須自行按下 Ctrl + C 將其強制中斷）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5WRcCbZERnvZ74e-o1XCA.png" /></figure><p>查看 stream.mp4，影片下載成功！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wBMtTETAo3QmXUcr0pPoDg.png" /></figure><p>有了影片作為輸入資料後，接下來使用 YOLOv4 進行偵測。</p><p>先切換至 a-team 目錄，執行以下指令以獲得最新 repo。</p><pre>git clone https://github.com/AlexeyAB/darknet.git</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hnjaMg9YMZcusv8YkOGWew.png" /></figure><p>接著，編譯 CPU 版本的 shared library，以供後續的 Python 程式使用。</p><p>開啟 Makefile 並將 AVX、 OPENMP 、以及 LIBSO 設為 1。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*gjWX44R4JlFAUojepi6vBQ.png" /></figure><p>執行 make ，待編譯完成後，我們即可在 darknet_video.py 中使用編譯好的 library 檔案。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hoajlB2fP7_Vji3HwW2MQQ.png" /></figure><p>而為了執行 YOLOv4，我們亦須下載 yolov4.weights 至 darknet 的目錄中。</p><p>yolov4.weights 的下載連結： <a href="https://drive.google.com/open?id=1cewMfusmPjYWbrnuJRuKhPMwRe_b9PaT">https://drive.google.com/open?id=1cewMfusmPjYWbrnuJRuKhPMwRe_b9PaT</a>。</p><p>為呈現完整的 end-to-end 即時偵測，我將<a href="https://github.com/AlexeyAB/darknet/blob/master/darknet_video.py">原版</a>的darknet_video.py 做了以下修改：</p><ol><li>修改主要的偵測程式區塊，讀入 stream.mp4，保存每張 frame 中 person、motorbike、以及 car 的偵測數量，並將 detection 結果輸出至 output.mp4</li><li>將每張 frame 的各類別數量輸出成圖片</li><li>根據保存類別的總量，簡單判斷其擁擠程度，並將前述的影片和圖片加入附件中，以 Email 寄送通知</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb67cad84261c72b062e505f7d4a74c9/href">https://medium.com/media/cb67cad84261c72b062e505f7d4a74c9/href</a></iframe><p>一切準備就緒後，執行 python darknet_video.py。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HHgH9zmzVgm9Cm4C11BbKQ.png" /></figure><p>執行完畢。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lla2MGca2YGoKexXHQXYKA.png" /></figure><p>查看發出的 Email，其中指出擁擠程度為低，並附上每張 frame 的數量圖以及 detection 結果的影片作為參考。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DiN-C6v84xVKZWj7hKvEOg.png" /></figure><p>每張 frame 的數量圖。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vEIP-61mRcO1fU2Ltj0acg.png" /></figure><p>detection 結果的影片。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDsAaeBksd_5jQxm7J8hNA.png" /></figure><p>觀察逐張影像和全部的結果後，目前的設計大致符合該地實際的擁擠程度。</p><p>而以 CPU 完成實驗後，接下來，試著以 GPU 執行。</p><p>選擇畫面左上方的 File → Hub Control Panel，點選 Stop My Server。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zFwUaWff2eV5CfobvztwqQ.png" /></figure><p>再點選 Start My Server 回到一開始的 Spawner 頁面！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTLX78gEXgUJld2qVz-iMA.png" /></figure><p>跟先前一樣，在 Group 選擇 The A-Team。</p><p>而 Instance Type 則選擇 GPU 1。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*McjtLlnvR5xtNKmkw2pAgQ.png" /></figure><p>Image 可選擇與先前相同的 TensorFlow 2.1 (Python 3.7) (Universal)。</p><p>目前 PrimeHub 供使用者設定 CPU、GPU、以及 Universal 的 Image：</p><ul><li>CPU：Instance Type 為 CPU 可使用</li><li>GPU：Instance Type 為 GPU 可使用</li><li>Universal：判斷使用者選擇的 Instance Type 為 CPU 或 GPU，自動載入對應的 Image</li></ul><p>因此，若事先建置好 Universal 的 Image，則日後選擇 Image 時只要專注於所需的機器學習框架和 Python 版本即可，相當方便！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sQ0OgzY9UhjmE41H-mzF6Q.png" /></figure><p>按下 Start Notebook，開出 GPU 的實驗環境。</p><p>這次跟先前步驟類似，首先要編譯 GPU 版本的 shared library，以供後續的 Python 程式使用。</p><p>開啟 Makefile 並將 GPU、 CUDNN、以及 CUDNN_HALF 設為 1，執行 make。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*mDkFOgytKUc235uQUnwSIw.png" /></figure><p>待編譯完畢後，執行 python darknet_video.py。</p><p>從 console log 的第 2 行可得知，本次實驗所使用的 GPU 為 Tesla K80。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gOXe0nhmBc1D9y_rrXS6jA.png" /></figure><p>後續的 logs 和 Email content 都與先前類似，不過經測量發現，使用 CPU 執行每秒可處理 0.04 張影像，而 GPU 則每秒可處理 7.21 張，速度方面 GPU 約為 CPU 的 180 倍。</p><h3>待續</h3><p>第二篇，我將介紹如何運用 PrimHub 的 Job Submission 功能，將實驗流程包裝成一個可重複運行的 Job，並以 GPU 運行確保即時性。</p><h3>搶先申請體驗⬇ ️</h3><p><a href="https://docs.google.com/forms/d/e/1FAIpQLSe_Z8JfIbYnvhOampGN_XXle4d3GVX04E8evnNI_Py3abth-A/viewform">申請表單</a></p><h3>PrimeHub 實戰系列文章</h3><p><a href="https://medium.com/infuseai/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-14cef9f583a9">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (1/4)</a></p><p><a href="https://medium.com/p/1b6f5150fbd">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (2/4)</a></p><p><a href="https://medium.com/p/c94a82e2cb9a">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (3/4)</a></p><p><a href="https://medium.com/p/5cb3f27a1676">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度 (4/4)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14cef9f583a9" width="1" height="1" alt=""><hr><p><a href="https://blog.infuseai.io/%E5%9C%A8-primehub-%E4%B8%AD%E4%BD%BF%E7%94%A8-yolov4-%E5%AE%9A%E6%99%82%E5%81%B5%E6%B8%AC%E6%99%AF%E9%BB%9E%E6%93%81%E6%93%A0%E5%BA%A6-14cef9f583a9">在 PrimeHub 中使用 YOLOv4 定時偵測景點擁擠度</a> was originally published in <a href="https://blog.infuseai.io/">InfuseAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[快速體驗 Databricks CE — 以新型冠狀病毒之資料視覺化為例]]></title>
            <link>https://blog.infuseai.io/%E5%BF%AB%E9%80%9F%E9%AB%94%E9%A9%97-databricks-ce-%E4%BB%A5%E6%96%B0%E5%9E%8B%E5%86%A0%E7%8B%80%E7%97%85%E6%AF%92%E4%B9%8B%E8%B3%87%E6%96%99%E8%A6%96%E8%A6%BA%E5%8C%96%E7%82%BA%E4%BE%8B-bd595b52386a?source=rss-c8111db71de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd595b52386a</guid>
            <category><![CDATA[notebook]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[資料視覺化]]></category>
            <category><![CDATA[機器學習]]></category>
            <dc:creator><![CDATA[Eric]]></dc:creator>
            <pubDate>Mon, 23 Mar 2020 00:53:05 GMT</pubDate>
            <atom:updated>2020-03-23T00:53:05.739Z</atom:updated>
            <content:encoded><![CDATA[<h3>快速體驗 Databricks CE — 以新型冠狀病毒之資料視覺化為例</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-AQTyUF7YJueFJWlCM_rRw.png" /></figure><p><a href="https://databricks.com/">Databricks</a> 成立於2013年，總部位於舊金山。今天我將試用 Databricks 的社群版本（Community Edition，CE），帶大家快速體驗 Databricks CE 的功能。而在範例要用到的 Dataset 是 <a href="https://www.kaggle.com/sudalairajkumar/novel-corona-virus-2019-dataset">Novel Corona Virus 2019 Dataset</a>、視覺化 notebook 則是 <a href="https://www.kaggle.com/holfyuen/coronavirus-2019-20-visualization">Coronavirus 2019–20 Visualization</a></p><p>首先，進入 Databricks 的首頁，點選畫面右上方的 TRY DATABRICKS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70gqduoiiQeWqh7T9pZ-QA.png" /></figure><p>輸入個人的基本資訊後，我們將試用右方的 COMMUNITY EDITION，按下 GET STARTED</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*8KLmuF1eJlsH26rs8OR2kg.png" /></figure><p>遵循相關步驟（驗證信箱、設定密碼等），我們即可進入 Databricks CE 的登入頁面</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NogoWXeyE_FpBOifguEX4Q.png" /></figure><p>輸入帳密資訊後，就進入主頁面囉！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*leiDxgOnv43h5ZyDuQ49jg.png" /></figure><p>在 Databricks 中，<a href="https://docs.databricks.com/clusters/index.html#clusters">Cluster</a> 是運算資源和環境設定的集成，可用來執行 notebook 或 job</p><blockquote><em>You can create an </em>all-purpose cluster<em> using the UI, CLI, or REST API. You can manually terminate and restart an all-purpose cluster. Multiple users can share such clusters to do collaborative interactive analysis.</em></blockquote><blockquote><em>The Databricks job scheduler creates </em>a job cluster<em> when you run a </em><a href="https://docs.databricks.com/jobs.html#jobs"><em>job</em></a><em> on a </em>new job cluster<em> and terminates the cluster when the job is complete. You </em>cannot<em> restart a job cluster.</em></blockquote><p>點選 side menu 中的 Clusters、再點選 + Create Cluster</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dzPM9gMqzw4G0iejgV0o_Q.png" /></figure><p>建立新 cluster 的頁面</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o6_kEdnpuwgvodCWit_hSA.png" /></figure><ul><li>在 Cluster Name 輸入 test-cluster</li><li>在 Databricks Runtime Version 選擇 6.4 ML 的 CPU 版本，Databricks 為每個 Runtime image 提供了詳細的<a href="https://docs.databricks.com/release-notes/runtime/6.4ml.html">資訊</a>，讓使用者能夠檢視其中安裝的 library 版本</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*M2v_9EsOyb6hABsxbmoxww.png" /></figure><ul><li>Availability Zone 保留預設值 us-west-2c</li><li>而在 Spark tab，我們可另外設定 Spark Config 以及 Environment Variables，此處我們先保留空白，並按下 Create Cluster</li></ul><p>稍待一會兒後，我們的 cluster 已建立完成！（在 Databricks CE ，閒置達到兩個小時的 cluster 會自動被 terminate 掉）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IHlrSFLoszOJuCexwicwug.png" /></figure><p>點選剛建立好的 test-cluster，有數個 logs 和 metrics tab 可供使用者檢視</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l4RIPfbPIp7H0PcfXohvew.png" /></figure><p>雖然我們選擇的 6.4 ML runtime image 已包含許多機器學習相關的 library，如果大家想額外安裝新的 library，則可點選 Libraries tab → Install New</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t5AeoTaJQoTcDTXb6q5Xrg.png" /></figure><p>設定完運算環境後，來將下載的 <a href="https://www.kaggle.com/sudalairajkumar/novel-corona-virus-2019-dataset">dataset</a> 上傳至 Databricks 吧！</p><p>點選 side menu 中的 Data，再點選 Add Data。輸入 covid-19 作為上傳後所屬的目錄名稱，並選擇 covid_19_data.csv，檔案即可上傳至 /dbfs/File/Store/tables/covid-19/covid_19_data.csv</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*xAUa_63GZuiwmy7m-6Hj5A.png" /></figure><p>準備完資料後，將下載的<a href="https://www.kaggle.com/holfyuen/coronavirus-2019-20-visualization">視覺化 notebook</a> 上傳至 Databricks</p><p>點選 side menu 中的 Workspace，再點選使用者名稱右側的箭頭，選擇 Import</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tDlYhPkgyuAJnbARCHlz3Q.png" /></figure><p>選擇要 import 的 notebook 檔案，並按下 Import</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6XiMD6HbeLpPTDBHqAIjg.png" /></figure><p>Import 完即可進入 notebook 的編輯頁面</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pkC6oogojBjCB2mbHf5npQ.png" /></figure><p>為了執行此 notebook，我們須先至畫面左上方，將 notebook attach 至先前建立的 test-cluster</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*izjHMERJ10GVP8ph9XaCaw.png" /></figure><p>接著，在第二個 cell 中做以下更改</p><ul><li>line 2: 加入 %matplotlib inline[<a href="https://docs.databricks.com/notebooks/visualizations/matplotlib-and-ggplot.html">Ref</a>]</li><li>line 11: 修改路徑為 /dbfs/FileStore/tables/covid-19/covid_19_data.csv</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NgJ-Pyb9FDFPa3JYur02rg.png" /></figure><p>點選畫面上方功能列的 Run All，執行結果與平時使用 Jupyter Notebook 類似，可查看每個 cell 產生的圖表。而 Databricks CE 的每個 cell 中亦紀錄了使用者、開始執行時間、執行所需時間、以及 attached cluster</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1-UTCIE5IRGJ9BkYCKkOIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02ecCbpU1ALz8xCh7dlEeQ.png" /></figure><p>我們再來看看功能列的幾個功能：Publish、Comments、Runs、Revision history</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*z3gi-WZZsAdEjnCq5Fdcbw.png" /></figure><h4>Publish</h4><p>將 notebook 發佈成公開的連結，即使將 attached cluster 刪除，該連結仍然有六個月的時效，這是我們發佈所產生的<a href="https://databricks-prod-cloudfront.cloud.databricks.com/public/4027ec902e239c93eaaa8714f173bcfc/7370063036011714/1743216192197879/4443843463627985/latest.html">連結</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*Yzvu-QS71DK3-svwBVDdIw.png" /></figure><h4>Comments</h4><p>使用者可在任意的程式片段中留下 comments</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B6X4LUCtPlzDpxE0CqBKLA.png" /></figure><h4>Runs</h4><p>此處的 Runs 可保存 <a href="https://www.mlflow.org/docs/latest/tracking.html">MLflow Tracking</a> 的紀錄</p><h4>Revision history</h4><p>檢視 notebook 歷史版本的修改紀錄，並可回到指定的歷史版本</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxLjNsyfKo4MTIYrdLVhag.png" /></figure><p>由於我們使用免費的社群版本，因此功能仍有限制，例如：</p><ul><li>最多只能建立一個 cluster</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ja9ZzY1X2DhooTVmfQQ8Ww.png" /></figure><ul><li>無法建立 <a href="https://docs.databricks.com/jobs.html">Jobs</a>、工作排程</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4oTfoYXufXtnJkXp_vOKjg.png" /></figure><p>Databricks CE 提供簡潔且實用的環境，讓使用者可在其平台上輕鬆進行開發。即使部分功能未完全於 CE 中呈現，還是很推薦大家可以試用看看！</p><p>此外，近來國際確診數目持續攀升，由衷希望疫情能儘早平息、網路上有關新型冠狀病毒的 dataset 也能儘早停止更新。</p><h4>References</h4><ul><li>Novel Corona Virus 2019 Dataset [<a href="https://www.kaggle.com/sudalairajkumar/novel-corona-virus-2019-dataset">Ref</a>]</li><li>Coronavirus 2019–20 Visualization [<a href="https://www.kaggle.com/holfyuen/coronavirus-2019-20-visualization">Ref</a>]</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd595b52386a" width="1" height="1" alt=""><hr><p><a href="https://blog.infuseai.io/%E5%BF%AB%E9%80%9F%E9%AB%94%E9%A9%97-databricks-ce-%E4%BB%A5%E6%96%B0%E5%9E%8B%E5%86%A0%E7%8B%80%E7%97%85%E6%AF%92%E4%B9%8B%E8%B3%87%E6%96%99%E8%A6%96%E8%A6%BA%E5%8C%96%E7%82%BA%E4%BE%8B-bd595b52386a">快速體驗 Databricks CE — 以新型冠狀病毒之資料視覺化為例</a> was originally published in <a href="https://blog.infuseai.io/">InfuseAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>