<?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 Yu Xuan Lee on Medium]]></title>
        <description><![CDATA[Stories by Yu Xuan Lee on Medium]]></description>
        <link>https://medium.com/@yxlee245?source=rss-98936f4f3a19------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0WQ1ipF9Bq3C0mEBPkijVQ.jpeg</url>
            <title>Stories by Yu Xuan Lee on Medium</title>
            <link>https://medium.com/@yxlee245?source=rss-98936f4f3a19------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:38:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yxlee245/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[Converting a Deep Learning Model with Multiple Outputs from PyTorch to TensorFlow]]></title>
            <link>https://medium.com/data-science/converting-a-deep-learning-model-with-multiple-outputs-from-pytorch-to-tensorflow-a2d27a8e44f4?source=rss-98936f4f3a19------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2d27a8e44f4</guid>
            <category><![CDATA[onnx]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Yu Xuan Lee]]></dc:creator>
            <pubDate>Sun, 18 Aug 2019 00:41:28 GMT</pubDate>
            <atom:updated>2019-12-18T11:49:12.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2e1yZyThky_exbt-fld49w.jpeg" /><figcaption>Reference: <a href="https://i.stack.imgur.com/4YBht.jpg">https://i.stack.imgur.com/4YBht.jpg</a></figcaption></figure><p><strong>Introduction</strong></p><p>Some time back, I wrote an <a href="https://towardsdatascience.com/converting-a-simple-deep-learning-model-from-pytorch-to-tensorflow-b6b353351f5d">article</a> describing how you could convert a simple deep learning model from PyTorch to TensorFlow using ONNX. Although this is applicable to many use cases, there are situations where you would need to convert a model with multiple outputs (e.g. object detection models). Here I would like to show how you could convert a model with multiple outputs from PyTorch to TensorFlow.</p><p>Many of the parts of the whole conversion process is a repetition of what I have mentioned in my previous article, so I will only mention the parts which are added or modified for the conversion of a model with multiple outputs.</p><p><strong>Generating and preparing the data</strong></p><p>The main difference in the data is that there are now 2 different sets of actual outputs, 1 as a continuous variable and the other in binary form. Also, I defined two functions to generate two different types of outputs for the data. The snippet below illustrates the process of generating the data and preparing them for model training and evaluation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1f3ead6164e64050b7f9ad8e48e79ac/href">https://medium.com/media/e1f3ead6164e64050b7f9ad8e48e79ac/href</a></iframe><p><strong>Defining, training and evaluating the example model</strong></p><p>The Model class defined is pretty similar to that in the previous article, except that the <em>forward()</em> method returns two output tensors instead of one. Two different kinds of loss objects are also defined for the outputs, with mean squared error loss for the continuous output and the binary cross-entropy loss for the binary output. The snippet below shows how the model, losses, and optimizer are defined.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd608a9f381280cc107f66c973f3f683/href">https://medium.com/media/bd608a9f381280cc107f66c973f3f683/href</a></iframe><p>The training and evaluation process is also similar, except that the losses have to be computed for both outputs and added together before performing backpropagation and model weight updates. The snippet below contains the process to train and evaluate the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20aabef00f46e28d84bb4f1171e4347a/href">https://medium.com/media/20aabef00f46e28d84bb4f1171e4347a/href</a></iframe><p><strong>Converting the model to TensorFlow</strong></p><p>Exporting the model to <em>.onnx</em> format is also quite similar, just that different names should be assigned to the output heads. In this example, the names ‘output1’ and ‘output2’ are assigned to the two output heads, as shown in the snippet below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8b4456c89a176d84244f52075bb9fd4/href">https://medium.com/media/a8b4456c89a176d84244f52075bb9fd4/href</a></iframe><p><strong>Doing inference in TensorFlow</strong></p><p>The inference step in TensorFlow is similar as per the previous article as well, with some minor changes to get two outputs instead of one, as shown below. The placeholder names for the input and outputs can be found in the same way as mentioned in my <a href="https://towardsdatascience.com/converting-a-simple-deep-learning-model-from-pytorch-to-tensorflow-b6b353351f5d">previous article</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa6bd148c1e033c76728e202404eca6c/href">https://medium.com/media/aa6bd148c1e033c76728e202404eca6c/href</a></iframe><p>If all goes well, the results of <em>print(‘output1:’, output1) </em>and<em> print(‘output2:’, output2) </em>should match that of <em>print(‘dummy_output_1:’, dummy_output_1) </em>and<em> print(‘dummy_output_1:’, dummy_output_1) </em>in the earlier step.</p><p><strong>Conclusion</strong></p><p>Converting a model with multiple outputs from PyTorch to TensorFlow can be a bit more challenging than doing the same process for a simple model with a single output, but can still be done. I hope this article has given you a bit more confidence in using ONNX to convert more complex models.</p><p>The Jupyter notebook containing all the codes can be found <a href="https://github.com/yxlee245/pytorch2tf/blob/master/PyTorch2TF_Multiple_Output.ipynb">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2d27a8e44f4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/converting-a-deep-learning-model-with-multiple-outputs-from-pytorch-to-tensorflow-a2d27a8e44f4">Converting a Deep Learning Model with Multiple Outputs from PyTorch to TensorFlow</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting a Simple Deep Learning Model from PyTorch to TensorFlow]]></title>
            <link>https://medium.com/data-science/converting-a-simple-deep-learning-model-from-pytorch-to-tensorflow-b6b353351f5d?source=rss-98936f4f3a19------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6b353351f5d</guid>
            <category><![CDATA[onnx]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Yu Xuan Lee]]></dc:creator>
            <pubDate>Wed, 22 May 2019 22:25:04 GMT</pubDate>
            <atom:updated>2019-12-18T11:47:16.257Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3fA77_mLNiJTSgZFhYnU0Q.png" /><figcaption>Reference: <a href="https://towardsdatascience.com/applied-deep-learning-part-1-artificial-neural-networks-d7834f67a4f6">https://towardsdatascience.com/applied-deep-learning-part-1-artificial-neural-networks-d7834f67a4f6</a></figcaption></figure><p><strong>Introduction</strong></p><p>TensorFlow and PyTorch are two of the more popular frameworks out there for deep learning. There are people who prefer TensorFlow for support in terms of deployment, and there are those who prefer PyTorch because of the flexibility in model building and training without the difficulties faced in using TensorFlow. The downside of using PyTorch is that the model built and trained using this framework cannot be deployed into production. (Update in Dec 2019: It is claimed that later versions of PyTorch have better support for deployment, but I believe that is something else to be explored.) To address the issue of deploying models built using PyTorch, one solution is to use ONNX (Open Neural Network Exchange).</p><p>As explained in ONNX’s <a href="https://onnx.ai/about">About page</a>, ONNX is like a bridge that links the various deep learning frameworks together. To this end, the ONNX tool enables the conversion of models from one framework to another. Up to the time of this writing, ONNX is limited to simpler model structures, but there may be further additions later on. This article will illustrate how a simple deep learning model can be converted from PyTorch to TensorFlow.</p><p><strong>Installing the necessary packages</strong></p><p>To start off, we would need to install PyTorch, TensorFlow, ONNX, and ONNX-TF (the package to convert ONNX models to TensorFlow). If using <em>virtualenv</em> in Linux, you could run the command below (replace <em>tensorflow</em> with <em>tensorflow-gpu</em> if you have NVidia CUDA installed). Do note that as of Dec 2019, ONNX does not work with TensorFlow 2.0 yet, so please take note of the version of the TensorFlow that you install.</p><pre>source &lt;your virtual environment&gt;/bin/activate<br>pip install tensorflow==1.15.0</pre><pre># For PyTorch, choose one of the following (refer to <a href="https://pytorch.org/get-started/locally/">https://pytorch.org/get-started/locally/</a> for further details)<br>pip install torch torchvision # if using CUDA 10.1<br>pip install torch==1.3.1+cu92 torchvision==0.4.2+cu92 -f <a href="https://download.pytorch.org/whl/torch_stable.html">https://download.pytorch.org/whl/torch_stable.html</a> # if using CUDA 9.2<br>pip install torch==1.3.1+cpu torchvision==0.4.2+cpu -f <a href="https://download.pytorch.org/whl/torch_stable.html">https://download.pytorch.org/whl/torch_stable.html</a> # if using CPU only</pre><pre>pip install onnx</pre><pre># For onnx-tensorflow, you may want to refer to the installation guide here: <a href="https://github.com/onnx/onnx-tensorflow">https://github.com/onnx/onnx-tensorflow</a><br>git clone <a href="https://github.com/onnx/onnx-tensorflow.git">https://github.com/onnx/onnx-tensorflow.git</a><br>cd onnx-tensorflow<br>pip install -e ..</pre><p>If using Conda, you may want to run the following commands instead:</p><pre>conda activte &lt;your virtual environment&gt;<br>conda install -c pytorch pytorch</pre><pre>pip install tensorflow==1.15.0</pre><pre>pip install onnx</pre><pre># For onnx-tensorflow, you may want to refer to the installation guide here: <a href="https://github.com/onnx/onnx-tensorflow">https://github.com/onnx/onnx-tensorflow</a><br>git clone <a href="https://github.com/onnx/onnx-tensorflow.git">https://github.com/onnx/onnx-tensorflow.git</a><br>cd onnx-tensorflow<br>pip install -e ..</pre><p>I find that installing TensorFlow, ONNX, and ONNX-TF using pip will ensure that the packages are compatible with one another. It is OK, however, to use other ways of installing the packages, as long as they work properly in your machine.</p><p>To test that the packages have been installed correctly, you can run the following commands:</p><pre>python<br>import tensorflow as tf<br>import torch<br>import onnx<br>from onnx_tf.backend import prepare</pre><p>If you do not see any error messages, it means that the packages are installed correctly, and we are good to go.</p><p>In this example, I used Jupyter Notebook, but the conversion can also be done in a .py file. To install Jupyter Notebook, you can run one of the following commands:</p><pre># Installing Jupyter Notebook via pip<br>pip install notebook</pre><pre># Installing Jupyter Notebook via Conda<br>conda install notebook</pre><p><strong>Building, training, and evaluating the example model</strong></p><p>The next thing to do is to obtain a model in PyTorch that can be used for the conversion. In this example, I generated some simulated data, and use this data for training and evaluating a simple Multilayer Perceptron (MLP) model. The following snippet shows how the installed packages are imported, and how I generated and prepared the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d09057f6a6ef72222e0c68c757451188/href">https://medium.com/media/d09057f6a6ef72222e0c68c757451188/href</a></iframe><p>I then created a class for the simple MLP model and defined the layers such that we can specify any number and size of hidden layers. I also defined a binary cross-entropy loss and Adam optimizer to be used for the computation of loss and weight updates during training. The following snippet shows this process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91631314e8e520f1c0aff478fe939c4c/href">https://medium.com/media/91631314e8e520f1c0aff478fe939c4c/href</a></iframe><p>After building the model and defining the loss and optimizer, I trained the model for 20 epochs using the generated training set, then used the test set for evaluation. The test loss and accuracy of the model was not good, but that does not really matter here, as the main purpose here is to show how to convert a PyTorch model to TensorFlow. The snippet below shows the training and evaluation process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6126bbeef5c0efb2480925b836f18db/href">https://medium.com/media/d6126bbeef5c0efb2480925b836f18db/href</a></iframe><p>After training and evaluating the model, we would need to save the model, as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ccea0b181f34f89bd6468508561039a/href">https://medium.com/media/0ccea0b181f34f89bd6468508561039a/href</a></iframe><p><strong>Converting the model to TensorFlow</strong></p><p>Now, we need to convert the <em>.pt</em> file to a <em>.onnx</em> file using the <em>torch.onnx.export</em> function. There are two things we need to take note here: 1) we need to define a dummy input as one of the inputs for the export function, and 2) the dummy input needs to have the shape (1, dimension(s) of single input). For example, if the single input is an image array with the shape (number of channels, height, width), then the dummy input needs to have the shape (1, number of channels, height, width). The dummy input is needed as an input placeholder for the resulting TensorFlow model). The following snippet shows the process of exporting the PyTorch model in the ONNX format. I included the input and output names as arguments as well to make it easier for inference in TensorFlow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd05f843619d0b971271237221f44ee2/href">https://medium.com/media/fd05f843619d0b971271237221f44ee2/href</a></iframe><p>After getting the <em>.onnx</em> file, we would need to use the <em>prepare()</em> function in ONNX-TF’s <em>backend</em> module to convert the model from ONNX to TensorFlow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec9dbcac92248af3cc318aa8d3989a6f/href">https://medium.com/media/ec9dbcac92248af3cc318aa8d3989a6f/href</a></iframe><p><strong>Doing inference in TensorFlow</strong></p><p>Here comes the fun part, which is to see if the resultant TensorFlow model can do inference as intended. Loading a TensorFlow model from a <em>.pb</em> file can be done by defining the following function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fbc7aa8a86c38d597909499a3c59cba/href">https://medium.com/media/8fbc7aa8a86c38d597909499a3c59cba/href</a></iframe><p>With the function to load the model defined, we need to start a TensorFlow graph session, specify the placeholders for the input and output, and feed an input into the session.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0257de3b32cb54e7b6d4667962428c5d/href">https://medium.com/media/0257de3b32cb54e7b6d4667962428c5d/href</a></iframe><p>The output of the snippet above would look like below. The names of the placeholders correspond to those specified in the torch.onnx.export function (indicated in bold).</p><pre>(&lt;tf.Tensor &#39;Const:0&#39; shape=(50,) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;Const_1:0&#39; shape=(50, 20) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;Const_2:0&#39; shape=(50,) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;Const_3:0&#39; shape=(50, 50) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;Const_4:0&#39; shape=(1,) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;Const_5:0&#39; shape=(1, 50) dtype=float32&gt;,)<br>(<strong>&lt;tf.Tensor &#39;input:0&#39; shape=(1, 20) dtype=float32&gt;,)</strong><br>(&lt;tf.Tensor &#39;flatten/Reshape/shape:0&#39; shape=(2,) dtype=int32&gt;,)<br>(&lt;tf.Tensor &#39;flatten/Reshape:0&#39; shape=(1, 20) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;transpose/perm:0&#39; shape=(2,) dtype=int32&gt;,)<br>(&lt;tf.Tensor &#39;transpose:0&#39; shape=(20, 50) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;MatMul:0&#39; shape=(1, 50) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;mul/x:0&#39; shape=() dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;mul:0&#39; shape=(1, 50) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;mul_1/x:0&#39; shape=() dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;mul_1:0&#39; shape=(50,) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;add:0&#39; shape=(1, 50) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;Relu:0&#39; shape=(1, 50) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;flatten_1/Reshape/shape:0&#39; shape=(2,) dtype=int32&gt;,)<br>(&lt;tf.Tensor &#39;flatten_1/Reshape:0&#39; shape=(1, 50) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;transpose_1/perm:0&#39; shape=(2,) dtype=int32&gt;,)<br>(&lt;tf.Tensor &#39;transpose_1:0&#39; shape=(50, 50) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;MatMul_1:0&#39; shape=(1, 50) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;mul_2/x:0&#39; shape=() dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;mul_2:0&#39; shape=(1, 50) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;mul_3/x:0&#39; shape=() dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;mul_3:0&#39; shape=(50,) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;add_1:0&#39; shape=(1, 50) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;Relu_1:0&#39; shape=(1, 50) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;flatten_2/Reshape/shape:0&#39; shape=(2,) dtype=int32&gt;,)<br>(&lt;tf.Tensor &#39;flatten_2/Reshape:0&#39; shape=(1, 50) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;transpose_2/perm:0&#39; shape=(2,) dtype=int32&gt;,)<br>(&lt;tf.Tensor &#39;transpose_2:0&#39; shape=(50, 1) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;MatMul_2:0&#39; shape=(1, 1) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;mul_4/x:0&#39; shape=() dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;mul_4:0&#39; shape=(1, 1) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;mul_5/x:0&#39; shape=() dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;mul_5:0&#39; shape=(1,) dtype=float32&gt;,)<br>(&lt;tf.Tensor &#39;add_2:0&#39; shape=(1, 1) dtype=float32&gt;,)<br><strong>(&lt;tf.Tensor &#39;output:0&#39; shape=(1, 1) dtype=float32&gt;,)</strong></pre><p>If all goes well, the result of <em>print(output) </em>should match that of <em>print(dummy_output)</em> in the earlier step.</p><p><strong>Conclusion</strong></p><p>ONNX can be pretty straightforward, provided that your model is not too complicated. The steps in this example would work for deep learning models with single input and output. For models with multiple inputs and/or outputs, it would be more challenging to convert them via ONNX. As such, an example to convert multiple input/output models would have to be done in another article, unless there are new versions of ONNX later on that can handle such models.</p><p>The Jupyter notebook containing all the codes can be found <a href="https://github.com/yxlee245/pytorch2tf/blob/master/PyTorch2TF_Simple.ipynb">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6b353351f5d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/converting-a-simple-deep-learning-model-from-pytorch-to-tensorflow-b6b353351f5d">Converting a Simple Deep Learning Model from PyTorch to TensorFlow</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Neural Network Model Using TensorFlow Eager Execution]]></title>
            <link>https://medium.com/data-science/simple-neural-network-model-using-tensorflow-eager-execution-997bbadef84a?source=rss-98936f4f3a19------2</link>
            <guid isPermaLink="false">https://medium.com/p/997bbadef84a</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[eager-execution]]></category>
            <dc:creator><![CDATA[Yu Xuan Lee]]></dc:creator>
            <pubDate>Wed, 08 May 2019 17:00:36 GMT</pubDate>
            <atom:updated>2019-05-12T13:09:51.459Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*qZXo39Qw2pzxLH3-IW5l6w.png" /><figcaption>Reference: <a href="https://colab.research.google.com/github/zaidalyafeai/Notebooks/blob/master/Eager_Execution_Enabled.ipynb">https://colab.research.google.com/github/zaidalyafeai/Notebooks/blob/master/Eager_Execution_Enabled.ipynb</a></figcaption></figure><p><strong>Introduction</strong></p><p>Eager Execution is a nifty approach in TensorFlow (TF) to build deep learning models from scratch. It allows you to build prototype models without the hassles that come with the graphical approach that TF uses conventionally.</p><p>For example, with Eager Execution, there is no need to start a graph session in order to perform tensor computations. This means faster debugging, as you could check each line of computation on-the-fly without needing to wrap the computation in a graph session.</p><p>As a disclaimer, however, using Eager Execution requires some knowledge on the matrix algebra concepts used in deep learning, particularly on how forward passes are done in a neural network. If you are looking for something more high-level and ready for use, I would advise using the Keras API in TF or PyTorch instead.</p><p>This article will provide an example of how Eager Execution can be used, by describing the procedure to build, train and evaluate a simple Multilayer Perceptron.</p><p><strong>Architecture and Notations</strong></p><p>The neural network built in this example consists of an input layer, one hidden layer, and an output layer. The input layer contains 3 nodes, the hidden layer 20 nodes, and the output layer has 1 node. The output value is continuous (i.e. the neural network performs regression).</p><p>The values of the input, hidden and output layers, as well as the weights between the layers, can be expressed as matrices. The biases to the hidden and output layers can be expressed as vectors (a special case of matrices with one row or column). The image below shows the dimensions for each of the matrices and vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2eI1b3lRB3K-bOVE32n9jQ.png" /><figcaption>Notations and dimensions for matrices and vectors</figcaption></figure><p><strong>Beginning Eager Execution</strong></p><p>After importing the dependencies needed for this example (mainly NumPy and TF), you would need to enable Eager Execution if you are not using TF 2.0. The code snippet below shows how Eager Execution can be enabled.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18fbaac56d3b455ee27e8b18e54df81f/href">https://medium.com/media/18fbaac56d3b455ee27e8b18e54df81f/href</a></iframe><p><strong>Preparing the Data for Training and Evaluation</strong></p><p>The next step is to randomly generate some data for use in training and evaluation (for illustration purposes of course), by using NumPy’s random module. With this approach, I created two separate sets of data, one for training and the other for evaluation.</p><p>Each set of data contained 1 input array and 1 output array. The input array was in the shape (number of observations, number of features), while the output array was in the shape (number of observations, number of output values per observation). The number of features corresponds to the number of nodes in the input layer, while the number of output values per observation corresponds to the number of nodes in the output layer.</p><p>After generating the data, I split the test data into batches, for more efficient evaluation. The train data will also be split into batches, but done during the training process itself.</p><p>The snippet below shows how I prepared the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdf168501fd3f96d9c06b61b89a1b935/href">https://medium.com/media/cdf168501fd3f96d9c06b61b89a1b935/href</a></iframe><p><strong>Building the Model</strong></p><p>What I did here was to create a Python class that stores the codes responsible for weight and bias initialization, forward pass, backpropagation and updates to weights and biases.</p><p>The weights and biases were initialized by sampling random values from a standard normal distribution. Random initialization of weights is typically preferred over initializing the weights with the value 0 or 1, in order to reduce the chance of getting issues such as vanishing gradients.</p><p>The forward pass can be described by the following equations. The relu() represents the Rectified Linear Unit function, which transforms the linear combination of inputs and biases in a non-linear way. There is no transform function for the equation of the output Y, as a continuous value is expected as the output. As a side note, a non-linear transform function such as sigmoid or softmax would be needed in the second equation if the output is expected to be categorical.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/0*NeCLtm7vRG7Ta2Cd.png" /><figcaption>Matrix algebra for the forward pass</figcaption></figure><p>The backpropagation of loss and updates of weights and biases are taken care with a few lines of codes (in the loss() and backward() methods of the model class respectively).</p><p>The rather long snippet below shows how the model building process can be implemented in a class. The additional compute_output() method is a wrapper over the forward pass algorithm, to facilitate the user in terms of selection of hardware device (CPU or GPU) for model training and evaluation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bff7028df44475499354c6f6001bb643/href">https://medium.com/media/bff7028df44475499354c6f6001bb643/href</a></iframe><p>You may have noticed the function tf.cast() used in the class. Reason being, there is this weird error that is triggered because the from_tensor_slices() method from the earlier snippet returns tensors in the tf.float64 data format, but the matrix operations (e.g. tf.matmul()) can only handle tensors in the tf.float32 data format. I have not tried doing Eager Execution on TF 2.0, so I am not sure if this issue has already been addressed in this new version. What I do know is that this issue of data format definitely occurs in the version of TF that I used for this example (i.e. 1.31.1), so this is something to take note of if using Eager Execution on older versions of TF.</p><p><strong>Training the Model</strong></p><p>After preparing the data and building the model, the next step is to train the model. Model training is pretty simple, with only a few lines of codes needed. The basic idea here is to repeat the following for each batch of data for every epoch: feed the input tensor through the model to get the prediction tensor, compute the loss, backpropagate the loss, and update the weights and biases. During every epoch, the training data will be split randomly into different batches, to increase the computational efficiency of model training and help the model generalize better. The following snippet illustrates how training can be done with Eager Execution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf89583c22e7a345b6d420ed2ab64a50/href">https://medium.com/media/cf89583c22e7a345b6d420ed2ab64a50/href</a></iframe><p><strong>Evaluating the Model</strong></p><p>The final step is to evaluate the model using the test set. The codes to do that are similar to that of training but without the backpropagation and updates of weights and biases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/117b202eff10c37b0a0c29e280fb95f1/href">https://medium.com/media/117b202eff10c37b0a0c29e280fb95f1/href</a></iframe><p><strong>Conclusion</strong></p><p>While Eager Execution is pretty straightforward to use, I would like to emphasize again that it is a low-level approach. I would advise against using Eager Execution, unless: 1) you are doing work that requires you to build a deep learning model from scratch (e.g. research/academic work on deep learning models), 2) you are trying to understand the mathematical stuff that is going on behind deep learning, or 3) you just like to build things from scratch.</p><p>Having said that though, I think Eager Execution is a pretty good approach in terms of helping you understand a bit better on what actually happens when we do deep learning, without having to juggle with complicated graphs or the other confusing stuff that come with the conventional TF approach.</p><p>The Google Colab notebook that I created for this example can be found <a href="https://colab.research.google.com/drive/1b16hdW6yjyVRGaxxfTPtEGG6x1pkdnmA">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=997bbadef84a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/simple-neural-network-model-using-tensorflow-eager-execution-997bbadef84a">Simple Neural Network Model Using TensorFlow Eager Execution</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Detection for Product Images by Shopee]]></title>
            <link>https://medium.com/@yxlee245/object-detection-for-product-images-by-shopee-fbaa640e5de0?source=rss-98936f4f3a19------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbaa640e5de0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[Yu Xuan Lee]]></dc:creator>
            <pubDate>Thu, 18 Apr 2019 19:09:01 GMT</pubDate>
            <atom:updated>2019-04-18T19:12:27.539Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Background Story</strong></p><p>Recently, I participated in the National Data Science Challenge (NDSC) 2019 by Shopee, together with 3 of my colleagues (one of them recently published his Medium article <a href="https://medium.com/@john.ang.rs/dear-business-managers-your-data-is-not-ready-for-machine-learning-heres-how-to-fix-it-149a558767ff">here</a>). We were in the Advanced Category of the competition, which required us to predict the attributes of products in three categories (namely beauty, fashion, and mobile) based on inputs such as product titles and images given in the dataset by Shopee. As my interest is more towards computer vision (CV), I concentrated more on working with the product images.</p><p><strong>The Motivation behind Object Detection</strong></p><p>While I was doing the standard data exploration, I noticed that the product images contained a significant amount of noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*lR0yOxGCqf1Dgia2wPJI6g.jpeg" /><figcaption>Example of product image with noise</figcaption></figure><p>As seen in the example above, the image shows not only the product but also irrelevant things (e.g. people, words). This causes a naive CV model (e.g. a Convolutional Neural Network model) to mistake such irrelevant stuff as features of the product.</p><p>Why is it undesirable for the CV model to treat people, words, etc as features? As a simple example, let’s say we have a set of training images where images for fashion product A contain European models and images for fashion product B contain Asian models (no offense intended towards any group of people). If a naive CV model trained on such a training set comes across a new image of product A containing an Asian model, it may think that the image shows product B and vice versa. This is because the model has mistakenly associated the product with the race of the person in the image, rather than the actual features of the product (color, shape, etc).</p><p>As such, there is a need to somehow separate the relevant object (i.e. the product itself) among all the irrelevant the stuff. Describing this in a more technical way, there is a need to improve the <em>signal-to-noise ratio</em> of the images before feeding them to a CV model for training. <em>Object detection</em> is one of the possible methods for performing this job.</p><p><strong>The Object Detection Model</strong></p><p>The model architecture that I applied for object detection was the SSD300 model. SSD is the abbreviation for <em>Single Shot Detector</em>, which is a type of object detection model, while 300 indicates that the required dimension of the input images is 300 pixels x 300 pixels. I came across <a href="https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Object-Detection">this repository by Github user sgrvinod</a>, which gives a detailed and useful explanation on how the SSD300 works and also contains the codes for implementing the SSD300 in PyTorch. As such, I would not go into details of how the whole model works.</p><p>In terms of the training and evaluation dataset for the SSD300, I sampled 500 images from each of the 3 categories and created XML files containing <em>annotations</em> in the <em>Pascal Visual Object Classes (VOC) format</em>. The VOC format is commonly used for training and validation data for various object detection models, the SSD300 being one of them. The code snippet below is an example of how an annotation in VOC format looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6ec62d067fbf07bf35b53217f23aa01/href">https://medium.com/media/c6ec62d067fbf07bf35b53217f23aa01/href</a></iframe><p>Thanks to the help from some of my colleagues, I found a <a href="https://github.com/tzutalin/labelImg">tool that helps me create the annotations very quickly and easily</a>. With this software, I managed to annotate around 1,000 images within 8 hours (The typical amount of time I spend at work each day).</p><p>The annotation file contains information like the image path, image size, as well as the label(s) and corner coordinates of the bounding box(es). Codes in Python, such as <a href="https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Object-Detection">those by sgrvinod</a>, can be written to extract the relevant information from the XML file via packages (e.g. the built-in ElementTree XML API).</p><p>I made some modifications to modularize the processes of <em>training</em>, <em>evaluation</em>, and <em>detection</em>, as well as to load in my own images and annotations rather than the dataset used by sgrvinod. The modified codes can be found in <a href="https://github.com/yxlee245/ndsc-2019">my Github repository for NDSC 2019</a>.</p><p>One SSD300 model was trained for each of the 3 product categories, as the products from each category have very different characteristics from those in the other categories. For each category, the corresponding dataset was <em>bootstrapped </em>(<em>sampled with replacement</em>) to obtain a larger amount of <em>out-of-bag validation data</em> while keeping the training dataset size constant. To prevent overfitting, the training dataset is put through <em>data augmentation</em> (random transformations on image to “create” new images) during the training phase.</p><p><strong>Results</strong></p><p>After some training and evaluation, I fed one image per category from the validation set to get a sense of how the object detection model proposes bounding box(es) and predicts the class of the object within each bounding box. The images with their proposed bounding boxes are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*JRxbCBXCBr9uYZHgNnh4nA.png" /><figcaption>Example of object detection for beauty product</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*kDk24DDUJTSLtf25i8T3rQ.png" /><figcaption>Example of object detection for fashion product</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*WfJPgZf3mPcuXHj0X6fegQ.png" /><figcaption>Example of object detection for mobile product</figcaption></figure><p>In terms of the evaluation metrics:</p><ol><li><em>Multibox Loss</em> (a combination of <em>regression loss</em> for bounding box corner coordinates and <em>classification loss</em> for the class within the bounding box): The multibox loss was the lowest for the SSD300 for fashion products (at 1.527), followed by 2.607 for mobile products and 3.173 for beauty products.</li><li><em>Average Precision</em>: The average precision was the highest for the SSD300 for fashion products (at 0.90), followed by 0.83 for mobile products and 0.75 for beauty products.</li></ol><p>The object detection model for fashion products seems to work the best, probably because fashion products (primarily clothing) are pretty much the same in terms of general shape. In contrast to this, beauty products (e.g. cosmetics, toiletries) come in all shapes and sizes, so it can be tougher for an object detection model to tell if one or more beauty products exist in an image. Nevertheless, the SSD300 models seem to work pretty well in the task of object detection, given that the amount of time needed to train these models is relatively short.</p><p><strong>Ending the Story</strong></p><p>Although my team didn’t win the top few prizes, NDSC 2019 was really memorable, at least for me. Through this competition, I realized that there was still much for me to learn in the field of machine learning. I also stepped out of my comfort zone by building CNN models in PyTorch (I used Keras prior to this competition). If there was any reward I got out of all this, it would be having object detection models that work surprisingly well with a small training set, and this reward is good enough for me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbaa640e5de0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>