Skip to main content

How to convert your YOLOv4 weights to TensorFlow 2.2.0?

Another post starts with you beautiful people!
Thank you all for your overwhelming response in my last two posts about the YOLOv4. It is quite clear that my beloved aspiring data scientists are very much curious to learn state of the art computer vision technique but they were not able to achieve that due to the lack of proper guidance. Now they have learnt exact steps to use a state of the art object detection and recognition technique from my last two posts. If you are new to my blog and want to use YOLOv4 in your project then please follow below two links-

  1. How to install and compile Darknet code with GPU?
  2. How to train your custom data with YOLOv4?
In my last post we have trained our custom dataset to identify eight types of Indian classical dance forms. After the model training we have got the YOLOv4 specific weights file as 'yolo-obj_final.weights'. This YOLOv4 specific weight file cannot be used directly to either with OpenCV or with TensorFlow currently because in the latest release of YOLO a new activation function-Mish is introduced. With current version of OpenCV and TF using YOLOv4 directly is not possible. In this blog post I am going to share you my jupyter notebook code for converting YOLOv4 weights to TF2.2.0.

TensorFlow(TF) is an easy to use framework in production. If we have a TF model we can deploy it in a web application, mobile application or embedded devices. Since I am a Keras guy, I prefer to use Keras API with TensorFlow backend in my projects :) . I have taken the help from the older post of Jason Brownlee PhD and modified the code with YOLOv4 related changes. You can fork or download the notebook from my github repository  You can gone through the notebook and if you want to update or add any thing to it, send me a PR in github :)

In the first cell of the notebook I have imported required libraries and also checking the TF and Keras version-
So we have the latest keras and TF version currently available in colab notebook. In next cell, I have defined the newly added activation function Mish as below-
And in third cell, this activation function is added to the convolution layer blocks-
In further cells, I have defined the YOLOv4 architecture as per keras & TF and then other helper functions like drawing bounding boxes, removing unwanted bounding boxes and showing the detecting in an image. Let me show you the screenshots where I have converted a pretrained YOLOv4 weights to a TF model file-

After running above cells you will have a .h5 format file which is infact a TensorFlow model file. Now we will verify that our converted model file is working same as YOLOv4 weights or not. To do so let's import this TensorFlow model file-
With this code our .h5 file is successfully loaded as keras model. Let's define a list of objects on which original YOLOv4 weights was trained and also a function to read those object labels-
Next step is to define a function to load and preprocess an image for keras-
Let's apply this preprocessing function to an image in this way-
Next, we will use the predict() function to make the prediction on our image-
As a last step we will draw the bounding boxes and predicted object on that bounding boxes in our picture. All required processing for this step is already done in the notebook.Once we run the following cell-
Along with predicted object with accuracy, it will give you following like image-
The above image and result confirms that our conversion code is working as expected. That's it for today guys! Go ahead- Fork or download the complete notebook from my github repo, try it yourself, explore it with your custom YOLOv4 weights file and see how can you make this notebook more useful. In my next blog post I will share my new learning with you all. Till then Go chase your dreams, have an awesome day, make every second count and see you later in my next post.

