<?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 Asmaa Mirkhan on Medium]]></title>
        <description><![CDATA[Stories by Asmaa Mirkhan on Medium]]></description>
        <link>https://medium.com/@asmaamirkhan.am?source=rss-dc118fbeb428------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mQTwoElxFhjq7VMF.jpg</url>
            <title>Stories by Asmaa Mirkhan on Medium</title>
            <link>https://medium.com/@asmaamirkhan.am?source=rss-dc118fbeb428------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:01:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asmaamirkhan.am/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[Training Custom Object Detector Step by Step]]></title>
            <link>https://medium.com/iuc-bilgisayar-kulubu/training-custom-object-detector-step-by-step-4ef47bc2cb03?source=rss-dc118fbeb428------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ef47bc2cb03</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[object-detection-api]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Asmaa Mirkhan]]></dc:creator>
            <pubDate>Wed, 22 Apr 2020 09:19:44 GMT</pubDate>
            <atom:updated>2020-11-15T07:44:57.411Z</atom:updated>
            <content:encoded><![CDATA[<p>The original version of this post is available <a href="https://dl.asmaamir.com/basics-of-object-detection/tensorflow-object-detection-api">here </a>at <a href="https://dl.asmaamir.com/">dl.asmaamir.com </a>✨</p><h3>🌱 Introduction</h3><ul><li>✨ <em>Tensorflow</em> object detection API is a powerful tool that allows us to create custom object detectors depending on pre-trained, fine tuned models even if we don’t have strong AI background or strong <em>TensorFlow</em> knowledge.</li><li>💁‍♀️ Building models depending on pre-trained models saves us a lot of time and labor since we are using models that maybe trained for weeks using very strong machines, this principle is called <a href="https://dl.asmaamir.com/5-dlstrategies/b-transferlearning"><strong>Transfer Learning</strong></a><strong>.</strong></li><li>🗃️ As a data set I will show you how to use <em>OpenImages</em> data set and converting its data to <em>TensorFlow</em>-friendly format.</li></ul><h3>🚩 Development Pipeline</h3><ol><li>👩‍💻 Environment Preparation</li><li>🖼️ Image acquiring</li><li>🤹‍♀️ Image Organization</li><li>🤖 Model Selecting</li><li>👩‍🔧 Model Configuration</li><li>👶 Training</li><li>👮‍♀️ Evaluation</li><li>👒 Model Exporting</li><li>📱 Converting to tflite</li></ol><blockquote>- 🤕 While you are applying the instructions if you get errors you can check out 🐞 Common Issues section at the end of the article</blockquote><blockquote>- 🤯 If your model isn’t learning as you expect, check out model debugging notes <a href="https://dl.asmaamir.com/basics-of-object-detection/model-debugging">here </a>(beta 🧪)</blockquote><h3>👩‍💻 Environment Preparation</h3><h4>🔸 Environment Info</h4><ul><li>🐍 Python version: 3.7</li><li>🔥 TensorFlow version: 1.15</li></ul><h4>🥦 Conda env Setting</h4><h4>🔮 Create new env</h4><ul><li>🥦 Install <a href="https://www.anaconda.com/"><strong>Anaconda</strong></a></li><li>💻 Open cmd and run:</li></ul><pre># conda create -n &lt;ENV_NAME&gt; python=&lt;REQUIRED_VERSION&gt;<br>conda create -n tf1 python=3.7</pre><h4>⚡ Activate the new env</h4><pre># conda activate &lt;ENV_NAME&gt;<br>conda activate tf1</pre><h4>🔽 Install Packages</h4><h4>💥 GPU vs CPU Computing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g-LA_wYM0vJSmTCflX3kMA.png" /><figcaption>GPU vs CPU computing</figcaption></figure><h4>🚀 Installing TensorFlow</h4><pre># for gpu<br>conda install tensorflow-gpu=1.15</pre><pre># for cpu<br>conda install tensorflow=1.15</pre><h4>📦 Installing other packages</h4><pre>conda install pillow Cython lxml jupyter matplotlib</pre><pre>conda install -c anaconda protobuf</pre><h4>🤖 Downloading models repository</h4><h4>🤸‍♀️ Cloning from GitHub</h4><ul><li>A repository that contains required utils for training and evaluation process</li><li>Open CMD and run in E disk and run:</li></ul><pre># note that every time you open CMD you have<br># to activate your env again by running:<br># under E:\&gt;</pre><pre>conda activate tf1</pre><pre>git clone <a href="https://github.com/tensorflow/models.git">https://github.com/tensorflow/models.git</a><br>cd models/research</pre><blockquote>🧐 I assume that you are running your commands under <em>E</em> disk.</blockquote><h4>🔃 Compiling Protobufs</h4><h4>💻 Windows</h4><pre># under (tf1) E:\models\research&gt;<br>for /f %i in (&#39;dir /b object_detection\protos\*.proto&#39;) ^do protoc object_detection\protos\%i --python_out=.</pre><p>🐧 Linux</p><pre># under /models/research<br>$ protoc object_detection/protos/*.proto --python_out=.</pre><h4>📦 Compiling Packages</h4><pre>#under (tf1) E:\models\research&gt;<br>python setup.py build<br>python setup.py install</pre><h4>🚩 Setting Python Path Temporarily</h4><p>💻 Windows</p><pre>#under (tf1) E:\models\research&gt;<br>set PYTHONPATH=E:\models\research;E:\models\research\slim</pre><p>🐧 Linux</p><pre># under /models/research<br>$ export PYTHONPATH=`pwd`:`pwd`/slim</pre><blockquote>👮‍♀️ Every time you open CMD you have to set <em>PYTHONPATH</em> again</blockquote><h4>👩‍🔬 Installation Test</h4><p>🧐 Check out that every thing is done</p><p><strong>💻 Command</strong></p><pre># under (tf1) E:\models\research&gt;<br>python python object_detection/builders/model_builder_tf1_test.py</pre><p><strong>🎉 Expected Output</strong></p><pre>Ran 17 tests in 0.833s</pre><pre>OK (skipped=1)</pre><h3>🖼️ Image Acquiring</h3><h4>👮‍♀️ Directory Structure</h4><ul><li>🏗️ I suppose that you created a structure like:</li></ul><pre>|___ models<br>|___ demo<br>    |___ annotations<br>    |___ eval<br>    |___ images<br>    |___ inference<br>    |___ OIDv4_ToolKit<br>    |___ OpenImagesTool<br>    |___ pre_trainded_model<br>    |___ scripts<br>    |___ training</pre><p>🤖 model: the repo <a href="https://github.com/tensorflow/models"><strong>here</strong></a></p><p>📄 annotations: will contain generated .csv and .record files</p><p>👮‍♀️ eval: will contain results of evaluation</p><p>🖼️ images: will contain image data set</p><p>▶️ inference: will contain exported models after training</p><p>🔽 OIDv4_ToolKit: the repo <a href="https://github.com/EscVM/OIDv4_ToolKit"><strong>here</strong></a> (<em>OpenImages</em> Downloader)</p><p>👩‍🔧 OpenImagesTool: the repo <a href="https://github.com/asmaamirkhan/OpenImagesTool"><strong>here</strong></a> (<em>OpenImages</em> Organizer)</p><p>👩‍🏫pre_trained_model: will contain files of <em>TensorFlow</em> model that we will retrain</p><p>👩‍💻 scripts: will contain scripts that we will use for pre-processing and training processes</p><p>🚴‍♀️ training: will contain generated check points during training</p><h4>🚀 OpenImages Dataset</h4><ul><li>🕵️‍♀️ You can get images in various methods</li><li>👩‍🏫 I will show process of organizing OpenImages data set</li><li>🗃️ OpenImages is a huge data set contains annotated images of 600 objects</li><li>🔍 You can explore images by categories from <a href="https://storage.googleapis.com/openimages/web/visualizer/index.html?set=train&amp;type=segmentation&amp;r=false&amp;c=%2Fm%2F0420v5"><strong>here</strong></a></li></ul><h4>🎨 Downloading By Category</h4><p><a href="https://github.com/EscVM/OIDv4_ToolKit"><strong>OIDv4_Toolkit</strong></a> is a tool that we can use to download OpenImages dataset by category and by set (test, train, validation)</p><p>💻 To clone and build the project, open CMD and run:</p><pre>(tf1) E:\demo&gt;git clone <a href="https://github.com/EscVM/OIDv4_ToolKit.git">https://github.com/EscVM/OIDv4_ToolKit.git</a></pre><pre>(tf1) E:\demo&gt;cd OIDv4_ToolKit</pre><pre>(tf1) E:\demo\OIDv4_ToolKit&gt;pip install -r requirements.txt</pre><p>⏬ To start downloading by category:</p><pre># python main.py downloader --classes &lt;OBJECT_LIST&gt; --type_csv &lt;TYPE&gt;</pre><pre># TYPE: all | test | train | validation</pre><pre>(tf1) E:\demo\OIDv4_ToolKit&gt;python main.py downloader --classes Apple Orange --type_csv validation</pre><blockquote>👮‍♀️ If object name consists of 2 parts then write it with <em>&#39;_&#39;, e.g.</em> Bell_pepper</blockquote><h3>🤹‍♀️ Image Organization</h3><h4>🔮 OpenImagesTool</h4><ul><li>👩‍💻 <a href="https://github.com/asmaamirkhan/OpenImagesTool"><strong>OpenImagesTool</strong></a> is a tool to convert OpenImages images and annotations to <em>TensorFlow</em>-friendly structure.</li><li>🙄 <em>OpenImages</em> provides annotations ad .txt files in a format like:&lt;OBJECT_NAME&gt; &lt;XMIN&gt; &lt;YMIN&gt; &lt;XMAX&gt; &lt;YMAX&gt; which is not compatible with <em>TensorFlow</em> that requires <em>VOC</em> annotation format</li><li>💫 To do that synchronization we can do the following</li></ul><p>💻 To clone and build the project, open <em>CMD</em> and run:</p><pre>(tf1) E:\demo&gt;git clone <a href="https://github.com/asmaamirkhan/OpenImagesTool.git">https://github.com/asmaamirkhan/OpenImagesTool.git</a></pre><pre>(tf1) E:\demo&gt;cd OpenImagesTool/src</pre><h4>💻 Applying Organizing</h4><p>🚀 Now, we will convert images and annotations that we have downloaded and save them to images folder</p><pre># under (tf1) E:\demo\OpenImagesTool\src&gt;</pre><pre># python script.py -i &lt;INPUT_PATH&gt; -o &lt;OUTPUT_PATH&gt;</pre><pre>python script.py -i E:\pre_trainded_model\OIDv4_ToolKit\OID\Dataset -o E:\pre_trainded_model\images</pre><blockquote>👩‍🔬 <em>OpenImagesTool</em> adds validation images to training set by default, if you wand to disable this behavior you can add <em>-v</em> flag to the command.</blockquote><h4>🏷️ Creating Label Map</h4><ul><li>⛓️ label_map.pbtxt is a file that maps object names to corresponded IDs</li><li>➕ Create label_map.pbtxtfile under annotations folder and open it in a text editor</li><li>🖊️ Write your objects names and IDs in the following format</li></ul><pre>item {<br>  id: 1<br>  name: &#39;Hamster&#39;<br>}</pre><pre>item {<br>  id: 2<br>  name: &#39;Apple&#39;<br>}</pre><blockquote><em>👮‍♀️ id:0</em> is reserved for background, so don&#39; t use it</blockquote><blockquote>🐞 Related error: <em>ValueError: Label map id 0 is reserved for the background label</em></blockquote><h4>🏭 Generating CSV Files</h4><ul><li>🔄 Now we have to convert .xml files to csv file</li><li>🔻 Download the script <a href="https://gist.github.com/asmaamirkhan/67daffbb542e2f60a291e81920b4ad0e"><strong>xml_to_csv.py</strong></a> script and save it under scripts folder</li><li>💻 Open CMD and run:</li></ul><h4>👩‍🔬 Generating train csv file</h4><pre># under (tf1) E:\demo\scripts&gt;</pre><pre>python xml_to_csv.py -i E:\demo\images\train -o E:\demo\annotations\train_labels.csv</pre><h4>👩‍🔬 Generating test csv file</h4><pre># under (tf1) E:\demo\scripts&gt;</pre><pre>python xml_to_csv.py -i E:\demo\images\test -o E:\demo\annotations\test_labels.csv</pre><h4>👩‍🏭 Generating TF Records</h4><ul><li>🙇‍♀️ Now, we will generate tfrecords that will be used in training precess</li><li>🔻 Download <a href="https://gist.github.com/asmaamirkhan/b777ce66f89083842cd633debc426287"><strong>generate_tfrecords.py</strong></a> script and save it under scripts folder</li></ul><h4>👩‍🔬 Generating train tfrecord</h4><pre># under (tf1) E:\demo\scripts&gt;</pre><pre># python generate_tfrecords.py --label_map=&lt;PATH_TO_LABEL_MAP&gt;</pre><pre># --csv_input=&lt;PATH_TO_CSV_FILE&gt; --img_path=&lt;PATH_TO_IMAGE_FOLDER&gt;</pre><pre># --output_path=&lt;PATH_TO_OUTPUT_FILE&gt;</pre><pre>python generate_tfrecords.py --label_map=E:\demo\annotations\label_map.pbtxt --csv_input=E:\demo\annotations\train_labels.csv --img_path= E:\demo\images\train --output_path=E:\demo\annotations\train.record</pre><h4>👩‍🔬 Generating test tfrecord</h4><pre># under (tf1) E:\demo\scripts&gt;</pre><pre>python generate_tfrecords.py --label_map=E:\demo\annotations\label_map.pbtxt --csv_input=E:\demo\annotations\test_labels.csv --img_path= E:\demo\images\test --output_path=E:\demo\annotations\test.record</pre><h3>🤖 Model Selecting</h3><ul><li>🎉 <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf1_detection_zoo.md#coco-trained-models"><strong>TensorFLow Object Detection Zoo</strong></a> provides a lot of pre-trained models</li><li>🕵️‍♀️ Models differentiate in terms of accuracy and speed, you can select the suitable model due to your priorities</li><li>💾 Select a model, extract it and save it under pre_trained_model folder</li><li>👀 Check out my notes <a href="https://dl.asmaamir.com/basics-of-object-detection"><strong>here</strong> </a>to get insight about differences between popular models</li></ul><h3>👩‍🔧 Model Configuration</h3><h4>⏬ Downloading config File</h4><ul><li>😎 We have downloaded the models (pre-trained weights) but now we have to download configuration file that contains training parameters and settings</li><li>👮‍♀️ Every model in TensorFlow Object Detection Zoo has a configuration file presented <a href="https://github.com/tensorflow/models/tree/master/research/object_detection/samples/configs"><strong>here</strong></a></li><li>💾 Download the config file that corresponds to the models you have selected and save it under training folder</li></ul><h4>👩‍🔬 Updating config File</h4><p>You have to update the following lines:</p><pre>// number of classes<br>num_classes: 1 // set it to total number of classes you have</pre><pre>// path of pre-trained checkpoint<br>fine_tune_checkpoint: &quot;E:/demo/pre_trained_model/ssd_mobilenet_v1_quantized_300x300_coco14_sync_2018_07_18/model.ckpt&quot;</pre><pre>// path to train tfrecord<br>tf_record_input_reader {<br>input_path: &quot;E:/demo/annotations/train.record&quot;<br>}</pre><pre>// number of images that will be used in evaluation process<br>eval_config: {<br>metrics_set: &quot;coco_detection_metrics&quot;<br>use_moving_averages: false</pre><pre>// I suggest setting it to total number of testing set to get accurate results</pre><pre>num_examples: 11193<br>}</pre><pre>eval_input_reader: {</pre><pre>tf_record_input_reader {<br>// path to test tfrecord<br>input_path: &quot;E:/demo/annotations/test.record&quot;<br>}</pre><pre>// path to label map<br>label_map_path: &quot;E:/demo/annotations/label_map.pbtxt&quot;</pre><pre>// set it to true if you want to shuffle test set at each evaluation<br>shuffle: false<br>num_readers: 1<br>}</pre><blockquote>🤹‍♀️ If you give the whole test set to evaluation process then shuffle functionality won’t affect the results, it will only give you different examples on TensorBoard</blockquote><h3>👶 Training</h3><ul><li>🎉 Now we have done all preparations</li><li>🚀 Let the computer start learning</li><li>💻 Open CMD and run:</li></ul><pre># under (tf1) E:\models\research\object_detection\legacy&gt;<br># python train.py --train_dir=&lt;DIRECTORY_TO_SAVE_CHECKPOINTS&gt;<br># --pipline_config_path=&lt;PATH_TO_CONFIG_FILE&gt;</pre><pre>python train.py --train_dir=E:/demo/training --pipeline_config_path=E:/demo/training/ssd_mobilenet_v1_quantized_300x300_coco14_sync.config</pre><ul><li>🕐 This process will take long (You can take a nap 🤭, but a long nap 🙄)</li><li>🕵️‍♀️ While model is being trained you will see loss values on CMD</li><li>✋ You can stop the process when the loss value achieves a good value (under 1)</li></ul><h3>👮‍♀️ Evaluation</h3><h4>🎳 Evaluating Script</h4><ul><li>🤭 After training process is done, let’s do an exam to know how good (or bad 🙄) is our model doing</li><li>🎩 The following command will use the model on whole test set and after that print the results, so that we can do error analysis.</li><li>💻 So that, open CMD and run:</li></ul><pre># under (tf1) E:\models\research\object_detection\legacy&gt;<br># python eval.py --logtostderr --pipline_config_path=&lt;PATH_TO_CONFIG_FILE&gt;<br># --checkpoint_dir=&lt;DIRECTORY_OF_CHECKPOINTS&gt; --eval_dir=&lt;DIRECTORY_TO_SAVE_EVAL_RESULTS&gt;</pre><pre>python eval.py --pipeline_config_path=E:/demo/training/ssd_mobilenet_v1_quantized_300x300_coco14_sync.config --checkpoint_dir=--pipeline_config_path=E:/demo/training --eval_dir=--pipeline_config_path=E:/demo/eval</pre><h4>👀 Visualizing Results</h4><ul><li>✨ To see results on charts and images we can use TensorBoard for better analyzing</li><li>💻 Open CMD and:</li></ul><h4>👩‍🏫 Training Values Visualization</h4><ul><li>🧐 Here you can see graphs of loss, learning rate and other values</li><li>🤓 And much more (You can investigate tabs at the top)</li><li>😋 It is feasable to use it while training (and exciting 🤩)</li></ul><pre># under (tf1) E:\&gt; <br>tensorboard --logdir=E:/demo/tarining</pre><h4>👮‍♀️ Evaluation Values Visualization</h4><ul><li>👀 Here you can see images from your test set with corresponded predictions</li><li>🤓 And much more (You can inspect tabs at the top)</li><li>❗ You must use this after running evaluation script</li></ul><pre># under (tf1) E:\&gt;<br>tensorboard --logdir=E:/demo/eval</pre><ul><li>🔍 See the visualized results on <a href="http://localhost:6006/">localhost:6006</a> and</li><li>🧐 You can inspect numerical values from report on terminal, result example:</li></ul><pre>Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.708<br>Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=100 ] = 0.984<br>Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=100 ] = 0.868<br>Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.289<br>Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.623<br>Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.767<br>Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=  1 ] = 0.779<br>Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets= 10 ] = 0.781<br>Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.781<br>Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.300<br>Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.703<br>Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.824</pre><ul><li>🎨 If you want to get metric report for each class you have to change evaluating protocol to <em>pascal metrics</em> by configuring metrics_set in .config file:</li></ul><pre>eval_config: {<br>...<br>metrics_set: &quot;weighted_pascal_voc_detection_metrics&quot;<br>...<br>}</pre><h3>👒 Model Exporting</h3><ul><li>🔧 After training and evaluation processes are done, we have to make the model in such a format that we can use</li><li>🦺 For now, we have only checkpoints, so that we have to export .pb file</li><li>💻 So, open CMD and run:</li></ul><pre># under (tf1) E:\models\research\object_detection&gt;<br># python export_inference_graph.py --input_type image_tensor<br># --pipeline_config_path &lt;PATH_TO_CONFIG_FILE&gt;<br># --trained_checkpoing_prefix &lt;PATH_TO_LAST_CHECKPOINT&gt;<br># --output_directory &lt;PATH_TO_SAVE_EXPORTED_MODEL&gt;</pre><pre>python export_inference_graph.py --input_type image_tensor --pipeline_config_path=E:/demo/training/ssd_mobilenet_v1_quantized_300x300_coco14_sync.config --trained_checkpoing_prefix E:/demo/training/model.ckpt-16438 --output_directory E:/demo/inference/ssd_v1_quant</pre><ul><li>If you are using SSD and planning to convert it to tflite later you have to run</li></ul><pre># under (tf1) E:\models\research\object_detection&gt;<br># python export_tflite_ssd_graph.py --input_type image_tensor<br># --pipeline_config_path &lt;PATH_TO_CONFIG_FILE&gt;<br># --trained_checkpoing_prefix &lt;PATH_TO_LAST_CHECKPOINT&gt;<br># --output_directory &lt;PATH_TO_SAVE_EXPORTED_MODEL&gt;</pre><pre>python export_tflite_ssd_graph.py --input_type image_tensor --pipeline_config_path=E:/demo/training/ssd_mobilenet_v1_quantized_300x300_coco14_sync.config --trained_checkpoing_prefix E:/demo/training/model.ckpt-16438 --output_directory E:/demo/inference/ssd_v1_quant</pre><h3>📱 Converting to tflite</h3><ul><li>💁‍♀️ If you want to use the model in mobile apps or tflite supported embedded devices you have to convert .pb file to .tflite file</li></ul><h4>📙 About TFLite</h4><ul><li>📱 TensorFlow Lite is TensorFlow’s lightweight solution for mobile and embedded devices.</li><li>🧐 It enables on-device machine learning inference with low latency and a small binary size.</li><li>😎 TensorFlow Lite uses many techniques for this such as quantized kernels that allow smaller and faster (fixed-point math) models.</li><li>📍 <a href="https://www.tensorflow.org/lite"><strong>Official site</strong></a></li></ul><p><strong>🍫 Converting Command</strong></p><ul><li>💻 To apply converting open CMD and run:</li></ul><pre># under (tf1) E:\&gt;<br># toco --graph_def_file=&lt;PATH_TO_PB_FILE&gt;<br># --output_file=&lt;PATH_TO_SAVE&gt; --input_shapes=&lt;INPUT_SHAPES&gt;<br># --input_arrays=&lt;INPUT_ARRAYS&gt; --output_arrays=&lt;OUTPUT_ARRAYS&gt;<br># --inference_type=&lt;QUATIZED_UINT8|FLOAT&gt; --change_concat_input_ranges=&lt;true|false&gt;<br># --alow_custom_ops<br># args for QUATIZED_UINT8 inference<br># --mean_values=&lt;MEAN_VALUES&gt; std_dev_values=&lt;STD_DEV_VALUES&gt;</pre><pre>toco --graph_def_file=E:\demo\inference\ssd_v1_quant\tflite_graph.pb --output_file=E:\demo\tflite\ssd_mobilenet.tflite --input_shapes=1,300,300,3 --input_arrays=normalized_input_image_tensor --output_arrays=TFLite_Detection_PostProcess,TFLite_Detection_PostProcess:1,TFLite_Detection_PostProcess:2,TFLite_Detection_PostProcess:3 --inference_type=QUATIZED_UINT8 --mean_values=128 --std_dev_values=128 --change_concat_input_ranges=false --allow_custom_ops</pre><h3>🐞 Common Issues</h3><h4>🥅 nets module issue</h4><p>ModuleNotFoundError: No module named &#39;nets&#39;</p><p>This means that there is a problem in setting PYTHONPATH, try to run:</p><pre># under (tf1) E:\models\research&gt;<br>set PYTHONPATH=E:\models\research;E:\models\research\slim</pre><h4>🗃️ tf_slim module issue</h4><p>ModuleNotFoundError: No module named &#39;tf_slim&#39;</p><p>This means that tf_slim module is not installed, try to run:</p><pre># under (tf1) E:\models\research&gt;<br>pip install tf_slim</pre><h4>🗃️ Allocation error</h4><pre>2020-08-11 17:44:00.357710: I tensorflow/core/common_runtime/bfc_allocator.cc:929] Stats:<br>Limit:                 10661327<br>InUse:                 10656704<br>MaxInUse:              10657688<br>NumAllocs:                 2959<br>MaxAllocSize:           3045064</pre><p>For me it is fixed by minimizing batch_size in .config file, it is related to your computations resources</p><pre>train_config: {<br>....<br>batch_size: 128<br>....<br>}</pre><h4>❗ no such file or directory error</h4><p>train.py tensorflow.python.framework.errors_impl.notfounderror no such file or directory</p><ul><li>🙄 For me it was a typo in train.py command</li><li><a href="https://github.com/tensorflow/models/issues/3762">📍 Related discussion 1</a></li><li><a href="https://github.com/tensorflow/models/issues/3954">📍 Related discussion 2</a></li></ul><h4>🤯 LossTensor is inf issue</h4><p>LossTensor is inf or nan. : Tensor had NaN values</p><ul><li>👀 Related discussion is <a href="https://github.com/tensorflow/models/issues/1881"><strong>here</strong></a>, it is common that it is an annotation problem</li><li>🙄 Maybe there is some bounding boxes outside the image boundaries</li><li>🤯 The solution for me was minimizing batch size in .config file</li></ul><h4>🙄 Ground truth issue</h4><p>The following classes have no ground truth examples</p><ul><li>👀 Related discussion is <a href="https://github.com/tensorflow/models/issues/1936"><strong>here</strong></a></li><li>👩‍🔧 For me it was a misspelling issue in label_map file,</li><li>🙄 Pay attention to small and capital letters</li></ul><h4>🏷️ labelmap issue</h4><p>ValueError: Label map id 0 is reserved for the background label</p><ul><li>👮‍♀️ id:0 is reserved for background, We can not use it for objects</li><li>🆔 start IDs from 1</li></ul><h4>🔦 No Variable to Save issue</h4><p>Value Error: No Variable to Save</p><ul><li>👀 Related solution is <a href="https://ai.yemreak.com/tensorflow-object-detection-api/hata-notlari#value-error-no-variable-to-save"><strong>here</strong></a></li><li>👩‍🔧 Adding the following line to .config file solved the problem</li></ul><pre>train_config: {<br>...<br>fine_tune_checkpoint_type:  &quot;detection&quot;<br>...<br>}</pre><h4>🧪 pycocotools module issue</h4><p>ModuleNotFoundError: No module named &#39;pycocotools&#39;</p><ul><li>👀 Related discussion is <a href="https://github.com/tensorflow/models/issues/3367"><strong>here</strong></a></li><li>👩‍🔧 Applying the downloading instructions provided <a href="https://github.com/philferriere/cocoapi"><strong>here</strong></a> solved the problem for me (on Windows 10)</li></ul><h4>🥴 pycocotools type error issue</h4><p>pycocotools typeerror: object of type cannot be safely interpreted as an integer.</p><ul><li>👩‍🔧 I solved the problem by editing the following lines in cocoeval.py script under pycocotools package (by adding casting)</li><li>👮‍♀️ Make sure that you are editting the package in you env not in other env.</li></ul><pre>self.iouThrs = np.linspace(.5, 0.95, int(np.round((0.95 - .5) / .05)) + 1, endpoint=True)</pre><pre>self.recThrs = np.linspace(.0, 1.00, int(np.round((1.00 - .0) / .01)) + 1, endpoint=True)</pre><h4>💣 Loss Exploding</h4><pre>INFO:tensorflow:global step 440: loss = 2106942657570782838784.0000 (0.405 sec/step)</pre><pre>INFO:tensorflow:global step 440: loss = 2106942657570782838784.0000 (0.405 sec/step)</pre><pre>INFO:tensorflow:global step 441: loss = 7774169971762292326400.0000 (0.401 sec/step)</pre><pre>INFO:tensorflow:global step 441: loss = 7774169971762292326400.0000 (0.401 sec/step)</pre><pre>INFO:tensorflow:global step 442: loss = 25262924095336287830016.0000 (0.404 sec/step)</pre><pre>INFO:tensorflow:global step 442: loss = 25262924095336287830016.0000 (0.404 sec/step)</pre><p>🙄 For me there were 2 problems:</p><p><strong>First:</strong></p><ul><li>Some of annotations were wrong and overflow the image (e.g. xmax &gt; width)</li><li>I could check that by inspecting .csv file</li><li>Example:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*zX4fH2rneo211mJGDFTG4A.png" /></figure><p><strong>Second:</strong></p><ul><li>Learning rate in .config file is too big (the default value was big 🙄)</li><li>The following values are valid and tested on mobilenet_ssd_v1_quantized (Not very good 🙄)</li></ul><pre>learning_rate: {<br>  cosine_decay_learning_rate {<br>    learning_rate_base: .01<br>    total_steps: 50000<br>    warmup_learning_rate: 0.005<br>    warmup_steps: 2000<br>  }<br>}</pre><ul><li><a href="https://github.com/tensorflow/models/issues/3868">👀 Related Discussion 1</a></li><li><a href="https://github.com/tensorflow/models/issues/8423">👀 Related Discussion 1</a></li></ul><h4>🥴 Getting convolution Failure</h4><pre>Error : Failed to get convolution algorithm. This is probably because cuDNN failed to initialize, so try looking to see if a warning log message was printed above.</pre><ul><li>It may be a <em>Cuda</em> version incompatibility issue</li><li>For me it was a memory issue and I solved it by adding the following line to train.py script</li></ul><pre>os.environ[&#39;TF_FORCE_GPU_ALLOW_GROWTH&#39;] = &#39;true&#39;</pre><ul><li><a href="https://github.com/tensorflow/tensorflow/issues/24828">👀 Related discussion</a></li><li><a href="https://www.tensorflow.org/guide/gpu#limiting_gpu_memory_growth">📖 About memory growth</a></li></ul><h4>📦 Invalid box data error</h4><pre>raise ValueError(&#39;Invalid box data. data must be a numpy array of &#39;<br>ValueError: Invalid box data. data must be a numpy array of N*[y_min, x_min, y_max, x_max]</pre><ul><li>🙄 For me it was a logical error, in test_labels.csv there were some invalid values like: <strong>file123.jpg,134,63,3,0,0,-1029,-615</strong></li><li>🔖 So, it was a labeling issue, fixing these lines solved the problem</li><li>👀 <a href="https://github.com/tensorflow/models/issues/3527">Related discussion</a></li></ul><h4>🔄 Image with id added issue</h4><pre>raise ValueError(&#39;Image with id {} already added.&#39;.format(image_id))<br>ValueError: Image with id 123.png already added.</pre><ul><li>☝ It is an issue in .config caused by giving value to num_example that is greater than total number of test image in test directory</li></ul><pre>eval_config: {<br>  metrics_set: &quot;coco_detection_metrics&quot;<br>  use_moving_averages: false<br>  num_examples: 1265 // &lt;--- this value was greater than total test images<br>}</pre><h3>🧐 References</h3><ul><li>📖 <a href="https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/training.html#">Training Custom Object Detector</a></li><li>📖 <a href="https://ai.yemreak.com/tensorflow-object-detection-api">TensorFlow Object Detection API</a></li><li>📖 <a href="https://towardsdatascience.com/custom-object-detection-using-tensorflow-from-scratch-e61da2e10087">Custom Object Detection using TensorFlow from Scratch</a></li><li>📖 <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/evaluation_protocols.md">Supported object detection evaluation protocols</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ef47bc2cb03" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iuc-bilgisayar-kulubu/training-custom-object-detector-step-by-step-4ef47bc2cb03">Training Custom Object Detector Step by Step</a> was originally published in <a href="https://medium.com/iuc-bilgisayar-kulubu">İÜC Bilgisayar Kulübü</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Training Custom Object Detector Step by Step]]></title>
            <link>https://medium.com/@asmaamirkhan.am/training-custom-object-detector-step-by-step-5f6f4d75b494?source=rss-dc118fbeb428------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f6f4d75b494</guid>
            <category><![CDATA[object-detection-api]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Asmaa Mirkhan]]></dc:creator>
            <pubDate>Sun, 12 Apr 2020 19:08:42 GMT</pubDate>
            <atom:updated>2020-11-15T07:44:34.767Z</atom:updated>
            <content:encoded><![CDATA[<p>The original version of this post is available <a href="https://dl.asmaamir.com/basics-of-object-detection/tensorflow-object-detection-api">here </a>at <a href="https://dl.asmaamir.com/">dl.asmaamir.com </a>✨</p><h3>🌱 Introduction</h3><ul><li>✨ <em>Tensorflow</em> object detection API is a powerful tool that allows us to create custom object detectors depending on pre-trained, fine tuned models even if we don’t have strong AI background or strong <em>TensorFlow</em> knowledge.</li><li>💁‍♀️ Building models depending on pre-trained models saves us a lot of time and labor since we are using models that maybe trained for weeks using very strong machines, this principle is called <a href="https://dl.asmaamir.com/5-dlstrategies/b-transferlearning"><strong>Transfer Learning</strong></a><strong>.</strong></li><li>🗃️ As a data set I will show you how to use <em>OpenImages</em> data set and converting its data to <em>TensorFlow</em>-friendly format.</li></ul><h3>🚩 Development Pipeline</h3><ol><li>👩‍💻 Environment Preparation</li><li>🖼️ Image acquiring</li><li>🤹‍♀️ Image Organization</li><li>🤖 Model Selecting</li><li>👩‍🔧 Model Configuration</li><li>👶 Training</li><li>👮‍♀️ Evaluation</li><li>👒 Model Exporting</li><li>📱 Converting to tflite</li></ol><blockquote>- 🤕 While you are applying the instructions if you get errors you can check out 🐞 Common Issues section at the end of the article</blockquote><blockquote>- 🤯 If your model isn’t learning as you expect, check out model debugging notes <a href="https://dl.asmaamir.com/basics-of-object-detection/model-debugging">here </a>(beta 🧪)</blockquote><h3>👩‍💻 Environment Preparation</h3><h4>🔸 Environment Info</h4><ul><li>🐍 Python version: 3.7</li><li>🔥 TensorFlow version: 1.15</li></ul><h4>🥦 Conda env Setting</h4><h4>🔮 Create new env</h4><ul><li>🥦 Install <a href="https://www.anaconda.com/"><strong>Anaconda</strong></a></li><li>💻 Open cmd and run:</li></ul><pre># conda create -n &lt;ENV_NAME&gt; python=&lt;REQUIRED_VERSION&gt;<br>conda create -n tf1 python=3.7</pre><h4>⚡ Activate the new env</h4><pre># conda activate &lt;ENV_NAME&gt;<br>conda activate tf1</pre><h4>🔽 Install Packages</h4><h4>💥 GPU vs CPU Computing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g-LA_wYM0vJSmTCflX3kMA.png" /><figcaption>GPU vs CPU computing</figcaption></figure><h4>🚀 Installing TensorFlow</h4><pre># for gpu<br>conda install tensorflow-gpu=1.15</pre><pre># for cpu<br>conda install tensorflow=1.15</pre><h4>📦 Installing other packages</h4><pre>conda install pillow Cython lxml jupyter matplotlib</pre><pre>conda install -c anaconda protobuf</pre><h4>🤖 Downloading models repository</h4><h4>🤸‍♀️ Cloning from GitHub</h4><ul><li>A repository that contains required utils for training and evaluation process</li><li>Open CMD and run in E disk and run:</li></ul><pre># note that every time you open CMD you have<br># to activate your env again by running:<br># under E:\&gt;</pre><pre>conda activate tf1</pre><pre>git clone <a href="https://github.com/tensorflow/models.git">https://github.com/tensorflow/models.git</a><br>cd models/research</pre><blockquote>🧐 I assume that you are running your commands under E disk.</blockquote><h4>🔃 Compiling Protobufs</h4><h4>💻 Windows</h4><pre># under (tf1) E:\models\research&gt;<br>for /f %i in (&#39;dir /b object_detection\protos\*.proto&#39;) ^do protoc object_detection\protos\%i --python_out=.</pre><p>🐧 Linux</p><pre># under /models/research<br>$ protoc object_detection/protos/*.proto --python_out=.</pre><h4>📦 Compiling Packages</h4><pre>#under (tf1) E:\models\research&gt;<br>python setup.py build<br>python setup.py install</pre><h4>🚩 Setting Python Path Temporarily</h4><p>💻 Windows</p><pre>#under (tf1) E:\models\research&gt;<br>set PYTHONPATH=E:\models\research;E:\models\research\slim</pre><p>🐧 Linux</p><pre># under /models/research<br>$ export PYTHONPATH=`pwd`:`pwd`/slim</pre><blockquote>👮‍♀️ Every time you open CMD you have to set PYTHONPATH again</blockquote><h4>👩‍🔬 Installation Test</h4><p>🧐 Check out that every thing is done</p><p><strong>💻 Command</strong></p><pre># under (tf1) E:\models\research&gt;<br>python python object_detection/builders/model_builder_tf1_test.py</pre><p><strong>🎉 Expected Output</strong></p><pre>Ran 17 tests in 0.833s</pre><pre>OK (skipped=1)</pre><h3>🖼️ Image Acquiring</h3><h4>👮‍♀️ Directory Structure</h4><ul><li>🏗️ I suppose that you created a structure like:</li></ul><pre>|___ models<br>|___ demo<br>    |___ annotations<br>    |___ eval<br>    |___ images<br>    |___ inference<br>    |___ OIDv4_ToolKit<br>    |___ OpenImagesTool<br>    |___ pre_trainded_model<br>    |___ scripts<br>    |___ training</pre><p>🤖 model: the repo <a href="https://github.com/tensorflow/models"><strong>here</strong></a></p><p>📄 annotations: will contain generated .csv and .record files</p><p>👮‍♀️ eval: will contain results of evaluation</p><p>🖼️ images: will contain image data set</p><p>▶️ inference: will contain exported models after training</p><p>🔽 OIDv4_ToolKit: the repo <a href="https://github.com/EscVM/OIDv4_ToolKit"><strong>here</strong></a> (<em>OpenImages</em> Downloader)</p><p>👩‍🔧 OpenImagesTool: the repo <a href="https://github.com/asmaamirkhan/OpenImagesTool"><strong>here</strong></a> (<em>OpenImages</em> Organizer)</p><p>👩‍🏫pre_trained_model: will contain files of <em>TensorFlow</em> model that we will retrain</p><p>👩‍💻 scripts: will contain scripts that we will use for pre-processing and training processes</p><p>🚴‍♀️ training: will contain generated check points during training</p><h4>🚀 OpenImages Dataset</h4><ul><li>🕵️‍♀️ You can get images in various methods</li><li>👩‍🏫 I will show process of organizing OpenImages data set</li><li>🗃️ OpenImages is a huge data set contains annotated images of 600 objects</li><li>🔍 You can explore images by categories from <a href="https://storage.googleapis.com/openimages/web/visualizer/index.html?set=train&amp;type=segmentation&amp;r=false&amp;c=%2Fm%2F0420v5"><strong>here</strong></a></li></ul><h4>🎨 Downloading By Category</h4><p><a href="https://github.com/EscVM/OIDv4_ToolKit"><strong>OIDv4_Toolkit</strong></a> is a tool that we can use to download OpenImages dataset by category and by set (test, train, validation)</p><p>💻 To clone and build the project, open CMD and run:</p><pre>(tf1) E:\demo&gt;git clone <a href="https://github.com/EscVM/OIDv4_ToolKit.git">https://github.com/EscVM/OIDv4_ToolKit.git</a></pre><pre>(tf1) E:\demo&gt;cd OIDv4_ToolKit</pre><pre>(tf1) E:\demo\OIDv4_ToolKit&gt;pip install -r requirements.txt</pre><p>⏬ To start downloading by category:</p><pre># python main.py downloader --classes &lt;OBJECT_LIST&gt; --type_csv &lt;TYPE&gt;</pre><pre># TYPE: all | test | train | validation</pre><pre>(tf1) E:\demo\OIDv4_ToolKit&gt;python main.py downloader --classes Apple Orange --type_csv validation</pre><blockquote>👮‍♀️ If object name consists of 2 parts then write it with &#39;_&#39;, e.g. Bell_pepper</blockquote><h3>🤹‍♀️ Image Organization</h3><h4>🔮 OpenImagesTool</h4><ul><li>👩‍💻 <a href="https://github.com/asmaamirkhan/OpenImagesTool"><strong>OpenImagesTool</strong></a> is a tool to convert OpenImages images and annotations to <em>TensorFlow</em>-friendly structure.</li><li>🙄 <em>OpenImages</em> provides annotations ad .txt files in a format like:&lt;OBJECT_NAME&gt; &lt;XMIN&gt; &lt;YMIN&gt; &lt;XMAX&gt; &lt;YMAX&gt; which is not compatible with <em>TensorFlow</em> that requires <em>VOC</em> annotation format</li><li>💫 To do that synchronization we can do the following</li></ul><p>💻 To clone and build the project, open <em>CMD</em> and run:</p><pre>(tf1) E:\demo&gt;git clone <a href="https://github.com/asmaamirkhan/OpenImagesTool.git">https://github.com/asmaamirkhan/OpenImagesTool.git</a></pre><pre>(tf1) E:\demo&gt;cd OpenImagesTool/src</pre><h4>💻 Applying Organizing</h4><p>🚀 Now, we will convert images and annotations that we have downloaded and save them to images folder</p><pre># under (tf1) E:\demo\OpenImagesTool\src&gt;</pre><pre># python script.py -i &lt;INPUT_PATH&gt; -o &lt;OUTPUT_PATH&gt;</pre><pre>python script.py -i E:\pre_trainded_model\OIDv4_ToolKit\OID\Dataset -o E:\pre_trainded_model\images</pre><blockquote>👩‍🔬 <em>OpenImagesTool</em> adds validation images to training set by default, if you wand to disable this behavior you can add -v flag to the command.</blockquote><h4>🏷️ Creating Label Map</h4><ul><li>⛓️ label_map.pbtxt is a file that maps object names to corresponded IDs</li><li>➕ Create label_map.pbtxtfile under annotations folder and open it in a text editor</li><li>🖊️ Write your objects names and IDs in the following format</li></ul><pre>item {<br>  id: 1<br>  name: &#39;Hamster&#39;<br>}</pre><pre>item {<br>  id: 2<br>  name: &#39;Apple&#39;<br>}</pre><blockquote>👮‍♀️ id:0 is reserved for background, so don&#39; t use it</blockquote><blockquote>🐞 Related error: ValueError: Label map id 0 is reserved for the background label</blockquote><h4>🏭 Generating CSV Files</h4><ul><li>🔄 Now we have to convert .xml files to csv file</li><li>🔻 Download the script <a href="https://gist.github.com/asmaamirkhan/67daffbb542e2f60a291e81920b4ad0e"><strong>xml_to_csv.py</strong></a> script and save it under scripts folder</li><li>💻 Open CMD and run:</li></ul><h4>👩‍🔬 Generating train csv file</h4><pre># under (tf1) E:\demo\scripts&gt;</pre><pre>python xml_to_csv.py -i E:\demo\images\train -o E:\demo\annotations\train_labels.csv</pre><h4>👩‍🔬 Generating test csv file</h4><pre># under (tf1) E:\demo\scripts&gt;</pre><pre>python xml_to_csv.py -i E:\demo\images\test -o E:\demo\annotations\test_labels.csv</pre><h4>👩‍🏭 Generating TF Records</h4><ul><li>🙇‍♀️ Now, we will generate tfrecords that will be used in training precess</li><li>🔻 Download <a href="https://gist.github.com/asmaamirkhan/b777ce66f89083842cd633debc426287"><strong>generate_tfrecords.py</strong></a> script and save it under scripts folder</li></ul><h4>👩‍🔬 Generating train tfrecord</h4><pre># under (tf1) E:\demo\scripts&gt;</pre><pre># python generate_tfrecords.py --label_map=&lt;PATH_TO_LABEL_MAP&gt;</pre><pre># --csv_input=&lt;PATH_TO_CSV_FILE&gt; --img_path=&lt;PATH_TO_IMAGE_FOLDER&gt;</pre><pre># --output_path=&lt;PATH_TO_OUTPUT_FILE&gt;</pre><pre>python generate_tfrecords.py --label_map=E:\demo\annotations\label_map.pbtxt --csv_input=E:\demo\annotations\train_labels.csv --img_path= E:\demo\images\train --output_path=E:\demo\annotations\train.record</pre><h4>👩‍🔬 Generating test tfrecord</h4><pre># under (tf1) E:\demo\scripts&gt;</pre><pre>python generate_tfrecords.py --label_map=E:\demo\annotations\label_map.pbtxt --csv_input=E:\demo\annotations\test_labels.csv --img_path= E:\demo\images\test --output_path=E:\demo\annotations\test.record</pre><h3>🤖 Model Selecting</h3><ul><li>🎉 <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf1_detection_zoo.md#coco-trained-models"><strong>TensorFLow Object Detection Zoo</strong></a> provides a lot of pre-trained models</li><li>🕵️‍♀️ Models differentiate in terms of accuracy and speed, you can select the suitable model due to your priorities</li><li>💾 Select a model, extract it and save it under pre_trained_model folder</li><li>👀 Check out my notes <a href="https://dl.asmaamir.com/basics-of-object-detection"><strong>here</strong> </a>to get insight about differences between popular models</li></ul><h3>👩‍🔧 Model Configuration</h3><h4>⏬ Downloading config File</h4><ul><li>😎 We have downloaded the models (pre-trained weights) but now we have to download configuration file that contains training parameters and settings</li><li>👮‍♀️ Every model in TensorFlow Object Detection Zoo has a configuration file presented <a href="https://github.com/tensorflow/models/tree/master/research/object_detection/samples/configs"><strong>here</strong></a></li><li>💾 Download the config file that corresponds to the models you have selected and save it under training folder</li></ul><h4>👩‍🔬 Updating config File</h4><p>You have to update the following lines:</p><pre>// number of classes<br>num_classes: 1 // set it to total number of classes you have</pre><pre>// path of pre-trained checkpoint<br>fine_tune_checkpoint: &quot;E:/demo/pre_trained_model/ssd_mobilenet_v1_quantized_300x300_coco14_sync_2018_07_18/model.ckpt&quot;</pre><pre>// path to train tfrecord<br>tf_record_input_reader {<br>input_path: &quot;E:/demo/annotations/train.record&quot;<br>}</pre><pre>// number of images that will be used in evaluation process<br>eval_config: {<br>metrics_set: &quot;coco_detection_metrics&quot;<br>use_moving_averages: false</pre><pre>// I suggest setting it to total number of testing set to get accurate results</pre><pre>num_examples: 11193<br>}</pre><pre>eval_input_reader: {</pre><pre>tf_record_input_reader {<br>// path to test tfrecord<br>input_path: &quot;E:/demo/annotations/test.record&quot;<br>}</pre><pre>// path to label map<br>label_map_path: &quot;E:/demo/annotations/label_map.pbtxt&quot;</pre><pre>// set it to true if you want to shuffle test set at each evaluation<br>shuffle: false<br>num_readers: 1<br>}</pre><blockquote>🤹‍♀️ If you give the whole test set to evaluation process then shuffle functionality won’t affect the results, it will only give you different examples on TensorBoard</blockquote><h3>👶 Training</h3><ul><li>🎉 Now we have done all preparations</li><li>🚀 Let the computer start learning</li><li>💻 Open CMD and run:</li></ul><pre># under (tf1) E:\models\research\object_detection\legacy&gt;<br># python train.py --train_dir=&lt;DIRECTORY_TO_SAVE_CHECKPOINTS&gt;<br># --pipline_config_path=&lt;PATH_TO_CONFIG_FILE&gt;</pre><pre>python train.py --train_dir=E:/demo/training --pipeline_config_path=E:/demo/training/ssd_mobilenet_v1_quantized_300x300_coco14_sync.config</pre><ul><li>🕐 This process will take long (You can take a nap 🤭, but a long nap 🙄)</li><li>🕵️‍♀️ While model is being trained you will see loss values on CMD</li><li>✋ You can stop the process when the loss value achieves a good value (under 1)</li></ul><h3>👮‍♀️ Evaluation</h3><h4>🎳 Evaluating Script</h4><ul><li>🤭 After training process is done, let’s do an exam to know how good (or bad 🙄) is our model doing</li><li>🎩 The following command will use the model on whole test set and after that print the results, so that we can do error analysis.</li><li>💻 So that, open CMD and run:</li></ul><pre># under (tf1) E:\models\research\object_detection\legacy&gt;<br># python eval.py --logtostderr --pipline_config_path=&lt;PATH_TO_CONFIG_FILE&gt;<br># --checkpoint_dir=&lt;DIRECTORY_OF_CHECKPOINTS&gt; --eval_dir=&lt;DIRECTORY_TO_SAVE_EVAL_RESULTS&gt;</pre><pre>python eval.py --pipeline_config_path=E:/demo/training/ssd_mobilenet_v1_quantized_300x300_coco14_sync.config --checkpoint_dir=--pipeline_config_path=E:/demo/training --eval_dir=--pipeline_config_path=E:/demo/eval</pre><h4>👀 Visualizing Results</h4><ul><li>✨ To see results on charts and images we can use TensorBoard for better analyzing</li><li>💻 Open CMD and:</li></ul><h4>👩‍🏫 Training Values Visualization</h4><ul><li>🧐 Here you can see graphs of loss, learning rate and other values</li><li>🤓 And much more (You can investigate tabs at the top)</li><li>😋 It is feasable to use it while training (and exciting 🤩)</li></ul><pre># under (tf1) E:\&gt; <br>tensorboard --logdir=E:/demo/tarining</pre><h4>👮‍♀️ Evaluation Values Visualization</h4><ul><li>👀 Here you can see images from your test set with corresponded predictions</li><li>🤓 And much more (You can inspect tabs at the top)</li><li>❗ You must use this after running evaluation script</li></ul><pre># under (tf1) E:\&gt;<br>tensorboard --logdir=E:/demo/eval</pre><ul><li>🔍 See the visualized results on <a href="http://localhost:6006/">localhost:6006</a> and</li><li>🧐 You can inspect numerical values from report on terminal, result example:</li></ul><pre>Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.708<br>Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=100 ] = 0.984<br>Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=100 ] = 0.868<br>Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.289<br>Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.623<br>Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.767<br>Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=  1 ] = 0.779<br>Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets= 10 ] = 0.781<br>Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.781<br>Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.300<br>Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.703<br>Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.824</pre><ul><li>🎨 If you want to get metric report for each class you have to change evaluating protocol to <em>pascal metrics</em> by configuring metrics_set in .config file:</li></ul><pre>eval_config: {<br>...<br>metrics_set: &quot;weighted_pascal_voc_detection_metrics&quot;<br>...<br>}</pre><h3>👒 Model Exporting</h3><ul><li>🔧 After training and evaluation processes are done, we have to make the model in such a format that we can use</li><li>🦺 For now, we have only checkpoints, so that we have to export .pb file</li><li>💻 So, open CMD and run:</li></ul><pre># under (tf1) E:\models\research\object_detection&gt;<br># python export_inference_graph.py --input_type image_tensor<br># --pipeline_config_path &lt;PATH_TO_CONFIG_FILE&gt;<br># --trained_checkpoing_prefix &lt;PATH_TO_LAST_CHECKPOINT&gt;<br># --output_directory &lt;PATH_TO_SAVE_EXPORTED_MODEL&gt;</pre><pre>python export_inference_graph.py --input_type image_tensor --pipeline_config_path=E:/demo/training/ssd_mobilenet_v1_quantized_300x300_coco14_sync.config --trained_checkpoing_prefix E:/demo/training/model.ckpt-16438 --output_directory E:/demo/inference/ssd_v1_quant</pre><ul><li>If you are using SSD and planning to convert it to tflite later you have to run</li></ul><pre># under (tf1) E:\models\research\object_detection&gt;<br># python export_tflite_ssd_graph.py --input_type image_tensor<br># --pipeline_config_path &lt;PATH_TO_CONFIG_FILE&gt;<br># --trained_checkpoing_prefix &lt;PATH_TO_LAST_CHECKPOINT&gt;<br># --output_directory &lt;PATH_TO_SAVE_EXPORTED_MODEL&gt;</pre><pre>python export_tflite_ssd_graph.py --input_type image_tensor --pipeline_config_path=E:/demo/training/ssd_mobilenet_v1_quantized_300x300_coco14_sync.config --trained_checkpoing_prefix E:/demo/training/model.ckpt-16438 --output_directory E:/demo/inference/ssd_v1_quant</pre><h3>📱 Converting to tflite</h3><ul><li>💁‍♀️ If you want to use the model in mobile apps or tflite supported embedded devices you have to convert .pb file to .tflite file</li></ul><h4>📙 About TFLite</h4><ul><li>📱 TensorFlow Lite is TensorFlow’s lightweight solution for mobile and embedded devices.</li><li>🧐 It enables on-device machine learning inference with low latency and a small binary size.</li><li>😎 TensorFlow Lite uses many techniques for this such as quantized kernels that allow smaller and faster (fixed-point math) models.</li><li>📍 <a href="https://www.tensorflow.org/lite"><strong>Official site</strong></a></li></ul><p><strong>🍫 Converting Command</strong></p><ul><li>💻 To apply converting open CMD and run:</li></ul><pre># under (tf1) E:\&gt;<br># toco --graph_def_file=&lt;PATH_TO_PB_FILE&gt;<br># --output_file=&lt;PATH_TO_SAVE&gt; --input_shapes=&lt;INPUT_SHAPES&gt;<br># --input_arrays=&lt;INPUT_ARRAYS&gt; --output_arrays=&lt;OUTPUT_ARRAYS&gt;<br># --inference_type=&lt;QUATIZED_UINT8|FLOAT&gt; --change_concat_input_ranges=&lt;true|false&gt;<br># --alow_custom_ops<br># args for QUATIZED_UINT8 inference<br># --mean_values=&lt;MEAN_VALUES&gt; std_dev_values=&lt;STD_DEV_VALUES&gt;</pre><pre>toco --graph_def_file=E:\demo\inference\ssd_v1_quant\tflite_graph.pb --output_file=E:\demo\tflite\ssd_mobilenet.tflite --input_shapes=1,300,300,3 --input_arrays=normalized_input_image_tensor --output_arrays=TFLite_Detection_PostProcess,TFLite_Detection_PostProcess:1,TFLite_Detection_PostProcess:2,TFLite_Detection_PostProcess:3 --inference_type=QUATIZED_UINT8 --mean_values=128 --std_dev_values=128 --change_concat_input_ranges=false --allow_custom_ops</pre><h3>🐞 Common Issues</h3><h4>🥅 nets module issue</h4><p>ModuleNotFoundError: No module named &#39;nets&#39;</p><p>This means that there is a problem in setting PYTHONPATH, try to run:</p><pre># under (tf1) E:\models\research&gt;<br>set PYTHONPATH=E:\models\research;E:\models\research\slim</pre><h4>🗃️ tf_slim module issue</h4><p>ModuleNotFoundError: No module named &#39;tf_slim&#39;</p><p>This means that tf_slim module is not installed, try to run:</p><pre># under (tf1) E:\models\research&gt;<br>pip install tf_slim</pre><h4>🗃️ Allocation error</h4><pre>2020-08-11 17:44:00.357710: I tensorflow/core/common_runtime/bfc_allocator.cc:929] Stats:<br>Limit:                 10661327<br>InUse:                 10656704<br>MaxInUse:              10657688<br>NumAllocs:                 2959<br>MaxAllocSize:           3045064</pre><p>For me it is fixed by minimizing batch_size in .config file, it is related to your computations resources</p><pre>train_config: {<br>....<br>batch_size: 128<br>....<br>}</pre><h4>❗ no such file or directory error</h4><p>train.py tensorflow.python.framework.errors_impl.notfounderror no such file or directory</p><ul><li>🙄 For me it was a typo in train.py command</li><li><a href="https://github.com/tensorflow/models/issues/3762">📍 Related discussion 1</a></li><li><a href="https://github.com/tensorflow/models/issues/3954">📍 Related discussion 2</a></li></ul><h4>🤯 LossTensor is inf issue</h4><p>LossTensor is inf or nan. : Tensor had NaN values</p><ul><li>👀 Related discussion is <a href="https://github.com/tensorflow/models/issues/1881"><strong>here</strong></a>, it is common that it is an annotation problem</li><li>🙄 Maybe there is some bounding boxes outside the image boundaries</li><li>🤯 The solution for me was minimizing batch size in .config file</li></ul><h4>🙄 Ground truth issue</h4><p>The following classes have no ground truth examples</p><ul><li>👀 Related discussion is <a href="https://github.com/tensorflow/models/issues/1936"><strong>here</strong></a></li><li>👩‍🔧 For me it was a misspelling issue in label_map file,</li><li>🙄 Pay attention to small and capital letters</li></ul><h4>🏷️ labelmap issue</h4><p>ValueError: Label map id 0 is reserved for the background label</p><ul><li>👮‍♀️ id:0 is reserved for background, We can not use it for objects</li><li>🆔 start IDs from 1</li></ul><h4>🔦 No Variable to Save issue</h4><p>Value Error: No Variable to Save</p><ul><li>👀 Related solution is <a href="https://ai.yemreak.com/tensorflow-object-detection-api/hata-notlari#value-error-no-variable-to-save"><strong>here</strong></a></li><li>👩‍🔧 Adding the following line to .config file solved the problem</li></ul><pre>train_config: {<br>...<br>fine_tune_checkpoint_type:  &quot;detection&quot;<br>...<br>}</pre><h4>🧪 pycocotools module issue</h4><p>ModuleNotFoundError: No module named &#39;pycocotools&#39;</p><ul><li>👀 Related discussion is <a href="https://github.com/tensorflow/models/issues/3367"><strong>here</strong></a></li><li>👩‍🔧 Applying the downloading instructions provided <a href="https://github.com/philferriere/cocoapi"><strong>here</strong></a> solved the problem for me (on Windows 10)</li></ul><h4>🥴 pycocotools type error issue</h4><p>pycocotools typeerror: object of type cannot be safely interpreted as an integer.</p><ul><li>👩‍🔧 I solved the problem by editing the following lines in cocoeval.py script under pycocotools package (by adding casting)</li><li>👮‍♀️ Make sure that you are editting the package in you env not in other env.</li></ul><pre>self.iouThrs = np.linspace(.5, 0.95, int(np.round((0.95 - .5) / .05)) + 1, endpoint=True)</pre><pre>self.recThrs = np.linspace(.0, 1.00, int(np.round((1.00 - .0) / .01)) + 1, endpoint=True)</pre><h4>💣 Loss Exploding</h4><pre>INFO:tensorflow:global step 440: loss = 2106942657570782838784.0000 (0.405 sec/step)</pre><pre>INFO:tensorflow:global step 440: loss = 2106942657570782838784.0000 (0.405 sec/step)</pre><pre>INFO:tensorflow:global step 441: loss = 7774169971762292326400.0000 (0.401 sec/step)</pre><pre>INFO:tensorflow:global step 441: loss = 7774169971762292326400.0000 (0.401 sec/step)</pre><pre>INFO:tensorflow:global step 442: loss = 25262924095336287830016.0000 (0.404 sec/step)</pre><pre>INFO:tensorflow:global step 442: loss = 25262924095336287830016.0000 (0.404 sec/step)</pre><p>🙄 For me there were 2 problems:</p><p><strong>First:</strong></p><ul><li>Some of annotations were wrong and overflow the image (e.g. xmax &gt; width)</li><li>I could check that by inspecting .csv file</li><li>Example:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*zX4fH2rneo211mJGDFTG4A.png" /></figure><p><strong>Second:</strong></p><ul><li>Learning rate in .config file is too big (the default value was big 🙄)</li><li>The following values are valid and tested on mobilenet_ssd_v1_quantized (Not very good 🙄)</li></ul><pre>learning_rate: {<br>  cosine_decay_learning_rate {<br>    learning_rate_base: .01<br>    total_steps: 50000<br>    warmup_learning_rate: 0.005<br>    warmup_steps: 2000<br>  }<br>}</pre><ul><li><a href="https://github.com/tensorflow/models/issues/3868">👀 Related Discussion 1</a></li><li><a href="https://github.com/tensorflow/models/issues/8423">👀 Related Discussion 1</a></li></ul><h4>🥴 Getting convolution Failure</h4><pre>Error : Failed to get convolution algorithm. This is probably because cuDNN failed to initialize, so try looking to see if a warning log message was printed above.</pre><ul><li>It may be a <em>Cuda</em> version incompatibility issue</li><li>For me it was a memory issue and I solved it by adding the following line to train.py script</li></ul><pre>os.environ[&#39;TF_FORCE_GPU_ALLOW_GROWTH&#39;] = &#39;true&#39;</pre><ul><li><a href="https://github.com/tensorflow/tensorflow/issues/24828">👀 Related discussion</a></li><li><a href="https://www.tensorflow.org/guide/gpu#limiting_gpu_memory_growth">📖 About memory growth</a></li></ul><h4>📦 Invalid box data error</h4><pre>raise ValueError(&#39;Invalid box data. data must be a numpy array of &#39;<br>ValueError: Invalid box data. data must be a numpy array of N*[y_min, x_min, y_max, x_max]</pre><ul><li>🙄 For me it was a logical error, in test_labels.csv there were some invalid values like: <strong>file123.jpg,134,63,3,0,0,-1029,-615</strong></li><li>🔖 So, it was a labeling issue, fixing these lines solved the problem</li><li>👀 <a href="https://github.com/tensorflow/models/issues/3527">Related discussion</a></li></ul><h4>🔄 Image with id added issue</h4><pre>raise ValueError(&#39;Image with id {} already added.&#39;.format(image_id))<br>ValueError: Image with id 123.png already added.</pre><ul><li>☝ It is an issue in .config caused by giving value to num_example that is greater than total number of test image in test directory</li></ul><pre>eval_config: {<br>  metrics_set: &quot;coco_detection_metrics&quot;<br>  use_moving_averages: false<br>  num_examples: 1265 // &lt;--- this value was greater than total test images<br>}</pre><h3>🧐 References</h3><ul><li>📖 <a href="https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/training.html#">Training Custom Object Detector</a></li><li>📖 <a href="https://ai.yemreak.com/tensorflow-object-detection-api">TensorFlow Object Detection API</a></li><li>📖 <a href="https://towardsdatascience.com/custom-object-detection-using-tensorflow-from-scratch-e61da2e10087">Custom Object Detection using TensorFlow from Scratch</a></li><li>📖 <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/evaluation_protocols.md">Supported object detection evaluation protocols</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f6f4d75b494" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>