<?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 Tijmen Verhulsdonck on Medium]]></title>
        <description><![CDATA[Stories by Tijmen Verhulsdonck on Medium]]></description>
        <link>https://medium.com/@tijmenlv?source=rss-b2c086e7a2cc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IaSZJnuGBjSm7mkn7WFQHg.jpeg</url>
            <title>Stories by Tijmen Verhulsdonck on Medium</title>
            <link>https://medium.com/@tijmenlv?source=rss-b2c086e7a2cc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:55:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tijmenlv/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[Setting up ML-Agents on linux]]></title>
            <link>https://medium.com/@tijmenlv/setting-up-ml-agents-on-linux-82972c353ad7?source=rss-b2c086e7a2cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/82972c353ad7</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Tijmen Verhulsdonck]]></dc:creator>
            <pubDate>Wed, 15 Aug 2018 10:32:12 GMT</pubDate>
            <atom:updated>2018-08-19T14:08:41.378Z</atom:updated>
            <content:encoded><![CDATA[<p>This will be a quick story on how to install the ML-agent environment and run the 3DBall example of the unity ML-agents <a href="https://github.com/Unity-Technologies/ml-agents/">github repo</a>. I wanted to start trying my hands at reinforcement learning and figured the ML-agents repo of Unity was a good place to start.</p><p>The installation <a href="https://github.com/Unity-Technologies/ml-agents/blob/master/docs/Installation.md">guide</a> is pretty clear and well done, but it only goes into depth on how to set everything up on Windows or OSX. I personally don’t have an OSX machine capable of any kind of serious machine learning and Tensorflow <a href="https://www.tensorflow.org/install/install_mac">no longer</a> supports GPU accelerated training on mac. I also don’t really want to setup and maintain a development environment on Windows. No, my preference is to use Linux to do machine learning experiments but unfortunately the ML-Agents installation guide does not really explain how to set this up. I did manage to get it working in the end and it wasn’t too much of a hassle but I hope maybe I can save someone else some time.</p><p>Note: The Linux version I use is Ubuntu 16.04 your mileage on other versions may vary.</p><h4>Step 1: Install Unity</h4><p>Unity is not yet fully supported and functional on Linux but a Beta version already exists which has all the functionality needed to experiment with ML-Agents. To install unity on Ubuntu download the latest version of the linux download assistant from <a href="https://forum.unity.com/threads/unity-on-linux-release-notes-and-known-issues.350256/page-2">here</a> (just go to the last post on the last page). Once that finishes downloading open terminal and navigate to the Downloads directory. Once there run the following command (you might need to adjust the filename to the specific version you downloaded):</p><pre>sudo chmod +x UnitySetup-2018.2.3f1</pre><p>After that a simple execution of the file will start the installer:</p><pre>./UnitySetup-2018.2.3f1</pre><p>At this point just follow the steps in the installer, I found I didn’t need to change anything and could just keep pressing forward.</p><h4>Step 2: Setup ML-agents</h4><p>Setting up the ml-agents repo is pretty simple, clone the git repo using the following command:</p><pre>git clone https://github.com/Unity-Technologies/ml-agents.git</pre><p>And then navigate to the python folder inside the cloned repo and using Python 3.5 or 3.6 run the following command:</p><pre>pip3 install .</pre><h4>Step 3: Run the example</h4><p>At this point everything is setup and we can follow the steps in the <a href="https://github.com/Unity-Technologies/ml-agents/blob/master/docs/Basic-Guide.md">basic guide</a>, the first problem however is that using the pretrained model with the Tensorflow Sharp plugin the editor crashes. I am not sure exactly why this happens but you don’t need it as you can do training and inference using the python interface. Skipping the pretrained model the following steps should result in a model being trained with Tensorflow. Keep in mind these steps are pretty much directly copied from <a href="https://github.com/Unity-Technologies/ml-agents/blob/master/docs/Basic-Guide.md">here</a> so if you get stuck maybe look over there as they did a slightly more elaborate explanation with supporting pictures.</p><ol><li>Launch Unity</li><li>On the Projects dialog, choose the Open option at the top of the window.</li><li>Using the file dialog that opens, locate the unity-environment folder within the the ML-Agents toolkit project and click Open.</li><li>Go to Edit &gt; Project Settings &gt; Player</li><li>For each of the platforms you target (PC, Mac and Linux Standalone, iOS or Android):</li><li>Option the Other Settings section.</li><li>Select Scripting Runtime Version to Experimental (.NET 4.6 Equivalent or .NET 4.x Equivalent)</li><li>In Scripting Defined Symbols, add the flag ENABLE_TENSORFLOW. After typing in the flag name, press Enter.</li><li>Go to File &gt; Save Project</li><li>In the Project window, go to Assets/ML-Agents/Examples/3DBall folder and open the 3DBall scene file.</li><li>In the Hierarchy window, select the Ball3DBrain child under the Ball3DAcademy GameObject to view its properties in the Inspector window.</li><li>On the Ball3DBrain object’s Brain component, change the Brain Type to <strong>External</strong>.</li><li>Open a command or terminal window.</li><li>Nagivate to the folder where you installed the ML-Agents toolkit.</li><li>Change to the python directory.</li><li>Run python3 learn.py --run-id=&quot;test&quot; --train</li><li>When the message <em>“Start training by pressing the Play button in the Unity Editor”</em> is displayed on the screen, you can press the play button in Unity to start training in the Editor.</li></ol><p>At this point you should see a bunch of platforms moving very erratically in the editor and slowly get better at balancing a ball on them. If that is the case then success! Now you can start experimenting with reinforcement learning.</p><p>Note: When using the external brain I find that the main camera frame is no longer centered in the window (only bottom right corner visible). By switching the layout using <strong>window-&gt;layout-&gt;2 by 3 </strong>I got a working camera view.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82972c353ad7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Advanced Example of Tensorflow Estimators Part (3/3)]]></title>
            <link>https://medium.com/@tijmenlv/an-advanced-example-of-tensorflow-estimators-part-3-3-8c2efe8ff6fa?source=rss-b2c086e7a2cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c2efe8ff6fa</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[scaffolding]]></category>
            <category><![CDATA[predictions]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Tijmen Verhulsdonck]]></dc:creator>
            <pubDate>Tue, 31 Jul 2018 15:50:30 GMT</pubDate>
            <atom:updated>2019-08-25T06:07:36.314Z</atom:updated>
            <content:encoded><![CDATA[<h4>Note: this story used to be part of a series however all parts are now combined a single <a href="https://towardsdatascience.com/an-advanced-example-of-tensorflow-estimators-part-1-3-c9ffba3bff03">post</a>.</h4><p>For the final part of the 3 part series (<a href="https://medium.com/@tijmenlv/an-advanced-example-of-tensorflow-estimators-part-1-3-c9ffba3bff03">part 1</a>, <a href="https://medium.com/@tijmenlv/an-advanced-example-of-tensorflow-estimators-part-2-3-5569fb93d9f8">part 2</a>) presenting an advanced usage example of the Tensorflow Estimator class, the “Scaffold” and “SessionRunHook” classes will be explained. Prediction will also be covered to finish up the complete picture of the Estimator class.</p><h4>`Switching to the Estimator class</h4><p>In <a href="https://medium.com/@tijmenlv/an-advanced-example-of-tensorflow-estimators-part-1-3-c9ffba3bff03">part 1</a> I explained the advantages of using the Estimator class, but switching to an Estimator from an existing code-base is not necessarily straightforward. As the Estimator class abstracts away most of the initialization and execution during training, any custom initialization and execution loops can no longer be an implementation using “<em>tf.Session</em>” and “<em>sess.run()</em>”. This could be a reason for companies with a large code-base not to transition to the Estimator class, as there is no easy and straightforward transition path. While this article is not a transition guide, it will clarify some of the new procedures for initialization and execution. This will hopefully fill in some of the gaps left by the official <a href="https://www.tensorflow.org/guide/estimators">tutorials</a>, and give someone the confidence needed to switch to Estimators.</p><h4>Scaffolds and SessionRunHooks</h4><p>The main tools to influence the initialization and execution loop are the “Scaffold” object and the “SessionRunHook” object. The “Scaffold” is used for custom first time initialization of a model and can only be used to construct an “EstimatorSpec” in training mode. The “SessionRunHook” on the other hand can be used to construct an “EstimatorSpec” for each mode and is used each time train, evaluate or predict is called. Both the “Scaffold” and “SessionRunHook” provide certain functions that the Estimator class calls during use. Below you can see a timeline showing which function is called and when during the initialization and training process. This also shows that the Estimator under the hood still uses “<em>tf.Session</em>” and “<em>sess.run</em>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ambZT56fJXdHfUDtxVDD2g.png" /><figcaption>Function execution timeline executed by the Estimator of the Scaffold and SessionRunHook classes.</figcaption></figure><p><strong>Scaffolds</strong></p><p>A <a href="https://www.tensorflow.org/versions/r1.8/api_docs/python/tf/train/Scaffold">scaffold</a> can be passed as the scaffold argument when constructing the “EstimatorSpec” for training. In a scaffold you can specify a number of different operations to be called during various stages of initialization. However for now we will focus on the “<em>init_fn</em>” argument as the others are more for distributed settings which this series will not cover. The “<em>init_fn</em>” is called after graph finalization but before the “<em>sess.run</em>” is called for the first time, it is only used once and thus perfect for custom variable initialization. A good example of this is if you want to finetune using a pretrained network and want to be selective about which variables to restore.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d2df111fa3a2cd9d78e6fb35be03f89/href">https://medium.com/media/7d2df111fa3a2cd9d78e6fb35be03f89/href</a></iframe><p>Above you can see an example of this implemented, the function checks for the existence of the finetune checkpoint and creates an initializer function using slim that filters on the “<em>scope_name</em>” variable. This function is then encapsulated in the function format that the Estimator expects which consumes the “Scaffold” object itself and a “<em>tf.Session</em>” object. Inside the “<em>init_fn</em>” the session is used to run the “<em>initializer_fn</em>”.</p><pre># setup fine tune scaffold<br>scaffold = tf.train.Scaffold(init_op=None,<br>     init_fn=tools.fine_tune.init_weights(params[&quot;fine_tune_ckpt&quot;]))<br><br># create estimator training spec<br>return tf.estimator.EstimatorSpec(tf.estimator.ModeKeys.TRAIN,<br>                                loss=loss,<br>                                train_op=train_op,scaffold=scaffold)</pre><p>This “<em>init_fn</em>” can then be passed as an argument to construct a “Scaffold” object, as show above. This “Scaffold” object is used to construct the “EstimatorSpec” for the train mode. While this is a relatively simple example (and can also be achieved with <a href="https://www.tensorflow.org/versions/r1.8/api_docs/python/tf/estimator/WarmStartSettings">“WarmStartSettings”</a>), it can be easily expanded for more advanced onetime initialization functionality.</p><p><strong>SessionRunHooks</strong></p><p>As shown in the timeline earlier the “<a href="https://www.tensorflow.org/api_docs/python/tf/train/SessionRunHook">SessionRunHook</a>” class can be used to alter certain parts of the training, evaluation or prediction loop. This is done using a concept known as <a href="https://en.wikipedia.org/wiki/Hooking">hooking</a>, I will not go into to much detail on what hooking is exactly as in this case it is pretty self explanatory. But using a “SessionRunHook” is slightly different from using a scaffold. Instead of initializing the “SessionRunHook” object with one or more functions as arguments it is used as a super class. It is then possible to overwrite the methods “<em>begin</em>”, “<em>after_create_session</em>”, “<em>before_run</em>”, “<em>after_run</em>” and “<em>end</em>”, to extend functionality. Below an excerpt showing how to overwrite the “<em>begin</em>” function is shown.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d1bd6bc6051e3d332a42588903538c5/href">https://medium.com/media/2d1bd6bc6051e3d332a42588903538c5/href</a></iframe><p>Keep in mind that the “<em>begin</em>” function does not get any arguments but each hook is slightly different, please refer <a href="https://www.tensorflow.org/api_docs/python/tf/train/SessionRunHook">here</a> to check what arguments are passed to which function. Now one can create a “SessionRunHook” with the extended begin method by calling:</p><pre>stats_hook = tools.stats.ModelStats(&quot;squeezenext&quot;,<br>                                    params[&quot;model_dir&quot;],<br>                                    self.batch_size)</pre><p>This object can then be used when constructing an “EstimatorSpec” for training, evaluating and predicting by passing it to the respective arguments “training_hooks”, “evaluation_hooks” and “prediction_hooks”. Note that each arguments ends with hooks, and they expect an iterable of one or multiple hooks so always encapsulate your hooks in an iterable.</p><h4>Prediction</h4><p>Part <a href="https://medium.com/@tijmenlv/an-advanced-example-of-tensorflow-estimators-part-1-3-c9ffba3bff03">1</a> and <a href="https://medium.com/@tijmenlv/an-advanced-example-of-tensorflow-estimators-part-2-3-5569fb93d9f8">2</a> of this series have extensively covered training and evaluation using Estimators, but prediction has not yet been fully explained. This is mostly because prediction is the easiest of the the 3 (train,eval,predict) Estimator modes, but there are still some pitfalls one can run into. In part 2 it was explained how to setup an “EstimatorSpec” for prediction, but not how to use it. Below an example is shown how to actually use an Estimator for prediction.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6a70a71e64fc744aec46bf0d4472806/href">https://medium.com/media/a6a70a71e64fc744aec46bf0d4472806/href</a></iframe><p>For prediction it does not make sense to make tfrecords, so instead the “<em>numpy_input_fn</em>” is used. To the “<em>x</em>” argument a dictionary of numpy arrays is passed containing the features, in this case an image.</p><blockquote>Note: Depending on whether or not you preprocess images in the “<em>input_fn</em>” during training, you would need to perform the same preprocessing here,either in numpy before passing to the “numpy_input_fn” or in Tensorflow.</blockquote><p>With the numpy input function setup, a simple call to predict is enough to create a prediction. The “<em>predictions</em>” variable in the example above will not actually contain the result yet, instead it is an object of the generator class, to get the actual result you need to iterate over the it. This iteration will start the Tensorflow execution and produce the actual result.</p><h4>Final Remarks</h4><p>In this final part the use of the “Scaffold” and “SessionRunHook” to influence the initialization and execution loop was explained. A short example of a prediction was also shown, which concludes this 3 part series. I hope it gave some more information and insight in the use of the Estimator class for a custom and slightly advanced application. All the code comes from this <a href="https://github.com/Timen/squeezenext-tensorflow">github repo</a>, and please leave a comment if you have any further questions I’d be happy to help. I plan to write another series of using video data for training, but that will take a little longer. Stay Tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c2efe8ff6fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Advanced Example of Tensorflow Estimators Part (2/3)]]></title>
            <link>https://medium.com/@tijmenlv/an-advanced-example-of-tensorflow-estimators-part-2-3-5569fb93d9f8?source=rss-b2c086e7a2cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/5569fb93d9f8</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[etl]]></category>
            <dc:creator><![CDATA[Tijmen Verhulsdonck]]></dc:creator>
            <pubDate>Mon, 30 Jul 2018 14:50:17 GMT</pubDate>
            <atom:updated>2019-08-25T06:07:28.442Z</atom:updated>
            <content:encoded><![CDATA[<h4>Note: this story used to be part of a series however all parts are now combined a single <a href="https://towardsdatascience.com/an-advanced-example-of-tensorflow-estimators-part-1-3-c9ffba3bff03">post</a>.</h4><p>This is the second part of a 3 part series showcasing a slightly advanced example of how to use Estimators in Tensorflow. In the first <a href="https://medium.com/@tijmenlv/an-advanced-example-of-tensorflow-estimators-part-1-3-c9ffba3bff03">part</a> the idea behind Estimators was introduced and the advantages of using them. A small example of how to setup a training and evaluation roster using the Tensorflow Estimator class was introduced and explained.</p><p>This part will go more in to depth on how to create an input function (“input_fn”) and the basics setup and implementation of a model function (“model_fn”). The input function will also introduce the use of the Dataset class to optimize the input pipeline, and achieve a greater throughput.</p><h4>Data Loading with Estimators and Datasets</h4><p>The last part glossed over the input function used during training and evaluation to generate the features and labels for the model function. However in my opinion this is one of the best things about Estimators, as you can combine them easily with the Dataset class.</p><p>Before the Estimator Dataset combination it was hard to prefetch and process examples on the CPU asynchronously from the GPU. Prefetching and processing on the CPU would in theory make sure there would be a batch of examples ready in memory any time the GPU was done processing the previous batch, in practice this was easier said then done. The problem with just assigning the fetch and process step to CPU is that unless it is done in parallel with the model processing on the GPU, the GPU still has to wait for the CPU to fetch the data from the storage disk and process it before it can start processing the next batch. For a long time queuerunners, asynchronous prefetching using python threads and other solutions were suggested, and in my experience none of them ever worked flawlessly and efficiently.</p><p>But using the Estimator class and combining it with the Dataset class is very easy, clean and works in parallel with the GPU. It allows the CPU to fetch, preprocess and que batches of examples such that there is always a new batch ready for the GPU. Using this method I have seen the utilization of a GPU stay close to 100% during training and global steps per second for small models(&lt;10MB) increase 4 fold.</p><h4>Dataset Class</h4><p>The Tensorflow Dataset class is designed as an <a href="https://en.wikipedia.org/wiki/Extract,_transform,_load">E.T.L</a>. process, which stands for Extract, Transform and Load. These steps will be defined soon, but this guide will only explain how to use tfrecords in combination with the Dataset class. For other formats (csv, numpy etc.) this page has a good <a href="https://www.tensorflow.org/guide/datasets">write-up</a>, however I suggest using tfrecords as they offer better <a href="https://www.tensorflow.org/performance/performance_guide">performance</a> and are easier to integrate with a Tensorflow development pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*tC0B2qUgpOlFzKMYdrlHwA.png" /><figcaption>From: <a href="http://blog.appliedinformaticsinc.com/etl-extract-transform-and-load-process-concept/">http://blog.appliedinformaticsinc.com/etl-extract-transform-and-load-process-concept/</a></figcaption></figure><p>The whole E.T.L. process can be implemented using the Dataset class in only 7 lines of code as shown below. It might look complicated at first but read on for a detailed explanation of each lines functionality.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb0011648871b92e1ee8405432a273cb/href">https://medium.com/media/cb0011648871b92e1ee8405432a273cb/href</a></iframe><p><strong>Extract</strong></p><p>The first step in a Dataset input pipeline is to load the data from the tfrecords into memory. This starts with making a list of tfrecords available using a glob pattern e.g. “./Datasets/train-*.tfrecords” and the list_files function of the Dataset class. The parallel_interleave function is applied to the list of files, which ensures parallel extraction of the data as explained <a href="https://www.tensorflow.org/performance/datasets_performance">here</a>. Finally a merged shuffle and repeat function is used to prefetch a certain number of examples from the tfrecords and shuffle them. The repeat ensures that there are always examples available by repeating from the start once the last example of every tfrecord is read.</p><pre>files = tf.data.Dataset.list_files(glob_pattern, shuffle=True)<br><br>dataset = files.apply(tf.contrib.data.parallel_interleave(<br>                          lambda filename:<br>                          tf.data.TFRecordDataset(filename),<br>                          cycle_length=threads*2)<br>                      )<br><br>dataset = dataset.apply(tf.contrib.data.shuffle_and_repeat<br>                         (32*self.batch_size))</pre><p><strong>Transform</strong></p><p>Now that the data is available in memory the next step is to transform it, preferably into something that does not need any further processing in order to be fed to the neural network input. A call to the dataset’s map function is required to do this as shown below, where “map_func” is the function applied to every individual example on the CPU and “num_parallel_calls” the number of parallel invocations of the “map_func” to use.</p><pre>threads = multiprocessing.cpu_count()</pre><pre>dataset = dataset.map(map_func=lambda example:<br>                           _parse_function(example, self.image_size,<br>                                self.num_classes,training=training),<br>                            num_parallel_calls=threads)</pre><p>In this case the “map_func” is the parse function shown below, this function processes an example from the tfrecords (created using this <a href="https://github.com/tensorflow/models/tree/master/research/inception/inception/data">repo</a>) and outputs a tuple of dictionaries containing tensors representing the features and labels respectively. Note the use of a lambda function to pass python variables separately from the example to the parse function, as the example is unparsed data from the tfrecord and provided by the Dataset class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b965336d43192a7d8878625da38ac19f/href">https://medium.com/media/b965336d43192a7d8878625da38ac19f/href</a></iframe><p>Keep in mind that this parse function only processes one example at the time as show by the tf.parse_single_example call, but does so a number of times in parallel. To prevent running into any CPU bottlenecks it is important to keep the parse function fast, some tips on how to do this can be found <a href="https://www.tensorflow.org/performance/performance_guide">here</a>. All the individually processed examples are then batched and ready for processing.</p><pre>dataset = dataset.batch(batch_size=self.batch_size)</pre><p><strong>Load</strong></p><p>The final step of the ETL process is loading the batched examples onto the accelerator (GPU) ready for processing. In the Dataset class this is achieved by prefetching, which is done by calling the prefetch function of the dataset.</p><pre>dataset = dataset.prefetch(buffer_size=self.batch_size)</pre><p>Prefetching uncouples the producer (Dataset object on CPU) from the consumer (GPU), this allows them to run in parallel for increased throughput.</p><p><strong>Input Function</strong></p><p>Once the whole E.T.L. process is fully defined and implemented, the “input_fn” can be created by initializing the iterator and grabbing the next example using the following line:</p><pre>input_fn = dataset.make_one_shot_iterator().get_next()</pre><p>This input function is used by the Estimator as an input for the model function.</p><h4>Defining Prediction,Training and Evaluation modes</h4><p>The model function the estimator invokes during training, evaluation and prediction, should accept the following arguments as explained in <a href="https://medium.com/@tijmenlv/an-advanced-example-of-tensorflow-estimators-part-1-3-c9ffba3bff03">part 1</a>:</p><pre>def model_fn(features, labels, mode, params):</pre><p>The features and labels are in this case supplied by the Dataset class, the params are mostly for hyper parameters used during network initialization, but the mode (of type “tf.estimator.ModeKeys”) dictates what action the model is going to be performing. Each mode is used to setup the model for that specific purpose, the available modes are prediction, training and evaluation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_x4FeMCpdP9rKp6PpGiA0A.jpeg" /><figcaption>From: <a href="https://k-d-w.org/blog/103/denoising-autoencoder-as-tensorflow-estimator">https://k-d-w.org/blog/103/denoising-autoencoder-as-tensorflow-estimator</a></figcaption></figure><p>The different modes can be used by calling the respective functions (shown above) of an Estimator Object namely; “predict”, “train” and “evaluate”. The code-path of every mode has to return an “EstimatorSpec” with the required fields for that mode, e.g. when the mode is predict, it has to return an “EstimatorSpec” that includes the predictions field:</p><pre>return tf.estimator.EstimatorSpec(mode, predictions=predictions)</pre><p><strong>Predict</strong></p><p>The most basic mode is the prediction mode “<em>tf.estimator.ModeKeys.PREDICT</em>”, which as the name suggests is used to do predictions on data using the Estimator object. In this mode the “EstimatorSpec” expects a dictionary of tensors which will be executed and the results of which will be made available as numpy values to python.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bea87eea6bf9417946493db8ad85305/href">https://medium.com/media/8bea87eea6bf9417946493db8ad85305/href</a></iframe><p>In this excerpt you can see the predictions dictionary setup to generate classical image classification results. The if statement ensures that this code path is only executed when the predict function of an Estimator object is executed. The dictionary of tensors is passed to the “EstimatorSpec” as the predictions argument together with the mode. It is smart to define the prediction code-path first as it is the simplest, and since most of the code is used for training and evaluation as-well it can show problems early on.</p><p><strong>Train</strong></p><p>To train a model in the “<em>tf.estimator.ModeKeys.TRAIN</em>” mode it is necessary to create a so called “train_op”, this op is a tensor that when executed performs the back propagation to update the model. Simply put it is the minimize function of an optimizer such as the <a href="https://www.tensorflow.org/api_docs/python/tf/train/AdamOptimizer">AdamOptimizer</a>. The “train_op” and the scalar loss tensor are the minimum required arguments to create an “EstimatorSpec” for training. Below you can see an example of this being done.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdcf62e2a80e68c2f3eb842d175241b7/href">https://medium.com/media/bdcf62e2a80e68c2f3eb842d175241b7/href</a></iframe><p>Note the non-required arguments “training_hooks” and “scaffold”, these will be explained in Part 3 of this series but in short they are used to add functionality to the setup and tear-down of a model and training session.</p><p><strong>Evaluate</strong></p><p>The final mode that needs a code-path in the model function is “<em>tf.estimator.ModeKeys.EVAL</em>”. The most important thing in order to perform an eval is the the metrics dictionary, this should be structured as a dictionary of tuples, where the first element of the tuple is a tensor containing the actual metric value and the second element is the tensor that updates the metric value. The update operation is necessary to ensure a reliable metric calculation over the whole validation set. Since it will often be impossible to evaluate the whole validation set in one batch, multiple batches have to be used. To prevent noise in the metric value due to per batch differences, the update operation is used to keep a running average (or gather all results) over all batches. This setup ensures the metric value is calculated over the whole validation set and not a single batch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0331ce0be5855018bbd6329dd1e5fd0/href">https://medium.com/media/d0331ce0be5855018bbd6329dd1e5fd0/href</a></iframe><p>In the example above only the “loss” and “eval_metric_ops” are required arguments, the third argument “evaluation_hooks” is used to execute “tf.summary” operations as they are not automatically executed when running the Estimators evaluate function. In this example the “evaluation_hooks” are used to store images from the validation set to display using a Tensorboard. To achieve this a “SummarySaverHook” with the same output directory as the “model_dir” is initialized with a “tf.summary.image” operation and passed (encapsulated in an iterable) to the “EstimatorSpec”.</p><h4>Final Remarks</h4><p>Implementing the model function and input function accounts for the largest part in setting up a Tensorflow Estimator. Using the Dataset class in the input function ensures maximum throughput by using an E.T.L. process, ensuring optimal accelerator usage. To fully support the prediction, training and evaluation in the Estimator the model function should contain code paths specific to each mode. All code paths share the code to setup the network but each returns a specific construction of an “EstimatorSpec” for that specific mode to function. In part 3 of this series the “SessionRunHooks” and “Scaffold” will be further explained together with some other miscellaneous things to complete the Estimator picture. Stay Tuned!</p><p>Part 3 can now be found <a href="https://medium.com/@tijmenlv/an-advanced-example-of-tensorflow-estimators-part-3-3-8c2efe8ff6fa">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5569fb93d9f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Advanced Example of the Tensorflow Estimator Class]]></title>
            <link>https://medium.com/data-science/an-advanced-example-of-tensorflow-estimators-part-1-3-c9ffba3bff03?source=rss-b2c086e7a2cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9ffba3bff03</guid>
            <category><![CDATA[estimators]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[squeezenext]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Tijmen Verhulsdonck]]></dc:creator>
            <pubDate>Fri, 27 Jul 2018 11:49:52 GMT</pubDate>
            <atom:updated>2019-09-03T07:35:32.391Z</atom:updated>
            <content:encoded><![CDATA[<h4>With code and an in-depth look into some of the hidden features.</h4><p>Estimators were introduced in version 1.3 of the Tensorflow API, and are used to abstract and simplify training, evaluation and prediction. If you haven’t worked with Estimators before I suggest to start by reading this <a href="https://medium.com/learning-machine-learning/introduction-to-tensorflow-estimators-part-1-39f9eb666bc7">article</a> and get some familiarity as I won’t be covering all of the basics when using estimators. Instead I hope to demystify and clarify some aspects more detailed aspects of using Estimators and switching to Estimators from an existing code-base.</p><h4>Why use Estimators?</h4><p>Anyone who has been working with Tensorflow for a long time will know that it used to be a lot more time consuming to setup and use Tensorflow as it is today. Today there are numerous libraries that simplify development such as slim, tflearn and more. These often reduced the code needed to define a network from multiple files and classes to a single function. They also simplified managing the training and evaluation, and to a small extend data preparation and loading. The Estimator class of Tensorflow does not change anything about the network definition but it simplifies and abstracts managing training, evaluation and prediction. It stands out from the other libraries due to it’s low level optimizations, useful abstractions and support from the core Tensorflow dev team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8e8Aq_GlJFy8tGuZx1F2IA.png" /><figcaption>Visualization of the different API levels</figcaption></figure><p>That is the long story, in short Estimators are faster to run and to implement, simpler (once you get used to them) and well supported.</p><h4>Article structure</h4><p>This article will break down some of the features of the Estimators, using examples from a GitHub project of mine <a href="https://github.com/Timen/squeezenext-tensorflow">SqueezeNext-Tensorflow</a>. The network implemented in the project is from a paper released in 2018 called “<a href="https://arxiv.org/pdf/1803.10615.pdf">SqueezeNext</a>”. This network is very lightweight and fast due to a novel approach to separable convolutions. The researchers released a <a href="https://github.com/amirgholami/SqueezeNext">caffe</a> version but to facilitate experimentation using the available Tensorflow libraries I recreated the algorithm from the paper in Tensorflow.</p><p><strong>The article is setup using the following structure:</strong></p><ul><li>Setting Up The Estimator</li><li>Data Loading with Estimators and Datasets</li><li>Defining Prediction,Training and Evaluation modes</li><li>Session hooks and scaffolds</li><li>Prediction</li></ul><h3>Setting up the Estimator</h3><p>In order to setup the Estimator for a certain training and evaluation roster it’s good to first understand how the Estimator setup works. To construct an instance of the Estimator class you can use the following call:</p><pre>classifier = tf.estimator.Estimator(model_dir=model_dir,<br>                                    model_fn=model_fn,<br>                                    params=params)</pre><p>In this call “model_dir” is the path to the folder where the Estimator should store and load checkpoints and event files. The “model_fn” parameter is a function that consumes the features, labels, mode and params in the following order:</p><pre>def model_fn(features, labels, mode, params):</pre><p>The Estimator will always supply those parameters when it executes the model function for training, evaluation or prediction. The features parameter contains a dictionary of tensors with the features that you want to feed to your network, the labels parameter contains a dictionary of tensors with the labels you want to use for training. These two parameters are generated by the input fn which will be explained later. The third parameter mode describes whether the “model_fn” is being called for training, evaluation or prediction. The final parameter params is a simple dictionary that can contain python variables and such that can be used during network definition (think total steps for learning rate schedule etc.).</p><h4>Train and evaluation example</h4><p>Now that the Estimator object is initialized it can be used to start training and evaluating the network. Below is an excerpt of <a href="https://github.com/Timen/squeezenext-tensorflow/blob/master/train.py">train.py</a> which implements the above instructions to create an Estimator object after which it starts training and evaluating.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50da89e975ab80562dfa67424c5e080f/href">https://medium.com/media/50da89e975ab80562dfa67424c5e080f/href</a></iframe><p>This snippet of code first sets up the config dictionary for the params, and uses it together with the “model_fn” to construct an Estimator Object. It then creates a “<em>TrainSpec</em>” with an “input_fn” and the “max_steps” the model should train for. A similar thing is done to create the “<em>EvalSpec</em>” where the “steps” are the number of steps of each evaluation, and “throttle_secs” defines the interval in seconds between each evaluation. The “<em>tf.estimator.train_and_evaluate</em>” is used to start the training and evaluation roster using the Estimator object, “<em>TrainSpec</em>” and “<em>EvalSpec</em>”. Finally an evaluation is explicitly called once more after the training finishes.</p><h3>Data Loading with Estimators and Datasets</h3><p>In my opinion the best things about Estimators, is that you can combine them easily with the <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset">Dataset class</a>. Before the Estimator and Dataset class combination it was hard to prefetch and process examples on the CPU asynchronously from the GPU. Prefetching and processing on the CPU would in theory make sure there would be a batch of examples ready in memory any time the GPU was done processing the previous batch, in practice this was easier said then done. The problem with just assigning the fetch and process step to CPU is that unless it is done in parallel with the model processing on the GPU, the GPU still has to wait for the CPU to fetch the data from the storage disk and process it before it can start processing the next batch. For a long time queuerunners, asynchronous prefetching using python threads and other solutions were suggested, and in my experience none of them ever worked flawlessly and efficiently.</p><p>But using the Estimator class and combining it with the Dataset class is very easy, clean and works in parallel with the GPU. It allows the CPU to fetch, preprocess and que batches of examples such that there is always a new batch ready for the GPU. Using this method I have seen the utilization of a GPU stay close to 100% during training and global steps per second for small models(&lt;10MB) increase 4 fold.</p><h4>Dataset Class</h4><p>The Tensorflow Dataset class is designed as an <a href="https://en.wikipedia.org/wiki/Extract,_transform,_load">E.T.L</a>. process, which stands for Extract, Transform and Load. These steps will be defined soon, but this guide will only explain how to use tfrecords in combination with the Dataset class. For other formats (csv, numpy etc.) this page has a good <a href="https://www.tensorflow.org/guide/datasets">write-up</a>, however I suggest using tfrecords as they offer better <a href="https://www.tensorflow.org/performance/performance_guide">performance</a> and are easier to integrate with a Tensorflow development pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*tC0B2qUgpOlFzKMYdrlHwA.png" /><figcaption>From: <a href="http://blog.appliedinformaticsinc.com/etl-extract-transform-and-load-process-concept/">http://blog.appliedinformaticsinc.com/etl-extract-transform-and-load-process-concept/</a></figcaption></figure><p>The whole E.T.L. process can be implemented using the Dataset class in only 7 lines of code as shown below. It might look complicated at first but read on for a detailed explanation of each lines functionality.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb0011648871b92e1ee8405432a273cb/href">https://medium.com/media/cb0011648871b92e1ee8405432a273cb/href</a></iframe><p><strong>Extract</strong></p><p>The first step in a Dataset input pipeline is to load the data from the tfrecords into memory. This starts with making a list of tfrecords available using a glob pattern e.g. “./Datasets/train-*.tfrecords” and the list_files function of the Dataset class. The parallel_interleave function is applied to the list of files, which ensures parallel extraction of the data as explained <a href="https://www.tensorflow.org/performance/datasets_performance">here</a>. Finally a merged shuffle and repeat function is used to prefetch a certain number of examples from the tfrecords and shuffle them. The repeat ensures that there are always examples available by repeating from the start once the last example of every tfrecord is read.</p><pre>files = tf.data.Dataset.list_files(glob_pattern, shuffle=True)</pre><pre>dataset = files.apply(tf.contrib.data.parallel_interleave(<br>                          lambda filename:<br>                          tf.data.TFRecordDataset(filename),<br>                          cycle_length=threads*2)<br>                      )</pre><pre>dataset = dataset.apply(tf.contrib.data.shuffle_and_repeat<br>                         (32*self.batch_size))</pre><p><strong>Transform</strong></p><p>Now that the data is available in memory the next step is to transform it, preferably into something that does not need any further processing in order to be fed to the neural network input. A call to the dataset’s map function is required to do this as shown below, where “map_func” is the function applied to every individual example on the CPU and “num_parallel_calls” the number of parallel invocations of the “map_func” to use.</p><pre>threads = multiprocessing.cpu_count()</pre><pre>dataset = dataset.map(map_func=lambda example:<br>                           _parse_function(example, self.image_size,<br>                                self.num_classes,training=training),<br>                            num_parallel_calls=threads)</pre><p>In this case the “map_func” is the parse function shown below, this function processes an example from the tfrecords (created using this <a href="https://github.com/tensorflow/models/tree/master/research/inception/inception/data">repo</a>) and outputs a tuple of dictionaries containing tensors representing the features and labels respectively. Note the use of a lambda function to pass python variables separately from the example to the parse function, as the example is unparsed data from the tfrecord and provided by the Dataset class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b965336d43192a7d8878625da38ac19f/href">https://medium.com/media/b965336d43192a7d8878625da38ac19f/href</a></iframe><p>Keep in mind that this parse function only processes one example at the time as show by the tf.parse_single_example call, but does so a number of times in parallel. To prevent running into any CPU bottlenecks it is important to keep the parse function fast, some tips on how to do this can be found <a href="https://www.tensorflow.org/performance/performance_guide">here</a>. All the individually processed examples are then batched and ready for processing.</p><pre>dataset = dataset.batch(batch_size=self.batch_size)</pre><p><strong>Load</strong></p><p>The final step of the ETL process is loading the batched examples onto the accelerator (GPU) ready for processing. In the Dataset class this is achieved by prefetching, which is done by calling the prefetch function of the dataset.</p><pre>dataset = dataset.prefetch(buffer_size=self.batch_size)</pre><p>Prefetching uncouples the producer (Dataset object on CPU) from the consumer (GPU), this allows them to run in parallel for increased throughput.</p><p><strong>Input Function</strong></p><p>Once the whole E.T.L. process is fully defined and implemented, the “input_fn” can be created by initializing the iterator and grabbing the next example using the following line:</p><pre>input_fn = dataset.make_one_shot_iterator().get_next()</pre><p>This input function is used by the Estimator as an input for the model function.</p><h3>Defining Prediction,Training and Evaluation modes</h3><p>A quick reminder, the model function the estimator invokes during training, evaluation and prediction, should accept the following arguments as explained earlier:</p><pre>def model_fn(features, labels, mode, params):</pre><p>The features and labels are in this case supplied by the Dataset class, the params are mostly for hyper parameters used during network initialization, but the mode (of type “tf.estimator.ModeKeys”) dictates what action the model is going to be performing. Each mode is used to setup the model for that specific purpose, the available modes are prediction, training and evaluation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_x4FeMCpdP9rKp6PpGiA0A.jpeg" /><figcaption>From: <a href="https://k-d-w.org/blog/103/denoising-autoencoder-as-tensorflow-estimator">https://k-d-w.org/blog/103/denoising-autoencoder-as-tensorflow-estimator</a></figcaption></figure><p>The different modes can be used by calling the respective functions (shown above) of an Estimator Object namely; “predict”, “train” and “evaluate”. The code-path of every mode has to return an “EstimatorSpec” with the required fields for that mode, e.g. when the mode is predict, it has to return an “EstimatorSpec” that includes the predictions field:</p><pre>return tf.estimator.EstimatorSpec(mode, predictions=predictions)</pre><p><strong>Predict</strong></p><p>The most basic mode is the prediction mode “<em>tf.estimator.ModeKeys.PREDICT</em>”, which as the name suggests is used to do predictions on data using the Estimator object. In this mode the “EstimatorSpec” expects a dictionary of tensors which will be executed and the results of which will be made available as numpy values to python.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bea87eea6bf9417946493db8ad85305/href">https://medium.com/media/8bea87eea6bf9417946493db8ad85305/href</a></iframe><p>In this excerpt you can see the predictions dictionary setup to generate classical image classification results. The if statement ensures that this code path is only executed when the predict function of an Estimator object is executed. The dictionary of tensors is passed to the “EstimatorSpec” as the predictions argument together with the mode. It is smart to define the prediction code-path first as it is the simplest, and since most of the code is used for training and evaluation as-well it can show problems early on.</p><p><strong>Train</strong></p><p>To train a model in the “<em>tf.estimator.ModeKeys.TRAIN</em>” mode it is necessary to create a so called “train_op”, this op is a tensor that when executed performs the back propagation to update the model. Simply put it is the minimize function of an optimizer such as the <a href="https://www.tensorflow.org/api_docs/python/tf/train/AdamOptimizer">AdamOptimizer</a>. The “train_op” and the scalar loss tensor are the minimum required arguments to create an “EstimatorSpec” for training. Below you can see an example of this being done.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdcf62e2a80e68c2f3eb842d175241b7/href">https://medium.com/media/bdcf62e2a80e68c2f3eb842d175241b7/href</a></iframe><p>Note the non-required arguments “training_hooks” and “scaffold”, these will be further explained later but in short they are used to add functionality to the setup and tear-down of a model and training session.</p><p><strong>Evaluate</strong></p><p>The final mode that needs a code-path in the model function is “<em>tf.estimator.ModeKeys.EVAL</em>”. The most important thing in order to perform an eval is the the metrics dictionary, this should be structured as a dictionary of tuples, where the first element of the tuple is a tensor containing the actual metric value and the second element is the tensor that updates the metric value. The update operation is necessary to ensure a reliable metric calculation over the whole validation set. Since it will often be impossible to evaluate the whole validation set in one batch, multiple batches have to be used. To prevent noise in the metric value due to per batch differences, the update operation is used to keep a running average (or gather all results) over all batches. This setup ensures the metric value is calculated over the whole validation set and not a single batch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0331ce0be5855018bbd6329dd1e5fd0/href">https://medium.com/media/d0331ce0be5855018bbd6329dd1e5fd0/href</a></iframe><p>In the example above only the “loss” and “eval_metric_ops” are required arguments, the third argument “evaluation_hooks” is used to execute “tf.summary” operations as they are not automatically executed when running the Estimators evaluate function. In this example the “evaluation_hooks” are used to store images from the validation set to display using a Tensorboard. To achieve this a “SummarySaverHook” with the same output directory as the “model_dir” is initialized with a “tf.summary.image” operation and passed (encapsulated in an iterable) to the “EstimatorSpec”.</p><h3>Switching to the Estimator class</h3><p>Now that I explained the advantages of using the Estimator class and how to use it, I hope you are excited to start using Estimators for your Tensorflow projects. However switching to Estimators from an existing code-base is not necessarily straightforward. As the Estimator class abstracts away most of the initialization and execution during training, any custom initialization and execution loops can no longer be an implementation using “<em>tf.Session</em>” and “<em>sess.run()</em>”. This could be a reason for someone with a large code-base not to transition to the Estimator class, as there is no easy and straightforward transition path. While this article is not a transition guide, I will clarify some of the new procedures for initialization and execution. This will hopefully fill in some of the gaps left by the official <a href="https://www.tensorflow.org/guide/estimators">tutorials</a>.</p><h4>Scaffolds and SessionRunHooks</h4><p>The main tools to influence the initialization and execution loop are the “Scaffold” object and the “SessionRunHook” object. The “Scaffold” is used for custom first time initialization of a model and can only be used to construct an “EstimatorSpec” in training mode. The “SessionRunHook” on the other hand can be used to construct an “EstimatorSpec” for each execution mode and is used each time train, evaluate or predict is called. Both the “Scaffold” and “SessionRunHook” provide certain functions that the Estimator class calls during use. Below you can see a timeline showing which function is called and when during the initialization and training process. This also shows that the Estimator under the hood still uses “<em>tf.Session</em>” and “<em>sess.run</em>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ambZT56fJXdHfUDtxVDD2g.png" /><figcaption>Function execution timeline executed by the Estimator of the Scaffold and SessionRunHook classes.</figcaption></figure><p><strong>Scaffolds</strong></p><p>A <a href="https://www.tensorflow.org/versions/r1.8/api_docs/python/tf/train/Scaffold">scaffold</a> can be passed as the scaffold argument when constructing the “EstimatorSpec” for training. In a scaffold you can specify a number of different operations to be called during various stages of initialization. However for now we will focus on the “<em>init_fn</em>” argument as the others are more for distributed settings which this series will not cover. The “<em>init_fn</em>” is called after graph finalization but before the “<em>sess.run</em>” is called for the first time, it is only used once and thus perfect for custom variable initialization. A good example of this is if you want to finetune using a pretrained network and want to be selective about which variables to restore.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d2df111fa3a2cd9d78e6fb35be03f89/href">https://medium.com/media/7d2df111fa3a2cd9d78e6fb35be03f89/href</a></iframe><p>Above you can see an example of this implemented, the function checks for the existence of the fine-tune checkpoint and creates an initializer function using slim that filters on the “<em>scope_name</em>” variable. This function is then encapsulated in the function format that the Estimator expects which consumes the “Scaffold” object itself and a “<em>tf.Session</em>” object. Inside the “<em>init_fn</em>” the session is used to run the “<em>initializer_fn</em>”.</p><pre># setup fine tune scaffold<br>scaffold = tf.train.Scaffold(init_op=None,<br>     init_fn=tools.fine_tune.init_weights(params[&quot;fine_tune_ckpt&quot;]))</pre><pre># create estimator training spec<br>return tf.estimator.EstimatorSpec(tf.estimator.ModeKeys.TRAIN,<br>                                loss=loss,<br>                                train_op=train_op,scaffold=scaffold)</pre><p>This “<em>init_fn</em>” can then be passed as an argument to construct a “Scaffold” object, as show above. This “Scaffold” object is used to construct the “EstimatorSpec” for the train mode. While this is a relatively simple example (and can also be achieved with <a href="https://www.tensorflow.org/versions/r1.8/api_docs/python/tf/estimator/WarmStartSettings">“WarmStartSettings”</a>), it can be easily expanded for more advanced onetime initialization functionality.</p><p><strong>SessionRunHooks</strong></p><p>As shown in the timeline earlier the “<a href="https://www.tensorflow.org/api_docs/python/tf/train/SessionRunHook">SessionRunHook</a>” class can be used to alter certain parts of the training, evaluation or prediction loop. This is done using a concept known as <a href="https://en.wikipedia.org/wiki/Hooking">hooking</a>, I will not go into to much detail on what hooking is exactly as in this case it is pretty self explanatory. But using a “SessionRunHook” is slightly different from using a scaffold. Instead of initializing the “SessionRunHook” object with one or more functions as arguments it is used as a super class. It is then possible to overwrite the methods “<em>begin</em>”, “<em>after_create_session</em>”, “<em>before_run</em>”, “<em>after_run</em>” and “<em>end</em>”, to extend functionality. Below an excerpt showing how to overwrite the “<em>begin</em>” function is shown.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d1bd6bc6051e3d332a42588903538c5/href">https://medium.com/media/2d1bd6bc6051e3d332a42588903538c5/href</a></iframe><p>Keep in mind that the “<em>begin</em>” function does not get any arguments but each hook is slightly different, please refer <a href="https://www.tensorflow.org/api_docs/python/tf/train/SessionRunHook">here</a> to check what arguments are passed to which function. Now one can create a “SessionRunHook” with the extended begin method by calling:</p><pre>stats_hook = tools.stats.ModelStats(&quot;squeezenext&quot;,<br>                                    params[&quot;model_dir&quot;],<br>                                    self.batch_size)</pre><p>This object can then be used when constructing an “EstimatorSpec” for training, evaluating and predicting by passing it to the respective arguments “training_hooks”, “evaluation_hooks” and “prediction_hooks”. Note that each arguments ends with hooks, and they expect an iterable of one or multiple hooks so always encapsulate your hooks in an iterable.</p><h4>Prediction</h4><p>Training and evaluation have extensively been covered, but prediction has not yet been fully explained. This is mostly because prediction is the easiest of the the 3 (train,eval,predict) Estimator modes, but there are still some pitfalls one can run into. I explained earlier how to setup an “EstimatorSpec” for prediction, but not how to use it. Below is a small example showing how to use an Estimator for prediction.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68887a96d07e5bc2b5b11bfcb224cf46/href">https://medium.com/media/68887a96d07e5bc2b5b11bfcb224cf46/href</a></iframe><p>For prediction it does not make sense to make/use tfrecords, so instead the “<em>numpy_input_fn</em>” is used. To the “<em>x</em>” argument a dictionary of numpy arrays is passed containing the features, in this case an image.</p><blockquote>Note: Depending on whether or not you are preprocess images in the “<em>input_fn</em>” during training, you would need to perform the same preprocessing here, either in numpy before passing to the “numpy_input_fn” or in Tensorflow.</blockquote><p>With the numpy input function setup, a simple call to predict is enough to create a prediction. The “<em>predictions</em>” variable in the example above will not actually contain the result yet, instead it is an object of the generator class, to get the actual result you need to iterate over the it. This iteration will start the Tensorflow execution and produce the actual result.</p><h4>Final Remarks</h4><p>I hope I was able to demystify some of the not so documented features of tensorflow Estimators and fill in the gaps left by the official tutorials. All the code in this post comes from this <a href="https://github.com/Timen/squeezenext-tensorflow">github repo</a>, so please head over there for an example of Estimators used in combination with the Datasets class. If you have any more questions please leave them here, I’ll try my best to answer them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9ffba3bff03" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/an-advanced-example-of-tensorflow-estimators-part-1-3-c9ffba3bff03">An Advanced Example of the Tensorflow Estimator Class</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>
    </channel>
</rss>