Comments

  1. I have bookmarked your site since this site contains significant data in it. You rock for keeping incredible stuff. I am a lot of appreciative of this site.
    masters in data science

    ReplyDelete
  2. This content of information has helped me a lot. It is very well explained and easy to understand.

    ReplyDelete
  3. Thanks For Sharing this Interesting Blog. it is really helpful blog. carry on. keep blogging. otherwise anyone wants to learn CREO training Course so, Contact here- +91-9311002620 or visit website- https://www.htsindia.com/Courses/cad-cam-cae/creo-for-industrial-designers-training-course

    ReplyDelete
  4. earn money online 2020,
    dark web earn money from dark web,darknet financial vendors reviews,deep web website reviews,dark web skrill transfer,dark web links,tor onion links,how to buy credit cards,dark web paypal transfer,paypal transfer dark web,deep web darkweb market,deepweb,dark web,dark web market,darkweb paypal,darkweb credit card,dark web cards,darkweb western union,dark web money transfer,buying cards from dark web,deep web credit card,deepweb sites.

    ReplyDelete
  5. A
    darknet market is a commercial website on the web that operates via darknets such as Tor or ... Many vendors list their wares on multiple markets, ensuring they retain their reputation even should a single ... Cyber crime and hacking services for financial institutions and banks have also been offered over the dark web.

    ReplyDelete
  6. Amazing blog.Thanks for sharing such excellent information with us. keep sharing...
    data analytics courses delhi

    ReplyDelete
  7. A really good post man, very thankful and hopeful that you will write many more posts like this one.



    ReplyDelete
  8. At this cell of the code I face the following problem please if anyone can solve this problem ASAP let me know.
    # Verifiy the saved model using keras
    # Load the model
    from keras.models import load_model, Model
    #yolo_model = load_model("yolov4.h5")

    ---------------------------------------------------------------------------
    ValueError Traceback (most recent call last)
    in ()
    3 import keras
    4 from keras.models import load_model, Model
    ----> 5 yolo_model = load_model("yolov4.h5")

    17 frames
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/utils/generic_utils.py in class_and_config_for_serialized_keras_object(config, module_objects, custom_objects, printable_module_name)
    294 cls = get_registered_object(class_name, custom_objects, module_objects)
    295 if cls is None:
    --> 296 raise ValueError('Unknown ' + printable_module_name + ': ' + class_name)
    297
    298 cls_config = config['config']

    ValueError: Unknown activation function: Mish

    ReplyDelete
    Replies
    1. 'Mish' activation function is added in YOLOv4 version and it seems somehow keras/TF is using older OpenCV internally . So you need to build and compile the latest OpenCV in your system.

      Delete
  9. At this cell of the code I face the following problem please if anyone can solve this problem ASAP let me know.
    # Verifiy the saved model using keras
    # Load the model
    from keras.models import load_model, Model
    yolo_model = load_model("yolov4.h5")

    ---------------------------------------------------------------------------
    ValueError Traceback (most recent call last)
    in ()
    3 import keras
    4 from keras.models import load_model, Model
    ----> 5 yolo_model = load_model("yolov4.h5")

    17 frames
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/utils/generic_utils.py in class_and_config_for_serialized_keras_object(config, module_objects, custom_objects, printable_module_name)
    294 cls = get_registered_object(class_name, custom_objects, module_objects)
    295 if cls is None:
    --> 296 raise ValueError('Unknown ' + printable_module_name + ': ' + class_name)
    297
    298 cls_config = config['config']

    ValueError: Unknown activation function: Mish

    ReplyDelete
    Replies
    1. 'Mish' activation function is added in YOLOv4 version and it seems somehow keras/TF is using older OpenCV internally . So you need to build and compile the latest OpenCV in your system or update the keras/TF to the latest.

      Delete
    2. Can you please explain how ?

      Delete
  10. Very nice blog. I really enjoyed it. I appreciated your effort in this blog. This is useful for more people who are looking for data science. Big thumbs up for sharing this blog.
    Data Science Course in Hyderabad

    ReplyDelete
  11. This article is a creative one and the concept is good to enhance our knowledge. Waiting for more updates
    Courses on Artificial Intelligence

    ReplyDelete

  12. TORONTO An Iranian
    Would-be medical exec from Iran barred from Canada over alleged ties to Tehran's nuclear program. Ramin Fallah was labeled a security threat because he ...
    You've visited this page many times. Last visit: 5/12/21

    ReplyDelete
  13. Thanks For Sharing this Interesting Blog. it is really helpful blog.

    For Online MBA check below.

    Innomatics Research Labs is collaborated with JAIN (Deemed-to-be University) and offering the Online MBA in Business Intelligence,Business Analytics Program. This two-year program from JAIN (deemed-to-be) University offers foundation courses, core courses, Specialization courses, and a comprehensive master thesis intermediary, apart from an option to pursue a cross-functional and open elective.
    Online MBA in Business Analytics
    Online MBA in Business Intelligence

    ReplyDelete
  14. Thanks for sharing the blog. It is quite knowledgeable.For best data science course visit 360digitmg

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete
  16. This comment has been removed by the author.

    ReplyDelete
  17. Thanks for sharing the article it was very helpful
    For data science certification courses please get in touch with 360DigiTMG team
    Data Science Course in Ireland

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. Data Science Institute in Gurgaon
    is known to provide its students with some of the best available content in the form of a Data Science Course in Gurgaon .

    ReplyDelete
  20. Thanks for sharing the awesome article about Python. I hope you will keep it up.

    ReplyDelete
  21. "Nice Blog! such a informative things you are sharing ,I really liked your content. If you wanna know about ""Skillslash | Training with live industry experience that gets you hired""
    go to Data Science Course"

    ReplyDelete
  22. This comment has been removed by the author.

    ReplyDelete
  23. Thanks For sharing. Especia Associates provide outsourcing Accounting Services. Finance and Accounting outsourcing service for measuring the Return on Investment(ROI) on every step you have taken, to make sure of your increased profits. A decision in haste might be working well short term but often have long term staggering consequences. Accounting and Bookkeeping services team to provide you the daily input of company records from a time-to-time basis. Enriching you with the ongoing market and whereabouts of the places to strike or back down as necessary. if you need Accounting Services call at 9310165114 or visit us Outsourcing Accounting

    ReplyDelete
  24. wow! very nice article. who want to learn online courses. visit:Online Courses with Certificates

    ReplyDelete
  25. This comment has been removed by the author.

    ReplyDelete
  26. This comment has been removed by the author.

    ReplyDelete

  27. Very Informative and creative contents. This concept is a good way to enhance the knowledge. thanks for sharing.
    Continue to share your knowledge through articles like these, and keep posting more blogs. Web Scraping Services in USA

    ReplyDelete
  28. Thank you for sharing an amazing & wonderful blog. This content is very useful, informative and valuable in order to enhance knowledge. Keep sharing this type of content with us & keep updating us with new blogs. Apart from this, if anyone who wants to join the Python Base training institute in Delhi, can contact 9311002620 or visit our website-
    https://www.htsindia.com/Courses/python/python-training-institute-in-delhi

    ReplyDelete
  29. Thank you so much for this article. I have one doubt that while loading the keras (.h5) model it's showing error for "ValueError: Unknown activation function: Mish." Kindly help and can connect on Linkedin : https://www.linkedin.com/in/praket-sanganeria-4ba508190/

    ReplyDelete
  30. Thank you sharing information, How to install and compile Darknet code.
    I am doing BCA with AI & Data Science.

    ReplyDelete
  31. I found one successful example of this truth through this blog. I am going to use such information now.
    Best Online Coding Classes Near me

    ReplyDelete
  32. A good communication skill is really important everyone should know. When it comes to good communication skills, a person should be good at speaking english. But many people face issues in speaking English fluently, for which they take online spoken english classes to improve their English speaking skills.
    https://onlinetuitionclassesadda.blogspot.com/2023/01/benefits-of-spoken-english-classes.html
    Benefits of Spoken English classes

    ReplyDelete
  33. it’s very helpful useful thanks for your valuable information follow us
    Data Science Online Training in Hyderabad

    ReplyDelete
  34. such a nice information thanks for sharing and keep post like this kind posts. Also, check this Data Science course in Bangalore with placements to start a career in Data Science.

    ReplyDelete
  35. I have a weird history with mercari. But its past me now. I've written all about it on my blog with PayPal and Mercari.

    ReplyDelete
  36. Looking for reliable accounting software solutions in Surat to elevate your financial management game? Look no further! Discover a range of cutting-edge accounting software options designed to meet the unique needs of businesses in Surat.

    ReplyDelete
  37. Advanced topics in Data Analytics at APTRON offer an exciting opportunity for individuals looking to deepen their understanding of this dynamic field. In today's data-driven world, the demand for skilled data analysts is skyrocketing, and APTRON is at the forefront of providing cutting-edge education in this domain.

    ReplyDelete
  38. If you're looking to embark on a transformative journey into the world of programming, Python Training in Gurgaon at APTRON offers an unparalleled learning experience. Python has become a cornerstone in the tech industry, and mastering this versatile language opens doors to a myriad of opportunities.

    ReplyDelete
  39. Thanks for sharing this information. Say goodbye to tedious manual calculations and embrace the ease of automated financial tracking. Our accounting software in Surat ensures accuracy and compliance, allowing you to focus on growing your business. Whether you're a small business or a large enterprise, our user-friendly interface makes financial management a breeze.

    ReplyDelete
  40. Your Post Proved to be very helpful thank you for sharing ..
    Check Out The Best Short-Term Computer Courses After 12th Class

    ReplyDelete
  41. Cool and that i have a neat supply: What Does A Full House Renovation Cost split level home kitchen remodel

    ReplyDelete

