{"id":7007,"date":"2021-04-16T09:14:49","date_gmt":"2021-04-16T13:14:49","guid":{"rendered":"https:\/\/blogs.mathworks.com\/deep-learning\/?p=7007"},"modified":"2022-04-11T13:25:30","modified_gmt":"2022-04-11T17:25:30","slug":"bringing-tensorflow-models-into-matlab","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/deep-learning\/2021\/04\/16\/bringing-tensorflow-models-into-matlab\/","title":{"rendered":"Bringing TensorFlow Models into MATLAB"},"content":{"rendered":"<em>The following is a post from Shounak Mitra, Product Manager for Deep Learning Toolbox, here to talk about practical ways to work with TensorFlow and MATLAB.<\/em>\r\n<h6><\/h6>\r\n<p style=\"font-size: 14px;\">In release R2021a, <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/64649-deep-learning-toolbox-converter-for-tensorflow-models\">a converter for TensorFlow models<\/a> was released as a support package supporting import of TensorFlow 2 models into Deep Learning Toolbox. In this blog, we will explore the ways you can use the converter for TensorFlow models and do the following:<\/p>\r\n\r\n<ol>\r\n \t<li><a href=\"#7764e3a2-3fed-46c2-b509-dc2f390b4178\"><span style=\"font-size: 14px;\">Visualize and analyze the network<\/span><\/a><\/li>\r\n \t<li><a href=\"#9dfb3b09-dd5a-4632-bdc2-55861c2e8ff7\"><span style=\"font-size: 14px;\">Generate C\/C++\/CUDA code<\/span><\/a><\/li>\r\n \t<li><a href=\"#c27ad943-f1e0-48d3-9a20-28fcf1dabc56\"><span style=\"font-size: 14px;\">Integrate the network with Simulink<\/span><\/a><\/li>\r\n<\/ol>\r\n<p style=\"font-size: 14px;\">To bring models trained in TensorFlow 2 into MATLAB, you can use the function <a href=\"https:\/\/www.mathworks.com\/help\/deeplearning\/ref\/importtensorflownetwork.html\"><span style=\"font-family: courier;\">importTensorFlowNetwork<\/span><\/a>, which enables you to import the model and its weights into MATLAB. (Note: you can also use <a href=\"https:\/\/www.mathworks.com\/help\/deeplearning\/ref\/importtensorflowlayers.html\"><span style=\"font-family: courier;\">importTensorFlowLayers<\/span><\/a> to import layers from TensorFlow).<\/p>\r\n\r\n\r\n<table>\r\n<tbody>\r\n<tr>\r\n<td><p style=\"font-size: 16px;\"><h6><\/h6> >>>>>>>>>>>>>>>>>>>>>>>>>>>>><h6><\/h6>To see a more-detailed post on <strong>how <\/strong>to bring in TensorFlow model into MATLAB, check out <a href=\"https:\/\/blogs.mathworks.com\/deep-learning\/2022\/03\/18\/importing-models-from-tensorflow-pytorch-and-onnx\/\"><u>this related post<\/u><\/a> on bringing in TensorFlow (and other) networks<h6><\/h6> >>>>>>>>>>>>>>>>>>>>>>>>>>>>><\/p><\/td>\r\n<td style=\"padding:10px;  border:1px solid black\">Related Post: <a href=\"https:\/\/blogs.mathworks.com\/deep-learning\/2022\/03\/18\/importing-models-from-tensorflow-pytorch-and-onnx\/\">Importing Models from TensorFlow, PyTorch, and ONNX<\/a> <img decoding=\"async\" loading=\"lazy\" width=\"300\" height=\"168\" src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2022\/03\/BlogImage1-300x168.png\" alt=\"\" class=\"alignnone size-medium wp-image-9166\" \/><\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n\r\nThe rest of this blog post will focus on what you can do with TensorFlow Models <em>after <\/em>they are brought into MATLAB.<\/p>\r\n\r\n<h6><\/h6>\r\n<p style=\"text-align: center;\"><strong>Figure 1: Common workflows after importing TensorFlow model into MATLAB<\/strong><\/p>\r\n\r\n<h6><\/h6>\r\n<span style=\"font-size: 18px; color: #042285;\">1. Visualize and analyze the network<a name=\"7764e3a2-3fed-46c2-b509-dc2f390b4178\"><\/a><\/span>\r\n<h6><\/h6>\r\n<p style=\"font-size: 14px;\">To understand the network, we'll use Deep Network Designer app to visualize the network architecture. To load up the app, type <span style=\"font-family: courier;\">deepNetworkDesigner<\/span> in the command line and load the network from workspace. Once imported into the app, the network looks like Figure 4a. The layer architecture contains skip-connections which is typical of ResNet architectures. You can at this stage use this network for transfer learning workflows. Check this video out to learn how to <a href=\"https:\/\/www.mathworks.com\/videos\/interactively-modify-a-deep-learning-network-for-transfer-learning-1547157074175.html\">interactively modify a deep learning network for transfer learning<\/a>. You can also click on the <em>Analyze<\/em> button in the app (Figure 4b) and investigate the activation sizes and see if the network has errors like incorrect tensor shapes, misplaced connections, etc.<\/p>\r\n<p style=\"text-align: center;\"><img decoding=\"async\" loading=\"lazy\" class=\"alignnone wp-image-7123 size-full\" src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2021\/04\/Fig4a.jpg\" alt=\"\" width=\"845\" height=\"794\" \/><\/p>\r\n<p style=\"text-align: center;\"><strong>Figure 4a:\u00a0ResNet50 architecture inside the Deep Network Designer app<\/strong><\/p>\r\n<p style=\"text-align: center;\"><a href=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2021\/04\/Fig4b-1.jpg\"><img decoding=\"async\" loading=\"lazy\" class=\"alignnone wp-image-7158 size-full\" src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2021\/04\/Fig4b-1.jpg\" alt=\"\" width=\"1614\" height=\"809\" \/><\/a><\/p>\r\n\r\n<h6><\/h6>\r\n<p style=\"text-align: center;\"><strong>Figure 4b: Analyze the imported network for errors and visualize the key components in the architecture \u2013 the skipped connections in the case of resnet50. Click for larger view.\u00a0<\/strong><\/p>\r\n\r\n<h6><\/h6>\r\n<span style=\"font-size: 18px; color: #042285;\">2. Generate C\/C++\/CUDA code<a name=\"9dfb3b09-dd5a-4632-bdc2-55861c2e8ff7\"><\/a><\/span>\r\n<h6><\/h6>\r\n<p style=\"font-size: 14px;\">One of the most common paths our customers take after importing a model is generating code, targeting different hardware platforms.<\/p>\r\n<p style=\"font-size: 14px;\">In this example we'll generate CUDA code, using <a href=\"https:\/\/www.mathworks.com\/products\/gpu-coder.html\">GPU Coder<\/a>, targeting the cuDNN library in 3 easy steps.<\/p>\r\n\r\n<h2>Step 1: Verify the GPU environment<\/h2>\r\n<p style=\"font-size: 14px;\">This performs a complete check of all third-party tools required for GPU code generation. The output shown here is representative. Your results might differ.<\/p>\r\n\r\n<table style=\"margin-left: auto; margin-right: auto;\">\r\n<tbody>\r\n<tr>\r\n<td style=\"vertical-align: middle;\">\r\n<pre>envCfg = coder.gpuEnvConfig('host');\r\nenvCfg.DeepLibTarget = 'cudnn';\r\nenvCfg.DeepCodegen = 1;\r\nenvCfg.Quiet = 1;\r\ncoder.checkGpuInstall(envCfg);\r\n<\/pre>\r\n<\/td>\r\n<td><img decoding=\"async\" loading=\"lazy\" class=\"alignnone wp-image-7127 size-full\" src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2021\/04\/Fig5.jpg\" alt=\"\" width=\"356\" height=\"542\" \/><\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<h6><\/h6>\r\n<p style=\"text-align: center;\"><strong>Figure 5:<\/strong> <strong>Verify the GPU environment to make sure all the essential libraries are available<\/strong><\/p>\r\n\r\n<h2>Step 2: Define Entry Point Function<\/h2>\r\n<p style=\"font-size: 14px;\">The\u00a0<span style=\"font-family: courier;\">resnet50_predict.m<\/span>\u00a0entry-point function takes an image input and runs prediction on the image using the imported ResNet50 model. The function uses a persistent object\u00a0<em>mynet<\/em>\u00a0to load the series network object and reuses the persistent object for prediction on subsequent calls.<\/p>\r\n\r\n<pre>function out = resnet50_predict(in)\r\n<span class=\"comment\">%#codegen <\/span>\r\npersistent mynet;\r\n\r\nif isempty(mynet)\r\n  mynet = coder.loadDeepLearningNetwork('resnet50.mat','net');\r\nend\r\n\r\n<span class=\"comment\">% pass in input <\/span>\r\nout = mynet.predict(in);\r\n\r\n<\/pre>\r\n<h6><\/h6>\r\n<h2>Step 3: Run MEX Code Generation<\/h2>\r\n<p style=\"font-size: 14px;\">Call the entry point function and generate C++ code targeting cudnn libraries<\/p>\r\n<p style=\"font-size: 14px;\">To generate CUDA code for the\u00a0<span style=\"font-family: courier;\">resnet50_predict.m<\/span> entry-point function, create a GPU code configuration object for a MEX target and set the target language to C++. Use the\u00a0<a href=\"https:\/\/www.mathworks.com\/help\/gpucoder\/ref\/coder.deeplearningconfig.html\">coder.DeepLearningConfig<\/a>\u00a0function to create a\u00a0CuDNN\u00a0deep learning configuration object and assign it to the\u00a0DeepLearningConfig\u00a0property of the GPU code configuration object. Run the\u00a0codegen\u00a0command and specify an input size of [224,224,3]. This value corresponds to the input layer size of the ResNet50 network.<\/p>\r\nRun MEX\r\n<pre>cfg = coder.gpuConfig('mex');\r\ncfg.TargetLang = 'C++';\r\ncfg.DeepLearningConfig = coder.DeepLearningConfig('cudnn');\r\ncodegen -config cfg resnet50_predict -args {ones(224,224,3)} -report\r\n<\/pre>\r\n<p style=\"font-size: 14px;\">GPU Coder creates a code generation report that provides an interface to examine the original MATLAB code and generated CUDA code. The report also provides a handy interactive code traceability tool to map between MATLAB code and CUDA. Figure 6 shows a screen capture of the tool in action.<\/p>\r\n<p style=\"text-align: center;\"><a href=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2021\/04\/Fig7b.jpg\"><img decoding=\"async\" loading=\"lazy\" class=\"alignnone wp-image-7129 size-large\" src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2021\/04\/Fig7b-1024x555.jpg\" alt=\"\" width=\"1024\" height=\"555\" \/><\/a><\/p>\r\n<p style=\"text-align: center;\"><strong>Figure 6:<\/strong> <strong>Generated report for code generation. Click to see details.<\/strong><\/p>\r\n<p style=\"font-size: 14px;\">In this example, we targeted the cuDNN libraries. You can also target Intel and ARM CPUs using <a href=\"https:\/\/www.mathworks.com\/products\/matlab-coder.html\">MATLAB Coder<\/a> and FPGAs and SoCs using <a href=\"https:\/\/www.mathworks.com\/products\/deep-learning-hdl.html\">Deep Learning HDL Toolbox<\/a>.<\/p>\r\n\r\n<h6><\/h6>\r\n<span style=\"font-size: 18px; color: #042285;\">3. Integrate the Network with Simulink<a name=\"c27ad943-f1e0-48d3-9a20-28fcf1dabc56\"><\/a><\/span>\r\n<h6><\/h6>\r\n<p style=\"font-size: 14px;\">Often, deep learning models are used as a component in bigger systems. Simulink helps explore a wide design space by modeling the system under test and the physical plant where you can use one multi-domain environment to simulate how all parts of the system behave. In this section, we will see how the resnet50 model imported from TensorFlow can be integrated into Simulink.<\/p>\r\n<p style=\"font-size: 14px;\">We'll integrate this model with Simulink in 3 easy steps. But first, save the Resnet50 model in your directory in MATLAB. Use <span style=\"font-family: courier;\">save('resnet50.mat','net')<\/span> to do so.<\/p>\r\n\r\n<h2>Step 1: Open Simulink and Access Library Browser<\/h2>\r\n<ul>\r\n \t<li>\r\n<p style=\"font-size: 14px;\">Open Simulink (type <span style=\"font-family: courier;\">simulink<\/span> in the command window) and choose 'Blank Model'<\/p>\r\n<\/li>\r\n \t<li>\r\n<p style=\"font-size: 14px;\">Click on Library Browser<\/p>\r\n<\/li>\r\n<\/ul>\r\n<p style=\"text-align: center;\"><img decoding=\"async\" loading=\"lazy\" class=\"alignnone wp-image-7153 size-full\" src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2021\/04\/2021-04-15_10-19-12-1.png\" alt=\"\" width=\"500\" height=\"108\" \/><\/p>\r\n\r\n<h2>Step 2: Add the Simulink Blocks<\/h2>\r\n<ul>\r\n \t<li>\r\n<p style=\"font-size: 14px;\"><u>Add an\u00a0image<\/u> from file\u00a0block from the\u00a0<strong>Computer Vision Toolbox<\/strong>library and set the\u00a0File name\u00a0parameter to\u00a0peppers.png. This is the sample image we are going to classify using the resnet50 model in Simulink.<\/p>\r\n<\/li>\r\n \t<li>\r\n<p style=\"font-size: 14px;\"><u>Preprocess the image<\/u>: We need to add a couple of preprocessing lines to make sure the network gets the image as expected. To write MATLAB code in Simulink, we will use MATLAB Function block. Click anywhere on the Simulink canvas and type From the list of options, <em>select MATLAB Function. <\/em>Inside the MATLAB Function block, we'll add a couple of lines to flip the image channels and resizing the image.<\/p>\r\n\r\n<pre>function y = preprocess_img(img)\r\n\r\n  img = flip(img,3);\r\n  img = imresize(img, [224 224]);\r\n  y = img; \r\nend\r\n<\/pre>\r\n<\/li>\r\n \t<li>\r\n<p style=\"font-size: 14px;\"><span style=\"text-decoration: underline;\">Add the ResNet50 model:<\/span>\u00a0Navigate to Deep Learning Toolbox --&gt; Deep Neural Networks in Simulink library browser and drag the 'Predict' block onto the Simulink model canvas.<\/p>\r\n\r\n<h6><\/h6>\r\n<p style=\"font-size: 14px;\">Double-click on the predict block which opens the <em>Block Parameters<\/em> dialogue and select the 'Network from MAT-file' option from the <em>Network<\/em> dropdown as shown. Navigate to the location where you've saved the resnet50 model and open it. Click <em>OK <\/em>once you're done.<\/p>\r\n<\/li>\r\n<\/ul>\r\n<h6><\/h6>\r\n<table style=\"margin-left: auto; margin-right: auto;\">\r\n<tbody>\r\n<tr>\r\n<td><\/td>\r\n<td><img decoding=\"async\" loading=\"lazy\" class=\"alignnone wp-image-7131 size-large\" src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2021\/04\/Fig9-1024x445.jpg\" alt=\"\" width=\"1024\" height=\"445\" \/><\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<h6><\/h6>\r\n<p style=\"text-align: center;\"><strong>Figure 7: Built-in deep learning blocks can be used for prediction and classification<\/strong><\/p>\r\n\r\n<h6><\/h6>\r\n<ul>\r\n \t<li>\r\n<p style=\"font-size: 14px;\"><u>Add an output to predict scores:<\/u> Next, click anywhere on your Simulink canvas and type <em>output and select the first option<\/em><\/p>\r\n<\/li>\r\n<\/ul>\r\n<p style=\"text-align: center;\"><img decoding=\"async\" loading=\"lazy\" class=\"alignnone wp-image-7143 size-full\" src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2021\/04\/Fig10-1.jpg\" alt=\"\" width=\"500\" height=\"230\" \/><\/p>\r\n\r\n<h6><\/h6>\r\n<p style=\"text-align: center;\"><strong>Figure 8<\/strong><\/p>\r\n\r\n<h6><\/h6>\r\n<ul>\r\n \t<li>\r\n<p style=\"font-size: 14px;\"><u>Connect the blocks<\/u> you've created so far. Once done, it should look like the below figure.<\/p>\r\n<\/li>\r\n<\/ul>\r\n<h6><\/h6>\r\n<p style=\"text-align: center;\"><img decoding=\"async\" loading=\"lazy\" width=\"1473\" height=\"327\" class=\"alignnone size-full wp-image-7029\" src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2021\/04\/Picture12.png\" alt=\"\" \/><\/p>\r\n\r\n<h6><\/h6>\r\n<p style=\"text-align: center;\"><strong>Figure 9<\/strong><\/p>\r\n\r\n<h2>Step 3: Run the simulation<\/h2>\r\n<p style=\"font-size: 14px;\">Once the simulation has run successfully, you absolutely should test if the simulation output predicts the bell pepper image correctly. Below is the prediction made by the output of the simulation on the image.<\/p>\r\n<p style=\"text-align: center;\"><img decoding=\"async\" loading=\"lazy\" width=\"949\" height=\"736\" class=\"alignnone size-full wp-image-7031\" src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2021\/04\/Picture13.jpg\" alt=\"\" \/><\/p>\r\n\r\n<h6><\/h6>\r\n<p style=\"text-align: center;\"><strong>Figure 10<\/strong><\/p>\r\n<p style=\"font-size: 14px;\">This was a simple example demonstrating how you'd integrate a simple model with Simulink, but the bigger systems are much more complex. Let's use an example of a lane following algorithm used by an autonomous car. There are many components that make this application successful: object detection, sensor fusion, acceleration control, braking, and quite a few more (See Figure 11). Deep learning algorithm represents one (but very important) component of the bigger system. It is used for detecting lanes and cars, and the deep learning system needs to work within the larger system. Below is a pictorial representation of such a system that performs Highway Lane Following. In Figure 11, only the 'Vision Detector' is the deep learning network and rest of the components in the system perform other tasks such as lane following control and sensor fusion.<\/p>\r\n<p style=\"font-size: 14px;\">We didn't discuss much about the highway lane following example here but if you're interested, <a href=\"https:\/\/www.mathworks.com\/help\/mpc\/ug\/highway-lane-following.html\">here is the link to the documentation example<\/a>.<\/p>\r\n\r\n<table style=\"margin-left: auto; margin-right: auto;\">\r\n<tbody>\r\n<tr>\r\n<td><img decoding=\"async\" loading=\"lazy\" class=\"alignnone wp-image-7135 size-full\" src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2021\/04\/Fig13.jpg\" alt=\"\" width=\"1833\" height=\"719\" \/><\/td>\r\n<td><\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<h6><\/h6>\r\n<p style=\"text-align: center;\"><strong>Figure 11: System showing how a typical plant looks like for building a bigger system where many components interact with each other<\/strong><\/p>\r\n\r\n<h6><\/h6>\r\n<span style=\"font-size: 20px;\"><strong>Conclusion<\/strong><\/span>\r\n<p style=\"font-size: 14px;\">In this blog we learned how we can collaborate in the AI ecosystem working with TensorFlow and MATLAB using the converter for TensorFlow models. We saw ways in which you could enhance TensorFlow workflows by bringing a model trained in TensorFlow into MATLAB via the converter and analyze, visualize, simulate, and generate code for the network.<\/p>\r\n\r\n<h2>What's Next<\/h2>\r\n<p style=\"font-size: 14px;\">In the next blog, we will look at the ability of the importer to autogenerate custom layers for the operators and layers that are not supported for conversion into a built-in layer by MATLAB's Deep Learning Toolbox.<\/p>\r\n<p style=\"font-size: 14px;\">We'd love to see you use the TensorFlow model converter and hear what your reasons are to bring in models from TensorFlow into MATLAB.<\/p>","protected":false},"excerpt":{"rendered":"<div class=\"overview-image\"><img decoding=\"async\"  class=\"img-responsive\" src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2022\/03\/BlogImage1-300x168.png\" onError=\"this.style.display ='none';\" \/><\/div><p>The following is a post from Shounak Mitra, Product Manager for Deep Learning Toolbox, here to talk about practical ways to work with TensorFlow and MATLAB.\r\n\r\nIn release R2021a, a converter for... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/deep-learning\/2021\/04\/16\/bringing-tensorflow-models-into-matlab\/\">read more >><\/a><\/p>","protected":false},"author":156,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[9],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/posts\/7007"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/users\/156"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/comments?post=7007"}],"version-history":[{"count":48,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/posts\/7007\/revisions"}],"predecessor-version":[{"id":9467,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/posts\/7007\/revisions\/9467"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/media?parent=7007"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/categories?post=7007"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/tags?post=7007"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}