<?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 SAGAR SHARMA on Medium]]></title>
        <description><![CDATA[Stories by SAGAR SHARMA on Medium]]></description>
        <link>https://medium.com/@sagarsharma4244?source=rss-165370addbb5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Yfq1AFxdV07S9TMoogUx2g.png</url>
            <title>Stories by SAGAR SHARMA on Medium</title>
            <link>https://medium.com/@sagarsharma4244?source=rss-165370addbb5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 12 Nov 2026 08:36:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sagarsharma4244/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[How to Send Emails using Python]]></title>
            <link>https://medium.com/hackernoon/how-to-send-emails-using-python-4293dacc57d9?source=rss-165370addbb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4293dacc57d9</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[SAGAR SHARMA]]></dc:creator>
            <pubDate>Wed, 24 Oct 2018 06:15:33 GMT</pubDate>
            <atom:updated>2019-04-16T19:14:19.985Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Send Emails with Python</h3><h4>Design Professional Mails using Flask!</h4><p>Have you ever wondered how companies like Medium send Emails to users that look so fancy that it is basically a website in a mail? And on top of that — they send millions of Emails to their Massive user-base in minutes DAILY!!! All Customized to the user&#39;s interests.</p><p>and if you don’t know JUST OPEN ANY OF YOUR EMAIL TAGGED PROMOTIONS</p><p>They have Images, Subscribe Buttons, Tables, GIF’s, Booking Buttons, Headers <em>(in the center)</em>,<em> </em>Logos, Amazing Fonts, Socials, and god knows what else.</p><p>So let’s make our own “Automatic-Pro-PythonCode-Email-Sender-Bot…ish”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRrwI-_ekP4PkQ4TDtYUyw.png" /></figure><p>Let’s write a few lines of Python code that will allow us to sent emails to 1000’s of people at once just by running that python script.</p><h4>Lets pip First</h4><p>We are going to use <strong>Flask </strong>and <a href="https://pythonhosted.org/Flask-Mail/"><strong>Flask-mail</strong></a> to do this. So open your command prompt &amp; do.</p><pre>pip install Flask Flask-Mail</pre><h3>Code 💻</h3><p>You only need 3 easy steps for this:</p><h4>1. Create a Flask App</h4><p>Let&#39;s start by creating a Flask app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*5ukhuSn0sBHrr_O-1QwZCA.png" /></figure><p>We will be using <em>mail </em>variable to manage the features the instance “<strong>Mail</strong>” present in the<em> </em><a href="https://pythonhosted.org/Flask-Mail/"><strong>Flask-Mail</strong></a> library.</p><h4>2. Add Your Details</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*JLI7SZLMZToRvZBzWkhmvA.png" /><figcaption><strong>Configure Details</strong></figcaption></figure><h4>3. Compose &amp; Send [Simple]</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VrejNCUcPEIIJEqajR3fKQ.png" /><figcaption><strong>Message Body</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WIhi84XNh1vdaxkiqRKmfA.png" /><figcaption><strong>OUTPUT</strong></figcaption></figure><h4>🍓 Compose &amp; Send [Advanced]</h4><p>By using .html instead of .body you can use different html tags and add <em>.svg</em>, <em>.png</em> too. I am using <em>&lt;img&gt;</em> argument to add image using Url.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_0nooHpNF3bBePm6axXfA.png" /><figcaption><strong>Message .HTML</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*EtDLMXCS76nanEH7nsnGng.png" /></figure><h4>🍓 Compose &amp; Send [Pro]</h4><p>Now that we know how add text &amp; image. We can use different .html tags in combination with text and images to make it impressive like any other company Email. Also add <em>&lt;button&gt; &lt;/button&gt; </em>redirecting users to your new websites.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*8xMggon62Wwp8R1qCI-P9w.png" /></figure><p><strong>Book Tickets </strong>🎫 button redirects you to the website <a href="http://www.bookmyshow.com/"><em>www.bookmyshow.com</em></a> by opening a new window.</p><p>Get the complete code on GitHub and try it yourself.</p><p><a href="https://github.com/Sagarsharma4244/FlaskMail">Sagarsharma4244/FlaskMail</a></p><h3>💁 Keep in Mind</h3><p>Since our code is not a full fledged app at this point, you may need to toggle your <a href="https://myaccount.google.com/lesssecureapps">Gmail Setting</a>.</p><p><strong>Turn it ON!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*vd0kXIICbB9OvfupIDg4ew.png" /><figcaption><strong>Keep it ON</strong></figcaption></figure><blockquote>How can I Send Personalized Email to 1000’s of Users?!</blockquote><h3><strong>Automate Mails 📬</strong></h3><p><em>(like)</em><strong> Change User’s Name — </strong>Use python to go through a <em>.txt</em> or excel document of your user base and parse through all the names one by one and replace it in the mail.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ffa0b2eb35d606612355c1e209c4cf0/href">https://medium.com/media/8ffa0b2eb35d606612355c1e209c4cf0/href</a></iframe><blockquote><strong>!dea</strong>: You can also change all the “he” to “she” or vice-versa depending on the gender.</blockquote><blockquote>How can I Attach Files with the Mail ?!</blockquote><h3>Attaching Files 📎</h3><p>Here we are attaching image.png file present in the same folder. You can also add pdf file by changing the name and extension.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a21c7292083e994b6cd7af28b5d19664/href">https://medium.com/media/a21c7292083e994b6cd7af28b5d19664/href</a></iframe><figure><a href="https://medium.com/@sagarsharma4244"><img alt="" src="https://cdn-images-1.medium.com/max/375/1*XeIoWj73eDBTaSrzsc7Yug.png" /></a></figure><figure><a href="https://dribbble.com/SagarSharma4244"><img alt="" src="https://cdn-images-1.medium.com/max/375/1*dqEgSo5ut3OQA6pC7bxeTQ.png" /></a></figure><figure><a href="https://twitter.com/SagarSharma4244"><img alt="" src="https://cdn-images-1.medium.com/max/375/1*XVl8ExX2iiO2RuzDq9ZTow.png" /></a></figure><figure><a href="https://www.linkedin.com/in/sagar-sharma-232a06148/"><img alt="" src="https://cdn-images-1.medium.com/max/375/1*bUuCry9VRNJ50gCxbveVwQ.png" /></a></figure><figure><a href="https://github.com/Sagarsharma4244"><img alt="" src="https://cdn-images-1.medium.com/max/375/1*NbmUlppHSfexjHoHhfuA8g.png" /></a></figure><figure><a href="https://www.instagram.com/sagarsharma4244/"><img alt="" src="https://cdn-images-1.medium.com/max/375/1*LatBtszPLbADNyq4UKBSqQ.png" /></a></figure><p>Any comments or if you have any question, <strong>write it in the comment section.</strong></p><p><strong>Clap it! Share it! Follow Me !</strong></p><p>Happy to be helpful. kudos…</p><h3>Previous stories you will love:</h3><ul><li><a href="https://towardsdatascience.com/activation-functions-neural-networks-1cbd9f8d91d6">Activation Functions in Neural Networks</a></li><li><a href="https://heartbeat.fritz.ai/neural-networks-on-mobile-devices-with-tensorflow-lite-a-tutorial-85b41f53230c">Neural Networks on Mobile Devices with TensorFlow Lite: A Tutorial</a></li><li><a href="https://towardsdatascience.com/tensorflow-image-recognition-python-api-e35f7d412a70">TensorFlow Image Recognition Python API Tutorial</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4293dacc57d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/how-to-send-emails-using-python-4293dacc57d9">How to Send Emails using Python</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Networks on Mobile Devices with TensorFlow Lite: A Tutorial]]></title>
            <link>https://heartbeat.comet.ml/neural-networks-on-mobile-devices-with-tensorflow-lite-a-tutorial-85b41f53230c?source=rss-165370addbb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/85b41f53230c</guid>
            <category><![CDATA[mobile-ml]]></category>
            <category><![CDATA[mobile-ml-tools]]></category>
            <category><![CDATA[heartbeat]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[SAGAR SHARMA]]></dc:creator>
            <pubDate>Wed, 15 Aug 2018 14:40:25 GMT</pubDate>
            <atom:updated>2021-10-05T13:44:39.155Z</atom:updated>
            <content:encoded><![CDATA[<h4>Training on your own Data</h4><p>This will be a practical, end-to-end guide on how to build a mobile application using TensorFlow Lite that classifies images from a dataset for your projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*kkEIDOMeTwZxFqaiPXcvwA.jpeg" /></figure><p>This application uses live camera and classifies objects instantly. The TFLite application will be smaller, faster, and more accurate than an application made using TensorFlow Mobile, because TFLite is made specifically to run neural nets on mobile platforms.</p><p>We’ll be using the MobileNet model to train our network, which will keep the app smaller.</p><h3>Getting Started</h3><h4>Requirements…</h4><ol><li>Python 3 .5 or higher<strong>—</strong> python3 -V</li><li>Tensorflow 1.9 or higher<strong> — </strong>pip3 install — upgrade tensorflow</li></ol><p>Also, open the terminal and type:</p><pre>alias python=python3</pre><p>Now, python3 will open with the python command. This will make it easier to implement the code just by copy-pasting without having to worry about 3 after typing Python.</p><h3>The TFLite tutorial contains the following steps:</h3><h4>Step 1: Download the Code Files</h4><p>Let’s start by downloading the code from the <a href="https://github.com/googlecodelabs/tensorflow-for-poets-2">tensorflow-for-poets</a> GitHub. Open the command prompt where you want to download the folder and type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3877fbb2b6f2a0b8141977a4e6ea56d4/href">https://medium.com/media/3877fbb2b6f2a0b8141977a4e6ea56d4/href</a></iframe><p>This will download the files and make a new folder called tensorflow-for-poets in your current directory.</p><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*JYQazYltUONhC0HXRe67MQ.png" /><figcaption>Download GitHub Files</figcaption></figure><p><strong><em>FYI</em></strong><em>: You can change the name of the folder to your project name after downloading.</em></p><blockquote><strong>Info:</strong> The folder contains the sub-folders</blockquote><blockquote>scripts — Contains the machine learning code .py files.</blockquote><blockquote>tf_files<em> </em>— It will contain output files like models — graph.pb, labels.txt</blockquote><blockquote>android — Contains Android app projects for both tfmobile and TFlite.</blockquote><blockquote>iOS — Contains the iOS app project files using <em>x</em>Code.</blockquote><h4>Step 2: Download the Dataset</h4><p>Let’s <a href="http://download.tensorflow.org/example_images/flower_photos.tgz">download</a> a 200MB publicly available dataset with 5 different flowers to classify from. Then extract the flower_photos.tgz inside the <strong><em>tf_files</em></strong> folder which will look something like this:</p><pre><em>tensorflow-for-poets-2 &gt; tf_files &gt; flower_photos</em></pre><blockquote><strong>Info</strong> — The 5 different category folders are Rose, Daisy, Dandelion, Sunflower and Tulip.</blockquote><h4>Step 3: Retrain the model</h4><p>Open the command prompt inside the “tensorflow-for-poets-2” folder and type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dddc927fe112b73b20c8f9ddc40cac4f/href">https://medium.com/media/dddc927fe112b73b20c8f9ddc40cac4f/href</a></iframe><p><strong>Output</strong></p><p>This will download the pre-trained frozen graph mobilenet_1.0_244</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*OCpJ8N8DBfJnVwr27qVmqw.png" /><figcaption>Download Graph</figcaption></figure><p>and create retrained_graph.pb and retrained_labels.txt files in the <em>tf_files</em> folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*9VXk62_wslAdD2GLGxojig.png" /><figcaption>Completed Result</figcaption></figure><h4>Open TensorBoard</h4><p>Open another command prompt in the current directory and point TensorBoard to the summaries_dir:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb709073feebee235b6425c552292068/href">https://medium.com/media/bb709073feebee235b6425c552292068/href</a></iframe><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eufyD8LdQvSCiUCDipYjYQ.png" /><figcaption>Open Tensorboard</figcaption></figure><p>Now you can open the 6006 port in your browser to see the results.</p><h4>Visualization</h4><p>🔴 Training &amp; 🔵 Validation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*tPe-O3s8hXFlWZkYg8Zv4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*ZwcHV0bcf678ys3nauEKFg.png" /><figcaption><strong>Tensorboard</strong> | <strong>Cross Entropy/Loss</strong>(Left) | <strong>Accuracy</strong>(Right)</figcaption></figure><p>Accuracy is above 0.90 and loss is below 0.4 for validation.</p><h4>Verify ✔️</h4><p>I downloaded a random rose image from the Internet in the current folder and used the following command to run the <em>label_image.py</em> script to detect the --image using the --graph file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/500ef2ee0970b062247c2d2b0df5dd26/href">https://medium.com/media/500ef2ee0970b062247c2d2b0df5dd26/href</a></iframe><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*1NO1Sdu5fPjsczegHxC1OA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*A8qyUAoa3Jk6ZtsVTkXt5A.jpeg" /></figure><p>The result gives 99% accuracy for the new_rose image.</p><h4>Step 4: Convert the Model to TFLite Format</h4><p><a href="https://www.tensorflow.org/lite/convert/">TOCO</a> (TensorFlow Lite Converter) is used to convert the file to .lite format. For more detail on TOCO arguments, use toco --help</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/deef85af2c21e373bb3c61180b83bdc4/href">https://medium.com/media/deef85af2c21e373bb3c61180b83bdc4/href</a></iframe><p>This will create an optimized_graph.lite file in your <em>tf_files</em> directory.</p><blockquote><strong>Info</strong>: Use the toco -h for more details</blockquote><blockquote>--input_file has been updated to --graph_def_file</blockquote><blockquote>--input_format is not need for the mobile_net graphs.</blockquote><blockquote><em>From here on, the tutorial is divided into two sections: iOS and Android.</em></blockquote><h3>🍎 iOS 📱</h3><h4>Step 5: Setup Xcode Studio and Test Run</h4><p><strong>Download Xcode</strong></p><p><a href="https://developer.apple.com/xcode/downloads/">Sign in with your Apple ID - Apple Developer</a></p><p><strong>Install</strong> <strong>Xcode</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8489446375cad701f432a265c0b2bbe/href">https://medium.com/media/f8489446375cad701f432a265c0b2bbe/href</a></iframe><p><strong>Install Cocoapods</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c2c90c504c4b4e297b897e163d46592/href">https://medium.com/media/7c2c90c504c4b4e297b897e163d46592/href</a></iframe><p><strong>Install TFLite Cocoapod</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05f4b7dfbc54273f831750a3b1f6d738/href">https://medium.com/media/05f4b7dfbc54273f831750a3b1f6d738/href</a></iframe><p><strong>Open the project with Xcode</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1811a54d1a65775f8652d77820c845f0/href">https://medium.com/media/1811a54d1a65775f8652d77820c845f0/href</a></iframe><h4>Test Run 🏃</h4><p>Press ▶️ to initiate the simulator in Xcode.</p><h4>Step 6: Run your Application</h4><p>First move the trained files into the assets folder of the application<strong>.</strong></p><p>Replace the graph.lite file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11caeb0d00263bcb4cf855a7f69eb991/href">https://medium.com/media/11caeb0d00263bcb4cf855a7f69eb991/href</a></iframe><p>And then thelabels.txt file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1667cb30e3f6f6aed42917c36840d992/href">https://medium.com/media/1667cb30e3f6f6aed42917c36840d992/href</a></iframe><p>Now just click the ▶️ to open the simulator and drop images to see the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*gcM0nVMkNHArtraMpYiAVQ.png" /></figure><p>👏 👏 👏 Congratulations! Now you can apply the same method in your next gazillion dollar app, enable doctors work to faster and better without expensive equipment in the rural parts of the world, or just have fun. 👏👏 👏</p><h3>🍭 🍦 Android 🍞🐝 🍩</h3><h4>Step 5: Setup Android Studio and Test Run</h4><p>There are two ways to do this: Android Studio and Bazel. I’ll be using AS since more people are familiar with it.</p><p>If you don’t have it installed already, go here and install it:</p><p><a href="https://developer.android.com/studio/index.html">Download Android Studio &amp; App Tools - Android Developers</a></p><h4>Test Run 🏃</h4><p>To make sure everything is working correctly in Android Studio, let’s do a test run.</p><p>🔸 Open Android Studio and select “📁Open an existing Android Studio project”.</p><p>🔸 Go to android/tfmobile<strong> </strong>directory.</p><p>🔸 If everything works perfectly, click the BUILD&gt;BUILD APK<strong> </strong>button.</p><p>Open the folder containing app-debug.apk file by clicking <em>locate</em>.</p><blockquote><strong>Note:</strong> Turn On the developer mode in your phone before installing the app.</blockquote><h4>Step 6: Run your Application</h4><p>First move the trained files into the assets folder of the application<strong>.</strong></p><p>Replace the graph.lite file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd9304ec5bdf0cc40508a4d1c563cea2/href">https://medium.com/media/cd9304ec5bdf0cc40508a4d1c563cea2/href</a></iframe><p>and then labels.txt file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66f4d976f5403810402e60684db8cabb/href">https://medium.com/media/66f4d976f5403810402e60684db8cabb/href</a></iframe><p>Now click Tools&gt;&gt; Build .apk file.</p><h4>Install Application</h4><p>Install the .apk file onyour phone and see the re-trained neural network detecting the objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*cu7nfm3II7yKrpUVOOO_0Q.png" /></figure><p>👏 👏 👏 Congratulations! Now you can apply the same method in your next gazillion dollar app, enable doctors to work faster and better without expensive equipment in rural parts of the world, or just have fun. 👏👏 👏</p><p><strong>If you hit a wall while implementing this post, reach out in the comments.</strong></p><p>For further tutorials on how to use <a href="https://heartbeat.comet.ml/building-pok%C3%A9dex-in-android-using-tensorflow-lite-and-firebase-cc780848395">TensorFlow in mobile apps</a> follow me on <a href="https://medium.com/@sagarsharma4244"><strong>Medium</strong></a><strong> </strong>and<strong> </strong><a href="https://twitter.com/SagarSharma4244"><strong>Twitter</strong></a> to see similar posts.</p><p><strong>Clap it! Share it! Follow Me!</strong></p><figure><a href="https://medium.com/@sagarsharma4244"><img alt="" src="https://cdn-images-1.medium.com/max/400/1*dBbsLTjkdMA45vnfBMbkGQ.png" /></a></figure><figure><a href="https://twitter.com/SagarSharma4244"><img alt="" src="https://cdn-images-1.medium.com/max/400/1*YnbtD8IipCsqVjNwkjtY8w.png" /></a></figure><p>Happy to be helpful. kudos…</p><p><strong>Discuss this post on </strong><a href="https://news.ycombinator.com/item?id=17766341"><strong>Hacker News</strong></a><strong> and </strong><a href="https://www.reddit.com/r/iOSProgramming/comments/97ispz/an_endtoend_guide_on_building_a_machine/"><strong>Reddit</strong></a><strong>.</strong></p><p><em>Editor’s Note: </em><a href="https://heartbeat.comet.ml/"><em>Heartbeat</em></a><em> is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.</em></p><p><em>Editorially independent, Heartbeat is sponsored and published by </em><a href="http://comet.ml/?utm_campaign=heartbeat-statement&amp;utm_source=blog&amp;utm_medium=medium"><em>Comet</em></a><em>, an MLOps platform that enables data scientists &amp; ML teams to track, compare, explain, &amp; optimize their experiments. We pay our contributors, and we don’t sell ads.</em></p><p><em>If you’d like to contribute, head on over to our</em><a href="https://heartbeat.fritz.ai/call-for-contributors-october-2018-update-fee7f5b80f3e"><em> call for contributors</em></a><em>. You can also sign up to receive our weekly newsletters (</em><a href="https://www.deeplearningweekly.com/"><em>Deep Learning Weekly</em></a><em> and the </em><a href="https://info.comet.ml/newsletter-signup/"><em>Comet Newsletter</em></a><em>), join us on</em><a href="https://join.slack.com/t/fritz-ai-community/shared_invite/enQtNTY5NDM2MTQwMTgwLWU4ZDEwNTAxYWE2YjIxZDllMTcxMWE4MGFhNDk5Y2QwNTcxYzEyNWZmZWEwMzE4NTFkOWY2NTM0OGQwYjM5Y2U"><em> </em></a><a href="https://join.slack.com/t/cometml/shared_invite/zt-49v4zxxz-qHcTeyrMEzqZc5lQb9hgvw"><em>Slack</em></a><em>, and follow Comet on </em><a href="https://twitter.com/Cometml"><em>Twitter</em></a><em> and </em><a href="https://www.linkedin.com/company/comet-ml/"><em>LinkedIn</em></a><em> for resources, events, and much more that will help you build better ML models, faster.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85b41f53230c" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/neural-networks-on-mobile-devices-with-tensorflow-lite-a-tutorial-85b41f53230c">Neural Networks on Mobile Devices with TensorFlow Lite: A Tutorial</a> was originally published in <a href="https://heartbeat.comet.ml/">Heartbeat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Policy Networks vs Value Networks in Reinforcement Learning]]></title>
            <link>https://medium.com/data-science/policy-networks-vs-value-networks-in-reinforcement-learning-da2776056ad2?source=rss-165370addbb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/da2776056ad2</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[SAGAR SHARMA]]></dc:creator>
            <pubDate>Sun, 05 Aug 2018 08:11:03 GMT</pubDate>
            <atom:updated>2018-08-07T05:03:20.827Z</atom:updated>
            <content:encoded><![CDATA[<p>In Reinforcement Learning, the agents take random decisions in their environment and learns on selecting the right one out of many to achieve their goal and play at a super-human level. Policy and Value Networks are used together in algorithms like <a href="https://towardsdatascience.com/monte-carlo-tree-search-158a9">Monte Carlo Tree Search</a> to perform Reinforcement Learning. Both the networks are an integral part of a method called Exploration in MCTS algorithm.</p><p>They are also known as policy iteration &amp; value iteration since they are calculated many times making it an iterative process.</p><p><strong>Let’s understand why are they so important in Machine Learning and what’s the difference between them?</strong></p><h3>What is a Policy Network?</h3><p>Consider any game in the world, input 🎮 given by user to the game is known as <strong>actions</strong> <strong>a</strong>. Every input (action) leads to a different output. These output are known as <strong>states</strong> <strong>s</strong> of the game.</p><p>From this, we can make different state-action pairs <strong>S</strong> = <strong>{(</strong>s0,a0<strong>)</strong>,s1,a1<strong>)</strong>,...,<strong>(</strong>sN,aN<strong>)}</strong> , representing which actions aN leads to which states sN. Also, we can say that <strong>S </strong>contains all the policies learned by the policy network.</p><blockquote>The Network which learns to give a definite output by giving a particular Input to the game is known as Policy Network</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*sDjnmi8Y8BrfE9jfmj13Tg.gif" /><figcaption><strong>Policy Network (</strong>action1️, state1<strong>)</strong> , <strong>(</strong>action2, state2<strong>)</strong></figcaption></figure><p>For Example: Input a1 gives a state s1 (moving up) &amp; Input a2 gives a state s2(going down) in the game.</p><p>Also, Some actions increase the points of the player lead to reward <strong>r</strong> .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*iwpyXFpny5Z0imRSgib3uw.gif" /><figcaption><strong>States Getting Rewards</strong></figcaption></figure><p>Let’s look at some obvious symbols:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*ldagjoG8r7l6zIOK6d33qg.jpeg" /><figcaption><strong>Usual Notations for RL environments</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*jnQX132sPVSnMzxhqZ3UIg.jpeg" /><figcaption><strong>Optimal Policy</strong></figcaption></figure><p><strong>Why are we using Discount Factor <em>γ</em></strong></p><blockquote>It is used as a precautionary measure (usually kept below 1). It prevent the reward<strong> r </strong>to reach infinite.</blockquote><p>An infinite reward for a policy will overwhelm our agent &amp; biased towards that specific action, killing the desire to explore unknown areas and actions of the game😵.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*UcVjEFeIStkbR0DBtZYvrw.png" /></figure><p><strong>But how do we know which state to choose for your next move, eventually leading to the final round?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*TsMgk14NLG9nNEStALqLvA.png" /></figure><h3>What is a Value Network?</h3><blockquote>The value network assigns value/score to the state of the game by calculating an expected cumulative score for the current state <strong>s</strong> . Every state goes through the value network. The states which gets more reward obviously get more value in the network.</blockquote><p>Keep in mind that the reward is<strong> expected rewards, </strong>because we are choosing the right one from the set of states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*pj4AJIVs4ULpHeC2NU9rkQ.jpeg" /><figcaption>Value Function</figcaption></figure><p>Now, the key objective is always to maximise the reward <em>(aka Markov Decision Process)</em>. Actions that results in a good state obviously get greater reward than others.</p><p>Since any game is won by following a sequence of actions one after the other. The optimal policy <strong><em>π* </em></strong>of the game consists a number of state-action pairs that helps in winning the game.</p><p>The state-action pair that achieve most reward is considered as optimal policy.</p><p>The equation for optimal policy is formally written using <em>arg max</em> as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*jnQX132sPVSnMzxhqZ3UIg.jpeg" /><figcaption><strong>Optimal Policy </strong><strong><em>π*</em></strong></figcaption></figure><p>Therefore, the optimal policy tells us which actions to take to maximises the cumulative discounted reward.</p><blockquote>The optimal policy learned by the policy network knows which actions should be performed at the current state to get maximum reward.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*5DtEcGD0_p7xVEk8302-yg.gif" /></figure><p>If you have any doubt, query or demand, comment down below or tweet me.</p><p><strong>Clap it… Share it! Follow me</strong> on <a href="https://medium.com/@sagarsharma4244"><strong>Medium</strong></a> to get similar fun content.</p><p>To get instant notification follow me on <a href="https://twitter.com/SagarSharma4244"><strong>Twitter</strong></a>.</p><figure><a href="https://twitter.com/SagarSharma4244"><img alt="" src="https://cdn-images-1.medium.com/max/400/1*YnbtD8IipCsqVjNwkjtY8w.png" /></a></figure><figure><a href="https://medium.com/@sagarsharma4244"><img alt="" src="https://cdn-images-1.medium.com/max/400/1*dBbsLTjkdMA45vnfBMbkGQ.png" /></a></figure><p>Happy to be helpful. kudos.</p><h3>Previous Stories You will Love:</h3><ul><li><a href="https://towardsdatascience.com/monte-carlo-tree-search-158a917a8baa">Monte Carlo Tree Search</a></li><li><a href="https://towardsdatascience.com/tensorflow-image-recognition-python-api-e35f7d412a70">TensorFlow Image Recognition Python API Tutorial</a></li><li><a href="https://towardsdatascience.com/activation-functions-neural-networks-1cbd9f8d91d6">Activation Functions in Neural Networks</a></li><li><a href="https://towardsdatascience.com/deepminds-playing-capture-the-flag-with-deep-reinforcement-learning-a9f71256442e">DeepMind’s Playing Capture The Flag with Deep Reinforcement Learning</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da2776056ad2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/policy-networks-vs-value-networks-in-reinforcement-learning-da2776056ad2">Policy Networks vs Value Networks in Reinforcement Learning</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[Monte Carlo Tree Search]]></title>
            <link>https://medium.com/data-science/monte-carlo-tree-search-158a917a8baa?source=rss-165370addbb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/158a917a8baa</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[SAGAR SHARMA]]></dc:creator>
            <pubDate>Wed, 01 Aug 2018 09:43:05 GMT</pubDate>
            <atom:updated>2019-04-19T08:33:30.086Z</atom:updated>
            <content:encoded><![CDATA[<h4>MCTS For Every Data Science Enthusiast</h4><p>The Games like Tic-Tac-Toe, Rubik’s Cube, Sudoku, Chess, Go and many others have common property that lead to exponential increase in the number of possible actions that can be played. These possible steps increase exponentially as the game goes forward. Ideally if you can predict every possible move and its result that may occur in the future. You can increase your chance of winning.</p><p>But since the moves increase exponentially — the computation power that is required to calculate the moves also goes through the roof.</p><p>Monte Carlo Tree Search is a method usually used in games to predict the path (moves) that should be taken by the policy to reach the final winning solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*LgpukIxbNKbZi9PohRh4zA.png" /><figcaption>Final output could be any one of these</figcaption></figure><p>Before we discover the right path(moves) that will lead us for the win. We first need to arrange the moves of the present state of the game. These moves connected together will look like a tree. Hence the name <em>Tree Search</em>. See the diagram below to understand the sudden exponential increase in moves.</p><h4><strong>Tree Search Algorithm</strong></h4><blockquote>It is a method used to search every possible move that may exist after a turn in the game. For Example: There are many different options for a player in the game of tic-tac-toe, which can be visualised using a tree representation. The move can be further increased for the next turn evolving the diagram into a tree.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hQgJNK1LGYpXzFjBVxnREw.jpeg" /><figcaption><a href="http://cse3521.artifice.cc/adversarial-search.html">Source</a></figcaption></figure><p>Brute forcing an exponential increasing tree to find the final solution for a problem by considering every children move/node requires alot of computational power. resulting in extremely slow output.</p><p><strong>💡</strong> Faster Tree Search can be achieved by making a policy — giving more importance to some nodes from others &amp; allowing their children nodes to be searched first to reach the correct solution.</p><p>But how to find that node which is most favourable to have the correct solution in their children nodes. Let’s find out…</p><h4>What is Monte Carlo Tree Search ?</h4><blockquote>MCTS is an algorithm that figures out the best move out of a set of moves by Selecting → Expanding → Simulating → Updating the nodes in tree to find the final solution. This method is repeated until it reaches the solution and learns the policy of the game.</blockquote><h4>How does Monte Carlo Tree Search Work?</h4><p>Let’s look at parts of the loop one-by-one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*OpJz2LcElVB_XPEYAvK87Q.jpeg" /><figcaption><strong>SELECTION</strong></figcaption></figure><p><strong>Selecting👆</strong>| This process is used to select a node on the tree that has the highest possibility of winning. For Example — Consider the moves with winning possibility 2/3, 0/1 &amp; 1/2 after the first move 4/6, the node <strong>2/3</strong> has the highest possibility of winning.</p><p>The node selected is searched from the current state of the tree and selected node is located at the end of the branch. Since the selected node has the highest possibility of winning — that path is also most likely to reach the solution faster than other path in the tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*3FaNj57GNMpUfRgkbkq7fA.jpeg" /><figcaption><strong>EXPANSION</strong></figcaption></figure><p><strong>Expanding — </strong>After selecting the right node. Expanding<strong> </strong>is used to increase the options further in the game by expanding the selected node and creating many children nodes. We are using only one children node in this case. These children nodes are the future moves that can be played in the game.</p><p>The nodes that are not expanded further for the time being are known are leaves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*B-7GJKfo5BNaCJObi_ml_g.jpeg" /><figcaption><strong>SIMULATION</strong></figcaption></figure><p><strong>Simulating|Exploring 🚀 </strong>Since nobody knows which node is the best children/ leaf from the group. The move which will perform best and lead to the correct answer down the tree. But,</p><p><strong><em>How do we find the best children which will lead us to the correct solution?</em></strong></p><p>We use Reinforcement Learning to make random decisions in the game further down from every children node. Then, reward is given to every children node — by calculating how close the output of their random decision was from the final output that we need to win the game.</p><p><strong>For example: </strong>In the game of Tic-Tac-Toe.<strong> </strong>Does the random decision to make cross(X) next to previous cross(X) in the game results in three consecutive crosses(X-X-X) that are needed to win the game?</p><blockquote>FYI: This can be considered as policy π of RL algorithm. Learn more about Policy &amp; Value Network…</blockquote><p><a href="https://towardsdatascience.com/policy-networks-vs-value-networks-in-reinforcement-learning-da2776056ad2">Policy Networks vs Value Networks in Reinforcement Learning</a></p><p>The simulation is done for every children node is followed by their individual rewards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*fb7wR8yryHJuX31WHhLaSg.jpeg" /><figcaption><strong>UPDATING | BACK-PROPAGATION</strong></figcaption></figure><p>Let’s say the simulation of the node gives optimistic results for its future and gets a positive score 1/1.</p><p><strong>Updating|Back-propagation — </strong>Due to the new nodes and their <em>positive or negative</em> scores in the environment. The total scores of their parent nodes must be updated by going back up the tree one-by-one. The new updated scores changes the state of the tree and may also change new future node of the selection process.</p><p>After updating all the nodes, the loop again begins by selection the best node in the tree→ <em>expanding</em> of the selected node → using RL for simulating exploration → <em>back-propagating</em> the updated scores → then finally <em>selecting</em> a new node further down the tree that is actual the required final winning result.</p><p>For Example: Solved Rubik’s Cube, Sudoku’s correct solution, Killing the King in Chess or</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*LgpukIxbNKbZi9PohRh4zA.png" /><figcaption>Final Required Solution of TIC-TAC-TOE</figcaption></figure><h4>Conclusion</h4><p>Instead of brute forcing from millions of possible ways to find the right path.</p><blockquote>Monte Carlo Tree Search algorithm chooses the best possible move from the current state of Game’s Tree with the help of Reinforcement Learning.</blockquote><p>Thanks for reading the article. If you have any doubt or just wants to talk Data Science, write it in the comments below.</p><h4>Clap it ! Share it! Follow Me!</h4><p>Follow me on <a href="https://medium.com/@sagarsharma4244"><strong>Medium</strong></a> and <a href="https://twitter.com/SagarSharma4244"><strong>Twitter</strong></a> to get more content like this.</p><figure><a href="https://twitter.com/SagarSharma4244"><img alt="" src="https://cdn-images-1.medium.com/max/400/1*YnbtD8IipCsqVjNwkjtY8w.png" /></a></figure><figure><a href="https://medium.com/@sagarsharma4244"><img alt="" src="https://cdn-images-1.medium.com/max/400/1*dBbsLTjkdMA45vnfBMbkGQ.png" /></a></figure><h3>Previous Stories You will Love:</h3><ul><li><a href="https://towardsdatascience.com/activation-functions-neural-networks-1cbd9f8d91d6">Activation Functions in Neural Networks</a></li><li><a href="https://towardsdatascience.com/epoch-vs-iterations-vs-batch-size-4dfb9c7ce9c9">Epoch vs Batch Size vs Iterations</a></li><li><a href="https://towardsdatascience.com/50-tensorflow-js-api-explained-in-5-minutes-tensorflow-js-cheetsheet-4f8c7f9cc8b2">50 TensorFlow.js API Explained in 5 Minutes | TensorFlow.js Cheetsheet</a></li><li><a href="https://towardsdatascience.com/tensorflow-on-mobile-tutorial-1-744703297267">TensorFlow on Mobile: Tutorial</a></li><li><a href="https://towardsdatascience.com/playing-atari-with-6-neurons-open-source-code-b94c764452ac">Playing ATARI with 6 Neurons | Open Source Code</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=158a917a8baa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/monte-carlo-tree-search-158a917a8baa">Monte Carlo Tree Search</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[DeepMind’s Playing Capture The Flag with Deep Reinforcement Learning]]></title>
            <link>https://medium.com/data-science/deepminds-playing-capture-the-flag-with-deep-reinforcement-learning-a9f71256442e?source=rss-165370addbb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9f71256442e</guid>
            <category><![CDATA[news]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[SAGAR SHARMA]]></dc:creator>
            <pubDate>Mon, 23 Jul 2018 08:36:39 GMT</pubDate>
            <atom:updated>2018-07-24T02:55:36.596Z</atom:updated>
            <content:encoded><![CDATA[<h4>#4 <a href="https://arxiv.org/abs/1807.01281">Research Paper</a> Explained</h4><p>DeepMind and other universities has published many End to End Reinforcement Learning papers that are used for problems that can be solved by a single agent. End to End RL algorithms learns both feature representation and decision making in the network by taking pixels as the input and the controls as output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v3SJHV_KuVSiSP7WiA-kSw.png" /><figcaption>Previous Work: Single player game <a href="https://www.google.com/url?sa=i&amp;source=images&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwicj_D8ppncAhUGu48KHT4hAlEQjRx6BAgBEAU&amp;url=https%3A%2F%2Fdanieltakeshi.github.io%2F2016%2F11%2F25%2Fframe-skipping-and-preprocessing-for-deep-q-networks-on-atari-2600-games%2F&amp;psig=AOvVaw21UK-nNUVQJ4JpWaWKWSZw&amp;ust=1531475887884647">Source</a></figcaption></figure><p>The real world contain problems that needs multiple individuals acting independently but still collaborating together to achieve a single goal. From playing games like football or basketball to landing a rocket on the moon, a team of individuals works together following a strategy to complete the faster, safer by reducing the risk of failure. This paper can be used to solve many real life tasks, so let’s breakdown the paper to understand their solution.</p><p>DeepMind has build an End-to-End population based RL algorithm that tackles the problem successfully using a two-tier optimisation process &amp; by training individuals, acting and learning independent to each other in a team based 3D multi-agent environment (Capture the Flag) working together strategically to achieve a single goal.</p><p>This leads to models that suffers from high complexity of the learning problem that arises from the concurrent adaptation of other learning agents in the environment.</p><p>The game <em>Capture the Flag</em> has all the traits of the problem above:</p><p>1.A 3D first person view multi-agent game.(<em>also can implemented in robotics due to fpv similarity</em>)</p><p>2. Agents unaware of each other decisions playing in same environment as opponent or teammate.</p><p>3.Strategy based game for learning higher cognitive skills<em>.</em></p><p>Also, the indoor &amp; outdoor theme maps are randomly generated for every game. Two opposing teams consisting of multiple individual players compete to capture each other’s flags by strategically navigating, tagging, and evading opponents. The team with the greatest number of flag captures after five minutes wins the game.</p><h4><strong>Ad-hoc teams</strong></h4><p>To develop more generalised policies &amp; learning agent capable of acquiring generalised skills, training fixed teams of agents on a fixed map reduces the diversity in the training data — instead the paper devise an algorithm &amp; training procedure that enables agents to acquire policies that are robust to the variability of maps, number of players, and choice of teammates, a paradigm closely related to <strong>ad-hoc team</strong> <strong>play</strong> .</p><p>The final win/loss is a delayed episodic signal received from the environment, making it difficult to optimise 1000’s of actions performed by the agent on the basis of only one binary signal at the end of 5 minute game.</p><p>This makes it difficult to recognise the actions that were effective in winning the game from the ones that did not help.</p><p>We can solve the problem by increasing the number of rewards in the game. By using more frequent <strong>Internal rewards</strong>, the rewards can be given on the basis of actions performed by the agent.</p><p>The memory and long-term temporal reasoning requirements of high level strategic CTF play is met by introducing an agent architecture that features a multi-timescale representation — reminiscent of what has been observed in primate cerebral cortex and an external working memory module — broadly inspired by human episodic memory.</p><p>These 3 innovations are integrated with in a scalable, massively distributed &amp; asynchronous computational framework.</p><p>In the game, agent receives raw RBG pixels input <strong>X</strong><em>t</em> from the first person perspective at timestep t, produces control action <strong>a</strong><em>t </em>and receives game points <strong>ρ</strong><em>t </em>to train agent’s policy π.</p><p>The goal of the reinforcement learning is to find a policy that maximises the the expected cumulative γ-discounted reward over a CTF game with T time steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*ogJNVTnc7T6_u9UDPf4IVQ.jpeg" /><figcaption><strong>Expected cumulative γ-discounted reward over a CTF game</strong></figcaption></figure><p>π is parameterised by a multi-time scale Recurrent Neural Network with external memory.</p><p>The agent’s architecture model constructs a temporally hierarchical temporal representation space and uses recurrent latent variable for sequential agent to promote the use of memory &amp; temporally coherent action sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*4D5cLNvwuTxOTzYjDd1mvA.jpeg" /><figcaption><strong>(Figure S10 in paper) Network architectures of agents</strong></figcaption></figure><h4>Probability of Winning</h4><p><strong>For</strong> <strong>Ad-hoc </strong>teams, the agent’s policy πo should maximise the probability of winning for its teams, { π0, π1, π2, ……… , π(N-1/2) } and its teammates’ policies { π1, π2, ……… , π(N-1/2) }, for a total of N players in the game:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*1LDc0Jbz33JDK2BUcCz5zg.jpeg" /><figcaption><strong>Ad-hoc probability of winning</strong></figcaption></figure><p>where winning operator &gt; returns 1 if left wins, 0 for losing, and randomly break ties. Also, ω representing specific maps of the games.</p><p><strong>F</strong>or <strong>T</strong>he <strong>W</strong>in teams — Now that we are using more frequent Internal Rewards <strong>r</strong><em>t</em>, we can operationalise the idea of each agent having a denser reward function by specifying <strong>r</strong><em>t = </em>w(<strong>ρ</strong><em>t</em>) based on available game point signals <strong>ρ</strong><em>t (points are registered for events such as capturing a flag)</em> and allowing the agent to learn the transformation w such that policy optimisation on the internal rewards r t optimises the policy <strong>F</strong>or <strong>T</strong>he <strong>W</strong>in, giving us the <em>FTW agent</em>.</p><p>Traditional methods used for training 1000s of multi-agent environment at such a high scale together is not supported making the methods unstable.</p><p><strong>Scalability — </strong>Population of total <strong>P </strong>different agents are trained in parallel with each other by introducing diversity amongst players to stabilise the training(54).</p><p><strong>Matchmaking — </strong>To improve the skills of the agents, the teammates &amp; opponents are sampled from population P . The agents indexed by <strong>ι</strong> for a training game using a stochastic matchmaking scheme mp(π) that biases co-players to be of similar skill to player p, increasing the uncertainty.</p><p><strong>Agent Skill Level —</strong> Agents skill score are estimated online by calculating <em>Elo Score </em>(15) based on the output of training games.</p><p><strong>Meta-optimization — </strong>It is a method of using one optimizaiton method to train other optimizers. The paper uses population to meta-optimize the internal rewards &amp; hyperparameters of RL process itself. This can be seen as <em>two-tier </em>optimization RL problem. <strong>Inner Optimisation </strong>aka<strong> J </strong><em>inner</em><strong>: </strong>The inner optimisation is soled by RL and it maximises J inner, the agents’ expected future discounted internal rewards. <strong>Outer Optimisation </strong>aka<strong> J </strong><em>outer</em><strong>: </strong>It is solved with Population Based Training (PBT) and it is maximised w.r.t. internal reward schemes <strong>w</strong>p and hyperparameters <strong>φ</strong>p , with the inner<br>optimisation providing the meta transition dynamics.</p><p><strong>PBT</strong> is an online evolutionary process which adapts internal rewards and hyperparameters and performs model selection by replacing under-performing agents with mutated versions of better agents.</p><p>This joint optimization of agents’ policies helps in utilising the potential of combining learning and evolution together which results in maximisation of:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*0Eb8ghLBP8iES5wVFrH6Uw.jpeg" /></figure><h4>Assessment during Training | Tournament</h4><p>To assess the generalisation performance of agents during training a tournament is conducted on procedurally generated maps with Ad-hoc matches involving three types of agents.</p><ol><li>Ablated version of FTW.</li><li>Quake 3 Arena scripted bots</li><li>Human participants with with first person game experience.</li></ol><h4>Results</h4><p>1. <strong>FTW</strong> clearly exceeded the win-rate of humans with maps which neither agent nor human had seen previously, i.e. zero-shot generalisation, with a team of two humans on average capturing 16 flags per game less than a team of two FTW agents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*b3mutHVYZEZUUCvVIO-_lw.jpeg" /></figure><p>2. <strong>Human-agent v/s agent-agent —</strong> Only as part of a h-a team did we observe a human winning over an a-a team (5% win probability).</p><p>3. <strong>Pro gamers v/s FTW —</strong> Even after twelve hours of practice the human game testers were only able to win 25% of games against the agent team.</p><p><strong>4.Tagging accuracy </strong>of agents FTW agents were 80% while humans were lagging at only 48% success. Agents won the match even after their tagging accuracy were artificially reduced to humans accuracy.</p><p>Superior observations &amp; controls resolution of humans helped them to surpass FTW agents in <strong>Successful long range tagging</strong> at 17% &amp; agents at 0.5%.</p><p>But FTW again surpassed humans in short range tagging reaction time with 258ms and humans at 559ms.</p><h4>Firing Neurons in the Network!!! | Knowledge Representation📺</h4><p>To investigate how network have learned skills with such high -level rich representation.The network was asking past, present or future states of the game. For Example —</p><ul><li><strong>Q:</strong> Do I have the Flag? <em>(Present)</em></li><li><strong>Q:</strong> Did I see my teammate recently? <em>(Past)</em></li><li><strong>Q: </strong>Will I be in the opponent’s base soon? (<em>Future)</em></li></ul><p>Similarly, total 200 binary questions was asked based on the features of the games to see the internal representation of the network.</p><h4>Results</h4><p>According to the authors, the agent has knowledge of a given feature if logistic regression on the internal state of the agent accurately models the feature. Interestingly, the FTW agent’s representation was found to encode features related to the past particularly well: e.g. the FTW agent was able to classify the state both flags are stray (<em>flags dropped not at base</em>) with 91% AUCROC (<em>area under the receiver operating characteristic curve</em>), compared to 70% with the self-play baseline.</p><p><em>I encourage you to look at the paper to see more detailed stats.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AwXifdWpdjxz4jRm2MB0wA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I03RDLIcutKT7_rsqIvW7g.jpeg" /><figcaption><strong>(<em>Fig: S4 in paper</em>) 40 Question on high-level game state feature(Columns) for different agents(Rows) for FTW agent</strong></figcaption></figure><h4>Visualisation</h4><p>There are many more visualisations in the paper for your help. I have selected few that need less explanation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BObGC4yEHPlUuhAyQ2RzKg.jpeg" /><figcaption><strong>(Fig: S7 in paper) Hilton Diagrams. At 450K the agent appears to have learned to read from near its own base and just outside the opponent base.</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*MZhP_k_RJVSvzo75GLxwOg.jpeg" /><figcaption>(Figure S6 in paper)<strong>Top two rows:</strong> Selected saliency analysis of FTW agent. <strong>Bottom:</strong> Saliency analysis of a single neuron that encodes whether an opponent is holding a flag.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XeEF7ZYT6uWtWHvtTUWXRg.jpeg" /><figcaption><strong>(Fig:- S8 in paper) internal representations learned from playing CTF for the FTW and Self-play + RS agent</strong></figcaption></figure><h3>Conclusion</h3><p>In this paper, artificial agent using only pixels and game points as input can learn to play highly competitively in a rich multi-agent environment. This was achieved by combining a number of innovations in agent training- population based training of agents, internal reward optimisation, and temporally hierarchical RL — together with scalable computational architectures.</p><p>This paper can be used to solve other problems around you that contain memory and temporally extended interfaces difficulties in their solution. So, I encourage you to read the paper to have fun &amp; understand the methods emerged at the edge of our knowledge about Machine Learning andpush the boundaries by implementing the paper, solving real world problems to live on the edge of the human knowledge.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FdltN4MxV1RI%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdltN4MxV1RI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FdltN4MxV1RI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bb4d951075ce5f27ab401c30f6db3cb/href">https://medium.com/media/6bb4d951075ce5f27ab401c30f6db3cb/href</a></iframe><p>Thank you for reading the article. To read more breakdown of your favroite papers and get #PaperExplained notifications. Follow me on <a href="https://medium.com/@sagarsharma4244">Medium</a> and <a href="https://twitter.com/SagarSharma4244">Twitter</a>.</p><figure><a href="https://twitter.com/SagarSharma4244"><img alt="" src="https://cdn-images-1.medium.com/max/400/1*YnbtD8IipCsqVjNwkjtY8w.png" /></a></figure><figure><a href="https://medium.com/@sagarsharma4244"><img alt="" src="https://cdn-images-1.medium.com/max/400/1*dBbsLTjkdMA45vnfBMbkGQ.png" /></a></figure><h3>Previous Stories you will Love:</h3><ul><li><a href="https://hackernoon.com/deepminds-amazing-mix-match-rl-techique-a6f8ce6ac0b4">DeepMind’s Amazing Mix &amp; Match RL Technique</a></li><li><a href="https://towardsdatascience.com/playing-atari-with-6-neurons-open-source-code-b94c764452ac">Playing ATARI with 6 Neurons | Open Source Code</a></li><li><a href="https://hackernoon.com/google-xs-deep-reinforcement-learning-in-robotics-using-vision-7a78e87ab171">Google X’s Deep Reinforcement Learning in Robotics using Vision</a></li><li><a href="https://towardsdatascience.com/activation-functions-neural-networks-1cbd9f8d91d6">Activation Functions in Neural Networks</a></li><li><a href="https://towardsdatascience.com/epoch-vs-iterations-vs-batch-size-4dfb9c7ce9c9">Epoch vs Batch Size vs Iterations</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9f71256442e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deepminds-playing-capture-the-flag-with-deep-reinforcement-learning-a9f71256442e">DeepMind’s Playing Capture The Flag with Deep Reinforcement Learning</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[Google X’s Deep Reinforcement Learning in Robotics using Vision]]></title>
            <link>https://medium.com/hackernoon/google-xs-deep-reinforcement-learning-in-robotics-using-vision-7a78e87ab171?source=rss-165370addbb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a78e87ab171</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[SAGAR SHARMA]]></dc:creator>
            <pubDate>Sat, 30 Jun 2018 14:00:26 GMT</pubDate>
            <atom:updated>2019-05-22T11:40:02.080Z</atom:updated>
            <content:encoded><![CDATA[<h4>#3 <a href="http://ai.googleblog.com/2018/06/scalable-deep-reinforcement-learning.html">Research Paper</a> Explained</h4><p><a href="https://hackernoon.com/tagged/google">Google</a> is famous for their cutting edge technology and projects including Self Driving Car, Project Loon (Internet balloon), Project Ara and the list goes on. But alot of research goes behind the scenes, which yields in some interesting research papers that literally gives us access and insight on these fun experiments. Encouraging us to replicate the experiments by ourselves and build further to push the boundaries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*6NbWiuuDq47bqEFtMfxNvw.gif" /><figcaption>Project Ara | <a href="https://www.google.com/url?sa=i&amp;rct=j&amp;q=&amp;esrc=s&amp;source=images&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwj6qaLEuvnbAhWTWysKHfOvCdkQjRx6BAgBEAU&amp;url=https%3A%2F%2Fdribbble.com%2Fshots%2F1507631-google-project-ara-animation&amp;psig=AOvVaw0SsdIcgwRdLXIVXgxI4yoH&amp;ust=1530375170666411">Source</a></figcaption></figure><p>The <a href="https://hackernoon.com/tagged/learning">Learning</a> Robots Project by <a href="https://x.company/projects/">GoogleX</a> has published <a href="https://arxiv.org/abs/1806.10293"><strong>QT-Opt: Scalable Deep Reinforcement Learning for Vision-Based Robotic Manipulation</strong></a><strong> </strong>that<strong> </strong>tries to master the simple task of picking and grasping different shaped objects. Aiming to replicate some common human activities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hPUCMLXiPFd5M6UfivRZCA.jpeg" /><figcaption><a href="https://ai.googleblog.com/">Source</a> (<strong>Look at robot no. 6 learning stuff</strong>)</figcaption></figure><p>And the success rate is fascinating.</p><p>This experiment uses 7 robotic arms that ran 800 hours at a course of 4 months to grasp objects placed infront of them. Each uses a RBG camera (<em>image above</em>) with a resolution of 472x472. The closed-loop vision-based control system is based on a general formulation of robotic manipulation as a Markov Decision Process (MDP).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*mJpFASqBjDApWht8l1hMPg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*xZQykZVJ7rQegfHFmuIINQ.jpeg" /><figcaption>Same objects with Different Colours | <a href="https://ai.googleblog.com/">Source</a></figcaption></figure><p>To be efficient, Off-policy Reinforcement Learning is used which has the ability to learn from data collected hours, days or even weeks ago.</p><p>The <strong>Qt-Opt</strong> algorithm is designed by combining two methods:</p><p><strong>1.L</strong><a href="https://ai.googleblog.com/2016/10/how-robots-can-acquire-new-skills-from.html"><strong>arge-scale Distributed Optimization</strong></a><strong> </strong><em>(using multiple robots to train model faster, making it a large-scale distributed system)</em></p><p>2.Deep <a href="https://en.wikipedia.org/wiki/Q-learning"><strong>Q-learning</strong></a> algorithm ( <em>RL technique used to learn a policy, which tells an agent which action to take under which circumstances)</em></p><h3>What is Qt-Opt?</h3><p>QT-Opt is a combination of large-scale distributed optimization<strong> </strong>and Q-learning algorithm<strong> </strong>resulting in<strong> Distributed Q-learning algorithm</strong> that supports continuous action spaces, making it well-suited to robotics problems.</p><p>To make the robot not go crazy at their initial attempts, the model is initially trained with offline data which doesn’t require real robots and improves the scalability.</p><p>For this case, the policy takes an image and returns the sequence on how the arm and gripper should move in 3D space.</p><h3>RESULTS</h3><p>The results gives a unbelievable 96% <em>grasp success rate</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhv7AS8vIX79Isk4Aoykog.jpeg" /><figcaption><a href="https://arxiv.org/abs/1806.10293">Source</a></figcaption></figure><p>The model learned many new things that are sophisticated and borderline humane.</p><p>1.When blocks are too close to each other and there is no space for the gripper, policy separates the blocks from the rest before picking it up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*uPmuUrPeUpxoNWnDUjX-aQ.gif" /><figcaption><a href="https://ai.googleblog.com/">Source</a></figcaption></figure><p>2.Swatting objects from gripper were not the part of dataset but it automatically repositions the gripper for another attempt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*LbZSbuKK2UW3_XKefNYw3g.gif" /><figcaption><a href="https://ai.googleblog.com/">Source</a></figcaption></figure><p>I encourage you to read the research paper for more insight.</p><p><strong>Follow me on Medium and Twitter</strong> for more <strong>#ResearchPaperExplained</strong> Notifications.</p><figure><a href="https://medium.com/@sagarsharma4244"><img alt="" src="https://cdn-images-1.medium.com/max/400/1*d318hSQDEA-NP2sgKkTINw.png" /></a></figure><figure><a href="https://twitter.com/SagarSharma4244"><img alt="" src="https://cdn-images-1.medium.com/max/400/1*YnbtD8IipCsqVjNwkjtY8w.png" /></a></figure><p>If you have any Query about the paper or want me to explain your favourite paper, comment below.</p><p><strong>Clap it… Share it…. and Clap it again.</strong></p><h3>Previous Stories you will Love:</h3><ul><li><a href="https://hackernoon.com/deepminds-amazing-mix-match-rl-techique-a6f8ce6ac0b4">DeepMind’s Amazing Mix &amp; Match RL Technique</a></li><li><a href="https://hackernoon.com/what-the-hell-is-tensor-in-tensorflow-e40dbf0253ee">What the Hell is “Tensor” in “TensorFlow”?</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a78e87ab171" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/google-xs-deep-reinforcement-learning-in-robotics-using-vision-7a78e87ab171">Google X’s Deep Reinforcement Learning in Robotics using Vision</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playing ATARI with 6 Neurons | Open Source Code]]></title>
            <link>https://medium.com/data-science/playing-atari-with-6-neurons-open-source-code-b94c764452ac?source=rss-165370addbb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b94c764452ac</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[news]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[SAGAR SHARMA]]></dc:creator>
            <pubDate>Fri, 29 Jun 2018 11:25:09 GMT</pubDate>
            <atom:updated>2018-06-29T14:02:30.308Z</atom:updated>
            <content:encoded><![CDATA[<h4>#2 <a href="https://arxiv.org/abs/1806.01363">Research Paper</a> Explained</h4><p>The doors this paper unlocks for the machine learning community are amazing. The tiny network actually plays Atari game with only 6 neurons comparable and occasionally superior making the previous networks look like jokes. And the best part is that the code is open source on <a href="https://github.com/giuse/DNE">GitHub</a> for everyone to play with. So, let’s get to it…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*aKb_0Ohsz5fXwlKeIOfQfQ.gif" /><figcaption><a href="http://www.reddit.com/r/oddlysatisfying/comments/39t04m/cube/">SOURCE</a></figcaption></figure><h3>How is it Possible!!!</h3><p>We already know that the Deep Reinforcement Learning network that play atari games are basically a <em>dense deep neural network </em>has <strong>both</strong> the responsibility of<em> </em>internally learning to extract features from the image with the first layers by mapping pixels to intermediate representations (<strong>aka feature extraction)</strong>, allowing the last (few) layer(s) to map these representations to actions and <strong>policy or decision making.</strong></p><p>Thus both are learned at the same time, making it almost impossible to study the policy separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*OiZ2Nk73JwrLuLGcB2G1hg.jpeg" /><figcaption><a href="https://www.google.com/url?sa=i&amp;rct=j&amp;q=&amp;esrc=s&amp;source=images&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=&amp;url=https%3A%2F%2Fwww.nature.com%2Farticles%2Fnature14236&amp;psig=AOvVaw0q5seT4_pWHGGBf2NONfwC&amp;ust=1530192629980612">Source</a></figcaption></figure><p>So just by separating the representation learning part from policy learning part relieves the network from constructing intermediate representation allowing it to specialise it in policy approximation which is trained online on the very observations obtained by the interactions.</p><p>This paper helps to learn the features <em>simultaneously</em> but <em>separately</em> in complex RL settings.</p><p>This allows a smaller policy network to be competitive and solve the problems with much greater sophistication.</p><p>We can get better control over the learning just by separating them into two different networks.</p><h4>To Learn Feature Extraction</h4><p>The paper uses two new methods based on <em>Vector Quantization</em> called <strong>Increasing Dictionary (VQ)</strong> and based on <em>Sparse Coding</em> called <strong>Direct Residual SC </strong>to train the network.</p><p>Let’s look at some one liners for quick understanding of the basic concept then I’ll explain the new stuff later in the article.</p><blockquote>Vector Quantization is a neural net algorithm used to learn the binary or multi classification by using a list of vectors called dictionary.</blockquote><p><strong>Note:</strong> I encourage you to learn further about <a href="https://www.techopedia.com/definition/32067/learning-vector-quantization-lvq"><strong>Vector Quantization</strong></a> and <a href="http://ufldl.stanford.edu/tutorial/unsupervised/SparseCoding/"><strong>Sparse Coding</strong> </a>for better understanding.</p><h4>To Learn Decision Making Policies</h4><p>policies are trained with a specialized version of <strong>Exponential Natural Evolution Strategy</strong> capable of coping with dimensionality growth.</p><h3>Lets Make the System 💻</h3><p>Now let’s understand how they have implemented this paper. Our system can be coded into <strong>4</strong> simple steps:</p><h3>1. ENVIRONMENT 👾</h3><p>The system is build on the OpenAI framework for Atari 2600, with all the limitations of the original console. The observations consists of a [210x180x3] tensor,representing RBG pixels of the screen input.</p><p>The output of the network is interpreted (using one-hot encoding) as one of 18 discrete actions, representing the potential inputs from the joystick. The frame-skipping is fixed at 5.</p><h3>2. COMPRESSOR 💼</h3><p>You can also call it a pre-processor.</p><p>The compressor is a neural network that extracts the low-dimensional code from observations when interfaced with the environment, in an <em>online fashion.</em></p><p>To get the top performance for online learning the paper uses two new methods which are combined together.</p><h4>Increasing Dictionary Vector Quantization</h4><p>This version of VQ increases the size of dictionary unlike the vector quantiztion which has fixed dictionary size.</p><p>Growth in dictionary size is regulated by a threshold δ, indicating the minimal aggregated residual considered to be a meaningful addition.</p><h4>Direct Residual Sparse Coding</h4><p>The performance of the dictionary-base algorithm depends more encoding than on dictionary training. So to improve the performance of IDVQ Direct Residual SC is used. For detailed explanation <a href="https://arxiv.org/abs/1806.01363">go here</a>.</p><h3>3. CONTROLLER 🎮</h3><p>The controller for all experiments is a single-layer fully-connected recurrent neural network (RNN).</p><p>Each neuron receives the following inputs through weighted connections: the inputs to the network, the output of all neurons from the previous activation (initially zeros), and a constant bias (always set to 1).</p><p>The <strong>number of inputs</strong> is equal at any given point in time to the size of the code coming from the <em>varying</em> output of the compressor.</p><p>The number of neurons in the <strong>output layer</strong> is kept equal to the actions for each game, as defined by the ALE simulator. This is as low as 6 in some games, and 18 atmost.</p><h3>4. OPTIMIZER 🚀</h3><p>The Optimizer is our learning algorithm, improving the performance of the network over time, in this case an Evolution Strategy called...</p><h4>Exponential Natural Evolution Strategy 💁<a href="http://people.idsia.ch/~juergen/xNES2010gecco.pdf">Paper</a></h4><p>Natural Evolution Strategies is a family of evolutionary algorithms that controls the parameters than the explicit population of individual.</p><h3>RESULTS</h3><p>The comparative results over a set of 10 Atari games from the hundreds available (<em>selected by the required criteria</em>) on the OpenAI’s ALE framework are given below.</p><p>They compared their work to two recent papers which offer a broad set of results across Atari games.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*T5r7h2aeqcQ9NOkyCwKsjA.jpeg" /><figcaption><strong>RESULTS</strong></figcaption></figure><h3>CONCLUSION</h3><p>We presented a method to learn effective policies for visual control in reinforcement learning tasks such as Atari games using tiny neural networks that are two orders of magnitude smaller than the deep neural networks typically used for these problems.</p><p>This is accomplished by decoupling policy learning from feature construction.</p><p>The feature construction is performed outside the network, through a novel and efficient vector quantization algorithm called Increasing Dictionary Vector Quantization, which is trained online (i.e. along the network) on the very observations obtained by the network’s interactions with the environment.</p><p>If you like the explanation that <strong>Clap</strong> and <strong>Share</strong> this with the community. Follow me on <strong>Medium</strong> and <strong>Twitter</strong> to get more #<strong>Research Paper Explained</strong> Notifications…</p><figure><a href="https://medium.com/@sagarsharma4244"><img alt="" src="https://cdn-images-1.medium.com/max/400/1*d318hSQDEA-NP2sgKkTINw.png" /></a></figure><figure><a href="https://twitter.com/SagarSharma4244"><img alt="" src="https://cdn-images-1.medium.com/max/400/1*YnbtD8IipCsqVjNwkjtY8w.png" /></a></figure><p>If you have any Query about the paper or want me to explain your favourite paper, comment below.</p><h3>Previous Stories you will Love:</h3><ul><li><a href="https://hackernoon.com/deepminds-amazing-mix-match-rl-techique-a6f8ce6ac0b4">DeepMind’s Amazing Mix &amp; Match RL Technique</a></li><li><a href="https://towardsdatascience.com/epoch-vs-iterations-vs-batch-size-4dfb9c7ce9c9">Epoch vs Batch Size vs Iterations</a></li><li><a href="https://towardsdatascience.com/50-tensorflow-js-api-explained-in-5-minutes-tensorflow-js-cheetsheet-4f8c7f9cc8b2">50 TensorFlow.js API Explained in 5 Minutes | TensorFlow.js Cheetsheet</a></li><li><a href="https://towardsdatascience.com/activation-functions-neural-networks-1cbd9f8d91d6">Activation Functions in Neural Networks</a></li><li><a href="https://towardsdatascience.com/tensorflow-on-mobile-tutorial-1-744703297267">TensorFlow on Mobile: Tutorial</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b94c764452ac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/playing-atari-with-6-neurons-open-source-code-b94c764452ac">Playing ATARI with 6 Neurons | Open Source Code</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[DeepMind’s Amazing Mix & Match RL Technique]]></title>
            <link>https://medium.com/hackernoon/deepminds-amazing-mix-match-rl-techique-a6f8ce6ac0b4?source=rss-165370addbb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6f8ce6ac0b4</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[SAGAR SHARMA]]></dc:creator>
            <pubDate>Sun, 10 Jun 2018 10:22:12 GMT</pubDate>
            <atom:updated>2019-05-22T11:40:02.526Z</atom:updated>
            <content:encoded><![CDATA[<h4>#1 Research Paper Explained</h4><h3>Mix &amp; Match — Agent Curricula for Reinforcement Learning [ <a href="https://arxiv.org/pdf/1806.01780">arxiv</a> ]</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SkHgi4zw9rCB6PvkApJcrg.png" /></figure><p>The <a href="https://hackernoon.com/tagged/reinforcement">Reinforcement</a> Learning Techniques that are used nowadays are very quick and give immediate results for less complex environments using the gradient based policy optimisations.</p><blockquote>The Gradient based policies are competitive and not collaborative.</blockquote><p>So what if we need long lasting results for more complex environments having agents with complex tasks to perform.</p><p>There are many world environment where we do not have the ability to modify the environments and performing Reinforcement <a href="https://hackernoon.com/tagged/learning">Learning</a> on the real world tasks are really time consuming. So to overcome that problem this paper tries to solve that issue with the help for <strong>Curriculum Learning</strong> and <strong>Population Based Training</strong>.</p><h3>Before You Start</h3><h4>Curriculum Learning [<a href="https://www.ijcai.org/proceedings/2017/0757.pdf">Paper</a>]</h4><blockquote>To design a sequence of task using transfer learning for an agent to train on, such that final performance or learning speed is improved.</blockquote><h4><strong>Population Based Training for Neural Networks [</strong><a href="https://deepmind.com/blog/population-based-training-neural-networks/"><strong>DeepMind Blog</strong></a><strong>]</strong></h4><blockquote>PBT has the ability to modify the hyper-parameters of the Network while training.</blockquote><h3>The Main Idea</h3><p>The main idea behind the Mix &amp; Match paper is to</p><blockquote>Generate multiple variants of RL agents where we don’t have the ability to modify task arranged according to training complexity but only use one MIX &amp; MATCH agent constructed by leveraging different agent varying structurally by their policy generation process.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*MCRo5w0W73MJYoadnc72SA.jpeg" /></figure><h3>MIX &amp; MATCH Framework</h3><p>Multiple agents that are arranged in learning complexity (shown above) are treated as one Mix &amp; Match Agent acting with a mixture of policies.</p><p>The <strong>knowledge transfer</strong> (i.e. distillation) is done in such a way that the complex agents are matched with the simpler ones early on.</p><p><strong>Mixing Coefficient</strong> is controlled such that ultimately complex target agent is used to generate experience.</p><h3>Method Details</h3><p>Let’s assume we are given a sequence of trainable agents 1 ( <em>with corresponding policies π 1 , …, π K , each parametrised with some θ i ⊂ θ which can share some parameters</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*teLh-aQdkmCzne71LSbhvg.jpeg" /></figure><p>The aim is to train π K ,while all remaining agents are there to induce faster/easier learning.</p><p>Let’s introduce <strong>categorical random variable ‘c’</strong> ∼ Cat(1, …, K|α) <strong>Probability mass function p(c = i) = α i</strong> ) which will be used to select a<br>policy at a given time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*sdqM9l8uGQCw6PN6EUzoNQ.jpeg" /></figure><p>The point of Mix &amp; Match is to allow curriculum learning, consequently we need the probability mass function (pmf) of c to be changed over time. Initially the pmf should have α 1 = 1 and near the end of training α K = 1 thus allowing the curriculum of policies from simple π 1 to the target one π K.</p><p>Now, it should be trained in such a way which maximises long lasting increase of performance and share knowledge together unlike those gradients.</p><p>To address this issue we will be using a <strong>Distillation-like Cost (D) </strong>which will align the policies together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*8SJWCTQfMZY7CUcbug2Zlw.jpeg" /></figure><p>The final optimisation problem we consider is just a weighted sum of the original <strong>L^RL</strong> <strong>loss </strong>(below), applied to the control policy <strong>π^mm</strong> and the knowledge transfer loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*ETLIY_PuKq20EUz1qdkxSA.jpeg" /></figure><p>Now, let’s understand the Mix &amp; Match Architecture in Steps →</p><h4>Policy Mixing</h4><p>Policy mixing will be done by explicit mixing for the sake of variance reduction.</p><h4>Knowledge Transfer</h4><p>For simplicity we consider the case of K = 2. Consider the problem of ensuring that<strong> final policy (π2)</strong> matches the <strong>simpler policy (π1)</strong> , while having access to samples from the <strong>control policy</strong>(π<strong>mm)</strong> .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*u3gpsmBdyepgO_X3ZU6uFQ.jpeg" /><figcaption><strong>Same as previous one</strong></figcaption></figure><p>For simplicity, we define our <strong>M&amp;M loss</strong> over the trajectories directly and <strong>trajectories (s ∈ S)</strong> are sampled from the control policy. The <strong>1 − α</strong> term is introduced so that the distillation cost disappears when we switch to <strong>π 2</strong> .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*_xVZrKscr84iMQHTempJww.jpeg" /></figure><h4>Adjusting α (alpha) through training</h4><p><strong>α </strong>is the variable used in the <strong>population mass function </strong>equation (f<em>irst equation</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*sdqM9l8uGQCw6PN6EUzoNQ.jpeg" /><figcaption>This is the first equation</figcaption></figure><p>An important component of the proposed method is how to set values of α through time. For simplicity let us again consider the case of K = 2, where one needs just a single α (as c now comes from Bernoulli distribution) which we<br>treat as a function of time t.</p><p><strong>Online hyperparameter tuning →</strong> Since α changes through time one cannot use typical hyperparameter tuning techniques as the space of possible values is exponential in number of timesteps (α = (α (1) , · · · , α (T ) ) ∈ 4 Tk−1 ,<br>where 4 k denotes a k dimensional simplex).</p><p>To solve this issue we use <strong>Population Based Training </strong>(PBT).</p><h4>Population Based Training and M&amp;M</h4><p><strong>Population Based Training </strong>(PBT) keeps a population of <strong>agents</strong>, trained in parallel, in order to optimise hyperparameters through time while training and periodically query each other to check how well they are doing relative to others. Badly performing agents copy the weights (neural network parameters) of stronger agents and perform local modifications of their hyperparameters.</p><p>This ability of PBT to modify hyperparameters throughout a single training run makes it is possible to discover powerful adaptive strategies e.g. <em>auto-tuned learning rate annealing schedules</em>.</p><blockquote>This way poorly performing agents are used to <strong>explore</strong> the hyperparameters space.</blockquote><p>So, we need to define <strong>two functions</strong> →</p><blockquote><strong>eval →</strong> which measures how strong a current agent is</blockquote><blockquote><strong>explore</strong> → which defines how to instigate the hyperparameters.</blockquote><h4>Note: Keep in mind the PBT agents are the MIX &amp; MATCH Agents which is already a mixture of constituent agents.</h4><p>Now, we should use one of the two schemes mentioned below, depending on the characteristics of the problem we are interested in.</p><ol><li>If models is having performance improvement by switching from simple to the more complex model, then</li></ol><p><strong>a ) </strong>Provide <strong>eval</strong> with performance (i.e. reward over k episodes) of the mixed policy.</p><p><strong>b )</strong> For an <strong>explore</strong> function for <strong>α </strong>we randomly add or subtract a fixed value (truncating between 0 and 1). Thus, once there is a significant benefit of switching to more complex one — PBT will do it automatically.</p><p>2. Often we want to switch from an unconstrained architecture to some specific, heavily constrained one (where there may not be an obvious benefit in performance from switching).</p><p>When training a multitask policy from constituent single-task policies, we can make <strong>eval</strong> an independent evaluation job which only looks at performance of an agent with <strong>α K = 1</strong>.</p><p>This way we directly optimise for the final performance of the model of interest, but at the cost of additional evaluations needed for PBT.</p><h3>EXPERIMENTS</h3><p>Let’s test and analyse whether our new M&amp;M method is working correctly in all circumstances. We will now consider 3 sets of Reinforcement Learning experiments which can be Scaled to large and complex action spaces, Complexities of Agents Architecture and Learning Multitask Policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wpNCl0GWXkzawZ-XLclscA.jpeg" /></figure><p>In all the process, we initialise α around 0 and analyse its adaptation through<br>time.</p><blockquote><strong>Note</strong> <strong>→</strong> that even though in the experimental sections we use K = 2, the actual curriculum goes through potentially infinitely many agents being a result of mixing between π 1 and π 2 .</blockquote><p>Unless otherwise stated, the eval function returns averaged rewards from last <strong>30 episodes</strong> of the control policy.</p><p>The Environment Suite of DeepMind Lab offers a range of challenging 3D, first-person view based tasks (see, appendix) for RL agents. Agents perceive <strong>96 × 72 pixel based RGB observations, at 60 fps and can move, rotate, jump and tag built-in bots</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-QH346AgHuGLJdCvaEvLgg.jpeg" /></figure><h4>1. Curricula Over Number of Actions Used</h4><p>The action space is complex represented in 6 dimensional vector where two action group are very high resolution (<em>rotation and looking up/down actions</em>) and remaining four are low resolution actions (<em>moving forward, backward or not moving at all, shooting or not shooting etc</em>).</p><p>Here, we use 9 actions to construct <strong>π 1</strong>, the simple policy (Small action space).</p><p>Similarly to the research in continuous control using diagonal Gaussian distributions we use a factorised policy π 2 (a 1 , a 2 , …, a 6 |s) := j=1 π̂ j (a j |s), which we refer to as Big action space.</p><p><strong>In order to be able to mix these two policies we map π 1 actions onto the corresponding ones in the action space of π 2.</strong></p><p>The mixing of values between networks of agents shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*p23awkQ6HcCwaqJsbJBQrg.jpeg" /></figure><p>The paper also discussed Shared Head and Masked KL techniques but both are wore than M&amp;M.</p><h4>RESULTS</h4><p>We see that the small action space leads to faster learning but hampers final performance as compared to the big action space.</p><blockquote>Mix &amp; Match applied to this setting gets the best of both worlds, it learns fast, and surpasses the final performance of the big action space.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7Ajy2LdFD_3yT67uamuUg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*FeHK4oEnMkVJkRnzwErXBg.jpeg" /><figcaption>FIG: Training in action<br>spaces experiments.</figcaption></figure><p>When plotting α through time (Fig. 5 Left) we see that the agent switches fully to the big action space early on, thus showing that small action space was useful only for initial phase of learning. This is further confirmed by looking at how varied the actions taken by the agent are through training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*xA5aOIOdkJ5xDty-1G9cug.jpeg" /></figure><p>Fig. 5 (Right) shows how the marginal distribution over actions evolves through time.We see that new actions are unlocked through training, and further that the final distribution is more entropic that the initial one, which means that more entropy leads to more stability.</p><h4>2. Curricula Over Agent Architecture</h4><p>We substitute the LSTM with a linear projection from the processed convolutional signal. We share both the convolutional modules as well as the policy/value function projections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*eU8EtpsFm98j97Q6988FLg.jpeg" /></figure><p>The experiments are focused on various <strong>navigation tasks</strong>.</p><p>On one hand, reactive policies (which can be represented solely by a Feed Forward policy) should learn reasonably quickly to move around and explore, while on the other hand, recurrent networks (which have memory) are needed to maximise the final performance — by either learning to navigate new maze layouts (Explore Object Location Small) or avoiding (seeking) explored unsuccessful (successful) paths through the maze.</p><h4>RESULTS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1MNj6MA-hPCghkCM8HXFuQ.jpeg" /><figcaption>FIG 6</figcaption></figure><p>M&amp;M applied to the transition of LSTM and FF, leads to significant improvement in the final performance. But not as fast as FF counterpart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*xIEXReFcho8faD2lHRPinA.jpeg" /><figcaption>FIG 7</figcaption></figure><p>FIG 8 leads to two observations</p><ol><li>The Green curve switches late to LSTM due to complexity in the level of Game.</li><li>The model (Blue Curve) has the ability to switch back to the mixture policy if needed.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*P_pCwpSHVnbqDyiGL9empA.jpeg" /></figure><h4>3. Curricula for Multitask</h4><p>As a final proof of concept we consider the task of learning a single policy capable of solving multiple RL problems at the same time. The basic approach for this sort of task is to train a model in a mixture of environments or equivalently to train a shared model in multiple environments in parallel.</p><p>This type of training can suffer from two drawbacks:</p><p>→ It is heavily reward scale dependent, and will be biased towards<br>high-reward environments.</p><p>→ Environments that are easy to train provide a lot of updates for the model and consequently can also bias the solution towards themselves.</p><p>Let’s take a look at the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MfQzBgXkAVQlUsQAV44xAw.jpeg" /><figcaption>FIG 9</figcaption></figure><p>One is <strong>Explore Object Locations Small</strong>, which has high rewards and a steep initial learning curve (lots of reward signal coming from gathering apples).</p><p>In remaining two problems training is hard, the agent is interacting with other bots as well as complex mechanics (pick up bonuses, tagging floors, etc.)</p><p>The multitask solution focuses on solving the navigation task, while performing comparitively poorly on the more challenging problems.</p><p>To apply M&amp;M to this problem we construct one agent per environment<br>(each acting as π 1 from previous sections) and then o<strong>ne centralised “multitask” agent</strong> (π 2 from previous sections). Crucially, agents share convolutional layers but have independent LSTMs.</p><p>Training is done in a multitask way, but the control policy in each environment is again a mixture between the task specific π i (the specialist) and π mt (centralised agent).</p><p>Since it is no longer beneficial to switch to the centralised policy, we use the<br>performance of π mt (i.e. the central policy) as the optimisation criterion (eval) for PBT, instead of the control policy.</p><p>We evaluate both the performance of the mixture and the centralised agent independently. Fig. 9 shows per task performance of the proposed method. One can notice much more uniform performance —</p><blockquote><strong>M&amp;M agent learns to play well in both challenging laser tag environments, while slightly sacrificing performance in a single navigation task.</strong></blockquote><p>One of the reasons of this success is the fact that knowledge transfer is done in policy space, which is invariant to reward scaling. While the agent can still focus purely on high reward environments once it has switched to using<br>only the central policy, this inductive bias in training with M&amp;M ensures a much higher minimum score.</p><h3>CONCLUSION</h3><p>Over time the component weightings of this mixture are adapted such that at the end of training we are left with a single active component consisting of the most complex agent. Also,</p><blockquote>Improved and Accelerated performance in Complex Environment.</blockquote><blockquote>Collection of agents is bound together as a single composite whole using<br>a mixture policy.</blockquote><blockquote>Information can be shared between the components via shared experience or shared architectural elements, and also through a distillation-like KL-matching loss.</blockquote><p>I will be posting 2 posts per week so don’t miss the tutorial.</p><p>So, follow me on <a href="https://medium.com/@sagarsharma4244"><strong>Medium</strong></a><strong> </strong>and <a href="https://twitter.com/SagarSharma4244"><strong>Twitter</strong></a><strong> </strong>to see similar posts.</p><p>Any comments or if you have any question, <strong>write it in the comment.</strong></p><p><strong>Clap it(Multiple Times)! Share it! Follow Me!</strong></p><p>Happy to be helpful. kudos…..</p><h3>Previous stories you will love:</h3><ul><li><a href="https://towardsdatascience.com/50-tensorflow-js-api-explained-in-5-minutes-tensorflow-js-cheetsheet-4f8c7f9cc8b2">50 TensorFlow.js API Explained in 5 Minutes | TensorFlow.js Cheetsheet</a></li><li><a href="https://towardsdatascience.com/tensorflow-1-9-has-arrived-1e6e9171ce5e">TensorFlow 1.9 has Arrived!</a></li><li><a href="https://towardsdatascience.com/tensorflow-on-mobile-tutorial-1-744703297267">TensorFlow on Mobile: Tutorial</a></li><li><a href="https://towardsdatascience.com/activation-functions-neural-networks-1cbd9f8d91d6">Activation Functions in Neural Networks</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6f8ce6ac0b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/deepminds-amazing-mix-match-rl-techique-a6f8ce6ac0b4">DeepMind’s Amazing Mix &amp; Match RL Technique</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TensorFlow 1.9 has Arrived!]]></title>
            <link>https://medium.com/data-science/tensorflow-1-9-has-arrived-1e6e9171ce5e?source=rss-165370addbb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e6e9171ce5e</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[news]]></category>
            <dc:creator><![CDATA[SAGAR SHARMA]]></dc:creator>
            <pubDate>Fri, 08 Jun 2018 17:52:21 GMT</pubDate>
            <atom:updated>2018-06-16T16:18:06.162Z</atom:updated>
            <content:encoded><![CDATA[<h4>Everything you need to know…</h4><p>At the time of writing this article <strong>TensorFlow 1.9</strong> is not updated on their official website but TensorFlow 1.9 rc-0 is out and released on their<strong> </strong><a href="https://github.com/tensorflow/tensorflow/releases/tag/v1.9.0-rc0?linkId=52763826"><strong>GitHub</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Q2EzYMZVBEKbY0gkd5oeg.jpeg" /></figure><h3>The Major and Improvements 🚀</h3><ol><li>Update your <strong>tf.keras </strong>to <strong>Keras 2.1 API.</strong></li><li>Please inherit tf.keras.Model because tfe.Network is <strong>deprecated</strong> now.</li><li>Adding support of core feature columns and losses to <strong>gradient boosted trees estimators.</strong></li><li>The Bijectors API supports broadcasting for Bijectors with new API changes.</li><li>Layered variable are changed in the following conditions</li></ol><ul><li>Using tf.layers in a subclassed tf.keras.Model class. <a href="https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/layers">Supported link</a></li></ul><h3>Might Break Here</h3><p><strong>Replace </strong><strong>variable_scope(&#39;&#39;, ...) by </strong><strong>variable_scope(</strong><strong>tf.get_variable_scope(), ...) </strong>if you are opening variable scopes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*g74faIHEwU84W3Y8s0L3rQ.png" /></figure><h3>Bug Fixes 🐛</h3><h4>tf.data</h4><ul><li>The DatasetBase::DebugString() method is now const.</li><li>Added the tf.contrib.data.sample_from_datasets() API for randomly sampling from multiple datasets.</li></ul><h4>tf.keras</h4><ul><li>Move Keras code out of _impl folder and <strong>remove API files</strong>.</li><li>tf.keras.Model.save_weights now saves in TensorFlow format by default.</li><li>Enable dataset iterators to be passed to tf.keras.Model training/eval methods.</li></ul><h4>Accelerated Linear Algebra (XLA)</h4><h4><a href="https://www.tensorflow.org/programmers_guide/debugger">TensorFlow Debugger (tfdbg) CLI</a></h4><h4>tf.contrib</h4><ul><li>Add tf.contrib.data.choose_from_datasets().</li><li>tf.contrib.data.make_csv_dataset() now supports line breaks in quoted strings. Two arguments were removed from make_csv_dataset.</li><li>tf.contrib.framework.zero_initializer supports ResourceVariable.</li><li>Adding “<strong>constrained_optimization</strong>” to tensorflow/contrib.</li></ul><blockquote>Go to the following link to <strong>see more </strong><a href="https://github.com/tensorflow/tensorflow/releases/tag/v1.9.0-rc0?linkId=52763826"><strong>Bug Fixes</strong></a>.</blockquote><p>Thanks for reading the article, hope you write efficient code with the new features.</p><p>For more updates on TensorFlow releases and more follow me on <a href="https://medium.com/@sagarsharma4244"><strong>Medium</strong></a><strong> and </strong><a href="https://twitter.com/SagarSharma4244"><strong>Twitter</strong></a><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*hQhW7g2Vgq7YqN1IAWlcNA.gif" /></figure><p><strong>Clap it! Share it! Follow Me!</strong></p><h3>Previous stories you will love:</h3><ul><li><a href="https://towardsdatascience.com/50-tensorflow-js-api-explained-in-5-minutes-tensorflow-js-cheetsheet-4f8c7f9cc8b2">50 TensorFlow.js API Explained in 5 Minutes | TensorFlow.js Cheetsheet</a></li><li><a href="https://towardsdatascience.com/tensorflow-on-mobile-tensorflow-lite-a5303eef77eb">TensorFlow on Mobile: TensorFlow Lite</a></li><li><a href="https://towardsdatascience.com/tensorflow-on-mobile-tutorial-1-744703297267">TensorFlow on Mobile: Tutorial</a></li><li><a href="https://towardsdatascience.com/activation-functions-neural-networks-1cbd9f8d91d6">Activation Functions in Neural Networks</a></li><li><a href="https://towardsdatascience.com/epoch-vs-iterations-vs-batch-size-4dfb9c7ce9c9">Epoch vs Batch Size vs Iterations</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e6e9171ce5e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/tensorflow-1-9-has-arrived-1e6e9171ce5e">TensorFlow 1.9 has Arrived!</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[50 TensorFlow.js API Explained in 5 Minutes | TensorFlow.js Cheetsheet]]></title>
            <link>https://medium.com/data-science/50-tensorflow-js-api-explained-in-5-minutes-tensorflow-js-cheetsheet-4f8c7f9cc8b2?source=rss-165370addbb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f8c7f9cc8b2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[SAGAR SHARMA]]></dc:creator>
            <pubDate>Thu, 07 Jun 2018 04:50:26 GMT</pubDate>
            <atom:updated>2018-07-09T08:20:01.840Z</atom:updated>
            <content:encoded><![CDATA[<h4>TensorFlow API Cheetsheet</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*krqfc0x1UtXBuv2IThIWjw.png" /></figure><p>In this article I really want to give a look at the TensorFlow<strong>.js</strong> APIs and understand the library as a whole and understand what are the amazing things it has to offer to the machine learning community.</p><p>I know this article should be 5 minutes long but don’t worry it will not take more than 5 minutes to understand the obvious APIs and even though many of them are very obvious from there names, it was important for me to keep it beginner friendly.</p><p>I have kept the rest of the article as to-the-point as possible with examples. But If you guys have any doubt, let’s have discussion in the comments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*P3TnhdZN7U65kw28YTonOw.png" /></figure><p>It will help you to write better &amp; versatile machine learning code for any new future projects.</p><h3><strong>CREATION 🚀</strong></h3><p>The APIs help to create things like tensors, clones etc.</p><blockquote><strong>1 </strong>-<strong> tf.tensor ( <em>values , </em></strong><em>shape?</em><strong><em> , </em></strong><em>dtype?</em><strong><em> </em>)</strong></blockquote><blockquote><strong>Creates a Tensor with the specified shape of data type.</strong></blockquote><pre><em>// Pass an array of values to create a vector.</em> <br>tf.tensor([1, 2, 3, 4]).print();</pre><pre><strong>------RESULT------</strong><br><strong>Tensor     [1, 2, 3, 4]</strong></pre><pre><em>// Pass a flat array and specify a shape yourself.</em> <br>tf.tensor([1, 2, 3, 4], [2, 2]).print();</pre><pre><strong>------RESULT------</strong><br><strong>Tensor     [[1, 2],      <br>            [3, 4]]</strong></pre><p>Returns → <strong>tf.Tensor</strong></p><blockquote><strong>Note</strong>: They also have shape specified APIs like <em>tf.tensor1d, tf.tensor2d,</em> <em>tf.tensor3d</em> and <em>tf.tensor4d</em>.</blockquote><blockquote><strong>2 </strong>- <a href="https://js.tensorflow.org/api/0.11.2/#buffer"><strong>tf.buffer</strong></a><strong> ( shape , dtype? , values? )</strong></blockquote><blockquote><strong>Creates a Buffer Tensor.</strong></blockquote><pre><em>// Create a buffer and set values at particular indices.</em> <br><strong>const</strong> buffer = tf.buffer([2, 2]); <br>buffer.set(3, 0, 0); <br>buffer.set(5, 1, 0);  <em>// Convert the buffer back to a tensor.</em> buffer.toTensor().print();</pre><pre><strong>-------RESULT------</strong><br><strong>Tensor     [[3, 0],<br>            [5, 0]]</strong></pre><p>Returns → <strong>tf.TensorBuffer</strong></p><blockquote><strong>3 </strong>- <a href="https://js.tensorflow.org/api/0.11.2/#fromPixels"><strong>tf.fromPixels</strong></a><strong> ( <em>pixels, </em></strong><em>numChannels?</em> <strong>)</strong></blockquote><blockquote><strong>Creates a Tensor from Images.</strong></blockquote><pre><strong>const</strong> image = new ImageData(1, 1); <br>image.data[0] = 100; <br>image.data[1] = 150; <br>image.data[2] = 200; <br>image.data[3] = 255;  <br>tf.fromPixels(image).print();</pre><pre><strong>------RESULT------</strong><br><strong>Tensor      [ [[100, 150, 200],]]</strong></pre><p>Returns → <strong>tf.Tensor3D</strong></p><blockquote><strong>4 </strong>- <a href="https://js.tensorflow.org/api/0.11.2/#linspace"><strong>tf.linspace</strong></a><strong> ( <em>start , stop , num </em>)</strong></blockquote><blockquote><strong>Creates a Tensor with evenly spaced numbers.</strong></blockquote><pre>tf.linspace(0, 9, 10).print();</pre><pre><strong>------RESULT------</strong><br><strong>Tensor     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</strong></pre><p>Returns → <strong>tf.Tensor1D</strong></p><blockquote><strong>5 </strong>- <a href="https://js.tensorflow.org/api/0.11.2/#oneHot"><strong>tf.oneHot</strong></a><strong> ( <em>indices , depth , </em></strong><em>onValue?</em><strong><em> ,</em></strong><em> offValue? </em><strong>)</strong></blockquote><blockquote><strong>Convert a set of sparse labels to a dense one-hot representation.</strong></blockquote><pre>tf.oneHot<strong>(</strong>tf.tensor1d([0, 1], &#39;int32&#39;), 3<strong>)</strong>.print();</pre><pre><strong>------RESULT------<br>Tensor     [[1, 0, 0],<br>            [0, 1, 0]]</strong></pre><p>Returns → <strong>tf.Tensor2D</strong></p><blockquote><strong>6 </strong>- <a href="https://js.tensorflow.org/api/0.11.2/#print"><strong>tf.print</strong></a><strong> ( <em>x , </em></strong><em>verbose?</em><strong><em> </em>)</strong></blockquote><blockquote><strong>Prints the info. about any Tensor.</strong></blockquote><pre><strong>const</strong> verbose = true; <br>tf.tensor2d([1, 2, 3, 4], [2, 2]).print(verbose);</pre><pre><strong>------RESULT------<br>Tensor   dtype: float32  <br>         rank: 2  <br>         shape: [2,2]  <br>         values:     [[1, 2], <br>                      [3, 4]]</strong></pre><p>Returns → <strong>void</strong></p><blockquote><strong>7</strong> - <a href="https://js.tensorflow.org/api/0.11.2/#variable"><strong>tf.variable</strong></a><strong> ( <em>initialValue , </em></strong><em>trainable? , name? , dtype? </em><strong>)</strong></blockquote><blockquote><strong>Creates a Tensor variable with provided initial value.</strong></blockquote><pre><strong>const</strong> x = tf.variable(tf.tensor([1, 2, 3]));<br>x.assign(tf.tensor([4, 5, 6]));<br>x.print();</pre><pre><strong>------RESULT------<br>Tensor     [4, 5, 6]</strong></pre><p>Returns → <strong>tf.Variable</strong></p><h3>METHODS for tf.Tensor</h3><blockquote>8 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Tensor.flatten"><strong>flatten</strong></a> ( )</blockquote><blockquote><strong>Flatten a Tensor to a 1D array</strong></blockquote><p>Returns → <strong>tf.Tensor1D</strong></p><blockquote>9 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Tensor.asScalar"><strong>asScalar</strong></a> ( )</blockquote><blockquote><strong>Converts a size-1 tf.Tensor to a tf.Scalar.</strong></blockquote><p>Returns → <strong>tf.Scalar</strong></p><blockquote>10.1 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Tensor.as1D"><strong>as1D</strong></a><strong> ( )</strong></blockquote><blockquote><strong>Converts a tf.Tensor to a tf.Tensor1D.</strong></blockquote><p>Returns→ <strong>tf.Tensor1D</strong></p><blockquote>10.2 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Tensor.as2D"><strong>as2D</strong></a><strong> (rows , columns)</strong></blockquote><blockquote><strong>Converts a tf.Tensor to a tf.Tensor2D.</strong></blockquote><p>Returns→ <strong>tf.Tensor2D</strong></p><blockquote>10.3 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Tensor.as3D"><strong>as3D</strong></a> ( <strong>rows , columns , depth </strong>)</blockquote><blockquote><strong>Converts a tf.Tensor to a tf.Tensor3D.</strong></blockquote><p>Returns→ <strong>tf.Tensor3D</strong></p><blockquote>10.4 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Tensor.as4D"><strong>as4D</strong></a> ( <strong>rows , columns , depth , depth2 </strong>)</blockquote><blockquote><strong>Converts a tf.Tensor to a tf.Tensor4D.</strong></blockquote><p>Returns→ <strong>tf.Tensor4D</strong></p><blockquote>11 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Tensor.asType"><strong>asType</strong></a><strong> ( dtype )</strong></blockquote><blockquote><strong>Casts a tf.Tensor to a specified dtype.</strong></blockquote><p>Returns→ <strong>this</strong></p><blockquote>12 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Tensor.buffer"><strong>buffer</strong></a><strong> ( )</strong></blockquote><blockquote><strong>Returns a tf.TensorBuffer that holds the underlying data.</strong></blockquote><p>Returns→ <strong>tf.TensorBuffer</strong></p><blockquote>13 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Tensor.data"><strong>data</strong></a><strong> </strong>( )</blockquote><blockquote><strong>The tf.data API helps to build flexible and efficient input pipelines.</strong></blockquote><p>Returns→ <strong>Promise</strong></p><blockquote>14 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Tensor.dispose"><strong>dispose</strong></a><strong> ( )</strong></blockquote><blockquote><strong>Disposes tf.Tensor from memory.</strong></blockquote><p>Returns→ <strong>void</strong></p><blockquote>15.1 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Tensor.toFloat"><strong>toFloat</strong></a><strong> ( )</strong></blockquote><blockquote><strong>Casts the array to type float32.</strong></blockquote><p>Returns→ <strong>this</strong></p><blockquote>15.2 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Tensor.toInt"><strong>toInt</strong></a><strong> ( )</strong></blockquote><blockquote><strong>Casts the array to type int32.</strong></blockquote><p>Returns→ <strong>this</strong></p><blockquote>15.3 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Tensor.toBool"><strong>toBool</strong></a><strong> ( )</strong></blockquote><blockquote><strong>Casts the array to type bool.</strong></blockquote><p>Returns→<strong>this</strong></p><blockquote>16 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Tensor.reshapeAs"><strong>reshapeAs</strong></a><strong> ( x )</strong></blockquote><blockquote><strong>Reshapes the tensor into the shape of the provided tensor.</strong></blockquote><p>Returns→ <strong>tf.Tensor</strong></p><blockquote>17 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Tensor.toString"><strong>toString</strong></a><strong> ( verbose? )</strong></blockquote><blockquote><strong>Returns a human-readable description of the tensor. Useful for logging.</strong></blockquote><p>Returns→ <strong>string</strong></p><h3>METHODS for tf.Variable EXTENDS to tf.Tensor</h3><blockquote>18 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Variable.assign"><strong>assign</strong></a><strong> (newValue)</strong></blockquote><blockquote><strong>Assign a new tf.Tensor to this variable.</strong></blockquote><p>Returns→ <strong>void</strong></p><h3><strong>METHODS for tf.TensorBuffer</strong></h3><p><strong>tf.TensorBuffer allows to set a value before declaring it a tf.Tensor whoch can’t be changed.</strong></p><blockquote>19 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.TensorBuffer.set"><strong>set</strong></a><strong> ( value , locs )</strong></blockquote><blockquote><strong>Sets a value in the buffer at a given location.</strong></blockquote><p>Returns→ <strong>void</strong></p><blockquote>20 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.TensorBuffer.get"><strong>get</strong></a><strong> ( locs )</strong></blockquote><blockquote><strong>Returns the value in the buffer at the provided location.</strong></blockquote><p>Returns→ <strong>number</strong></p><blockquote>21 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.TensorBuffer.toTensor"><strong>toTensor</strong></a><strong> ( )</strong></blockquote><blockquote><strong>Creates an immutable tf.Tensor object from the buffer.</strong></blockquote><p>Returns→<strong>tf.Tensor</strong></p><h3>TRANSFORAMTIONS</h3><blockquote>22 - <a href="https://js.tensorflow.org/api/0.11.2/#expandDims"><strong>tf.expandDims</strong></a><strong> ( x , axis? )</strong></blockquote><blockquote><strong>Returns a tf.Tensor that has expanded rank, by inserting a dimension into the tensor’s shape.</strong></blockquote><pre><strong>const</strong> x = tf.tensor1d([1, 2, 3, 4]); <br><strong>const</strong> axis = 1; <br>x.expandDims(axis).print();</pre><pre><strong>------RESULT------<br>Tensor     [[1],      [2],      [3],      [4]]</strong></pre><p>Returns→ <strong>tf.Tensor</strong></p><blockquote>23 - <a href="https://js.tensorflow.org/api/0.11.2/#cast"><strong>tf.cast</strong></a><strong> ( x , dtype )</strong></blockquote><blockquote><strong>Casts a tf.Tensor to a new dtype.</strong></blockquote><pre><strong>const</strong> x = tf.tensor1d([1.5, 2.5, 3]);<br>tf.cast(x, &#39;int32&#39;).print();</pre><pre><strong>------RESULT------<br>Tensor     [1, 2, 3]</strong></pre><p>Returns→ <strong>tf.Tensor</strong></p><blockquote>24 - <a href="https://js.tensorflow.org/api/0.11.2/#pad"><strong>tf.pad</strong></a><strong> ( x , paddings , constantValue? )</strong></blockquote><blockquote><strong>Pads a tf.Tensor with a given value and paddings.</strong></blockquote><pre>const x = tf.tensor1d([1, 2, 3, 4]);<br>x.pad([[1, 2]]).print();</pre><pre><strong>------RESULT------<br>Tensor     [0, 1, 2, 3, 4, 0, 0]</strong></pre><p>Returns→ <strong>tf.Tensor</strong></p><blockquote>25 - <a href="https://js.tensorflow.org/api/0.11.2/#reshape"><strong>tf.reshape</strong></a><strong> ( x , shape)</strong></blockquote><blockquote><strong>Reshapes a tf.Tensor to a given shape.</strong></blockquote><pre><strong>const</strong> x = tf.tensor1d([1, 2, 3, 4]); <br>x.reshape([2, 2]).print();</pre><pre><strong>------RESULT------<br>Tensor     [[1, 2],      <br>            [3, 4]]</strong></pre><p>Returns→ <strong>tf.Tensor</strong></p><blockquote>26 - tf.squeeze ( x , axis? )</blockquote><blockquote><strong>Removes dimensions of size 1 from the shape of a tf.Tensor</strong></blockquote><pre>const x = tf.tensor([1, 2, 3, 4], [1, 1, 4]);<br>x.squeeze().print();</pre><pre><strong>------RESULT------<br>Tensor     [1, 2, 3, 4]</strong></pre><p>Returns→ <strong>tf.Tensor</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*-eVfVO9rzOUWEb4h4IWx4g.jpeg" /></figure><h3>MODELS</h3><p>Models are a collection of Layers, see Model Creation for details about how Layers can be connected.</p><blockquote>27 - <a href="https://js.tensorflow.org/api/0.11.2/#sequential">tf.</a><a href="https://js.tensorflow.org/api/0.11.2/#model">model</a> ( ) EXTENDS to CONTAINERS</blockquote><blockquote><strong>A model is a data structure that consists of Layers and have nodes defined as inputs and outputs.</strong></blockquote><p>Models made with tf.model are just more generic than <strong>tf.sequential</strong> models.</p><blockquote>The following code snippet defines a model consisting of <strong>two dense layers (fully connected)</strong>, with <strong>10 and 4 units.</strong></blockquote><pre><em>//Define input, which has a size of 5(not including batch dimension)</em><br><strong>const input = tf.input({shape: [5]});  </strong><br><em>// First dense layer uses relu activation.</em> <br><strong>const denseLayer1 = tf.layers.dense({units: 10, activation: &#39;relu&#39;});</strong> <br><em>// Second dense layer uses softmax activation.</em> <br><strong>const denseLayer2 = tf.layers.dense({units: 2, activation: &#39;softmax&#39;})</strong>;  <br><em>// Obtain the output symbolic tensor by applying the layers on the input.</em> <br><strong>const output = denseLayer2.apply(denseLayer1.apply(input));  <br></strong><em>// Create the model based on the inputs.</em> <br><strong>const model = tf.model({inputs: input, outputs: output});  <br></strong><em>// The model can be used for training, evaluation and prediction.</em> <br><em>// For example, the following line runs prediction with the model on</em> <em>// some fake data.</em> <br><strong>model.predict(tf.ones([2, 5])).print();</strong></pre><pre><strong>------RESULT------<br>Tensor     [[0.3465916, 0.6534085],      [0.3465916, 0.6534085]]</strong></pre><blockquote>27.1 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Model.compile"><strong>compile</strong></a><strong> ( config )</strong></blockquote><blockquote><strong>Configures and prepares the model for training and evaluation. Compiling outfits the model with an config (optimizer, loss, and/or metrics). Calling fit or evaluate on an un-compiled</strong> <strong>model will throw an error.</strong></blockquote><p>Returns→ <strong>void</strong></p><blockquote>27.2 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Model.evaluate"><strong>evaluate</strong></a><strong> ( x , y , config? )</strong></blockquote><blockquote>Returns the loss value &amp; metrics values for the model in test mode which are specified during compile(), which needs to happen before calls to evaluate().</blockquote><pre><strong>const</strong> model = tf.sequential({    <br>layers: [tf.layers.dense({units: 1, inputShape: [10]})] }); model.compile({optimizer: &#39;sgd&#39;, loss: &#39;meanSquaredError&#39;}); <br><strong>const</strong> result = <strong>model.evaluate(tf.ones([8, 10]), tf.ones([8, 1]),               { batchSize: 4})</strong>; <br>result.print();<br><strong>------RESULT------<br>Tensor     0.00010169133020099252</strong></pre><p>Returns→ <strong>tf.Scalar</strong> or <strong>tf.Scalar[]</strong></p><blockquote>27.3 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Model.predict"><strong>predict</strong></a><strong> ( x , config? )</strong></blockquote><blockquote><strong>Generates output predictions for the input samples and the computations is done in batches.</strong></blockquote><pre><strong>const</strong> model = tf.sequential({<br>   layers: [tf.layers.dense({units: 1, inputShape: [10]})]<br>});<br>model.predict(tf.ones([8, 10]), {batchSize: 4}).print();<br><strong>------RESULT------<br>Tensor    <br>[[1.8470926],      <br>[1.8470926],      <br>[1.8470926],      <br>[1.8470926],      <br>[1.8470926],      <br>[1.8470926],      <br>[1.8470926],      <br>[1.8470926]]</strong></pre><p>Returns→ <strong>tf.Tensor </strong>or <strong>tf.Tensor[]</strong></p><blockquote>27.4 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Model.predictOnBatch"><strong>predictOnBatch</strong></a><strong> ( x )</strong></blockquote><blockquote><strong>Returns predictions for a single batch of samples where x is a tensor.</strong></blockquote><pre><strong>const</strong> model = tf.sequential({<br>   layers: [tf.layers.dense({units: 1, inputShape: [10]})]<br>});<br>model.predictOnBatch(tf.ones([8, 10])).print();<br><strong>------RESULT------<br>Tensor     <br>[[-1.1825931],      <br>[-1.1825931],      <br>[-1.1825931],      <br>[-1.1825931],      <br>[-1.1825931],      <br>[-1.1825931],      <br>[-1.1825931],      <br>[-1.1825931]]</strong></pre><p>Returns→ <strong>tf.Tensor </strong>or <strong>tf.Tensor[ ]</strong></p><blockquote>27.5 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Model.fit"><strong>fit</strong></a><strong> ( x , y , config? )</strong></blockquote><blockquote><strong>Trains the model for a fixed number of epochs (iterations on a dataset).</strong></blockquote><pre><strong>const</strong> model = tf.sequential({      <br>layers: [tf.layers.dense({units: 1, inputShape: [10]})] }); model.compile({optimizer: &#39;sgd&#39;, loss: &#39;meanSquaredError&#39;}); <br>for (let i = 1; i &lt; 5 ; ++i) {    <br><strong>const</strong> h = await model.fit(tf.ones([8, 10]), tf.ones([8, 1]), <br>                          { batchSize: 4, epochs: 3    });    <br>console.log(&quot;Loss after Epoch &quot; + i + &quot; : &quot; + h.history.loss[0]); <br>}<br><strong>------RESULT------<br>Loss after Epoch 1 : 0.32676371932029724 <br>Loss after Epoch 2 : 0.016571789979934692 <br>Loss after Epoch 3 : 0.0008404387044720352 <br>Loss after Epoch 4 : 0.00004262066795490682</strong></pre><p>Returns→ <strong>Promise</strong></p><blockquote>28 - <a href="https://js.tensorflow.org/api/0.11.2/#model"><strong>tf.</strong></a><a href="https://js.tensorflow.org/api/0.11.2/#sequential">sequential</a><strong> ( ) EXTENDS to tf.Model</strong></blockquote><blockquote><strong>A model with a stack of layers, feeding linearly from one to the next.</strong></blockquote><pre><em>// Define a model for linear regression.</em>   <br><strong>const</strong> model = tf.sequential();   <br>model.add(tf.layers.dense({units: 1, inputShape: [1]}));    <br><em>//Prepare model for training: Specify the loss and the optimizer.</em>   <br>model.compile({loss: &#39;meanSquaredError&#39;, optimizer: &#39;sgd&#39;});    <br><em>// Generate some synthetic data for training.</em>   <br><strong>const</strong> xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);   <br><strong>const</strong> ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);    <br><em>// Train the model using the data then do inference on a data point //the</em> <em>model hasn&#39;t seen:</em>   <br>await model.fit(xs, ys);   model.predict(tf.tensor2d([5], [1, 1])).print();</pre><pre><strong>------RESULT------<br>Tensor      [[3.1389987],]</strong></pre><blockquote>28.1 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Sequential.add"><strong>add</strong></a><strong> ( layer )</strong></blockquote><blockquote><strong>Adds a layer instance on top of the layer stack.</strong></blockquote><pre>const model = tf.sequential();<br>model.add(tf.layers.dense({units: 8, inputShape: [1]})); model.add(tf.layers.dense({units: 4, activation: &#39;relu6&#39;})); model.add(tf.layers.dense({units: 1, activation: &#39;relu6&#39;}));<br>  <br><em>// Note that the untrained model is random at this point.</em><br> model.predict(tf.randomNormal([10, 1])).print();</pre><pre><strong>------RESULT------<br>Tensor     [[0.0679427],      <br>[0.3440365],      <br>[0.4146437],      <br>[0        ],      <br>[0.0855753],      <br>[0.0688378],      <br>[0.1540508],      <br>[0        ],      <br>[0        ],      <br>[0        ]]</strong></pre><p>Returns→ <strong>void</strong></p><blockquote>28.2 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Sequential.evaluate"><strong>evaluate</strong></a><strong> ( x , y , config? )</strong></blockquote><blockquote><strong>Returns the loss value &amp; metrics values for the model in test mode and Computation is done in batches.</strong></blockquote><pre><strong>const</strong> model = tf.sequential({<br>   layers: [tf.layers.dense({units: 1, inputShape: [10]})]<br>});<br>model.compile({optimizer: &#39;sgd&#39;, loss: &#39;meanSquaredError&#39;});<br><strong>const</strong> result = model.evaluate(tf.ones([8, 10]), tf.ones([8, 1]), {<br>   batchSize: 4,<br>});<br>result.print();</pre><pre><strong>------RESULT------<br>Tensor     5.569275379180908</strong></pre><p>Returns→<strong>tf.Scalar</strong> or <strong>tf.Scalar[]</strong></p><blockquote>28.3 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Sequential.predict"><strong>predict</strong></a><strong> ( x , config? )</strong></blockquote><blockquote><strong>Generates output predictions for the input samples and Computation is done in batches.</strong></blockquote><pre><strong>const</strong> model = tf.sequential({<br>   layers: [tf.layers.dense({units: 1, inputShape: [10]})]<br>});<br>model.predict(tf.ones([2, 10])).print();</pre><pre><strong>------RESULT------<br>Tensor     [[-0.6576568],      [-0.6576568]]</strong></pre><p>Returns→ <strong>tf.Tensor </strong>or <strong>tf.Tensor[]</strong></p><blockquote>28.4 - <a href="https://js.tensorflow.org/api/0.11.2/#tf.Sequential.fit"><strong>fit</strong></a><strong> ( x , y , config? )</strong></blockquote><blockquote><strong>Trains the model for a fixed number of epochs (iterations on a dataset).</strong></blockquote><pre><strong>const</strong> model = tf.sequential({<br>   layers: [tf.layers.dense({units: 1, inputShape: [10]})]<br>});<br>model.compile({optimizer: &#39;sgd&#39;, loss: &#39;meanSquaredError&#39;});<br><strong>const</strong> history = await model.fit(tf.ones([8, 10]), tf.ones([8, 1]), {<br>   batchSize: 4,<br>   epochs: 3<br>});<br>console.log(history.history.loss[0]);</pre><pre><strong>------RESULT------<br>0.486328125</strong></pre><p>Returns→ <strong>Promise</strong></p><blockquote>29 - <a href="https://js.tensorflow.org/api/0.11.2/#loadModel"><strong>tf.loadModel</strong></a><strong> ( path or IOHandler )</strong></blockquote><blockquote><strong>Load a model, including its topology and optionally weights.</strong></blockquote><p><strong>Example 1</strong>: Save tf.model()’s topology and weights to browser local storage; then load it back.</p><pre><strong>const</strong> model = tf.sequential(<br>     {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});<br>console.log(&#39;Prediction from original model:&#39;);<br>model.predict(tf.ones([1, 3])).print();<br><br><strong>const</strong> saveResults = await model.save(&#39;localstorage://my-model-1&#39;);<br><br><strong>const</strong> loadedModel = await tf.loadModel(&#39;localstorage://my-model-1&#39;);<br>console.log(&#39;Prediction from loaded model:&#39;);<br>loadedModel.predict(tf.ones([1, 3])).print();</pre><pre><strong>------RESULT------<br>Prediction from original model: Tensor      [[0.7820088],] Prediction from loaded model: Tensor      [[0.7820088],]</strong></pre><p><strong>Example 2:</strong> Load a model from user-selected files from HTML file input elements.</p><pre><em>// Note: this code snippet will not work without the HTML elements in the page</em><br><strong>const</strong> jsonUpload = document.getElementById(&#39;json-upload&#39;);<br><strong>const</strong> weightsUpload = document.getElementById(&#39;weights-upload&#39;);</pre><pre><strong>const</strong> model = await tf.loadModel<strong>(</strong><br>tf.io.browserFiles([jsonUpload.files[0],     weightsUpload.files[0]])<strong>)</strong>;</pre><p><strong>Example 3: </strong>Load a model from an HTTP server.</p><pre><strong>const</strong> model = await<br>     tf.loadModel(&#39;https://storage.googleapis.com/tfjs-models/tfjs/iris_v1/model.json&#39;)</pre><h3>MODEL MAGEMENT</h3><blockquote>30.1 - <a href="https://js.tensorflow.org/api/0.11.2/#copyModel"><strong>tf.copyModel</strong></a><strong> ( sourceURL , destURL )</strong></blockquote><blockquote><strong>Copy a model from one URL to another.</strong></blockquote><pre><em>// First create and save a model.</em> <br><strong>const</strong> model = tf.sequential(); <br>model.add(tf.layers.dense<strong>(</strong>      {units: 1, inputShape: [10], activation: &#39;sigmoid&#39;})<strong>)</strong>; <br>await model.save(&#39;localstorage://demo/management/model1&#39;); <br> <br><em>// Then list existing models.</em> <br>console.log(await tf.io.listModels());  </pre><pre><em>// Copy the model, from Local Storage to IndexedDB.</em> <br>await tf.io.copyModel(&#39;localstorage://demo/management/model1&#39;,      &#39;indexeddb://demo/management/model1&#39;);  </pre><pre><em>// List models again.</em> <br>console.log(await tf.io.listModels()); <br> <br><em>// Remove both models.</em> <br>await tf.io.removeModel(&#39;localstorage://demo/management/model1&#39;); await tf.io.removeModel(&#39;indexeddb://demo/management/model1&#39;);</pre><pre><strong>------RESULT------<br>[object Object] [object Object]</strong></pre><p>Returns→ <strong>Promise</strong></p><blockquote>30.2 - <a href="https://js.tensorflow.org/api/0.11.2/#listModels"><strong>tf.listModels</strong></a><strong> ( )</strong></blockquote><blockquote><strong>List all models stored in registered storage mediums.</strong></blockquote><pre><em>// First create and save a model.</em> <br>const model = tf.sequential(); <br>model.add<strong>(</strong>tf.layers.dense(  {units: 1, inputShape: [10], activation:   &#39;sigmoid&#39;})<strong>)</strong>; <br>await model.save(&#39;localstorage://demo/management/model1&#39;);<br> <br><em>// Then list existing models.</em> <br>console.log(await tf.io.listModels());  </pre><pre><em>// Delete the model.</em> <br>await tf.io.removeModel(&#39;localstorage://demo/management/model1&#39;); <br> <br><em>// List models again.</em> <br>console.log(await tf.io.listModels());</pre><pre><strong>------RESULT------<br>[object Object] [object Object]</strong></pre><p>Returns:→<strong>Promise</strong></p><blockquote>30.3 - <a href="https://js.tensorflow.org/api/0.11.2/#moveModel"><strong>tf.moveModel</strong></a><strong> ( sourceURL , destURL )</strong></blockquote><blockquote><strong>Move a model from one URL to another.</strong></blockquote><pre><em>// First create and save a model.</em> <br><strong>const</strong> model = tf.sequential(); <br>model.add(tf.layers.dense({units: 1, inputShape: [10], activation: &#39;sigmoid&#39;})); <br>await model.save(&#39;localstorage://demo/management/model1&#39;);  </pre><pre><em>// Then list existing models.</em> <br>console.log(await tf.io.listModels()); </pre><pre> <em>// Move the model, from Local Storage to IndexedDB.</em> <br>await tf.io.moveModel(&#39;localstorage://demo/management/model1&#39;,      &#39;indexeddb://demo/management/model1&#39;);  </pre><pre><em>// List models again.</em> <br>console.log(await tf.io.listModels());  </pre><pre><em>// Remove the moved model.</em> <br>await tf.io.removeModel(&#39;indexeddb://demo/management/model1&#39;);</pre><pre><strong>------RESULT------<br>[object Object] [object Object]</strong></pre><p>Returns→ <strong>Promise</strong></p><blockquote>30.4 - <a href="https://js.tensorflow.org/api/0.11.2/#removeModel"><strong>tf.removeModel</strong></a><strong> ( url )</strong></blockquote><blockquote><strong>Remove a model specified by URL from a registered storage medium.</strong></blockquote><pre><em>// First create and save a model.</em> <br><strong>const</strong> model = tf.sequential(); <br>model.add(tf.layers.dense(      {units: 1, inputShape: [10], activation: &#39;sigmoid&#39;})); <br>await model.save(&#39;localstorage://demo/management/model1&#39;);  </pre><pre><em>// Then list existing models.<br></em> console.log(await tf.io.listModels());  </pre><pre><em>// Delete the model.</em> <br>await tf.io.removeModel(&#39;localstorage://demo/management/model1&#39;);  </pre><pre><em>// List models again.</em> <br>console.log(await tf.io.listModels());<br><strong>------RESULT------<br>[object Object] [object Object]</strong></pre><p>Returns→ <strong>Promise</strong></p><h3>LAYERS ( Advanced Activation )</h3><blockquote>31.1 - <a href="https://js.tensorflow.org/api/0.11.2/#layers.leakyReLU"><strong>tf.layers.leakyReLU</strong></a><strong> ( config? )</strong></blockquote><blockquote><strong>Input shape: Arbitrary. Use the configuration </strong><strong>inputShape when using this layer as the first layer in a model.</strong></blockquote><blockquote>(x) = alpha * x for x &lt; 0. f(x) = x for x &gt;= 0.</blockquote><blockquote>Output shape→ Same shape as the input.</blockquote><p>Returns→ <strong>tf.layers.Layer</strong></p><blockquote>31.2 - <a href="https://js.tensorflow.org/api/0.11.2/#layers.softmax"><strong>tf.layers.softmax</strong></a><strong> ( config? )</strong></blockquote><blockquote><strong>Input shape</strong>→ Arbitrary. Use the configuration inputShape when using this layer as the first layer in a model.</blockquote><blockquote><strong>Output shape</strong> → Same shape as the input.</blockquote><p>Returns→ <strong>tf.layers.Layer</strong></p><h3>LAYERS (Basic Functions)</h3><blockquote>32.1 - <a href="https://js.tensorflow.org/api/0.11.2/#layers.dense"><strong>tf.layers.dense</strong></a><strong> (units, activation fun., config? )</strong></blockquote><blockquote><strong>Creates a dense (fully connected) layer.</strong></blockquote><blockquote><strong>output = acticvation(dot(input, kernel(aka weights) ) + bias)</strong></blockquote><p><strong>units</strong> (number) Positive integer, dimensionality of the output space.</p><p>Returns→ <strong>tf.layers.Layer</strong></p><blockquote>32.2 - <a href="https://js.tensorflow.org/api/0.11.2/#layers.dropout"><strong>tf.layers.dropout</strong></a><strong> (rate , config? )</strong></blockquote><blockquote><strong>Applies dropout to the input.</strong></blockquote><p><strong>rate</strong> (number) Float between 0 and 1. Fraction of the input units to drop.</p><p>Returns→ <strong>tf.layers.Layer</strong></p><blockquote>32.3 - <a href="https://js.tensorflow.org/api/0.11.2/#layers.flatten"><strong>tf.layers.flatten</strong></a><strong> ( config? )</strong></blockquote><blockquote><strong>Flattens the input and does not affect the batch size.</strong></blockquote><blockquote><strong>It flattens each batch in its inputs to 1D (making the output 2D).</strong></blockquote><pre><strong>const</strong> input = tf.input({shape: [4, 3]});<br><strong>const</strong> flattenLayer = tf.layers.flatten();</pre><pre><em>// Inspect the inferred output shape of flatten layer, which</em><br><em>// equals `[null, 12]`. The 2nd dimension is 4 * 3, i.e., the result // of the flattening.(The 1st dimension is undermined batch size.)</em></pre><pre>console.log(JSON.stringify(flattenLayer.apply(input).shape));</pre><pre><strong>------RESULT------<br>[null,12]</strong></pre><p>Returns→ <strong>tf.layers.Layer</strong></p><h3>LAYERS (Convolutional)</h3><blockquote>33 - <a href="https://js.tensorflow.org/api/0.11.2/#layers.conv2d"><strong>tf.layers.conv2d</strong></a><strong> ( filters )</strong></blockquote><blockquote><strong>This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs.</strong></blockquote><p><strong>filters</strong> (number) The dimensionality of the output space (i.e. the number of filters in the convolution).</p><p>Returns→ <strong>tf.layers.Layer</strong></p><blockquote>34 - <a href="https://js.tensorflow.org/api/0.11.2/#layers.cropping2D"><strong>tf.layers.cropping2D</strong></a><strong> ( cropping, config? )</strong></blockquote><blockquote><strong>This layer can crop an input at the top, bottom, left and right side of an image tensor.</strong></blockquote><p><strong>cropping</strong> (number|[number, number]|[[number, number], [number, number]])Dimension of the cropping along the width and the height.</p><pre><strong>const</strong> model = tf.sequential(); model.add(tf.layers.cropping2D({cropping:[[2, 2], [2, 2]],                                 inputShape: [128, 128, 3]})); </pre><pre><em>//now output shape is [batch, 124, 124, 3]</em></pre><p>Returns→ <strong>tf.layers.Layer</strong></p><h3>LAYERS (Normalization)</h3><blockquote>35 - <a href="https://js.tensorflow.org/api/0.11.2/#layers.batchNormalization"><strong>tf.layers.batchNormalization</strong></a><strong> ( axis, config? )</strong></blockquote><blockquote><strong>Normalize the activations of the previous layer at each batch, i.e. applies a transformation that maintains the mean activation close to 0 and the activation standard deviation close to 1.</strong></blockquote><p><strong>axis</strong> (number) The integer axis that should be normalized (typically the features axis). Defaults to -1.</p><p>Returns→ <strong>tf.layers.Layer</strong></p><h3>LAYERS (Pooling)</h3><blockquote>36 - <a href="https://js.tensorflow.org/api/0.11.2/#layers.averagePooling1d"><strong>tf.layers.averagePooling2d</strong></a><strong> ( poolSize, config )</strong></blockquote><blockquote><strong>Average pooling operation for spatial data.</strong></blockquote><p><strong>poolSize</strong> (number or [number, number]) Factors by which to downscale in each dimension [vertical, horizontal]. Expects an integer or an array of 2 integers.</p><p>Returns→ <strong>tf.layers.Layer</strong></p><blockquote>Note: They also have <strong>averagePooling1d</strong> and <strong>globalAveragePooling</strong> etc.</blockquote><blockquote>37 - <a href="https://js.tensorflow.org/api/0.11.2/#layers.maxPooling2d"><strong>tf.layers.maxPooling2d</strong></a><strong> ( </strong>poolSize, <strong>config )</strong></blockquote><blockquote><strong>Max pooling operation for spatial data.</strong></blockquote><p><strong>poolSize</strong> (number|[number, number]) Factors by which to downscale in each dimension [vertical, horizontal]. Expects an integer or an array of 2 integers.</p><p>Returns→ <strong>tf.layers.Layer</strong></p><blockquote>Note: They also have <strong>maxPooling1d</strong> and <strong>globalMaxPooling</strong> etc.</blockquote><h3>LAYERS (Wrapper)</h3><blockquote>38 - <a href="https://js.tensorflow.org/api/0.11.2/#layers.bidirectional"><strong>tf.layers.bidirectional</strong></a><strong> ( layer, config )</strong></blockquote><blockquote><strong>It involves duplicating the first recurrent layer in the network so that there are now two layers side-by-side, then providing the input sequence as-is as input to the first layer and providing a reversed copy of the input sequence to the second. This technique helps in LSTMs.</strong></blockquote><p><strong>layer</strong> (RNN) The instance of an RNN layer to be wrapped.</p><p>Returns → <strong>Wrapper</strong></p><blockquote>39 - <a href="https://js.tensorflow.org/api/0.11.2/#layers.timeDistributed"><strong>tf.layers.timeDistributed</strong></a><strong> ( layer )</strong></blockquote><blockquote><strong>The input should be at least 3D, and the dimension of the index 1 will be considered to be the temporal dimension.</strong></blockquote><p>Returns→ <strong>tf.layers.Layer</strong></p><h3>LAYERS (Reccurent)</h3><blockquote>40 - <a href="https://js.tensorflow.org/api/0.11.2/#layers.rnn"><strong>tf.layers.rnn</strong></a><strong> ( cell</strong>(tf.RNNCell or tf.RNNCell[ ] <strong>) )</strong></blockquote><blockquote><strong>Input shape: 3D tensor with shape .</strong></blockquote><p>Returns→ <strong>tf.layers.Layer</strong></p><blockquote>41 - <a href="https://js.tensorflow.org/api/0.11.2/#layers.simpleRNN"><strong>tf.</strong></a><a href="https://js.tensorflow.org/api/0.11.2/#multiRNNCell"><strong>multiRNNCell</strong></a><strong> (lstmCells, data, c, h)</strong></blockquote><blockquote><strong>Computes the next states and outputs of a stack of LSTMCells.</strong></blockquote><blockquote><strong>Each cell output is used as input to the next cell</strong></blockquote><p><strong>lstmCells</strong> <em>Array of LSTMCell functions</em>.</p><p><strong>data</strong> <em>The input to the cell.</em></p><p><strong>c</strong> <em>Array of previous cell states.</em></p><p><strong>h</strong> <em>Array of previous cell outputs.</em></p><p>Returns→<strong> [tf.Tensor2D[], tf.Tensor2D[]]</strong></p><blockquote>Note: They also have <a href="https://js.tensorflow.org/api/0.11.2/#layers.simpleRNNCell"><strong>tf.layers.simpleRNNCell</strong></a><strong> ,</strong></blockquote><blockquote><a href="https://js.tensorflow.org/api/0.11.2/#layers.stackedRNNCells"><strong>tf.layers.stackedRNNCells</strong></a><strong> (config) ,</strong></blockquote><blockquote><a href="https://js.tensorflow.org/api/0.11.2/#layers.simpleRNN"><strong>layers.simpleRNN</strong></a><strong> (config)</strong></blockquote><blockquote>42 - <a href="https://js.tensorflow.org/api/0.11.2/#layers.lstm"><strong>tf.layers.lstm</strong></a><strong> (config)</strong></blockquote><blockquote><strong>Long-Short Term Memory layer</strong></blockquote><pre><strong>const</strong> lstm = tf.layers.lstm({units: 8, returnSequences: true});  </pre><pre><em>// Create an input with 10 time steps.</em> <br><strong>const</strong> input = tf.input({shape: [10, 20]}); <br><strong>const</strong> output = lstm.apply(input);  </pre><pre>console.log(JSON.stringify(output.shape)); </pre><pre><em>// [null, 10, 8]: 1st dimension is unknown batch size; <br>// 2nd dimension is the same as the sequence length of [tf.input()]//(#input), due to `returnSequences`: `true`;</em> <br><em>// 3rd dimension is the `LSTMCell`&#39;s number of units.</em></pre><pre><strong>------RESULT------<br>[null,10,8]</strong></pre><p>Returns→ <strong>tf.layers.Layer</strong></p><blockquote>43 - <a href="https://js.tensorflow.org/api/0.11.2/#layers.lstmCell"><strong>tf.layers.lstmCell</strong></a><strong> (config)</strong></blockquote><blockquote><strong>LSTM Cell is distinct from the RNN subclass LSTM in that its apply method takes the input data of only a single time step and returns the cell&#39;s output at the time step, while LSTM takes the input data over a number of time steps.</strong></blockquote><p>For example:</p><pre>const cell = tf.layers.lstmCell({units: 2}); <br>const input = tf.input({shape: [10]}); <br>const output = cell.apply(input);  console.log(JSON.stringify(output.shape)); <br><em>// [null, 10]: This is cell&#39;s output at a single time step. The 1st</em> <em>// dimension is the unknown batch size.</em></pre><pre><strong>------RESULT------<br>[null,10]</strong></pre><p>The most typical use of LSTMCell workflow is to combine a number of cells into a stacked RNN cell. For Example</p><pre><strong>const</strong> cells = [tf.layers.lstmCell({units: 4}),          tf.layers.lstmCell({units: 8}), ]; <br>const rnn = tf.layers.rnn({cell: cells, returnSequences: true});  </pre><pre><em>//Create input with 10 time steps and length-20 vector at each step.</em> <br>const input = tf.input({shape: [10, 20]}); <br>const output = rnn.apply(input);</pre><pre>console.log(JSON.stringify(output.shape)); </pre><pre><em>// [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension //is the</em> <em>same as the sequence length of [tf.input()](#input), due to //`returnSequences`: `true`;</em> <em>3rd dimension is the last `lstmCell`&#39;s //number of units.</em></pre><pre><strong>------RESULT------<br>[null,10,8]</strong></pre><p>Returns→ <strong>tf.RNNCell</strong></p><blockquote>44 - <a href="https://js.tensorflow.org/api/0.11.2/#basicLSTMCell"><strong>tf.basicLSTMCell</strong></a><strong> ( forgetBias , lstmKernel , lstmBias , data , c , h )</strong></blockquote><blockquote><strong>Computes the next state and output of a BasicLSTMCell.</strong></blockquote><p><strong>c</strong> Previous cell state.</p><p><strong>h</strong> Previous cell output.</p><p>Returns→ <strong>[tf.Tensor2D, tf.Tensor2D]</strong></p><h3>TRAINING (Gradient)</h3><blockquote>45 - <a href="https://js.tensorflow.org/api/0.11.2/#grad"><strong>tf.grad</strong></a><strong> ( f )</strong></blockquote><blockquote><strong>f</strong> stands for mathematical function.</blockquote><pre><em>// f(x) = x ^ 2</em> <br><strong>const</strong> f = x =&gt; x.square(); </pre><pre><em>// f&#39;(x) = 2x</em> <br><strong>const</strong> g = tf.grad(f); <br> <br><strong>const</strong> x = tf.tensor1d([2, 3]); <br>g(x).print();</pre><pre><strong>------RESULT------<br>Tensor     [4, 6]</strong></pre><p>Another Example</p><pre><em>// f(x) = x ^ 3</em> <br><strong>const</strong> f = x =&gt; x.pow(tf.scalar(3, &#39;int32&#39;)); </pre><pre><em>// f&#39;(x) = 3x ^ 2</em> <br><strong>const</strong> g = tf.grad(f); </pre><pre><em>// f&#39;&#39;(x) = 6x</em> <br><strong>const</strong> gg = tf.grad(g);  <br><strong>const</strong> x = tf.tensor1d([2, 3]); <br>gg(x).print();</pre><pre><strong>------RESULT------<br>Tensor     [12, 18.0000038]</strong></pre><p>Returns→ <strong>(x: </strong><a href="https://js.tensorflow.org/api/0.11.2/#class:Tensor"><strong>tf.Tensor</strong></a><strong>, dy?: </strong><a href="https://js.tensorflow.org/api/0.11.2/#class:Tensor"><strong>tf.Tensor</strong></a><strong>) =&gt; </strong><a href="https://js.tensorflow.org/api/0.11.2/#class:Tensor"><strong>tf.Tensor</strong></a></p><blockquote>46 - <a href="https://js.tensorflow.org/api/0.11.2/#customGrad"><strong>tf.customGrad</strong></a><strong> ( f )</strong></blockquote><pre><em>// Override gradient of our custom x ^ 2 op to be dy * abs(x);</em><br><strong>const</strong> customOp = tf.customGrad<strong>(</strong>x =&gt; {    <br>    return {value: x.square(), gradFunc: dy =&gt; [dy.mul(x.abs())]}; <br>}<strong>)</strong>;</pre><pre><strong>const</strong> x = tf.tensor1d([-1, -2, 3]); <br><strong>const</strong> dx = tf.grad(x =&gt; customOp(x));  <br>console.log(`f(x):`); <br>customOp(x).print(); <br>console.log(`f&#39;(x):`); <br>dx(x).print();</pre><pre><strong>------RESULT------<br>f(x): Tensor     [1, 4, 9] f&#39;(x): Tensor     [1, 2, 3]</strong></pre><p>Returns→ <strong>(…args: </strong><a href="https://js.tensorflow.org/api/0.11.2/#class:Tensor"><strong>tf.Tensor</strong></a><strong>[]) =&gt; </strong><a href="https://js.tensorflow.org/api/0.11.2/#class:Tensor"><strong>tf.Tensor</strong></a></p><h3>TRAINING (Optimizers)</h3><blockquote>47 - <a href="https://js.tensorflow.org/api/0.11.2/#train.adam"><strong>tf.train.adam</strong></a><strong> ( learningRate?, beta1?, beta2?, epsilon? )</strong></blockquote><blockquote><strong>Constructs a AdamOptimizer that uses the Adam algorithm. <em>See </em></strong><a href="https://arxiv.org/abs/1412.6980"><em>https://arxiv.org/abs/1412.6980</em></a></blockquote><h4>Parameters:</h4><p><strong>learningRate</strong> (number) It is used for the Adam gradient descent algorithm. Optional</p><p><strong>beta1</strong> (number) The exponential decay rate for the 1st moment estimates. Optional</p><p><strong>beta2</strong> (number) The exponential decay rate for the 2nd moment estimates. Optional</p><p><strong>epsilon</strong> (number) A small constant for numerical stability. Optional</p><p>Returns→ <strong>AdamOptimizer</strong></p><blockquote>48 - <a href="https://js.tensorflow.org/api/0.11.2/#train.rmsprop"><strong>tf.train.rmsprop</strong></a><strong> ( learningRate , decay? , momentum? , epsilon? , centered? )</strong></blockquote><blockquote><strong>Constructs a tf.RMSPropOptimizer that uses RMSProp gradient descent.</strong></blockquote><h4>Parameters:</h4><p><strong>learningRate</strong> (number) The learning rate to use for the RMSProp gradient descent algorithm.</p><p><strong>decay</strong> (number) The discounting factor for the history/coming gradient. Optional</p><p><strong>momentum</strong> (number) The momentum to use for the RMSProp gradient descent algorithm. Optional</p><p><strong>epsilon</strong> (number) Small value to avoid zero denominator. Optional</p><p><strong>centered</strong> (boolean) If true, gradients are normalized by the estimated variance of the gradient. Optional</p><p>Returns→ <strong>tf.RMSPropOptimizer</strong></p><h3>TRAINING (Losses)</h3><blockquote>49 - <a href="https://js.tensorflow.org/api/0.11.2/#losses.meanSquaredError"><strong>tf.losses.meanSquaredError</strong></a><strong> (labels, predictions, weights?, reduction?)</strong></blockquote><blockquote><strong>Computes the mean squared error between two tensors.</strong></blockquote><p>Returns→ <strong>tf.Tensor</strong></p><blockquote>50 - <a href="https://js.tensorflow.org/api/0.11.2/#losses.softmaxCrossEntropy"><strong>tf.losses.softmaxCrossEntropy</strong></a><strong> ( labels , logits , dim? )</strong></blockquote><blockquote><strong>Computes softmax cross entropy between logits and labels. It measures the probability error in discrete classification tasks in which the classes are mutually exclusive.</strong></blockquote><p>For example, each CIFAR-10 image is labeled with one and only one label: an image can be a dog or a truck, but not both.</p><p>Returns→<strong> tf.Tensor</strong></p><h3>Note to Self: Don’t Make Long Lists</h3><h3>— — — — — — — — — BONUS — — — — — — — — — —</h3><h3>PERFORMANCE</h3><blockquote><a href="https://js.tensorflow.org/api/0.11.2/#tidy"><strong>tf.tidy</strong></a><strong> ( nameOrFn , fn? , gradMode? )</strong></blockquote><blockquote><strong>Executes the provided function f and after it is executed, cleans up all intermediate tensors allocated by f except those returned by f.</strong></blockquote><p>Using this method helps avoid memory leaks. In general, wrap calls to operations in <a href="https://js.tensorflow.org/api/0.11.2/#tidy">tf.tidy()</a> for automatic memory cleanup.</p><pre><em>// y = 2 ^ 2 + 1</em> <br><strong>const</strong> y = tf.tidy(() =&gt; {    <em>/<br>/ a, b, and one will be cleaned up when the tidy ends.</em>    <br><strong>const</strong> one = tf.scalar(1);    <br><strong>const</strong> a = tf.scalar(2);    <br><strong>const</strong> b = a.square();     <br>console.log(&#39;numTensors (in tidy): &#39; + tf.memory().numTensors);     <em>// The value returned inside the tidy function will return</em>    <br><em>// through the tidy, in this case to the variable y.</em>    <br>return b.add(one); });  <br>console.log(&#39;numTensors (outside tidy): &#39; + tf.memory().numTensors); <strong>y.print();</strong></pre><pre><strong>------RESULT------<br>numTensors (in tidy): 16 <br>numTensors (outside tidy): 14 <br>Tensor     5</strong></pre><p>Returns→ <strong>void|number|string|tf.Tensor|tf.Tensor[]|{[key: string]:tf.Tensor|number|string}</strong></p><blockquote><a href="https://js.tensorflow.org/api/0.11.2/#keep"><strong>tf.keep</strong></a><strong> ( result )</strong></blockquote><blockquote><strong>Keeps a tf.Tensor generated inside a tf.tidy() from being disposed automatically.</strong></blockquote><pre><strong>let</strong> b; <br><strong>const</strong> y = tf.tidy<strong>(</strong>() =&gt; <strong>{</strong>    <br>      const one = tf.scalar(1);    <br>      const a = tf.scalar(2);     </pre><pre><em>// b will not be cleaned up by the tidy. a and one will be cleaned //up when the tidy ends.</em>    <br>b = tf.keep(a.square());     <br>console.log(&#39;numTensors (in tidy): &#39; + tf.memory().numTensors);     </pre><pre><em>// The value returned inside the tidy function will return</em>    <br><em>// through the tidy, in this case to the variable y.</em>    <br>return b.add(one); <br><strong>})</strong>;  </pre><pre>console.log(&#39;numTensors (outside tidy): &#39; + tf.memory().numTensors); console.log(&#39;y:&#39;); </pre><pre>y.print(); <br>console.log(&#39;b:&#39;); <br>b.print();</pre><pre><strong>------RESULT------<br>numTensors (in tidy): 16 <br>numTensors (outside tidy): 15 <br>y: Tensor     5 <br>b: Tensor     4</strong></pre><p>Returns→ <strong>tf.Tensor</strong></p><blockquote><a href="https://js.tensorflow.org/api/0.11.2/#memory"><strong>tf.memory</strong></a><strong> ( )</strong></blockquote><blockquote><strong>Returns memory info at the current time in the program.</strong></blockquote><p>Returns→ <strong>MemoryInfo</strong></p><blockquote><a href="https://js.tensorflow.org/api/0.11.2/#time"><strong>tf.time</strong></a><strong> ( f )</strong></blockquote><blockquote><strong>Executes </strong>f( )<strong> and returns a promise that resolves with timing information.</strong></blockquote><pre><strong>const</strong> x = tf.randomNormal([20, 20]); <br><strong>const</strong> time = await tf.time(() =&gt; x.matMul(x));  </pre><pre>console.log<strong>(</strong>`kernelMs: ${time.kernelMs},                       wallTimeMs:   ${time.wallMs}`<strong>)</strong>;</pre><pre><strong>------RESULT------<br>kernelMs: 0.10000000149011612, wallTimeMs: 33.40000000037253</strong></pre><p>Returns→ <strong>Promise</strong></p><blockquote><a href="https://js.tensorflow.org/api/0.11.2/#setBackend"><strong>tf.setBackend</strong></a><strong> ( backendType , safeMode? )</strong></blockquote><blockquote><strong>Sets the backend (cpu, webgl, etc) responsible for creating tensors and executing operations on those tensors.</strong></blockquote><p>Returns→ <strong>void</strong></p><blockquote><a href="https://js.tensorflow.org/api/0.11.2/#toPixels"><strong>tf.toPixels</strong></a><strong> ( img , canvas? )</strong></blockquote><blockquote><strong>Draws a </strong><a href="https://js.tensorflow.org/api/0.11.2/#class:Tensor"><strong>tf.Tensor</strong></a><strong> of pixel values to a byte array or optionally a canvas.</strong></blockquote><p>Also, When the dtype of the input is ‘float32’, we assume values in the range [0–1]. Otherwise, when input is ‘int32’, we assume values in the range [0–255].</p><p><strong>canvas</strong> (HTMLCanvasElement) The canvas to draw to. Optional</p><p><strong>img</strong> (tf.Tensor2D or tf.Tensor3D) A rank-2 or rank-3 tensor. If rank-2, draws grayscale. If rank-3, must have depth of 1, 3 or 4. When depth of 1, draws grayscale.</p><p>Returns→ <strong>Promise</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*plqfUZ6F48nsC0v1zM2a0Q.gif" /></figure><p>Now… I’m pretty sure that I have missed your favourite API so don’t forget to mention it in the comments or any queries.</p><blockquote>Thanks for reading the post.</blockquote><blockquote>I hope this article helped you in any way.</blockquote><p>Follow me on <a href="https://medium.com/@sagarsharma4244"><strong>Medium</strong></a> to get more amazing Tutorials.</p><p><strong>Clap it! Share it! Follow Me!</strong></p><p>Happy to be helpful. kudos…..</p><h3>Previous stories you will love:</h3><ul><li><a href="https://towardsdatascience.com/tensorflow-on-mobile-tensorflow-lite-a5303eef77eb">TensorFlow on Mobile: TensorFlow Lite</a></li><li><a href="https://towardsdatascience.com/epoch-vs-iterations-vs-batch-size-4dfb9c7ce9c9">Epoch vs Batch Size vs Iterations</a></li><li><a href="https://towardsdatascience.com/tensorflow-on-mobile-tutorial-1-744703297267">TensorFlow on Mobile: Tutorial</a></li><li><a href="https://towardsdatascience.com/activation-functions-neural-networks-1cbd9f8d91d6">Activation Functions in Neural Networks</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f8c7f9cc8b2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/50-tensorflow-js-api-explained-in-5-minutes-tensorflow-js-cheetsheet-4f8c7f9cc8b2">50 TensorFlow.js API Explained in 5 Minutes | TensorFlow.js Cheetsheet</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>