<?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 Jason Li on Medium]]></title>
        <description><![CDATA[Stories by Jason Li on Medium]]></description>
        <link>https://medium.com/@jason.li_24651?source=rss-508c5ca9c59b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*p8Z6Llf67vJbZJFk</url>
            <title>Stories by Jason Li on Medium</title>
            <link>https://medium.com/@jason.li_24651?source=rss-508c5ca9c59b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 15:46:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jason.li_24651/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[Deploy ML models on Vertex AI using custom containers]]></title>
            <link>https://medium.com/ml6team/deploy-ml-models-on-vertex-ai-using-custom-containers-c00f57efdc3c?source=rss-508c5ca9c59b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c00f57efdc3c</guid>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[gcp]]></category>
            <dc:creator><![CDATA[Jason Li]]></dc:creator>
            <pubDate>Wed, 17 Nov 2021 15:53:53 GMT</pubDate>
            <atom:updated>2021-11-17T15:53:53.074Z</atom:updated>
            <content:encoded><![CDATA[<p>Google Cloud Platform (GCP) <a href="https://blog.ml6.eu/why-google-just-released-vertex-ai-and-what-it-means-for-you-ee1fc8231ef3">Vertex AI</a> enables us to serve machine learning models with ease. Typically, you can deploy a TensorFlow SavedModel on an endpoint, then make prediction requests to the endpoint. However, sometimes you might want to deploy ML models that are exported by other frameworks such as PyTorch, Darknet, Sklearn, xgboost, etc., or add more complex workflows around the served model such as pre-processing and post-processing. In these cases, a single SavedModel may not be sufficient, some custom codes are needed in the backend. Fortunately, Vertex AI supports custom containers to tackle these situations. In this blogpost, we are going to show you how we create a custom container and deploy it on Vertex AI.</p><h3>Model and Endpoint</h3><p>When you deploy a model on Vertex AI, there are two main concepts you need to know: Model and Endpoint. A Model is a static collection of all the components that are relevant to model serving, e.g. run environment, ML framework, saved model and backend microservice. You can consider it as a docker image that contains everything you need for running the model. On the other hand, an Endpoint is the compute resources where your model is actually running on, and you can make prediction requests to it. Depending on the setting, it could be one or more compute nodes, with or without GPU. You have to deploy a Model to an Endpoint in order to accept the prediction requests.</p><p>By default, Vertex AI provides many pre-built containers in which your model can run. For example, if you want to deploy an end-to-end <a href="https://www.tensorflow.org/guide/saved_model">TensorFlow SavedModel</a>, you can create a Vertex AI Model by choosing one of the default containers and specify the path of your SavedModel. Then, you can deploy this Model to an Endpoint. After these two steps your model is already up and running, and you can make prediction requests in your preferred way, e.g. Python, Node.js, curl, etc. If you’re interested in this approach, you may check <a href="https://blog.ml6.eu/how-to-deploy-a-yolov4-darknet-model-to-vertex-ai-a8df1b783341">this blogpost</a> in which we illustrate how we serve an end-to-end Darknet trained Yolov4 model on Vertex AI using pre-built containers.</p><p>Pre-built containers are convenient but they don’t offer you a chance to customize your workflow beyond the SavedModel. For more complex scenarios, custom containers are the solution.</p><h3>Custom container</h3><p>A custom container is basically a custom docker container that serves your model. You can build this container in your preferred way but it has to comply with several rules required by Vertex AI. There are mainly three requirements: (1) HTTP server (2) health check and (3) request/response format.</p><h4>HTTP server</h4><p>Your custom container must run a HTTP server that listens for requests on 0.0.0.0. You can choose any port and specify it as an environment variable when you create a Vertex AI Model. The HTTP server can be implemented in any programming language and network framework. In this tutorial, we create the HTTP server using the Flask &amp; Connexion web framework in Python. Here is how your <em>main.py</em> should look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a23097169cc66a2477e8b0b02b63b08/href">https://medium.com/media/2a23097169cc66a2477e8b0b02b63b08/href</a></iframe><p>In the following sections we will explain how to add necessary elements to make it an ad-hoc Flask server for handling Vertex AI predictions.</p><h4>Health check</h4><p>As described by Google: Vertex AI intermittently performs health checks on your HTTP server while it is running to ensure that it is ready to handle prediction requests. The service uses a health probe to send HTTP GET requests to a configurable health check path on your server. The HTTP server should respond with status code 200 OK when it is ready to handle prediction requests. Otherwise it should respond with any other status code.</p><p>In our case, we add a new path “/health” in <em>swagger.yaml</em> for the health check GET request. We can simply respond an empty message with status code 200 OK, so it’s not necessary to define a schema for request and response:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bec15b7a188dcc7b1104ce289c68b3b1/href">https://medium.com/media/bec15b7a188dcc7b1104ce289c68b3b1/href</a></iframe><p>We can specify the path “/health” when we create the Vertex AI Model in a later step.</p><h4>Request format</h4><p>The HTTP server accepts prediction requests in JSON format. Every request must contain an <em>instances</em> field, which is an array of one or more JSON values of any type. Each value represents an instance that you are providing a prediction for. Optionally, you can also add a <em>parameters</em> field in the request to provide additional information.</p><p>Let’s take an example: assume that you want to send 2 images and their names to the deployed model. These images come from a small dataset called “test_images”. You also want to send the dataset name to the backend so that it can keep a track. In this case, you should put 2 base64-encoded images and their names under the <em>instances</em> field as an array. Since each prediction request must be 1.5 MB or smaller and it has to be written in JSON, we use base64 encoding to encode the image array. As for the dataset name, you should put it under the <em>parameters</em> field. Eventually your request JSON would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a8f66a71bcb86ebfeff6d0613c2371c/href">https://medium.com/media/2a8f66a71bcb86ebfeff6d0613c2371c/href</a></iframe><p>In the backend Flask server, we add a new path “/inference” in swagger.yaml for the inference POST request. It accepts request type “application/json” and the request parameters correspond to the JSON format that we defined above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9444b55d00b912b97fdf65c8cb498973/href">https://medium.com/media/9444b55d00b912b97fdf65c8cb498973/href</a></iframe><h4>Response format</h4><p>The response from the HTTP server is a JSON dictionary with one field <em>predictions</em>. It is an array of JSON values representing the predictions that your container has generated for the <em>instances</em> in the corresponding request. Just like with the prediction requests, each prediction response must also be 1.5 MB or smaller.</p><p>Assume that our backend Flask server is serving an object detection model. This would mean that the response would be an array where each item represents one or more detected objects in one image. Each detected object consists of a score, class and bounding box.</p><p>For example, the response for the 2 images prediction request could be like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3554c6527be6f249aa49a0eaaeef82cd/href">https://medium.com/media/3554c6527be6f249aa49a0eaaeef82cd/href</a></iframe><p>In <em>swagger.yaml</em>, we define a response schema to produce responses that comply with the above format:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0219bd7dd5fbabeec07a94f7858c3fd2/href">https://medium.com/media/0219bd7dd5fbabeec07a94f7858c3fd2/href</a></iframe><h3>Build image</h3><p>In the above sections we have explained how to implement a HTTP server using the Flask web framework. We also implemented a health check path and an inference path that processes the requests and responses using the correct format required by Vertex AI. Notice that we only illustrated the interface definitions whilst we skipped the code of model inference itself. In order to serve a model, you still need to implement the main workflows yourself such as pre-processing, model inference and post-processing, then incorporate them with the Flask server. We will not dive into that part because the focus of this tutorial is deployment on Vertex AI.</p><p>Once you complete the Flask server, you need to wrap everything into a container image, which means you have to provide a <em>Dockerfile</em> first. You can do anything you like for this container image as long as it launches an HTTP server that supports health checks and inference. Here we give an example <em>Dockerfile</em> that enables GPU:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b55315d677f82c9a4006dfda4e14b2a/href">https://medium.com/media/0b55315d677f82c9a4006dfda4e14b2a/href</a></iframe><p>Since we will deploy the model on Vertex AI, we can simply build the container image using <em>gcloud builds</em> command, which will build on cloud and automatically push the image to the container registry on GCP:</p><pre>gcloud builds submit — tag eu.gcr.io/your-gcp-project-name/object_detection_inference — timeout “30m”</pre><p>Sometimes the building process can take quite long, so we explicitly set a high timeout to ensure that the building process won’t be accidentally terminated.</p><h3>Deployment on Vertex AI</h3><p>Now that we’ve created a backend microservice that serves your model, by compiling it to a container image and storing it in the container registry, it’s time to deploy it on Vertex AI. Normally the deployment can be done via the Vertex AI dashboard or Python API. In this tutorial we will create a Python script to deploy the custom container. Because currently the Vertex AI dashboard is not working stably yet, some operations can only be performed by Python API. In order to use Vertex AI’s Python API, you need to install the <a href="https://pypi.org/project/google-cloud-aiplatform"><em>google-cloud-aiplatform</em></a> package.</p><p>First of all, we import necessary modules, define some common names and initialize the Vertex AI module:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb4c2c73828fb8ae6911167c270afd43/href">https://medium.com/media/eb4c2c73828fb8ae6911167c270afd43/href</a></iframe><p>Then we create a new endpoint if it doesn’t exist yet. Otherwise, we can get the endpoint with the defined name. We said before that an endpoint is the compute resource where the model will be running. However, when we create a new endpoint here, it will not allocate the resources right away. An endpoint is effective only when you deploy a model on it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50cfe93405126c66443bad6fd5dd2512/href">https://medium.com/media/50cfe93405126c66443bad6fd5dd2512/href</a></iframe><p>The model is similar to the endpoint, we can either get an existing model or upload a new model. When we upload a model, we need to specify the container image URI, health check path, inference path and container port. The container image URI is the tag you created when you run <em>gcloud builds</em>. The health check and inference path is defined in <em>swagger.yaml</em>. The container port can be set to any port, just make sure that the Flask server listens on the corresponding port when you initialize it in main.py.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43c3c7f011f4bd10b2ba15b95731331b/href">https://medium.com/media/43c3c7f011f4bd10b2ba15b95731331b/href</a></iframe><p>Finally, we have created the endpoint and uploaded the model. Now we can deploy the model to the endpoint. Here we must specify the compute resources that we’ll need, e.g. machine type, number of replicas, GPU type, number of GPUs, etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dbd1335ef565e279b623ac9ccd1ecfa/href">https://medium.com/media/1dbd1335ef565e279b623ac9ccd1ecfa/href</a></iframe><p>Usually the deployment process can take 20–40 mins. You can check the status and logs in the Vertex AI dashboard. If it succeeds, you should see the green ticks on both the Models and Endpoints pages, which means your custom container is up and running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/0*e72bZXPRJzTprzo5" /><figcaption>Model created</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*74OXn_JP0DkAzR9Q" /><figcaption>Endpoint created</figcaption></figure><h3>Delete resources</h3><p>When the customer container is up and running, it starts to cost money. If you no longer need it, you can delete the endpoint and model using Python API. To do so, first use the code above to get a reference to the existing endpoint or model, then simply call the <em>delete</em> method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b167a9077b84993dad5dcf41bb9fe622/href">https://medium.com/media/b167a9077b84993dad5dcf41bb9fe622/href</a></iframe><h3>Making predictions</h3><p>After deploying the model to an endpoint, you can make predictions by calling the endpoint using Python API. In order to make the call, you need not only the image file and extra parameters, but also the GCP project name, endpoint region and endpoint ID. You can find the endpoint ID in the Vertex AI dashboard.</p><p>Here an example of sending an image to Vertex AI to get predictions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a8cf623c4f7d5ef490e39e51f302d5a/href">https://medium.com/media/3a8cf623c4f7d5ef490e39e51f302d5a/href</a></iframe><h3><strong>Conclusion</strong></h3><p>The biggest advantage of using a custom container is that you can add extra workflows outside of the ML model itself, or deploy something completely different with a TensorFlow model. Compared to the optimized pre-built containers, custom containers are more difficult to implement and more complex to set up, but it does provide more flexibility. Besides this, the benefit of deploying models on Vertex AI is that the deployed models will become managed services that support auto-scaling. Everything except for the core logics of model inference is taken care of by Vertex AI. At the moment we write this blogpost, Vertex AI still has some issues and there aren’t many documents available explaining every step of the deployment. Our main goal is to clear the barriers on the way of deploying custom containers on Vertex AI and provide you with a working solution. Hope everything is clear and enjoy the customizable workflows!</p><h3><strong>Reference</strong></h3><ul><li><a href="https://cloud.google.com/vertex-ai/docs/general/import-model">Import models to Vertex AI | Google Cloud</a></li><li><a href="https://cloud.google.com/vertex-ai/docs/predictions/getting-predictions">Request predictions | Vertex AI | Google Cloud</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c00f57efdc3c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ml6team/deploy-ml-models-on-vertex-ai-using-custom-containers-c00f57efdc3c">Deploy ML models on Vertex AI using custom containers</a> was originally published in <a href="https://medium.com/ml6team">ML6team</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retraining EfficientDet for High-Accuracy Object Detection]]></title>
            <link>https://medium.com/ml6team/retraining-efficientdet-for-high-accuracy-object-detection-961e906cae8?source=rss-508c5ca9c59b------2</link>
            <guid isPermaLink="false">https://medium.com/p/961e906cae8</guid>
            <category><![CDATA[efficientdet]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[license-plate-detection]]></category>
            <dc:creator><![CDATA[Jason Li]]></dc:creator>
            <pubDate>Tue, 03 Nov 2020 15:42:17 GMT</pubDate>
            <atom:updated>2020-11-03T15:42:17.654Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A practical guide to fine-tuning EfficientDet for transfer learning on a custom dataset</blockquote><p>Many computer vision projects today revolve around identifying specific objects in pictures or videos and then performing certain operations on them such as classification or segmentation. Typically, a labelled dataset is created by domain experts and then machine learning engineers train or rather retrain an object detection model (applying transfer learning) on this dataset to be able to mimic the experts’ knowledge. When your use case primarily requires high speed such as in the case of video processing, today one of the YOLO variants are probably the go-to model, but when your use case requires high accuracy with manageable size and speed, EfficientDet should probably your first choice.</p><p>This blog post explains and demonstrates how to optimize this process when aiming for high accuracy using Google’s lightweight EfficientDet object detection model. (Want to jump directly to code?➡ <a href="https://colab.research.google.com/drive/1iOydvFQVE-syG-ixEyam04X3E40Lx7NA?usp=sharing">Colab Notebook</a>)</p><h4>EfficientDet: A lightweight, high-accuracy object detection model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*IKBg9FxkSCJcfhwy" /><figcaption>EfficientDet’s performance.</figcaption></figure><p>EfficientDet is an object detection model that was published by the Google Brain team in March 2020. It achieves state-of-the-art 53.7% COCO average precision (AP) with fewer parameters and FLOPs than previous detectors such as Mask R-CNN. It exists in 8 base variations, D0 to D7, with increasing size and accuracy. Moreover, an extra large version D7x was released recently, which achieves 55.1% AP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/0*XfvZAn4qsSInhbos" /><figcaption>Variant EfficientDet models.</figcaption></figure><p>Choosing an EfficientDet model involves a trade-off between accuracy and performance, which depends on the use case. For example, if the model needs to be deployed on an edge device, then a small variant should be used. Similarly, if the goal is to use the model for real-time video analysis, a smaller variant would be preferred because it provides higher frames per second (FPS). On the other hand, larger variants are suitable for those tasks that tolerate longer inference time, e.g. one-time analysis of static images, as they show better results in terms of accuracy.</p><p>In this blog post, we provide a practical guide to fine-tuning EfficientDet on a custom dataset. As an example use case we will use license plate detection which can be used both in surveillance and anonymization applications. Thereby we will focus on the following:</p><ul><li>Convert the custom dataset into the required TFRecord format</li><li>Explain the usage and effect of the most important hyperparameters and give some tips</li><li>Describe how to fine-tune EfficientDet using GPU</li><li>Benchmark on the test set</li></ul><h4>Getting the model</h4><p>The original implementation of EfficientDet is open-sourced in the <a href="https://github.com/google/automl">Google AutoML repository</a> on GitHub. The repository is still actively being maintained, thus the implementation details in the <a href="https://colab.research.google.com/drive/1iOydvFQVE-syG-ixEyam04X3E40Lx7NA?usp=sharing">Colab notebook</a> may change somewhat as time goes by.</p><p>Notice that EfficientDet is also integrated in the <a href="https://github.com/tensorflow/models/tree/master/research/object_detection">TensorFlow Object Detection API v2</a>. In this tutorial, however, we will focus on the original implementation as it is a pure implementation containing the latest features.</p><h4>Choosing and preparing the dataset</h4><p>The Chinese City Parking Dataset (CCPD) is a comprehensive license plate dataset containing over 250k unique car images with carefully annotated bounding boxes around the license plates. The images in the dataset represent real-world conditions featuring distortions such as rotation, snow or fog, uneven illumination and vagueness. This makes inference on this dataset a challenging proposition requiring a powerful, high-precision object detection model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JGj4FDh1j3qW7FP5" /><figcaption>Example images and labels in CCPD2019 dataset.</figcaption></figure><p>Before training the model, we first need to preprocess the dataset. CCPD is already split into a training set, validation set and test set which are each described by a text file. The labels are included in the filenames of the images, from which the bounding boxes’ coordinates and other information can be extracted by string resolving, e.g. using regular expressions. Finally, we need to convert the raw image files and labels into the TFRecord format, which is required by EfficientDet.</p><h4>Hyperparameter tuning</h4><p>EfficientDet provides a set of hyperparameters which allow for the alteration of both the network architecture and the training strategy. These should be fine-tuned in accordance with the training data, so that the model can fit the data better which usually results in more efficient training and better results.</p><p>The default hyperparameter settings can be found in the configuration file at <em>hparams_config.py</em>. They are wrapped by the default_detection_configs function. However, while these editable hyperparameters provide a lot of flexibility, they are not always documented in detail. Sometimes the usages or scopes of some hyperparameters can be confusing. Hence we give a brief description of some of the most important hyperparameters and how to fine-tune them effectively.</p><p><strong>image_size:</strong></p><p>Can be set as an integer, e.g. <em>640</em>, which stands for 640x640. A rectangular resolution can be specified by a string such as <em>“640x320”</em>. However, in our experience, using rectangular resolution results in a lower mAP accuracy than a square resolution with the same settings.</p><p>In order to ensure the correct sizes of the backbone’s convolutional layers, it is advised to set both the width and height of the image to be a multiple of 16.</p><p><strong>input_rand_hflip:</strong></p><p>EfficientDet supports a number image preprocessing operations. By default the input image has 50% of chance to be flipped horizontally, which acts as a basic image augmentation technique.</p><p><strong>jitter_min/max:</strong></p><p>These two hyperparameters define the range of the random scale factor for the scaling preprocessing, which is another basic image augmentation technique. By default they are set to <em>0.1</em> and <em>2.0</em> respectively, meaning each input image will be scaled by a random factor within range [0.1, 2.0]. If the scaled image is larger than the required input size, a random region with the required input size will be cropped. If the scaled image is smaller than the required input size, the image will be padded with zeros to match the required input size.</p><p><strong>use_augmix:</strong></p><p>EfficientDet supports many data augmentation strategies, as described in <a href="https://arxiv.org/abs/1906.11172">this paper</a>. This hyperparameter can be set to a string <em>“v0”</em>, <em>“v1”</em>, <em>“v2”</em> or <em>“v3”</em> to use different compound data augmentations. More details are explained in <em>aug/autoaugment.py</em>.</p><p><strong>num_classes:</strong></p><p>Number of classes. It should be set to the number of object types in your dataset. In our case we only have only one type of object that needs to be detected: license plates. We should then set this hyperparameter value to <em>1</em>. Notice that in the current implementation the background class is implicitly reserved. This setting may change in the future so you should pay attention to this as it directly affects the model outputs.</p><p><strong>label_map:</strong></p><p>The mapping between the class as an integer and its label in string format. In our case we can set it to a one item dictionary <em>“{1: license_plate}”</em> in the YAML configuration file. The label “license_plate” will then be plotted when visualizing the detection results.</p><p><strong>aspect_ratios:</strong></p><p>EfficientDet is an anchor-based detector so the anchor setting is vital to the model training. This hyperparameter defines a list of float numbers, whereby each float represents an aspect ratio (w/h) of the anchor box. By default there are 3 aspect ratios <em>1.0</em>, <em>2.0</em> and <em>0.5</em>. However, when we retrain EfficientDet on our custom dataset, we should modify them according to our data. The aspect ratios should reveal the average shape of our objects in the dataset, so that the model can easily fit the anchor box to the ground truth bounding box. If the anchors’ aspect ratios are deviating too much from the actual objects’ aspect ratios, it’s more difficult to train the detector because it relies on the regression subnet to fix the coordinates of the resulting bounding boxes.</p><p>The K-means clustering algorithm is generally used to find the average shape of objects in the custom dataset. For more details, you may refer to <a href="https://github.com/joydeepmedhi/Anchor-Boxes-with-KMeans">this repository</a>.</p><p><strong>num_scales:</strong></p><p>Each anchor box can also have multiple scales. This hyperparameter is set to <em>3</em> by default which can often be left unchanged. You may change it if you want to have anchor boxes with more fine-grained scales, e.g. when you have large input images.</p><p>Assuming there are 3 aspect ratios and 3 scales, then there are in total 3x3=9 anchor boxes at each anchor position in the image.</p><p><strong>anchor_scale:</strong></p><p>This is a general scale factor for all the anchor boxes. It’s set to <em>4.0</em> by default which can normally be left unchanged. You may decrease/increase it when you’re facing mainly small/large objects in your dataset, so that all the anchor boxes are scaled down/up, which makes it easier to fit the actual objects.</p><p><strong>is_training_bn:</strong></p><p>EfficientDet contains batch normalization layers whereby the mean and variance of the batch normalization layer is different for training and inference. In order to use the correct mean and variance, this hyperparameter will be automatically set to <em>True</em> during training, and to <em>False</em> during inference. There’s no need to create two configuration files to specify this hyperparameter for training and inference.</p><p><strong>heads:</strong></p><p>It can be set to <em>[‘object_detection’]</em> to create an object detection model, or set to <em>[‘segmentation’]</em> to create an object segmentation model. Notice that the original EfficientDet paper only discusses the object detection model. The image segmentation functionality was added recently.</p><p><strong>strategy:</strong></p><p>Set to None to use the default TensorFlow training strategy, namely CPU or GPU. It can also be set to <em>“gpus”</em> or <em>“tpu”</em> to use additional computational resources.</p><p><strong>mixed_precision:</strong></p><p>Set to False to always use FP32 precision. Set to True to use a mix of FP16 and FP32. Using FP16 will lose some precision but speed up the model training. It can also save a significant amount of GPU memory so that a larger model can be fitted. However, based on our experience with NVIDIA Tesla P100 and NVIDIA RTX 2080Ti GPUs, using the mixed precision results in very slow training. The reason could be incompatibility of some GPUs with EfficientDet’s implementation.</p><p><strong>var_freeze_expr:</strong></p><p>By default, the training of EfficientDet will apply to all layers. However, sometimes freezing some layers can provide better results. This hyperparameter is a regular expression that indicates which layers in the network we would like to freeze. We can use the following script to print out all layer names of a checkpoint file:</p><blockquote>from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file</blockquote><blockquote>print_tensors_in_checkpoint_file(file_name=CKPT_PATH, tensor_name=’’, all_tensors=False)</blockquote><p>Based on the printed layer names. We can set this hyperparameter to <em>“(efficientnet)”</em> to freeze the backbone, or set it to <em>“(efficientnet|fpn_cells|resample_p6)”</em> so that only class_net and box_net will be fine-tuned.</p><p><strong>Modify the hyperparameters</strong></p><p>If you want to modify these hyperparameters, you can create a YAML file and pass its path to the training script. Then your custom setting will override the default settings in <em>hparams_config.py</em>.</p><p>In our use case, we create the following YAML file to specify the image resolution, class information and basic data augmentation parameters:</p><blockquote>image_size: 1024x1024</blockquote><blockquote>num_classes: 1</blockquote><blockquote>label_map: {1: license_plate}</blockquote><blockquote>input_rand_hflip: true</blockquote><blockquote>jitter_min: 0.8</blockquote><blockquote>jitter_max: 1.2</blockquote><h4>Pre-trained weights</h4><p>Since we want to fine-tune EfficientDet, we first need to download the weights that resulted from pretraining on the COCO dataset. The pre-trained weights of all variant models are provided at <a href="https://github.com/google/automl/tree/master/efficientdet">Google AutoML repository</a>. You can download the appropriate model and decompress it to <em>automl/efficientdet</em> directory (where you can find <em>main.py</em>).</p><p>In our case, we download a lightweight variant EfficientDet D1 which has 6.6M parameters and its pretrained weights which have a size of 46.6MB. This should be sufficient to achieve a relatively high mAP accuracy on the CCPD dataset.</p><h4>Training</h4><p>When the TFRecords, hyperparameter configurations and pre-trained models are all ready, we can start training by running main.py. There are several additional arguments that we can pass to main.py. In our case, we fine-tune the pre-trained EfficientDet D1 for 1 epoch with 5000 steps. We set the batch size to be 2 so that 11GB GPU memory is sufficient to train it. Since the total number of steps is 5000 and batch size is 2, in total 10,000 examples from the training set are used.</p><p>During training, the model checkpoints will be automatically saved in a temporary directory. In fact, when we run the training script, it will first try to restart training from the latest checkpoint in this temporary directory. If none are found, it will restart training from the original pre-trained checkpoint that we put in the <em>efficientdet</em> folder. Therefore, make sure you delete this temporary folder if you intend to retrain from the original pre-trained model. Especially when you change some hyperparameters and wish to restart the fine-tuning process again, you should delete this temporary directory to avoid strange errors.</p><p>The training should be finished after about one hour using one GPU and should result in around 74% mAP, 100% mAP50 and 94% mAP75 on the validation set which is far from bad in view of the small training set and short training time. The formal evaluation result is as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*EWYEN_7ZaV9U_Y0MdZsZAQ.png" /></figure><h4>Exporting and inference</h4><p>The retrained model is saved as a checkpoint file in which the model weights are stored but not the model architecture. In order to do inference using our fine-tuned model, we first need to export the model into the saved model (.pb format). Notice that the pre-processing and post-processing operations will also be integrated into the exported model, so there are some parameters that you should specify during the exporting, e.g. the minimum score threshold that is used to filter out low confidence bounding boxes.</p><p>Here are some result images when we run inference on the “ccpd_fn” subset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCSj00rRoI7Aa_85xg8Law.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hAT8ufj6FuGRDIDBaQmdcw.png" /></figure><h3>Conclusion</h3><p>EfficientDet is a powerful yet lightweight object detector that is relatively easy to retrain on custom datasets. Its various models can cover most use cases in terms of either speed or accuracy. Although EfficientDet is in general slower than YOLOv4, it can assure you higher accuracy and it’s rather easy to get started with. The Google AutoML implementation of EfficientDet supports a variety of hyperparameter settings that allow you to easily fine-tune the model. Hence, whenever you are facing an object detection problem, you could take EfficientDet into consideration. Hope this tutorial has offered enough help for you to get EfficientDet working on your own dataset. (Our code can be found in this <a href="https://colab.research.google.com/drive/1iOydvFQVE-syG-ixEyam04X3E40Lx7NA?usp=sharing">Colab Notebook</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=961e906cae8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ml6team/retraining-efficientdet-for-high-accuracy-object-detection-961e906cae8">Retraining EfficientDet for High-Accuracy Object Detection</a> was originally published in <a href="https://medium.com/ml6team">ML6team</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>