{"id":10794,"date":"2022-12-12T10:11:01","date_gmt":"2022-12-12T15:11:01","guid":{"rendered":"https:\/\/blogs.mathworks.com\/deep-learning\/?p=10794"},"modified":"2024-02-12T20:37:29","modified_gmt":"2024-02-13T01:37:29","slug":"quickly-investigate-pytorch-models-from-matlab","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/deep-learning\/2022\/12\/12\/quickly-investigate-pytorch-models-from-matlab\/","title":{"rendered":"Quickly Investigate PyTorch Models from MATLAB"},"content":{"rendered":"<em>The following post is from <a href=\"https:\/\/www.linkedin.com\/in\/sivylla-p-05865a82\/\">Sivylla Paraskevopoulou<\/a>, Product Marketing Manager at MathWorks, and <a href=\"https:\/\/www.linkedin.com\/in\/yanndebray\/\">Yann Debray<\/a>, Product Manager at MathWorks.<\/em>\r\n<h6><\/h6>\r\nThis blog post talks about how MATLAB, PyTorch\u00ae, and TensorFlow\u2122 can be used together.\r\n<h6><\/h6>\r\nDeep learning models commonly exist within a complete AI system, which can involve preparing the data, building the model, designing the system on which the model will run, and deploying to hardware or production. MATLAB provides tools to help you at each step of the AI system design.\r\n<h6><\/h6>\r\nYou can get a pretrained deep learning model from the <a href=\"https:\/\/github.com\/matlab-deep-learning\/MATLAB-Deep-Learning-Model-Hub\">MATLAB Deep Learning Model Hub<\/a>, or from TensorFlow, PyTorch, or ONNX\u2122 repositories. We will show here you how to quickly compare PyTorch image classification models without leaving the MATLAB environment.\r\n<h6><\/h6>\r\n&nbsp;\r\n<h6><\/h6>\r\n<img decoding=\"async\" loading=\"lazy\" class=\"alignnone wp-image-10800 \" src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2022\/11\/AI_flow.png\" alt=\"\" width=\"674\" height=\"421\" \/>\r\n<h6><\/h6>\r\n<strong>Figure:<\/strong> Adding an extra step to my existing workflow in order to find the right PyTorch model\r\n<h6><\/h6>\r\n&nbsp;\r\n<h6><\/h6>\r\nOur image classification workflow includes loading and preprocessing an image, importing an image classification model from PyTorch, and using the imported network to predict the image label. This workflow is presented in the documentation example <a href=\"https:\/\/www.mathworks.com\/help\/deeplearning\/ref\/importnetworkfrompytorch.html#mw_addb7732-c424-4797-9765-3992bcd9752e\">Import Network from PyTorch and Classify Image<\/a>.\r\n<h6><\/h6>\r\nLet\u2019s assume the most important selection factor for the classifier model is the model\u2019s prediction speed. The <a href=\"https:\/\/pytorch.org\/vision\/0.8\/models.html\">torchvision.models<\/a> library alone has 12 models to choose from. It would be quite cumbersome to import each of these 12 models for our comparison test. We will show you here how you can call PyTorch from MATLAB to run an inference speed test quickly on multiple PyTorch models.\r\n<h6><\/h6>\r\nIn this blog post we won\u2019t show you all the details for each step. You can find the detailed example at\u00a0<a href=\"https:\/\/github.com\/matlab-deep-learning\/compare-PyTorch-models-from-MATLAB\">Call Python from MATLAB to Compare PyTorch Models for Image Classification<\/a>. Instead, here we are focusing on key takeaways on exploring PyTorch models with co-execution from MATLAB.\r\n<h6><\/h6>\r\n&nbsp;\r\n<p style=\"font-size: 18px;\"><strong>Preprocess Image<\/strong><\/p>\r\nRead the image you want to classify. Resize the image to the input size of the network.\r\n<pre>imgOriginal = imread(\"banana.png\");\r\nInputSize = [224 224 3];\r\nimg = imresize(imgOriginal,InputSize(1:2));\r\n<\/pre>\r\nYou must preprocess the image in the same way as the training data. For more information, see <a href=\"https:\/\/www.mathworks.com\/help\/deeplearning\/ug\/tips-on-importing-models-from-tensorflow-pytorch-and-onnx.html#mw_7d593336-5595-49a0-9bc0-184ba6cebb80\">Input Data Preprocessing<\/a>.\r\n<h6><\/h6>\r\nRescale the image. Then, normalize the image by subtracting the training images mean and dividing by the training images standard deviation.\r\n<pre>imgProcessed = rescale(img,0,1);\r\n\r\nmeanIm = [0.485 0.456 0.406];\r\nstdIm = [0.229 0.224 0.225];\r\nimgProcessed = (imgProcessed - reshape(meanIm,[1 1 3])).\/reshape(stdIm,[1 1 3]);\r\n<\/pre>\r\n<h6><\/h6>\r\nPermute the image data from the Deep Learning Toolbox dimension ordering (<em>HWCN<\/em>) to the PyTorch dimension ordering (<em>NCHW<\/em>), where <em>H<\/em> is the height of the images, <em>W<\/em> is the width of the images, <em>C<\/em> is the number of channels, and <em>N<\/em> is the number of observations. This is a necessary step to use the image for prediction with a PyTorch model (before importing it into MATLAB).\r\n<h6><\/h6>\r\n<pre>imgForTorch = permute(img,[4 3 1 2]);\r\n<\/pre>\r\n<h6><\/h6>\r\nFor more information on input dimension data ordering for different deep learning platforms, see <a href=\"https:\/\/www.mathworks.com\/help\/deeplearning\/ug\/tips-on-importing-models-from-tensorflow-pytorch-and-onnx.html#mw_ca5d4cba-9c12-4f01-8fe1-6329730c92b2\">Input Dimension Ordering<\/a>.\r\n<h6><\/h6>\r\n<table style=\"height: 70px;\" width=\"600\">\r\n<tbody>\r\n<tr>\r\n<td style=\"padding: 10px; border: 2px solid black; background-color: #e2f0ff;\"><strong>Takeaways:<\/strong>\r\n<ol>\r\n \t<li>Data preprocessing for prediction must match the training data preprocessing.<\/li>\r\n \t<li>Permute the data from MATLAB to PyTorch dimension ordering to use the input data with a PyTorch model.<\/li>\r\n<\/ol>\r\n<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<h6><\/h6>\r\n&nbsp;\r\n<p style=\"font-size: 18px;\"><strong>Install Python and Libraries<\/strong><\/p>\r\nYou might have multiple versions of Python installed on your desktop. For example, a MacBook has a pre-installed Python version 2.7, which is likely not the version you want to use. So, it is good practice to create a virtual environment for your project to be in control of the Python version and libraries that you are using.\r\n<h6><\/h6>\r\nThe following commands show how you can setup a virtual environment on a MacBook. If you are using a Windows machine, the commands might be slightly different.\r\n<h6><\/h6>\r\nGo to your working folder. Create and activate the Python virtual environment <span style=\"font-family: courier;\">env<\/span> in your working folder.\r\n<h6><\/h6>\r\n<pre class=\"brush: python\" style=\"background-color: white;\">python3.10 -m venv env\r\nsource env\/bin\/activate\r\n<\/pre>\r\n<h6><\/h6>\r\nInstall the necessary Python libraries for this example. Check the installed versions of the libraries.\r\n<h6><\/h6>\r\n<pre class=\"brush: python\" style=\"background-color: white;\">pip3 install numpy torch torchvision\r\npython3 -m pip show numpy torch torchvision\r\n<\/pre>\r\n<h6><\/h6>\r\nFor reference, we used:\r\n<ul>\r\n \t<li>Python 3.10.8<\/li>\r\n \t<li>numpy 1.23.4<\/li>\r\n \t<li>torch 1.13.0<\/li>\r\n \t<li>torchvision 1.13.0<\/li>\r\n<\/ul>\r\n<h6><\/h6>\r\nSet up the Python interpreter for MATLAB.\r\n<h6><\/h6>\r\n<pre>pe = pyenv(ExecutionMode=\"OutOfProcess\",Version=\".\/env\/bin\/python3.10\");\r\n<\/pre>\r\n<h6><\/h6>\r\nNow, you are ready to call Python from MATLAB.\r\n<h6><\/h6>\r\n<table style=\"height: 70px;\" width=\"600\">\r\n<tbody>\r\n<tr>\r\n<td style=\"padding: 10px; border: 2px solid black; background-color: #e2f0ff;\"><strong>Takeaways:<\/strong>\r\n<ol>\r\n \t<li>Create a Python virtual environment in your working folder.<\/li>\r\n \t<li>Be aware of Python and library versions.<\/li>\r\n<\/ol>\r\n<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<h6><\/h6>\r\n&nbsp;\r\n<p style=\"font-size: 18px;\"><strong>Explore PyTorch Models<\/strong><\/p>\r\nGet three pretrained PyTorch models (VGG, MobileNet v2, and MNASNet) from the torchvision library. For more information on each model and how to load it, see <a href=\"https:\/\/pytorch.org\/vision\/0.8\/models.html\">torchvision.models<\/a>.\r\n<h6><\/h6>\r\nYou can access Python libraries directly from MATLAB by adding the <span style=\"font-family: courier;\">py.<\/span> prefix to the Python name. For more information on how to access Python libraries, see <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/matlab_external\/create-object-from-python-class.html\">Getting Started: Access Python Modules from MATLAB<\/a>.\r\n<h6><\/h6>\r\n<pre>model1 = py.torchvision.models.vgg16(pretrained=true);\r\nmodel2 = py.torchvision.models.mobilenet_v2(pretrained=true);\r\nmodel3 = py.torchvision.models.mnasnet1_0(pretrained=true);\r\n<\/pre>\r\n<h6><\/h6>\r\nConvert the image to a tensor in order to classify the image with a PyTorch model.\r\n<h6><\/h6>\r\n<pre>X = py.numpy.asarray(imgForTorch);\r\nX_torch = py.torch.from_numpy(X).float();\r\n<\/pre>\r\n<h6><\/h6>\r\nTo find the fastest PyTorch model by calling Python from MATLAB, predict the image classification label multiple times for each of the models. We run the speed test on all models, but we are showing here only how to compute the average speed for the MNASNet model.\r\n<h6><\/h6>\r\n<pre>N = 30;\r\nfor i = 1:N\r\n    tic\r\n    model3(X_torch);\r\n    T(i) = toc;\r\nend\r\nmean(T)\r\n<\/pre>\r\n<h6><\/h6>\r\n<p style=\"font-size: 12px;\"><span style=\"font-family: courier;\">\u00a0 ans = 0.1096<\/span><\/p>\r\n\r\n<h6><\/h6>\r\nThis simple test showed that the fastest model in predicting is MNASNet. You can run different tests on PyTorch models easily and fast with co-execution to find the model that best suits your application and workflow.\r\n<h6><\/h6>\r\nTo import the PyTorch model into MATLAB, you first must trace the model and save it, which you can also do by co-executing Python from MATLAB. Execute Python statements in the Python interpreter directly from MATLAB by using the <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/pyrun.html\"><span style=\"font-family: courier;\">pyrun<\/span><\/a> function. The <span style=\"font-family: courier;\">pyrun<\/span> function is a stateful interface between MATLAB and Python, which saves the state between the two platforms.\r\n<h6><\/h6>\r\nSave the fastest PyTorch model, among the three models compared. Then, trace the model. For more information on how to trace a PyTorch model, see <a href=\"https:\/\/pytorch.org\/docs\/stable\/generated\/torch.jit.trace.html\">Torch documentation: Tracing a function<\/a>.\r\n<h6><\/h6>\r\n<pre>pyrun(\"import torch;X_rnd = torch.rand(1,3,224,224)\")\r\npyrun(\"traced_model = torch.jit.trace(model3.forward,X_rnd)\",model3=model3)\r\npyrun(\"traced_model.save('traced_mnasnet1_0.pt')\")\r\n<\/pre>\r\n<h6><\/h6>\r\n<table style=\"height: 70px;\" width=\"600\">\r\n<tbody>\r\n<tr>\r\n<td style=\"padding: 10px; border: 2px solid black; background-color: #e2f0ff;\"><strong>Takeaways:<\/strong>\r\n<ol>\r\n \t<li>Run comparison tests on open-source models without leaving the MATLAB environment by calling PyTorch from MATLAB (co-execution).<\/li>\r\n \t<li>Access Python libraries by adding the <span style=\"font-family: courier;\">py.<\/span> prefix and execute Python statements by using <span style=\"font-family: courier;\">pyrun<\/span>.<\/li>\r\n \t<li>A co-execution step can be a quick addition to your already established workflow in MATLAB.<\/li>\r\n<\/ol>\r\n<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<h6><\/h6>\r\n&nbsp;\r\n<p style=\"font-size: 18px;\"><strong>Import PyTorch Network<\/strong><\/p>\r\nImport the MNASNet model by using the <a href=\"https:\/\/www.mathworks.com\/help\/deeplearning\/ref\/importnetworkfrompytorch.html\"><span style=\"font-family: courier;\">importNetworkFromPyTorch<\/span><\/a> function.\r\n<h6><\/h6>\r\n<pre>net = importNetworkFromPyTorch(\"traced_mnasnet1_0.pt\");\r\n<\/pre>\r\n<h6><\/h6>\r\nThe <span style=\"font-family: courier;\">importNetworkFromPyTorch<\/span> function was introduced in MATLAB R2022b as part of the <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/111925-deep-learning-toolbox-converter-for-pytorch-models\">Deep Learning Toolbox Converter for PyTorch Models<\/a> support package. For more information, read our previous blog post <a href=\"https:\/\/blogs.mathworks.com\/deep-learning\/2022\/10\/04\/whats-new-in-interoperability-with-tensorflow-and-pytorch\/\">What\u2019s New in Interoperability with TensorFlow and PyTorch<\/a>.\r\n<h6><\/h6>\r\nThe function imports the model as an uninitialized <span style=\"font-family: courier;\">dlnetwork<\/span> object. Create an image input layer. Then, add the image input layer to the imported network and initialize the network by using the <a href=\"https:\/\/www.mathworks.com\/help\/deeplearning\/ref\/dlnetwork.addinputlayer.html\"><span style=\"font-family: courier;\">addInputLayer<\/span><\/a> function.\r\n<h6><\/h6>\r\n<pre>inputLayer = imageInputLayer(InputSize,Normalization=\"none\");\r\nnet = addInputLayer(net,inputLayer,Initialize=true);\r\n<\/pre>\r\n<h6><\/h6>\r\nHere a simple image classification was shown . By converting a PyTorch or TensorFlow model into a MATLAB network, you gain access to all the deep learning workflows that MATLAB supports for building complete AI systems.\r\n<h6><\/h6>\r\nFor more information on working with models imported versus co-execution, see the \u2018Comparison of capabilities for working with deep learning models in MATLAB\u2019 table in our previous blog 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> (Summary section).\r\n<h6><\/h6>\r\n<table style=\"height: 70px;\" width=\"600\">\r\n<tbody>\r\n<tr>\r\n<td style=\"padding: 10px; border: 2px solid black; background-color: #e2f0ff;\"><strong>Takeaways:<\/strong>\r\n<ol>\r\n \t<li>The <span style=\"font-family: courier;\">importNetworkFromPyTorch<\/span> function can import image classification models into MATLAB.<\/li>\r\n \t<li>By importing your model of choice into MATLAB, you can integrate the deep learning model into an AI system.<\/li>\r\n<\/ol>\r\n<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<h6><\/h6>\r\n&nbsp;\r\n<p style=\"font-size: 18px;\"><strong>Conclusion<\/strong><\/p>\r\nKey takeaways were presented for each step of the workflow. If we had to pick the three key takeaways\u2026\r\n<h6><\/h6>\r\n<table style=\"height: 60px;\" width=\"600\">\r\n<tbody>\r\n<tr>\r\n<td style=\"padding: 10px; border: 2px solid black; background-color: #00a9e0;\"><strong>Key Takeaways:<\/strong>\r\n<ol>\r\n \t<li>Co-execution and model import are MATLAB tools that enable MATLAB and PyTorch to be used together.<\/li>\r\n \t<li>Co-execution of MATLAB and PyTorch can be an efficient way to determine which PyTorch model to import.<\/li>\r\n \t<li>Access Python libraries by adding the <span style=\"font-family: courier;\">py.<\/span> prefix and execute Python statements by using <span style=\"font-family: courier;\">pyrun<\/span>.<\/li>\r\n<\/ol>\r\n<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<h6><\/h6>\r\nFor more examples on co-execution between MATLAB, TensorFlow, and PyTorch, check out:\r\n<ul>\r\n \t<li><a href=\"https:\/\/github.com\/matlab-deep-learning\/Image-Classification-in-MATLAB-Using-TensorFlow\">Image Classification in MATLAB Using TensorFlow<\/a><\/li>\r\n \t<li><a href=\"https:\/\/github.com\/matlab-deep-learning\/Hyperparameter-Tuning-in-MATLAB-using-Experiment-Manager-and-TensorFlow\">Hyperparameter Tuning in MATLAB using Experiment Manager &amp; TensorFlow<\/a><\/li>\r\n \t<li><a href=\"https:\/\/github.com\/matlab-deep-learning\/coexecution_speech_command\">PyTorch and TensorFlow Co-Execution for Training a Speech Command Recognition System<\/a><\/li>\r\n<\/ul>\r\nFor our previous blog posts on interoperability between MATLAB, TensorFlow, and PyTorch, check out:\r\n<ul>\r\n \t<li><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><\/li>\r\n \t<li><a href=\"https:\/\/blogs.mathworks.com\/deep-learning\/2022\/10\/04\/whats-new-in-interoperability-with-tensorflow-and-pytorch\/\">What\u2019s New in Interoperability with TensorFlow and PyTorch<\/a><\/li>\r\n<\/ul>\r\n<p style=\"text-align: right; font-size: xx-small; font-weight: lighter; font-style: italic; color: gray;\"><a href=\"https:\/\/github.com\/matlab-deep-learning\/compare-PyTorch-models-from-MATLAB\"><span style=\"font-size: x-small; font-style: italic;\">Get\r\nthe MATLAB code<\/span><\/a><\/p>","protected":false},"excerpt":{"rendered":"<div class=\"overview-image\"><img src=\"https:\/\/blogs.mathworks.com\/deep-learning\/files\/2022\/11\/PyTorch_exploration_thumbnail.png\" class=\"img-responsive attachment-post-thumbnail size-post-thumbnail wp-post-image\" alt=\"\" decoding=\"async\" loading=\"lazy\" \/><\/div><p>The following post is from Sivylla Paraskevopoulou, Product Marketing Manager at MathWorks, and Yann Debray, Product Manager at MathWorks.\r\n\r\nThis blog post talks about how MATLAB, PyTorch\u00ae, and... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/deep-learning\/2022\/12\/12\/quickly-investigate-pytorch-models-from-matlab\/\">read more >><\/a><\/p>","protected":false},"author":194,"featured_media":11082,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[9,39,45],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/posts\/10794"}],"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\/194"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/comments?post=10794"}],"version-history":[{"count":125,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/posts\/10794\/revisions"}],"predecessor-version":[{"id":14022,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/posts\/10794\/revisions\/14022"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/media\/11082"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/media?parent=10794"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/categories?post=10794"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/deep-learning\/wp-json\/wp\/v2\/tags?post=10794"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}