Post a Comment

Popular posts from this blog

How to use opencv-python with Darknet's YOLOv4?

Another post starts with you beautiful people 😊 Thank you all for messaging me your doubts about Darknet's YOLOv4. I am very happy to see in a very short amount of time my lovely aspiring data scientists have learned a state of the art object detection and recognition technique. If you are new to my blog and to computer vision then please check my following blog posts one by one- Setup Darknet's YOLOv4 Train custom dataset with YOLOv4 Create production-ready API of YOLOv4 model Create a web app for your YOLOv4 model Since now we have learned to use YOLOv4 built on Darknet's framework. In this post, I am going to share with you how can you use your trained YOLOv4 model with another awesome computer vision and machine learning software library-  OpenCV  and of course with Python 🐍. Yes, the Python wrapper of OpenCV library has just released it's latest version with support of YOLOv4 which you can install in your system using below command- pip install opencv-python --up

How to install and compile YOLO v4 with GPU enable settings in Windows 10?

Another post starts with you beautiful people! Last year I had shared a post about  installing and compiling Darknet YOLOv3   in your Windows machine and also how to detect an object using  YOLOv3 with Keras . This year on April' 2020 the fourth generation of YOLO has arrived and since then I was curious to use this as soon as possible. Due to my project (built on YOLOv3 :)) work I could not find a chance to check this latest release. Today I got some relief and successfully able to install and compile YOLOv4 in my machine. In this post I am going to share a single shot way to do the same in your Windows 10 machine. If your machine does not have GPU then you can follow my  previous post  by just replacing YOLOv3 related files with YOLOv4 files. For GPU having Windows machine, follow my steps to avoid any issue while building the Darknet repository. My machine has following configurations: Windows 10 64 bit Intel Core i7 16 GB RAM NVIDIA GeForce GTX 1660 Ti Version 445.87