<?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 Mohammed AL-Ma&#39;amari on Medium]]></title>
        <description><![CDATA[Stories by Mohammed AL-Ma&#39;amari on Medium]]></description>
        <link>https://medium.com/@mamarih1?source=rss-6238d4ba3932------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QDfpZrkAUQkg5w_jrXUW9Q.jpeg</url>
            <title>Stories by Mohammed AL-Ma&amp;#39;amari on Medium</title>
            <link>https://medium.com/@mamarih1?source=rss-6238d4ba3932------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:56:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mamarih1/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[FREE GPU to Train Your Machine Learning Models]]></title>
            <link>https://mamarih1.medium.com/free-gpu-to-train-your-machine-learning-models-4015541a81f8?source=rss-6238d4ba3932------2</link>
            <guid isPermaLink="false">https://medium.com/p/4015541a81f8</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Mohammed AL-Ma'amari]]></dc:creator>
            <pubDate>Sun, 11 Jul 2021 19:45:16 GMT</pubDate>
            <atom:updated>2021-08-16T04:47:08.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iEK4xCBsdKZLByBJuX6t4A.jpeg" /></figure><h3>Table of Contents:</h3><ol><li><a href="#f581"><strong>Introduction</strong></a></li><li><a href="#03d5"><strong>First Way: Using Google Colaboratory</strong></a><strong>:</strong></li></ol><ul><li><a href="#fc4d">What is Colaboratory?</a></li><li><a href="#b84b">How to use GPU in Google Colaboratory Notebook</a></li><li><a href="#102d">Compare Google Colaboratory CPU VS GPU</a></li><li><a href="#9894">Limitations of Google Colaboratory Notebooks</a></li></ul><p><strong>3. </strong><a href="#9067"><strong>Second Way: Using Kaggle</strong></a></p><ul><li><a href="#d2ee">How to use GPU in Kaggle Notebooks</a></li><li><a href="#7bb6">Compare Google Colaboratory CPU VS GPU</a></li><li><a href="#d277">Limitations of Kaggle Notebooks</a></li><li><a href="#fa3d">Why Kaggle Notebooks are Much Better Than Google Colab?</a></li></ul><p><strong>4. </strong><a href="#2314"><strong>Resources</strong></a></p><h3>Why do we need GPUs:</h3><blockquote><em>Training a deep learning model that involves intensive compute tasks on extremely large datasets could take days to run on a single processor. However, if you design your program to offload those tasks to one or more GPUs, you can reduce training time to hours instead of days. </em><a href="https://cloud.google.com/ai-platform/training/docs/using-gpus"><em>[source]</em></a></blockquote><p><a href="https://cloud.google.com/ai-platform/training/docs/using-gpus">[read more]</a> or <a href="https://www.analyticsvidhya.com/blog/2017/05/gpus-necessary-for-deep-learning/">[here]</a></p><h3>How Much Do GPUs Usually Cost?</h3><p>GPU cloud services could cost from 3 cents to more than 3$ per hour.</p><p>This blog shows a comparison of the GPU cloud pricing</p><p><a href="https://www.simform.com/compute-pricing-comparison-aws-azure-googlecloud/">Cloud Pricing Comparison 2021: AWS vs Azure vs Google Cloud</a></p><p>But how can one use high-end GPUs for free?</p><p>In this blog, I am willing to show you two ways that allow you to train your Machine Learning models for free and without subscribing to any paid service.</p><h3>First Way: Using Google Colaboratory:</h3><h4><strong>What is Colaboratory?</strong></h4><p>As mentioned on the <a href="https://research.google.com/colaboratory/faq.html">official page</a>, “Colaboratory, or “Colab” for short, is a product from Google Research. Colab allows anybody to write and execute arbitrary python code through the browser, and is especially well suited to machine learning, data analysis, and education. More technically, Colab is a hosted Jupyter notebook service that requires no setup to use, while providing free access to computing resources including GPUs.”</p><h4>How to use GPU in Google Colaboratory Notebook:</h4><p><strong>1- Create a Google Colaboratory Notebook:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*z0Dmqur-Nns38_W_GwNQNw.png" /><figcaption>[<a href="https://colab.research.google.com/">From Here</a>]</figcaption></figure><p>or you can try one of my notebooks <a href="https://colab.research.google.com/drive/1mFjoGlsoAl8W3E_6PNCNYCRHH1ZZbHnZ?usp=sharing">[here]</a>:</p><p><strong>2- Change the Runtime Type:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*Z7UMKO6QfruYMnUjI_CgZQ.png" /></figure><p>a small window will appear:</p><p>Choose GPU and save, the notebook will be reset with the new runtime type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*RLFxFt9_cSxNvDYR1TnwOQ.png" /></figure><h4>CPU VS GPU:</h4><p>To see if using GPU really reduces the training process time, training time using CPU is compared to GPU training time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LXE1x_1ixe2eYGhUPNtlVw.png" /></figure><p>Training time when using CPU would be about <strong>an hour per epoch</strong></p><p>On the other hand, training using GPU took exactly <strong>74 seconds (~37 sec/epoch) </strong>proving that GPUs are much much faster than CPU when it comes to fitting(training) Neural Networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oY6Vl2lA8T_V6n0uRWJ1PQ.png" /></figure><h4>What are the Limitations of Google Colaboratory Notebooks:</h4><blockquote><em>Colab resources are not guaranteed and not unlimited, and the usage limits sometimes fluctuate. This is necessary for Colab to be able to provide resources for free. </em><a href="https://research.google.com/colaboratory/faq.html"><em>[source]</em></a></blockquote><p><strong>How long can notebooks run in Colab?</strong></p><p>The session can run up to 12 hours, but if the notebook was idle for a long time session could end in less than 1 hour.</p><p><strong>What are the usage limits of Colab?</strong></p><p>The resources limits can defer from time to time, but usually it is around:</p><ul><li>Around 12.5 GB of RAM (when not using GPU runtime)</li><li>12GB of NVIDIA Tesla K80 GPU (when using GPU runtime)</li><li>Disk space depends on the free space in your Google Drive.</li></ul><p>For more details, see <a href="https://research.google.com/colaboratory/faq.html#resource-limits">Resource Limits</a>.</p><p>You can measure the GPU memory allocated for your notebook using the code provided <a href="https://stackoverflow.com/questions/48750199/google-colaboratory-misleading-information-about-its-gpu-only-5-ram-available">[here]</a></p><h3>Second Way: Using Kaggle:</h3><p>This is the best way and my go to solution because of many reasons that will be introduced later.</p><h4>How to use GPU in Kaggle Notebooks:</h4><p><strong>1- Create a </strong>Kaggle<strong> Notebook:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtRkmr7gxMTbsAg3snoEfw.png" /><figcaption><a href="https://www.kaggle.com/notebooks">[From Here]</a></figcaption></figure><p>or you can try one of my notebooks [<a href="https://www.kaggle.com/modmari/keras-digit-recognition-ex">here</a>]:</p><p>2- Change the Advanced Settings and Choose GPU as the Accelerator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*vODnysaph-BigIGYoo86tg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*pew3w91INm0-SE3cAZ7qjQ.png" /></figure><h4>CPU VS GPU:</h4><p>To see if using GPU really reduces the training process time, training time using CPU is compared to GPU training time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*lzYS522T7xGrzicNvJaHkg.png" /></figure><p>Training time when using CPU would be about <strong>33 minutes</strong> <strong>per epoch</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*tqOPfMBVToDVoH8aO1D4zA.png" /></figure><p>Training using GPU took exactly <strong>42 seconds (21 sec/epoch) </strong>proving that GPUs are much much faster than CPU when it comes to fitting(training) Neural Networks.</p><p>Can I change from CPU to using GPU after creating the notebook?</p><p>Yes, from the right side Settings -&gt; Accelerator -&gt; GPU</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-e5Z0QcgsxmFhNwRue4EAw.png" /></figure><h4>What are the Limitations of Kaggle Notebooks:</h4><ul><li>Session time is 9 hours (32400 seconds).</li><li>CPU usage time is unlimited.</li><li>GPU quota fluctuates from 30 to 50 hours/week</li></ul><p>For more details see <a href="https://www.kaggle.com/docs/notebooks#modifying-the-default-environment">[Kaggle Notebooks Documentation]</a></p><h4>Why Kaggle Notebooks are Much Better Than Google Colab:</h4><p>1- Google Colab notebooks need to be open and active during the using and training time, while you can commit a kaggle notebook then close it if you want to come later and see the training results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ce1W1KXF02iiNNdDvWsNBw.png" /><figcaption>Committing a Kaggle notebook</figcaption></figure><p>2- In Kaggle you can use any dataset from Kaggle, you can also connect your notebook to your Google Drive.</p><p>3- Google Colab uses your Google Drive disk space, so if you run out of disk space you have to free some space out of your Drive, while Kaggle gives you 4GB of disk space.</p><p>4- Google Colab gives you ~13GB of GPU memory space, while Kaggle allocates 16GB of GPU memory space to your notebook.</p><p>These 4 reasons are not the only reasons that using Kaggle would be your best choice but they are enough to make you prefer Kaggle on Colab.</p><h3>Resources:</h3><ul><li><a href="https://cloud.google.com/ai-platform/training/docs/using-gpus">Using GPUs for training models in the cloud</a></li><li><a href="https://www.analyticsvidhya.com/blog/2017/05/gpus-necessary-for-deep-learning/">Why are GPUs necessary for training Deep Learning models?</a></li><li><a href="https://www.simform.com/compute-pricing-comparison-aws-azure-googlecloud/">AWS vs Azure vs Google Cloud: Pricing Comparison of Virtual Machines</a></li><li><a href="https://colab.research.google.com/notebooks/">Google Colab</a></li><li><a href="https://research.google.com/colaboratory/faq.html#resource-limits">Google Colaboratory FAQ</a></li><li><a href="https://www.kaggle.com/notebooks">Kaggle Notebooks</a></li><li><a href="https://www.kaggle.com/docs/notebooks#modifying-the-default-environment">How to Use Kaggle: Modifying the Default Environment</a></li><li><a href="https://subcontracteu.com/uploads/pages/535eee07e8fd4c9fabc377cd464c1d74.png">Cover Image</a></li></ul><h4>You can follow me on:</h4><ul><li><a href="https://twitter.com/ModMaamari"><strong><em>Twitter</em></strong></a></li><li><a href="https://www.linkedin.com/in/mohammed-maamari/"><strong><em>LinkedIn</em></strong></a></li><li><a href="https://www.facebook.com/mamarih1/"><strong><em>FaceBook</em></strong></a></li></ul><h4>You may also like:</h4><ul><li><a href="https://mamarih1.medium.com/deploy-machine-learning-projects-online-using-flask-ecdec4c023bb"><strong>Deploy Machine Learning Projects Online Using Flask</strong></a></li><li><a href="https://medium.com/@mamarih1/deep-neural-networks-for-regression-problems-81321897ca33"><strong>Deep Neural Networks for Regression Problems</strong></a></li><li><a href="https://towardsdatascience.com/reinforcement-learning-with-python-part-1-creating-the-environment-dad6e0237d2d"><strong>Deep Reinforcement Learning With Python</strong></a></li><li><a href="https://blog.goodaudience.com/ai-generates-taylor-swifts-song-lyrics-6fd92a03ef7e"><strong>AI Generates Taylor Swift’s Song Lyrics</strong></a></li><li><a href="https://medium.com/datadriveninvestor/introduction-to-random-forest-algorithm-with-python-9efd1d8f0157"><strong>Introduction to Random Forest Algorithm with Python</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4015541a81f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Machine Learning Projects Online Using Flask]]></title>
            <link>https://medium.com/analytics-vidhya/deploy-machine-learning-projects-online-using-flask-ecdec4c023bb?source=rss-6238d4ba3932------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecdec4c023bb</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mohammed AL-Ma'amari]]></dc:creator>
            <pubDate>Sat, 10 Jul 2021 21:04:18 GMT</pubDate>
            <atom:updated>2021-08-12T08:05:57.825Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ctbcTo0hXCcftghs-zXiFQ.gif" /></figure><p>Getting your machine learning (ML) project working is not enough, to shine among other developers you need to show the world your work. The best way to do this is to deploy your ML project online. Flask is a Python micro web framework that gives you the ability to make web applications.</p><h4><strong>In this article, we will go through:</strong></h4><ul><li><a href="#5644">Installing Flask and getting it ready.</a></li><li><a href="#9625">Developing the front-end interface.</a></li><li><a href="#5e63">Coding the back-end</a> which is our python code that will get the data from the front-end and use a pre-trained ML model then send the results back to the front-end showing it to the user.</li><li><a href="#5b51">Connecting the front-end to the back-end.</a></li><li><a href="#e5e8">Using our ML web application.</a></li></ul><h4>Prerequisites:</h4><ol><li>Python 3.5+</li><li>Requirements file (requirements.txt) of python libraries used in your ML project.</li></ol><p><strong>Optional</strong>:</p><ul><li><a href="https://www.anaconda.com/products/individual">Anaconda</a></li><li>You can clone/download the example project used in this tutorial from: [<a href="https://github.com/ModMaamari/digit-recognizer">Digit Recognizer - Python Flask Web App</a>]</li></ul><h4>Installing Flask:</h4><p>It is preferable to create a new environment for this project:</p><p>⚠️ <strong>Note: </strong>You can use Windows command line if you have already added <em>conda </em>to PATH.</p><p>In your Anaconda prompt run the next line:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*VyTWr1CWht0Cxk87_EVtLA.png" /></figure><pre>conda create -n env_name python</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*yEtdsDWjFpY3WR0Q48se7A.png" /></figure><p>then activate the new environment :</p><pre>conda activate env_name</pre><p>Now, install Flask:</p><pre>pip install Flask</pre><p>Now, after we installed Flask, let’s install the requirements from the <em>requirements.txt</em> file:</p><ol><li>Make sure that you are running the command line in the directory where the<strong>requirements.txt</strong> is in.</li><li>Run pip install -r requirements.txt</li></ol><h4>Project Background:</h4><p>The machine learning project used in this tutorial is a <a href="https://github.com/ModMaamari/digit-recognizer">digit recognizer</a>, it takes an image drawn by the user and predicts the drawn digit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*qoT1cqOuR4NsnTXMl1lweQ.png" /></figure><p>We trained a convolutional neural network with (28*28) nodes as the input layer and 10 nodes for the output layer (each node presents the probability of each digit).</p><p>Once you have a trained model, you can save it as a <em>.model </em>file. This allows you to use the model anytime without rebuilding the model or retraining it.</p><h4>The Front-End:</h4><p>The directory tree of your project should be like the following:</p><pre>Project_Folder<br>|   myModel.model     # The pre-trained model<br>|   requirements.txt  # The requirements file<br>|   run.py            # Run this file using &lt;python run.py&gt;<br>|   <br>\---digitReader<br>    |   routes.py     # The main back-end code<br>    |   __init__.py   # Initializing the app<br>    |   <br>    +---static<br>    |   +---CSS<br>    |   |       Here you put all the  .css files<br>    |   |       <br>    |   \---JS<br>    |           Here you put all the  .js files<br>    |           <br>    +---templates<br>            Here you put all the  .html files</pre><p>For the main interface, we will create an HTML file inside the templatesfolder.</p><p>⚠️ <strong>Note </strong>that the name of your HTML file will be used later in the back-end code.</p><p>Here is the HTML code:</p><p><a href="https://github.com/ModMaamari/digit-recognizer/blob/main/digitRecognizer/templates/home.html">ModMaamari/digit-recognizer</a></p><p><strong>Helpful resources to create a front-end interface:</strong></p><ul><li><a href="https://www.youtube.com/watch?v=MwZwr5Tvyxo&amp;list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH">Python Flask Tutorial: Full-Featured Web App</a></li><li><a href="https://www.youtube.com/watch?v=mqhxxeeTbu0">How to Make Websites with Python</a></li><li><a href="https://getbootstrap.com/docs/4.1/getting-started/introduction/">Bootstrap</a></li></ul><p>Example front-end interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*--1yBJpP0QZY9446ZrPbfg.png" /><figcaption>Front-End Interface</figcaption></figure><p>⚠️ <strong>Note:</strong> Make sure you put the used css files inside static/CSS folder, and the used js files inside static/JS folder.</p><h4>The Back-End:</h4><p>Here, we have 3 python files (shown in the previous directory tree):</p><p><strong>First: </strong>__init__.py</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74ac3d0443549fdadee7f1d2ec41731a/href">https://medium.com/media/74ac3d0443549fdadee7f1d2ec41731a/href</a></iframe><p><strong>Second:</strong> routes.py</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca2aa5771ba43834525b5a37430d7d5c/href">https://medium.com/media/ca2aa5771ba43834525b5a37430d7d5c/href</a></iframe><p><strong>Finally:</strong> run.py</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdce39c6a78a4dd91c04ad03b862cb66/href">https://medium.com/media/fdce39c6a78a4dd91c04ad03b862cb66/href</a></iframe><h4>Front-End Back-End Connection:</h4><p>Flask is responsible for connecting the front-end to the back-end, flask functions that do this:</p><ul><li><strong><em>render_template</em></strong>: this function renders an HTML page, it supports <a href="https://code.tutsplus.com/tutorials/templating-with-jinja2-in-flask-essentials--cms-25571">Jinja syntax</a>.</li><li><strong><em>url_for</em></strong>: dynamically creating URLs of routes.</li></ul><h4>Running the Application:</h4><p>To run the app, run anaconda command line(you can also use windows command line provided you have python pre-installed and added to PATH)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*2JOPI6jAu2OgIsHdU52NMw.png" /></figure><ol><li>Ensure that you run the command line from the project directory</li><li>Type <em>cmd </em>in the title bar and press enter</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*2sTkGyGGESvNVk1vvKBZ4A.png" /></figure><ol><li>Activate the environment that you have created for your project, note that after you activate the env using conda activate &lt;env_name&gt; all the following command lines will start with(env_name )</li><li>Run python run.py</li><li>Open a new internet browser window and go to <a href="http://127.0.0.1:5000/">http://127.0.0.1:5000/</a></li></ol><p>Congrats, you have successfully created your first ML web app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ctbcTo0hXCcftghs-zXiFQ.gif" /></figure><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecdec4c023bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/deploy-machine-learning-projects-online-using-flask-ecdec4c023bb">Deploy Machine Learning Projects Online Using Flask</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Reinforcement Learning With Python | Part 3| Using Tensorboard to Analyse Trained Models]]></title>
            <link>https://medium.com/data-science/deep-reinforcement-learning-with-python-part-3-using-tensorboard-to-analyse-trained-models-606c214c14c7?source=rss-6238d4ba3932------2</link>
            <guid isPermaLink="false">https://medium.com/p/606c214c14c7</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Mohammed AL-Ma'amari]]></dc:creator>
            <pubDate>Tue, 14 Jul 2020 14:51:37 GMT</pubDate>
            <atom:updated>2020-07-14T14:51:37.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a9F8vOTfpDEM52eW5SSXAQ.jpeg" /></figure><h3>In The Previous Parts:</h3><ul><li><a href="https://medium.com/p/reinforcement-learning-with-python-part-1-creating-the-environment-dad6e0237d2d">First part</a> explained and created the game environment.</li></ul><p><a href="https://towardsdatascience.com/reinforcement-learning-with-python-part-1-creating-the-environment-dad6e0237d2d">Reinforcement Learning With Python | Part 1 | Creating The Environment</a></p><ul><li><a href="https://medium.com/p/deep-reinforcement-learning-with-python-part-2-creating-training-the-rl-agent-using-deep-q-d8216e59cf31">Second part</a> discussed the process of training the DQN, explained DQNs and gave reasons to choose DQN over Q-Learning.</li></ul><p><a href="https://towardsdatascience.com/deep-reinforcement-learning-with-python-part-2-creating-training-the-rl-agent-using-deep-q-d8216e59cf31">Deep Reinforcement Learning With Python | Part 2 | Creating &amp; Training The RL Agent Using Deep Q…</a></p><h3>In This Part:</h3><p>We are going to:</p><ul><li>Use Tensorboard to visualize the goodness of trained models.</li><li>Explain the way of loading and trying a trained model.</li><li>Use the best model and let it play the game.</li></ul><h3>Using Tensorboard:</h3><p>1- Use a modified Tensorboard to make Tensorboard logs the data from all episodes in the training process in one log file instead of making a new log file every time we fit the model.</p><p>The next code of the <strong><em>ModifiedTensorBoard</em></strong> is from <a href="https://pythonprogramming.net/deep-q-learning-dqn-reinforcement-learning-python-tutorial/">this blog</a> by sentdex, I just changed it a little bit to make it run on TensorFlow2.0:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/335efedb0625038cccf42782095727bc/href">https://medium.com/media/335efedb0625038cccf42782095727bc/href</a></iframe><p>2- Define an object of the modified tensorboard in the __init__ of the agent class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5d4af0ab524aededc9d124a49ec06c6/href">https://medium.com/media/c5d4af0ab524aededc9d124a49ec06c6/href</a></iframe><p><strong><em>PATH</em></strong> and <strong><em>name </em></strong>are used to define the full path where the log file will be saved in.</p><p>3- Pass the modified tensorboard as a callback when fitting the model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38849be16f8f89a6509f9231bebccd34/href">https://medium.com/media/38849be16f8f89a6509f9231bebccd34/href</a></iframe><p>4- At the start of each episode :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bea74f5979b2ebabc95f715777ac5f9/href">https://medium.com/media/0bea74f5979b2ebabc95f715777ac5f9/href</a></iframe><p>5- To update the logs, use the next line:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/868f0af0dee70a090fc61cc74b465941/href">https://medium.com/media/868f0af0dee70a090fc61cc74b465941/href</a></iframe><h3>Visualising the logs :</h3><p>Open the terminal on the directory where the “logs” folder is and run:</p><pre>tensorboard --logdir=&quot;logs/&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*giG_mlt6Di1yeBsNr286qQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*UjS3b35XTQY8ojFtXgfBzA.jpeg" /></figure><p>A browser window will appear:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTYckogSPDhnZnLqZ5YCSg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Tm5fqeB_40FhSys_FjD4Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XLCNE9lfRIOZMHXZDNCNog.jpeg" /></figure><p>You can try the other options by yourself.</p><p>By using these visualisations we can see the relations between logged variables, such as <em>epsilon</em> and <em>max_reward.</em></p><h3>Loading and Using Trained Models:</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43ff705c97a0d16cd0ca7f2c8a7888a5/href">https://medium.com/media/43ff705c97a0d16cd0ca7f2c8a7888a5/href</a></iframe><h3>Some Shots of Agents Playing The Game:</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_Mv1OrD64h0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_Mv1OrD64h0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_Mv1OrD64h0%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/f011cd55ddf5e7b678643ed6e8e1d58c/href">https://medium.com/media/f011cd55ddf5e7b678643ed6e8e1d58c/href</a></iframe><h3>Resources :</h3><ul><li><a href="https://www.youtube.com/watch?v=t3fbETsIBCY&amp;list=PLQVvvaa0QuDezJFIOU5wDdfy4e9vdnx-7&amp;index=5"><strong>Deep Q Learning w/ DQN — Reinforcement Learning p.5</strong></a></li></ul><p>Other parts of this series:</p><ul><li><a href="https://towardsdatascience.com/reinforcement-learning-with-python-part-1-creating-the-environment-dad6e0237d2d">Reinforcement Learning With Python | Part 1 | Creating The Environment</a></li><li><a href="https://towardsdatascience.com/deep-reinforcement-learning-with-python-part-2-creating-training-the-rl-agent-using-deep-q-d8216e59cf31">Deep Reinforcement Learning With Python | Part 2 | Creating &amp; Training The RL Agent Using Deep Q…</a></li></ul><p>You can follow me on:</p><ul><li><a href="https://twitter.com/ModMaamari"><strong><em>Twitter</em></strong></a></li><li><a href="https://www.linkedin.com/in/mohammed-maamari/"><strong><em>LinkedIn</em></strong></a></li><li><a href="https://www.facebook.com/mamarih1/"><strong><em>FaceBook</em></strong></a></li></ul><h3>You may also like:</h3><ul><li><a href="https://medium.com/@mamarih1/deep-neural-networks-for-regression-problems-81321897ca33"><strong>Deep Neural Networks for Regression Problems</strong></a></li><li><a href="https://blog.goodaudience.com/ai-generates-taylor-swifts-song-lyrics-6fd92a03ef7e"><strong>AI Generates Taylor Swift’s Song Lyrics</strong></a></li><li><a href="https://medium.com/datadriveninvestor/introduction-to-random-forest-algorithm-with-python-9efd1d8f0157"><strong>Introduction to Random Forest Algorithm with Python</strong></a></li><li><a href="https://medium.com/@mamarih1/machine-learning-crash-course-with-tensorflow-apis-summary-524e0fa0a606"><strong>Machine Learning Crash Course with TensorFlow APIs Summary</strong></a></li><li><a href="https://medium.com/@mamarih1/how-to-make-a-cnn-using-tensorflow-and-keras-dd0aaaed8ab4"><strong>How To Make A CNN Using Tensorflow and Keras</strong></a><strong> ?</strong></li><li><a href="https://medium.com/@mamarih1/how-to-choose-the-best-machine-learning-model-e1dbb46bdd4d"><strong>How to Choose the Best Machine Learning Model ?</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=606c214c14c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deep-reinforcement-learning-with-python-part-3-using-tensorboard-to-analyse-trained-models-606c214c14c7">Deep Reinforcement Learning With Python | Part 3| Using Tensorboard to Analyse Trained Models</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[Deep Reinforcement Learning With Python | Part 2 | Creating & Training The RL Agent Using Deep Q…]]></title>
            <link>https://medium.com/data-science/deep-reinforcement-learning-with-python-part-2-creating-training-the-rl-agent-using-deep-q-d8216e59cf31?source=rss-6238d4ba3932------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8216e59cf31</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Mohammed AL-Ma'amari]]></dc:creator>
            <pubDate>Thu, 09 Jul 2020 14:53:12 GMT</pubDate>
            <atom:updated>2020-07-28T22:26:15.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a9F8vOTfpDEM52eW5SSXAQ.jpeg" /></figure><h3>Deep Reinforcement Learning With Python | Part 2 | Creating &amp; Training The RL Agent Using Deep Q Network (DQN)</h3><p>In the <a href="https://bit.ly/3eAg32L"><strong><em>first part</em></strong></a><strong><em>,</em></strong> we went through making the game environment and explained it line by line. In this part, we are going to learn how to create and train a Deep Q Network (DQN) and enable agents to use it in order to be experts at our game.</p><p><a href="https://towardsdatascience.com/reinforcement-learning-with-python-part-1-creating-the-environment-dad6e0237d2d">Reinforcement Learning With Python | Part 1 | Creating The Environment</a></p><p>In this part, we are going to be discussing :</p><p>1- Why Deep Q Network (DQN) ?</p><p>2- What is DQN?</p><p>3- How DQN Works?</p><p>4- Explaining our DQN Architecture.</p><p>5- Explaining the Agent Class.</p><p>6- Training the Agent.</p><p>Someone might ask “Why didn’t you use Q-Learning instead of DQN ?” The answer to this question depends on many things such as:</p><h4>How complex the environment is ?</h4><p>In our case, we can answer this question in two ways:</p><ul><li>If we want the input to the RL agent to be as close as the input to a human, we will choose the input to be the array representation of the field.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vPtWdTFjDIozwWEOKs0eDg.png" /><figcaption>What the RL agent sees VS What a human player sees</figcaption></figure><p>In this case, the environment would be complex as we use Q-Learning and since the Q-Table is tremendously big, it would be impossible to store it. To prove this, consider the following calculations:</p><blockquote><strong>Number of states that the input array has =</strong> (number of different values every item in the array can take) ^ (width*height)</blockquote><blockquote><strong>Number of states that the input array can has =</strong> 4 ^ 10 * 20</blockquote><blockquote>= 4 ^ 200 = 2.58225e120</blockquote><blockquote><strong>Q-Table size</strong> = ACTION_SPACE size * Number of states that the input array can has</blockquote><blockquote><strong>Q-Table size</strong> = 5 * 2.58225e120 = 1.291125e121</blockquote><blockquote>To store an array with this number of items (each item is 8 bits), we need 9.39417077e109 Terabytes.</blockquote><p>That is why we simply use DQN instead of Q-Learning.</p><ul><li>On the other hand, if you want to use Q-Learning, it would be more efficient to use another kind of input. For example, you can use the <em>X</em> coordinate of the player and the hole, player’s width and hole’s width. This way the input is much simpler than using array representation.</li></ul><h3>What is DQN ?</h3><p>It is simply a normal neural network, the only difference is that its input is a state of the environment and its output is the best action to perform in order to maximise the reward for the current step.</p><p>We do this by using <strong>Experience Replay and Replay Memory, </strong>those concepts will be explained in the next section.</p><h3>How Deep Q Network (DQN) Works ?</h3><p>To fully understand how DQN works, you need to know some concepts related to DQN:</p><h4>1- Experience Replay and Replay Memory :</h4><p>Similar to the way humans learn by using their memory of previous experience DQNs use this technique too.</p><p><strong>Experience Replay : </strong>some data that is collected after every step the agent perform, this <strong>experience replay </strong>contains [current_state, current_action, step_reward, next_state].</p><p><strong>Replay Memory : </strong>is a stack of <em>n </em><strong>experience replays, </strong>replay memory is mainly used to train the DQN by getting a random sample of replays and use those replays as the input to the DQN.</p><p><strong>Why Using random sample of replays instead of using sequential replays?</strong></p><ul><li>When using sequential replays the DQN tends to overfit instead of generalizing.</li></ul><blockquote>A key reason for using replay memory is to break the correlation between consecutive samples.</blockquote><h4>2- Model and Target Model:</h4><p>To get a consistent results we will train two models, the first model <strong>“model” </strong>will be fit after every step made by the agent, on the other hand, the second model <strong>“target_model” </strong>loads the weights of <strong>“model” </strong>every n steps (n = UPDATE_TARGET_EVERY).</p><p>We do this because on the beginning, everything is random, from the initial weights of the <strong>“model” </strong>to the actions performed by the agent. This randomness makes it harder on the <strong>model</strong> to perform good actions, but when we have another model that uses the knowledge gained by the first model every n steps, we have some degree of consistency.</p><p>After we explained some key concepts know we can summarize the process of learning, I will use the words of DeepLizard from <a href="https://deeplizard.com/learn/video/xVkPh9E9GfE">this wonderful blog </a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/828a549f840abfd04068c2dc7fb33e06/href">https://medium.com/media/828a549f840abfd04068c2dc7fb33e06/href</a></iframe><h3>Explaining Our DQN Architecture:</h3><p>For our DQN many architectures were tried many of them did not work, but eventually one architecture proved to be working well.</p><h4>Failed Tries:</h4><ul><li>One of the first failures was an architecture with two output layers, the first output layer is responsible for predicting the best move (left, right, or no move) while the other output layer is responsible for predicting the best width changing action (increasing the width, decreasing the width, not changing the width).</li><li>Another failures included too deep networks, in addition to their slow training process their performance were too poor.</li></ul><h4>Finding Better Architectures:</h4><p>After some failures a grid search was performed to find architectures that can outperform humans playing the game, following tables show results of some grid searches:</p><p><em>Note: next tables are ordered to show best result lastly.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c292b71abb7db34ee98edfe98664cdff/href">https://medium.com/media/c292b71abb7db34ee98edfe98664cdff/href</a></iframe><p>From the result of the first grid search we can clearly see that complicated and deep networks failed to learn how to play the game, on the other hand, the simplest network worked the best.</p><p>Using the result from the first grid search, another grid search was performed and got some good results:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/467b16cb227c4b4b23d36dfee0cd4d91/href">https://medium.com/media/467b16cb227c4b4b23d36dfee0cd4d91/href</a></iframe><p>From this result we see that “<strong><em>Best Only</em></strong>”<strong><em> </em></strong>does not enhance the model’s performance, on the other side, using both ECC(Epsilon Conditional Constentation) and EF(Epsilon Fluctuation) together can improve the model’s performance.</p><p>We will discuss ECC and EF in another blog.</p><p>Some other grid searches results:</p><ul><li>Testing <strong><em>“Best Only”:</em></strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7f8bd1a698dceb4c61f1d8b0e748a7c/href">https://medium.com/media/d7f8bd1a698dceb4c61f1d8b0e748a7c/href</a></iframe><ul><li>Testing even simpler networks:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4ced46892fcb89289b53a20975af31e/href">https://medium.com/media/e4ced46892fcb89289b53a20975af31e/href</a></iframe><p>After all these grid searches we finally settled on using an architecture with one convolutional layer with 32 filter, batch size of 128, two dense(fully connected) layers with 32 nodes each, and we will use both ECC and EF together.</p><h4>Network Summary:</h4><pre>Model: &quot;model_1&quot;<br>_________________________________________________________________<br>Layer (type)                 Output Shape              Param #   <br>=================================================================<br>input_1 (InputLayer)         (None, 20, 10, 1)         0         <br>_________________________________________________________________<br>conv2d_1 (Conv2D)            (None, 18, 8, 32)         320       <br>_________________________________________________________________<br>dropout_1 (Dropout)          (None, 18, 8, 32)         0         <br>_________________________________________________________________<br>flatten_1 (Flatten)          (None, 4608)              0         <br>_________________________________________________________________<br>dense_1 (Dense)              (None, 32)                147488    <br>_________________________________________________________________<br>dense_2 (Dense)              (None, 32)                1056      <br>_________________________________________________________________<br>output (Dense)               (None, 5)                 165       <br>=================================================================<br>Total params: 149,029<br>Trainable params: 149,029<br>Non-trainable params: 0<br>_________________________________________________________________</pre><ul><li><strong>Input Layer :</strong> The input shape is the same as the shape of the array that represents the playing field <em>(20 by 10).</em></li><li><strong>Convolutional layers : </strong>One Conv2D layer with 32 filters with size of <em>2*2</em></li><li>Dropout of 20%</li><li><strong>Flatten</strong> : convert the output of the convolutional layer from 2D into 1D array.</li><li><strong>Dense (Fully Connected) layers</strong> : Two dense layers each has 32 nodes.</li><li><strong>Output Layer : </strong>The output layer contains 5 output nodes each node represents an action <em>[no_action, move_left, move_right, decrease_width, increase_width]</em></li></ul><h3>Explaining the <strong><em>Agent </em></strong>Class:</h3><p><strong>Agent </strong>class is a class that contains everything related to the agent such as the DQN, the training function, the replay memory and other stuff, following is a line-by-line explanation of this class.</p><h4>Model Creation :</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ac78fd26696ede05aec84672d78f83f/href">https://medium.com/media/7ac78fd26696ede05aec84672d78f83f/href</a></iframe><p>These two functions are used to create a model given two lists:</p><ul><li><strong>conv_list :</strong> each item of this list defines number of filters for a convolutional layer.</li><li><strong>dense_list :</strong> each item of this list defines number of nodes for a dense layer.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26d923325b8c38422a3aa1405b7f7fde/href">https://medium.com/media/26d923325b8c38422a3aa1405b7f7fde/href</a></iframe><h3>Training the Agent:</h3><p>In order to keep tracking the best model and save it to be used after training the following function is used :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dff6872fd2c7d556e31252e29bae3d17/href">https://medium.com/media/dff6872fd2c7d556e31252e29bae3d17/href</a></iframe><p>Next are some constants :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f95cf36c836c5026e61d8f4d5cb4e19d/href">https://medium.com/media/f95cf36c836c5026e61d8f4d5cb4e19d/href</a></iframe><p>Then comes the architectures that will be trained:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1295731a808efcc1e30c303c07511327/href">https://medium.com/media/1295731a808efcc1e30c303c07511327/href</a></iframe><p>A grid search will be performed using the previous three architectures and the result of the grid search is stored in a dataframe.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f73b02b0d960c030fcc2340b0722b2e/href">https://medium.com/media/5f73b02b0d960c030fcc2340b0722b2e/href</a></iframe><p>Check out my Github repository of this code:</p><p><a href="https://github.com/ModMaamari/reinforcement-learning-using-python">ModMaamari/reinforcement-learning-using-python</a></p><p>To recap, we discussed:</p><ul><li>The reasons behind choosing DQN instead of Q-Learning.</li><li>DQNs, a brief explanation.</li><li>How DQNs work?</li><li>What architectures we used and why?</li><li>The <strong><em>Agent </em></strong>class, explained code.</li><li>The process of training the models and grid search for the best one.</li></ul><p>In the next part we will :</p><ul><li>Analyse the training results using Tensorboard.</li><li>Trying the best model.</li></ul><h3>Resources :</h3><ul><li><a href="https://www.youtube.com/watch?v=t3fbETsIBCY&amp;list=PLQVvvaa0QuDezJFIOU5wDdfy4e9vdnx-7&amp;index=5"><strong>Deep Q Learning w/ DQN — Reinforcement Learning p.5</strong></a></li><li><a href="https://www.youtube.com/watch?v=qfovbG84EBg&amp;list=PLQVvvaa0QuDezJFIOU5wDdfy4e9vdnx-7&amp;index=6"><strong>Training &amp; Testing Deep reinforcement learning (DQN) Agent — Reinforcement Learning p.6</strong></a></li><li><a href="https://www.youtube.com/watch?v=wrBUkpiRvCA&amp;list=PLZbbT5o_s2xoWNVdDudn51XM8lOuZ_Njv&amp;index=11"><strong>Deep Q-Learning — Combining Neural Networks and Reinforcement Learning</strong></a></li><li><a href="https://www.youtube.com/watch?v=Bcuj2fTH4_4&amp;list=PLZbbT5o_s2xoWNVdDudn51XM8lOuZ_Njv&amp;index=12"><strong>Replay Memory Explained — Experience for Deep Q-Network Training</strong></a></li></ul><p>Other parts of this series:</p><ul><li><a href="https://towardsdatascience.com/reinforcement-learning-with-python-part-1-creating-the-environment-dad6e0237d2d">Reinforcement Learning With Python | Part 1 | Creating The Environment</a></li><li><a href="https://towardsdatascience.com/deep-reinforcement-learning-with-python-part-3-using-tensorboard-to-analyse-trained-models-606c214c14c7">Deep Reinforcement Learning With Python | Part 3| Using Tensorboard to Analyse Trained Models</a></li></ul><p>You can follow me on:</p><ul><li><a href="https://twitter.com/ModMaamari"><strong><em>Twitter</em></strong></a></li><li><a href="https://www.linkedin.com/in/mohammed-maamari/"><strong><em>LinkedIn</em></strong></a></li><li><a href="https://www.facebook.com/mamarih1/"><strong><em>FaceBook</em></strong></a></li></ul><h3>You may also like:</h3><ul><li><a href="https://medium.com/@mamarih1/deep-neural-networks-for-regression-problems-81321897ca33"><strong>Deep Neural Networks for Regression Problems</strong></a></li><li><a href="https://blog.goodaudience.com/ai-generates-taylor-swifts-song-lyrics-6fd92a03ef7e"><strong>AI Generates Taylor Swift’s Song Lyrics</strong></a></li><li><a href="https://medium.com/datadriveninvestor/introduction-to-random-forest-algorithm-with-python-9efd1d8f0157"><strong>Introduction to Random Forest Algorithm with Python</strong></a></li><li><a href="https://medium.com/@mamarih1/machine-learning-crash-course-with-tensorflow-apis-summary-524e0fa0a606"><strong>Machine Learning Crash Course with TensorFlow APIs Summary</strong></a></li><li><a href="https://medium.com/@mamarih1/how-to-make-a-cnn-using-tensorflow-and-keras-dd0aaaed8ab4"><strong>How To Make A CNN Using Tensorflow and Keras</strong></a><strong> ?</strong></li><li><a href="https://medium.com/@mamarih1/how-to-choose-the-best-machine-learning-model-e1dbb46bdd4d"><strong>How to Choose the Best Machine Learning Model ?</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8216e59cf31" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deep-reinforcement-learning-with-python-part-2-creating-training-the-rl-agent-using-deep-q-d8216e59cf31">Deep Reinforcement Learning With Python | Part 2 | Creating &amp; Training The RL Agent Using Deep Q…</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[Reinforcement Learning With Python | Part 1 | Creating The Environment]]></title>
            <link>https://medium.com/data-science/reinforcement-learning-with-python-part-1-creating-the-environment-dad6e0237d2d?source=rss-6238d4ba3932------2</link>
            <guid isPermaLink="false">https://medium.com/p/dad6e0237d2d</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[games]]></category>
            <dc:creator><![CDATA[Mohammed AL-Ma'amari]]></dc:creator>
            <pubDate>Wed, 24 Jun 2020 21:08:21 GMT</pubDate>
            <atom:updated>2020-07-28T22:27:42.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a9F8vOTfpDEM52eW5SSXAQ.jpeg" /></figure><h3>Deep Reinforcement Learning With Python | Part 1 | Creating The Environment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*X3zZn4Ic5nFl3a_QyRfbog.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*y8G1qC-SmTk_cOVDXpnhsQ.gif" /><figcaption>Left Gif: Explanation of the game rules | | Right Gif: The game played by a human</figcaption></figure><p>In this tutorial series, we are going through every step of building an expert Reinforcement Learning (RL) agent that is capable of playing games.</p><p>This series is divided into three parts:</p><ul><li><strong>Part 1</strong>: Designing and Building the Game Environment. In this part we will build a game environment and customize it to make the RL agent able to train on it.</li><li><a href="https://towardsdatascience.com/deep-reinforcement-learning-with-python-part-2-creating-training-the-rl-agent-using-deep-q-d8216e59cf31"><strong>Part 2</strong></a>: Build and Train the Deep Q Neural Network (DQN). In this part, we define and build the different layers of DQN and train it.</li></ul><p><a href="https://towardsdatascience.com/deep-reinforcement-learning-with-python-part-2-creating-training-the-rl-agent-using-deep-q-d8216e59cf31">Deep Reinforcement Learning With Python | Part 2 | Creating &amp; Training The RL Agent Using Deep Q…</a></p><ul><li><a href="https://towardsdatascience.com/deep-reinforcement-learning-with-python-part-3-using-tensorboard-to-analyse-trained-models-606c214c14c7"><strong>Part 3</strong></a>: Test and Play the Game.</li></ul><p>We might also try making another simple game environment and use Q-Learning to create an agent that can play this simple game.</p><h3>The Motivation:</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fk-rWB1jOt9s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dk-rWB1jOt9s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fk-rWB1jOt9s%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f68f7dda1df1fe9363a58257bbab8e2/href">https://medium.com/media/4f68f7dda1df1fe9363a58257bbab8e2/href</a></iframe><p>One time I was in the rabbit hole of YouTube and <a href="https://www.youtube.com/watch?v=k-rWB1jOt9s">THIS VIDEO</a> was recommended to me, it was about the <strong>sense of self</strong> in human babies, after watching the video a similar question popped into my mind<em> “Can I develop a smart agent that is smart enough to have a sense of its body and has the ability to change its features to accomplish a certain task?”</em></p><p>This series is my way of answering this question.</p><h3>Designing the Environment:</h3><p>For this environment, we want the agent to develop a sense of its body and how to change its body features to avoid losing the game.</p><h4>First: The Elements of The Environment:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CWzzRutHg1gYW2V87440JA.jpeg" /><figcaption>The Environment</figcaption></figure><p><strong>1-</strong> <strong>The Field</strong> contains all the other elements. We represent it in code by class named “Field” as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/891dc4e61fde97cb5cb1c78436f8f81b/href">https://medium.com/media/891dc4e61fde97cb5cb1c78436f8f81b/href</a></iframe><p><strong>Field</strong> attributes:</p><ul><li><strong><em>width</em> </strong>(int)<strong>: </strong>the width of the field (not in pixels)</li><li><strong><em>height</em></strong> (int: the height of the field (not in pixels)</li><li><strong><em>body</em> </strong>(np.array)<strong>: </strong>holds the array representation of the game elements (player and walls). This array is passed to the <strong>DQN</strong> and also used to draw the interface using <strong>pygame.</strong></li></ul><p><strong>Field</strong> methods:</p><ul><li><strong><em>update_field</em></strong>(self,walls, player) : updates the field.</li></ul><p><strong>2- The Walls :</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e045d6da775621cded8b70232960aa3/href">https://medium.com/media/4e045d6da775621cded8b70232960aa3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5YoIb8kU41MsDecUCIbr3g.jpeg" /><figcaption>The Wall</figcaption></figure><p><strong>Wall</strong> attributes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/210bc830ecacdedb452b2a2be8b8bb94/href">https://medium.com/media/210bc830ecacdedb452b2a2be8b8bb94/href</a></iframe><p><strong>Wall</strong> methods:</p><ul><li><strong><em>create_hole</em></strong>(self): Creates a hole in the wall that its width = self.<strong>hole_width.</strong></li><li><strong><em>move</em></strong>(self): Moves the wall vertically (every time it get called the wall moves n steps from downward (n = self.speed))</li></ul><p><strong>3- The Player :</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60be4989fa9fd5cf077833b2bbd4768b/href">https://medium.com/media/60be4989fa9fd5cf077833b2bbd4768b/href</a></iframe><p><strong>Player</strong> attributes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6fe9b829d2ecf45db184cbb30469f86/href">https://medium.com/media/c6fe9b829d2ecf45db184cbb30469f86/href</a></iframe><p><strong>Player</strong> methods:</p><ul><li><strong><em>move</em></strong>(self, field, direction = 0 ): Moves the player :</li></ul><blockquote>- direction = 0 -&gt; No change</blockquote><blockquote>- direction = 1 -&gt; left</blockquote><blockquote>- direction = 2 -&gt; right</blockquote><ul><li><strong><em>change_width</em></strong>(self, action = 0):</li></ul><blockquote>- action = 0 -&gt; No change</blockquote><blockquote>- action = 3 -&gt; narrow by one unit</blockquote><blockquote>- action = 4 -&gt; widen by one unit</blockquote><h3>The “<strong>Environment”</strong> Class :</h3><p>This class facilitates the communication between the environment and the agent, it is designed to with an RL agent or with a human player.</p><h4>Main Components Needed by the RL Agent:</h4><p>1- <strong>ENVIRONMENT_SHAPE attribute: used by the DQN to set the shape of the input layer.</strong></p><p><strong>2- ACTION_SPACE attribute: used by the DQN to set the shape of the output layer.</strong></p><p>3- <strong>PUNISHMENT</strong> and <strong>REWARD: set the values of both punishment and reward, used to train the agent (we use these values to tell the agent if its previous actions were good or bad).</strong></p><p>4- <strong><em>reset</em></strong> method: to reset the environment.</p><p>5- <strong><em>step</em></strong> method: takes an action as an argument and returns <strong><em>next state</em>, <em>reward</em>, </strong>a boolean variable named <strong>game_over</strong> that is used to tell us if the game is over (the player lost) or not.</p><p>It is clear that this environment is not different, it subsumes all the required components and more.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb1439d51563c47fa18a84bd1633e75e/href">https://medium.com/media/eb1439d51563c47fa18a84bd1633e75e/href</a></iframe><p><strong>Environment</strong> attributes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04aefcd4e61f2eb1a409e3bc8bd98321/href">https://medium.com/media/04aefcd4e61f2eb1a409e3bc8bd98321/href</a></iframe><p><strong>Environment</strong> methods:</p><ul><li><strong><em>__init__</em></strong>(self) : initializes the environment by initializing some attributes and calling the <strong><em>reset </em></strong>method.</li><li><strong><em>reset</em></strong>(self) : resets the environment and returns the state of the game field after resetting it.</li><li><strong><em>print_text</em></strong>(self, WINDOW = None, text_cords = (0,0), center = False, text = “”, color = (0,0,0), size = 32): prints a text in a given pygame.display (WINDOW) with the given features.</li></ul><h4><strong><em>+ step</em></strong>(self, action):</h4><p>1- Call the player’s move method to move the player.</p><p>2- Call the player’s change_width method to move the player.</p><p>3- Move the wall one step.</p><p>4- Update the field.</p><p>5- Check if the player passed a wall successfully. If so, gives the player a reward and increase its stamina.</p><p>6- Check the three losing conditions: the player loses the game if at least one of these three conditions met.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54a1d80f9ffb5e093dfd94b41db0522f/href">https://medium.com/media/54a1d80f9ffb5e093dfd94b41db0522f/href</a></iframe><p>when a player loses, the value of returned <strong><em>reward</em></strong> will equal PUNISHMENT, and the indicator of the game state (<strong><em>game_over</em></strong>) changes from false to true.</p><p>7- Check if the current wall hits the bottom of the field, when that happens, the out of range wall is replaced by a new wall.</p><p>8- Return <strong><em>next_state</em></strong> normalized, <strong><em>reward</em></strong>, <strong><em>game_over</em></strong></p><h4>+ render(self, WINDOW = None, human=False):</h4><p><strong>Arguments:</strong></p><ul><li><strong><em>WINDOW</em></strong> (pygame.display): the pygame.display that the game will be rendered on.</li><li><strong><em>human</em></strong> (bool): If a human will play the game, this argument is set to True, in this case pygame catch pressed keyboard keys to get the action that will be performed.</li></ul><p>Explanation of <strong><em>render </em></strong>method line by line:</p><p>1- Check if the player is a human. If so, get the pressed key and translate it to the corresponding action (ex: if the right arrow is pressed then set action = 2, that means move the player on step to the right), then call <strong><em>step </em></strong>method to perform the chosen action.</p><p>2- Update the field then start drawing the walls and the player as blocks.</p><p>3- Print the score and the player’s stamina.</p><p>4- Finally, update the display to show the rendered screen.</p><h3>Finally: Put it all together</h3><p>Now we are going to use everything we explained and play the game:</p><p>The following code repeats the game until the player wins by getting a score higher than or equals <strong><em>winning_score, </em></strong>or quits the game.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb1b83db99342c4b5ad7d396941d773d/href">https://medium.com/media/fb1b83db99342c4b5ad7d396941d773d/href</a></iframe><p>You can get the full code <a href="https://github.com/ModMaamari/reinforcement-learning-using-python">HERE</a>.</p><ul><li><a href="https://towardsdatascience.com/deep-reinforcement-learning-with-python-part-2-creating-training-the-rl-agent-using-deep-q-d8216e59cf31">Deep Reinforcement Learning With Python | Part 2 | Creating &amp; Training The RL Agent Using Deep Q…</a></li><li><a href="https://towardsdatascience.com/deep-reinforcement-learning-with-python-part-3-using-tensorboard-to-analyse-trained-models-606c214c14c7">Deep Reinforcement Learning With Python | Part 3| Using Tensorboard to Analyse Trained Models</a></li></ul><p>You can follow me on Twitter <a href="https://twitter.com/ModMaamari">@ModMaamari</a></p><h3>You may also like:</h3><ul><li><a href="https://medium.com/@mamarih1/deep-neural-networks-for-regression-problems-81321897ca33"><strong>Deep Neural Networks for Regression Problems</strong></a></li><li><a href="https://blog.goodaudience.com/ai-generates-taylor-swifts-song-lyrics-6fd92a03ef7e"><strong>AI Generates Taylor Swift’s Song Lyrics</strong></a></li><li><a href="https://medium.com/datadriveninvestor/introduction-to-random-forest-algorithm-with-python-9efd1d8f0157"><strong>Introduction to Random Forest Algorithm with Python</strong></a></li><li><a href="https://medium.com/@mamarih1/machine-learning-crash-course-with-tensorflow-apis-summary-524e0fa0a606"><strong>Machine Learning Crash Course with TensorFlow APIs Summary</strong></a></li><li><a href="https://medium.com/@mamarih1/how-to-make-a-cnn-using-tensorflow-and-keras-dd0aaaed8ab4"><strong>How To Make A CNN Using Tensorflow and Keras</strong></a><strong> ?</strong></li><li><a href="https://medium.com/@mamarih1/how-to-choose-the-best-machine-learning-model-e1dbb46bdd4d"><strong>How to Choose the Best Machine Learning Model ?</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dad6e0237d2d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/reinforcement-learning-with-python-part-1-creating-the-environment-dad6e0237d2d">Reinforcement Learning With Python | Part 1 | Creating The Environment</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[NLP | Sequence to Sequence Networks| Part 2|Seq2seq Model (EncoderDecoder Model)]]></title>
            <link>https://medium.com/data-science/nlp-sequence-to-sequence-networks-part-2-seq2seq-model-encoderdecoder-model-6c22e29fd7e1?source=rss-6238d4ba3932------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c22e29fd7e1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Mohammed AL-Ma'amari]]></dc:creator>
            <pubDate>Thu, 15 Nov 2018 19:30:02 GMT</pubDate>
            <atom:updated>2021-04-22T03:59:31.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RspNg2-o0dL8IoSgBCkqQQ.png" /></figure><p>In [<a href="https://towardsdatascience.com/nlp-sequence-to-sequence-networks-part-1-processing-text-data-d141a5643b72">NLP | Sequence to Sequence Networks| Part 1| Processing text data</a>] we learnt how to process text data, In this part we will create the model which will take the data we processed and use it to train to translate English sentences to French.</p><p>We will use an architecture called (seq2seq) or ( Encoder Decoder), It is appropriate in our case where the length of the input sequence ( English sentences in our case) does not has the same length as the output data ( French sentences in our case)</p><h4>What is Encoder Decoder Architecture ?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*BpmYIit1tmLKlpDm.png" /><figcaption><a href="https://smerity.com/articles/2016/google_nmt_arch.html">Encoder Decoder Architecture</a></figcaption></figure><p>Encoder decoder architecture consists of two main parts :</p><ol><li><strong>Encoder</strong>:</li></ol><p>The encoder simply takes the input data, and train on it then it passes the last state of its recurrent layer as an initial state to the first recurrent layer of the decoder part.</p><pre>Encoder input : English sentences</pre><pre>Encoder initial state : It depends on the initializer we use</pre><p><strong>2. Decoder :</strong></p><p>The decoder takes the last state of encoder’s last recurrent layer and uses it as an initial state to its first recurrent layer , the input of the decoder is the sequences that we want to get ( in our case French sentences).</p><pre>Decoder input : French sentences</pre><pre>Decoder initial state : The last state of encoder’s last recurrent layer</pre><p><strong>Some other images explaining the encoder decoder:</strong></p><figure><img alt="Image result for encoder decoder model" src="https://cdn-images-1.medium.com/proxy/1*3lj8AGqfwEE5KCTJ-dXTvg.png" /><figcaption><a href="https://towardsdatascience.com/sequence-to-sequence-model-introduction-and-concepts-44d9b41cd42d">Simple Representation</a></figcaption></figure><figure><img alt="Image result for encoder decoder model" src="https://cdn-images-1.medium.com/proxy/1*sO-SP58T4brE9EHazHSeGA.png" /><figcaption><a href="https://medium.com/botsupply/generative-model-chatbots-e422ab08461e">Generative Model Chatbots</a></figcaption></figure><p>To learn more about encoder decoder architecture [<a href="https://smerity.com/articles/2016/google_nmt_arch.html">0</a>],[<a href="https://machinelearningmastery.com/define-encoder-decoder-sequence-sequence-model-neural-machine-translation-keras/">1</a>],[<a href="https://machinelearningmastery.com/encoder-decoder-models-text-summarization-keras/">2</a>],[<a href="https://machinelearningmastery.com/develop-encoder-decoder-model-sequence-sequence-prediction-keras/">3</a>],[<a href="https://www.liip.ch/en/blog/sentiment-detection-with-keras-word-embeddings-and-lstm-deep-learning-networks">4</a>]</p><h4>Building the Model:</h4><p>First, Import needed dependencies :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85a65caff939525cf0ae85a19bb6caeb/href">https://medium.com/media/85a65caff939525cf0ae85a19bb6caeb/href</a></iframe><p><strong>Building the encoder :</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3539fbda2f4e49698e98378ad49ac1d9/href">https://medium.com/media/3539fbda2f4e49698e98378ad49ac1d9/href</a></iframe><p>We use the (<a href="https://keras.io/getting-started/functional-api-guide/">Keras Functional API</a>) to build such complex models, if you want to learn more about Keras functional API : [<a href="https://www.youtube.com/watch?v=elOLCEJV-dc">1</a>],[<a href="https://machinelearningmastery.com/keras-functional-api-deep-learning">2</a>]</p><p><strong>The encoder is made up of :</strong></p><ol><li>Input Layer : Takes the English sentence and pass it to the embedding layer.</li><li>Embedding Layer : Takes the English sentence and convert each word to fixed size vector</li><li>First LSTM Layer : Every time step, it takes a vector that represents a word and pass its output to the next layer, We used CuDNNLSTM layer instead of LSTM because it’s much much faster.</li><li>Second LSTM Layer : It does the same thing as the previous layer, but instead of passing its output, it passes its states to the first LSTM layer of the decoder .</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3pH2NH_8i7QMxpV0TFOdxw.jpeg" /></figure><p><strong>Building the decoder :</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eeeb1f24b4fd1cc75752a0422a29c7d1/href">https://medium.com/media/eeeb1f24b4fd1cc75752a0422a29c7d1/href</a></iframe><p><strong>The decoder is made up of :</strong></p><ol><li>Input Layer : Takes the French sentence and pass it to the embedding layer.</li><li>Embedding Layer : Takes the French sentence and convert each word to fixed size vector</li><li>First LSTM Layer : Every time step, it takes a vector that represents a word and pass its output to the next layer, but here in the decoder, we initialize the state of this layer to be the last state of the last LSTM layer from the decoder .</li><li>Second LSTM Layer : Processing the output from the previous layer and passes its output to a dense layer .</li><li>Dense Layer (Output Layer) : Takes the output from the previous layer and outputs a one hot vector representing the target French word</li></ol><p><strong>Note :</strong></p><p>We have to know that we don’t convert each English sentence into French in one time step, we do that in a number of time steps that equals the number of words that the longest English sentence has.</p><p>so if the longest English sentence has 10 words, we have to take 10 time steps to get its French translation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sDlV9_-PXBlt8jol-7Xjhg.jpeg" /></figure><p>I simplified the encoder decoder model using the previous blocks, Where in reality, we have many time steps, not just one as in the simplified representation, and the final output is not a sentence that we can read directly, what is really happening is that every time step we get a one hot vector that represent the target word.</p><p><strong>Bringing the encoder and decoder together into one model :</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/915b751c02a59a4e5bdd673b22ea07b8/href">https://medium.com/media/915b751c02a59a4e5bdd673b22ea07b8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*SMZbHBbXyhhpneqjRqlg6g.png" /><figcaption>Model Summary</figcaption></figure><h4>Training the Model :</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cda3f5fa83e33509a4915993d5d4ef9d/href">https://medium.com/media/cda3f5fa83e33509a4915993d5d4ef9d/href</a></iframe><p>I only used 9000 samples because I did not have enough memory to use the whole dataset, and because of that, the result wasn’t good enough.</p><p>The optimizer we used is <a href="https://keras.io/optimizers"><strong>rmsprop </strong></a><strong>, </strong>it is used in models that have recurrent layers.</p><blockquote>This optimizer is usually a good choice for recurrent neural networks.</blockquote><p>We used <strong>categorical_crossentropy </strong>as the loss function, because we treat each word as a category (our output is a one hot vector that represents a word)</p><h4>To Recall :</h4><ul><li>We got to know what an encoder decoder model is.</li><li>How to create the encoder</li><li>How to use the embedding layer</li><li>How to make the decoder</li><li>We understood how the encoder decoder model works</li><li>We trained the model</li></ul><h3>What’s Next :</h3><p>In the next part of this series, we will use the trained model to translate English sentences to French.</p><h3>NLP | Sequence to Sequence Networks :</h3><p><a href="https://towardsdatascience.com/nlp-sequence-to-sequence-networks-part-1-processing-text-data-d141a5643b72">1- NLP | Sequence to Sequence Networks| Part 1| Processing text data</a></p><p>2- <a href="https://medium.com/@mamarih1/nlp-sequence-to-sequence-networks-part-2-seq2seq-model-encoderdecoder-model-6c22e29fd7e1">NLP | Sequence to Sequence Networks| Part 2|Seq2seq Model (Encoder Decoder Model)</a></p><h4>References :</h4><p>All the references o this series will be at the end of the last part.</p><p>You can follow me on Twitter <a href="https://twitter.com/ModMaamari">@ModMaamari</a></p><h4>You may also like :</h4><ul><li><a href="https://blog.goodaudience.com/ai-generates-taylor-swifts-song-lyrics-6fd92a03ef7e"><strong>AI Generates Taylor Swift’s Song Lyrics</strong></a></li><li><a href="https://medium.com/@mamarih1/deep-neural-networks-for-regression-problems-81321897ca33"><strong>Deep Neural Networks for Regression Problems</strong></a></li><li><a href="https://medium.com/@mamarih1/machine-learning-crash-course-with-tensorflow-apis-summary-524e0fa0a606"><strong>Machine Learning Crash Course with TensorFlow APIs Summary</strong></a></li><li><a href="https://medium.com/@mamarih1/how-to-make-a-cnn-using-tensorflow-and-keras-dd0aaaed8ab4"><strong>How To Make A CNN Using Tensorflow and Keras</strong></a></li><li><a href="https://medium.com/@mamarih1/how-to-choose-the-best-machine-learning-model-e1dbb46bdd4d"><strong>How to Choose the Best Machine Learning Model ?</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c22e29fd7e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/nlp-sequence-to-sequence-networks-part-2-seq2seq-model-encoderdecoder-model-6c22e29fd7e1">NLP | Sequence to Sequence Networks| Part 2|Seq2seq Model (EncoderDecoder Model)</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[NLP | Sequence to Sequence Networks| Part 1| Processing text data]]></title>
            <link>https://medium.com/data-science/nlp-sequence-to-sequence-networks-part-1-processing-text-data-d141a5643b72?source=rss-6238d4ba3932------2</link>
            <guid isPermaLink="false">https://medium.com/p/d141a5643b72</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Mohammed AL-Ma'amari]]></dc:creator>
            <pubDate>Thu, 08 Nov 2018 20:57:42 GMT</pubDate>
            <atom:updated>2021-04-22T03:58:49.444Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RspNg2-o0dL8IoSgBCkqQQ.png" /></figure><p>There are many benefits you can get by understanding NLP, you can make your own model to answer questions and use it in a chat bot, or you can make a translator to translate a text from your language to English language or the opposite, or maybe you make a text summarizer.</p><p>In this tutorial series, we will learn how to make a seq2seq network and train it to translate English text to French, or you can use it in another seq2seq purpose.</p><p>In this part of the series, we will learn about processing text data to feed it to the seq2seq network.</p><p>We will learn two methods to process texts</p><ul><li>Character level processing</li><li>Word level processing ( using embedding)</li></ul><p>I used a dataset of English → French sentences, You can get the dataset I used from [<a href="http://www.manythings.org/anki/fra-eng.zip">Here</a>].</p><p>For other languages, you can get the datasets using [<a href="http://www.manythings.org/anki/">this</a>] link</p><h3>First : Character level processing</h3><h4>Overview :</h4><p>I explained the text processing steps in the next pictures :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3dJqwlv2TyKvMib0_Lpuww.jpeg" /></figure><p>So, to represent the word <strong>ball :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*clOGgaE0nxsJAeJ2kM_hTQ.jpeg" /></figure><p>and, , to represent the sentence <strong>hello world! :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRbEaatZ95qs-nlgvr_dXw.jpeg" /></figure><p>I hope that you got some intuition of the steps of processing the text data.</p><p>Now we will do some coding using python :</p><p>First, lets import numpy :</p><pre>import numpy as np</pre><p>Then, load the text file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c64eee18a020e9bc18389d6145cabc0/href">https://medium.com/media/3c64eee18a020e9bc18389d6145cabc0/href</a></iframe><p>After that, split the samples and get the necessary dictionaries :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d596b20341f2047cd2499c4d8520bb3/href">https://medium.com/media/1d596b20341f2047cd2499c4d8520bb3/href</a></iframe><p>Make the needed dictionaries to convert characters to integers and the opposite :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d9f8faf466ab1c5fa4c6ff4e3b3a1fc/href">https://medium.com/media/9d9f8faf466ab1c5fa4c6ff4e3b3a1fc/href</a></iframe><p>Compute the length of the longest sample and some other variables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63a15cc8eaa216479ec463cc35fc2157/href">https://medium.com/media/63a15cc8eaa216479ec463cc35fc2157/href</a></iframe><p>Output :</p><pre>Number of E Samples  	: 160872<br>Number of D Samples 	: 160872<br>Number of D Chars  	: 115<br>Number of E Chars 	: 92<br>The Longest D Sample has 351 Chars<br>The Longest E Sample has 286 Chars</pre><p>E → the input text ( Will be encoded later )<br>D → the output text ( Will be decoded later )</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/774b71958e210925c3b98e420989ff7c/href">https://medium.com/media/774b71958e210925c3b98e420989ff7c/href</a></iframe><p>Next, we will <strong>One Hot Encode the </strong>samples by letters <br><strong>ex</strong>:</p><p>Hi — -&gt; [[0,0,0,…,1,0,0,0],[0,0,0,…,0,1,0,0]] <br>where we represent each sample as an array of zeros that has (n) rows and (j) columns<br><strong>n = Number of Characters in the longest Sample<br>j = number of chars in our dictionary</strong></p><p>We will make three sets of data :<br>1- Encoder Input Samples ( English sentences )<br>2- Decoder Input Samples ( French sentences)<br>3- Target ( French sentences)</p><p><strong>Target</strong> will be the same data as <strong>Decoder Input </strong>but it will be one character ahead of it <br><strong>Ex :</strong> <br>Decoder Input = ‘\tHow are yo’<br>Target = ‘How are you’</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aae4dfbcab38aa7f6a974594e0d47a9a/href">https://medium.com/media/aae4dfbcab38aa7f6a974594e0d47a9a/href</a></iframe><pre>[Output]:<br>Shape of encoder_input_data : (160872, 286, 92) <br>Shape of decoder_input_data : (160872, 351, 115) <br>Shape of target_data        : (160872, 351, 115)</pre><p>Now, the data is ready to be used by a seq2seq model.</p><h3>ٍSecond: Word level processing (using embedding):</h3><h4>overview:</h4><p>In this method, we do the same steps as the first method, but here instead of make a dictionary of characters, we make a dictionary of the words used in the text we want to process or sometimes we use the most frequent 10,000 words of the text’s language.</p><p>To make it easy to understand what we are going to do, we will :</p><ol><li>Convert text to lowercase</li><li>Clean data from digits and punctuation .</li><li>append ‘SOS’ and ‘EOS’ to the target data:</li></ol><blockquote>SOS → Start of Sentience</blockquote><blockquote>EOS → End of Sentience</blockquote><p>4. Make dictionaries to convert words to indexed numbers .</p><p>5. Use embedding layer to convert each word to a fixed length vector .</p><blockquote>Word embeddings provide a dense representation of words and their relative meanings.</blockquote><p>To learn more about word embeddings : [<a href="https://machinelearningmastery.com/use-word-embedding-layers-deep-learning-keras/">1</a>] , [<a href="https://keras.io/layers/embeddings/">2</a>], [<a href="https://www.youtube.com/watch?v=5PL0TmQhItY">3</a>],[<a href="https://www.youtube.com/watch?v=Qu-cvY4HP4g">4</a>]</p><p>6. Now, the data is ready to be used by seq2seq network.</p><p>Load the text data :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b921f083d311ee11bc33a80ef4ef81f6/href">https://medium.com/media/b921f083d311ee11bc33a80ef4ef81f6/href</a></iframe><h4>Data Cleanup :</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c1b2913045f327c1ba309ec62c68fc1/href">https://medium.com/media/2c1b2913045f327c1ba309ec62c68fc1/href</a></iframe><h4>Sample Processing :</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c85b534d3ea9e6934a4b380051e5920/href">https://medium.com/media/6c85b534d3ea9e6934a4b380051e5920/href</a></iframe><h4>Using Word Embeddings :</h4><p>I will show the line where I used the embedding layer, the whole network will be explained in the next part of this tutorial series.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acc3c090e8e316e07da561e904473504/href">https://medium.com/media/acc3c090e8e316e07da561e904473504/href</a></iframe><pre>num_words : is the number of words in the dictionary we used to convert words to numbers<br>vec_len : The length of the vector that will represent the words</pre><h3>What Next:</h3><p>In the next part [<a href="https://medium.com/@mamarih1/nlp-sequence-to-sequence-networks-part-2-seq2seq-model-encoderdecoder-model-6c22e29fd7e1"><strong>part 2</strong></a>] we will make the model and train it, then use it to translate English text to French.</p><h4>References :</h4><p>All the references o this series will be at the end of the last part.</p><p><strong>You can follow me on Twitter </strong><a href="https://twitter.com/ModMaamari"><strong>@ModMaamari</strong></a></p><h3>NLP | Sequence to Sequence Networks :</h3><p><a href="https://towardsdatascience.com/nlp-sequence-to-sequence-networks-part-1-processing-text-data-d141a5643b72">1- NLP | Sequence to Sequence Networks| Part 1| Processing text data</a></p><p>2- <a href="https://medium.com/@mamarih1/nlp-sequence-to-sequence-networks-part-2-seq2seq-model-encoderdecoder-model-6c22e29fd7e1">NLP | Sequence to Sequence Networks| Part 2|Seq2seq Model (Encoder Decoder Model)</a></p><h4>You may also like :</h4><ul><li><a href="https://blog.goodaudience.com/ai-generates-taylor-swifts-song-lyrics-6fd92a03ef7e"><strong>AI Generates Taylor Swift’s Song Lyrics</strong></a></li><li><a href="https://medium.com/@mamarih1/deep-neural-networks-for-regression-problems-81321897ca33"><strong>Deep Neural Networks for Regression Problems</strong></a></li><li><a href="https://medium.com/@mamarih1/machine-learning-crash-course-with-tensorflow-apis-summary-524e0fa0a606"><strong>Machine Learning Crash Course with TensorFlow APIs Summary</strong></a></li><li><a href="https://medium.com/@mamarih1/how-to-make-a-cnn-using-tensorflow-and-keras-dd0aaaed8ab4"><strong>How To Make A CNN Using Tensorflow and Keras</strong></a></li><li><a href="https://medium.com/@mamarih1/how-to-choose-the-best-machine-learning-model-e1dbb46bdd4d"><strong>How to Choose the Best Machine Learning Model ?</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d141a5643b72" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/nlp-sequence-to-sequence-networks-part-1-processing-text-data-d141a5643b72">NLP | Sequence to Sequence Networks| Part 1| Processing text data</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[ML Client/Server Using gRPC in Python]]></title>
            <link>https://medium.com/good-audience/ml-client-server-using-grpc-in-python-3cba7693d1f5?source=rss-6238d4ba3932------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cba7693d1f5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Mohammed AL-Ma'amari]]></dc:creator>
            <pubDate>Thu, 04 Oct 2018 17:18:37 GMT</pubDate>
            <atom:updated>2018-10-13T16:21:29.728Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GZ4CU2TkmU1Rfo87DRLP4w.jpeg" /></figure><p>A machine learning model by its own is not enough, we have to deploy it to use it efficiently.</p><p>Imagine that we want to make a microservice to predict home pricing, this service will be deployed in a phone app or in a web app, then we have to make a client/server to serve the clients.</p><p>In this article we will learn how to make a simple gRPC client/server to respond to the clients’ requests.</p><h3>Steps:</h3><p>1- Write the service to be served.</p><p>2- Make a proto file to define the messages and services.</p><p>3- Use the proto file to generate gRPC classes for Python</p><p>4- Create the server.</p><p>5- Create the client .</p><h4>Step 1 : Write the Service :</h4><p>In our case, the service is predicting house pricing, I have already trained a model to do that, I will use it in this example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/061ac09cbd284d2d9b51c4557ae31e78/href">https://medium.com/media/061ac09cbd284d2d9b51c4557ae31e78/href</a></iframe><p>We used <strong>joblib </strong>to load the trained model.</p><p>This model has 5 input arguments (features of the house that we want to predict its sale price)</p><h4>Step 2 : Make the Proto File :</h4><p>gRPC uses proto instead of Json.</p><p>If you want to learn about proto files read :</p><ul><li><a href="https://developers.google.com/protocol-buffers/docs/overview">What are protocol buffers and how they work ?</a></li><li><a href="https://medium.com/@caffeinocode/bye-bye-json-welcome-protocol-buffers-a3e4319ba51">Bye bye JSON! Welcome Protocol Buffers!</a></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02fd1da67373587ce065e6a881ebca48/href">https://medium.com/media/02fd1da67373587ce065e6a881ebca48/href</a></iframe><p>Here, we did not give values to the features, those numbers indicate the order of serializing the features.</p><h4>Step 3 : Generate gRPC classes for Python :</h4><p>Open the terminal, change the directory to be in the same folder that the proto file is in.</p><p>To generate the gRPC classes we have to install the needed libraries first:</p><pre>#Install gRPC :<br>python -m pip install grpcio</pre><pre>#To install gRPC tools, run:</pre><pre>python -m pip install grpcio-tools googleapis-common-protos</pre><p>for more details, visit (<a href="https://grpc.io/docs/quickstart/python.html#install-grpc">How to install gRPC for Python</a>)</p><p>Now, run the following command:</p><pre>python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. ML_example.proto</pre><p>This command used ML_example.proto file to generate the needed stubs to create the client/server.</p><p>The files generated will be as follows:</p><p><strong>ML_example_pb2.py — contains message classes</strong></p><ul><li><strong>ML_example_pb2</strong>.<strong>Features</strong> for the input features</li><li><strong>ML_example_pb2</strong>.<strong>Prediction</strong> for the prediction price</li></ul><p><strong>ML_example_pb2_grpc.py — contains server and client classes</strong></p><ul><li><strong>ML_example_pb2_grpc</strong>.<strong>PredictServicer </strong>will be used by the server</li><li><strong>ML_example_pb2_grpc</strong>.<strong>PredictStub</strong> the client will use it</li></ul><h4>Step 4 : Creating the Server :</h4><p>The server will import the generated files and the function that will handle the predictions.</p><p>Then we will define a class that will take a request from the client and uses the prediction function to return a respond.</p><p>The request gives us the five features ,the respond is a prediction.</p><p>After that, we will use <strong>add_PredictServicer_to_server</strong>function from (<strong>ML_example_pb2_grpc.py</strong>)file that was generated before to add the class PredictSevicer to the server .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82783f029ca045560b0264a24f35fa44/href">https://medium.com/media/82783f029ca045560b0264a24f35fa44/href</a></iframe><h4>Step 5: Creating the Client :</h4><p>In the client file we will do the following :</p><ul><li>Open a gRPC channel</li><li>Create a <a href="https://whatis.techtarget.com/definition/stub">stub</a></li><li>Create a request message</li><li>Use the stub to call the service</li></ul><p>We generated a hundred samples of house features to test the prediction function, we passed the generated samples as arguments to the prediction function.</p><p>We used two timers to measure the performance of our client/server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c146d48d463d10068e1b4211dd158a4/href">https://medium.com/media/1c146d48d463d10068e1b4211dd158a4/href</a></iframe><p>Now its time to try our client/server</p><p>First, put all the needed files in one directory, for example :</p><pre>ML_example/<br>├── predict_sale_price.py       # Prediction function<br>|<br>├── ML_example.proto             # protobuf definition file<br>|<br>├── ML_example_pb2_grpc.py       # generated class for server/client<br>├── ML_example_pb2.py            # generated class for message<br><br>|   # a server to expose the function<br>├── house_price_prediction_server.py     </pre><pre>|   # The client<br>└── house_price_prediction_client.py</pre><p>Now run the server :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*0t4wsZvjv1dd3p4hU7hiFw.png" /></figure><p>After that, in another terminal window, run the client :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*U1MpovNdk__LFBZs2TZCQg.png" /></figure><p>You can see the results yourself, It worked like a charm.</p><p>Now, after we learned how to make a client/server, we can deploy any ML model we make, we can make a server and use it in phone apps or web apps.</p><h3>What Next :</h3><ul><li>Now you can make your own ML model and deploy it.</li><li>Learn more about gRPC (you can find some helpful references below)</li><li>Try to use Go language to make the client and see how will it effect the performance</li></ul><h3>References :</h3><ul><li><a href="https://grpc.io/docs/quickstart/python.html">gRPC using Python</a></li><li><a href="https://grpc.io/docs/guides/">Guide to gRPC</a></li><li><a href="https://engineering.semantics3.com/a-simplified-guide-to-grpc-in-python-6c4e25f0c506">A simplified guide to gRPC in Python</a></li><li><a href="https://developers.google.com/protocol-buffers/docs/overview">Protocol Buffers | Developer Guide</a></li><li><a href="https://grpc.io/docs/tutorials/basic/python.html">gRPC Basics — Python</a></li></ul><p><strong>You can follow me on Twitter </strong><a href="https://twitter.com/ModMaamari"><strong>@ModMaamari</strong></a></p><h4>You may also like :</h4><ul><li><a href="https://blog.goodaudience.com/ai-generates-taylor-swifts-song-lyrics-6fd92a03ef7e"><strong>AI Generates Taylor Swift’s Song Lyrics</strong></a></li><li><a href="https://towardsdatascience.com/deep-neural-networks-for-regression-problems-81321897ca33"><strong>Deep Neural Networks for Regression Problems</strong></a></li><li><a href="https://medium.com/datadriveninvestor/introduction-to-random-forest-algorithm-with-python-9efd1d8f0157"><strong>Introduction to Random Forest Algorithm with Python</strong></a></li><li><a href="https://medium.com/@mamarih1/machine-learning-crash-course-with-tensorflow-apis-summary-524e0fa0a606"><strong>Machine Learning Crash Course with TensorFlow APIs Summary</strong></a></li><li><a href="https://medium.com/@mamarih1/how-to-make-a-cnn-using-tensorflow-and-keras-dd0aaaed8ab4"><strong>How To Make A CNN Using Tensorflow and Keras</strong></a><strong> ?</strong></li><li><a href="https://medium.com/@mamarih1/how-to-choose-the-best-machine-learning-model-e1dbb46bdd4d"><strong>How to Choose the Best Machine Learning Model ?</strong></a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F7b0181%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F7b0181%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/748a06e9019942f2677bba917ef55804/href">https://medium.com/media/748a06e9019942f2677bba917ef55804/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cba7693d1f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/good-audience/ml-client-server-using-grpc-in-python-3cba7693d1f5">ML Client/Server Using gRPC in Python</a> was originally published in <a href="https://medium.com/good-audience">Good Audience</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Neural Networks for Regression Problems]]></title>
            <link>https://medium.com/data-science/deep-neural-networks-for-regression-problems-81321897ca33?source=rss-6238d4ba3932------2</link>
            <guid isPermaLink="false">https://medium.com/p/81321897ca33</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[kaggle]]></category>
            <dc:creator><![CDATA[Mohammed AL-Ma'amari]]></dc:creator>
            <pubDate>Sat, 29 Sep 2018 00:54:26 GMT</pubDate>
            <atom:updated>2018-10-25T20:05:10.825Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUKwarc7rCouMzSt0Ksakw.jpeg" /><figcaption><a href="https://paulvanderlaken.files.wordpress.com/2017/10/1-0flvittznpkh8qkj7upleq.png?w=700">Image Source</a></figcaption></figure><p>Neural networks are well known for classification problems, for example, they are used in handwritten digits classification, but the question is will it be fruitful if we used them for regression problems?</p><p>In this article I will use a deep neural network to predict house pricing using a dataset from Kaggle .</p><p>You can download the dataset from <a href="https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data">Here</a></p><p>I highly recommend you to try running the code using my notebook on Google colab [<a href="https://colab.research.google.com/drive/1J8ZTI2UIJCwml2nrLVu8Gg0GXEz-7ZK0">Here</a>]</p><h3>Contents :</h3><blockquote>1- Process the dataset<br>2- Make the deep neural network<br>3- Train the DNN<br>4- Test the DNN<br>5- Compare the result from the DNN to another ML algorithm</blockquote><p><strong>First of all, we will import the needed dependencies :</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ae5d71445700640f4d0f8ee3bda3ae9/href">https://medium.com/media/7ae5d71445700640f4d0f8ee3bda3ae9/href</a></iframe><h3>First : Processing the dataset</h3><p>We will not go deep in processing the dataset, all we want to do is getting the dataset ready to be fed into our models .</p><p>We will get rid of any features with missing values, then we will encode the categorical features, that’s it.</p><h4>Load the dataset :</h4><ul><li>Load train and test data into pandas DataFrames</li><li>Combine train and test data to process them together</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74079f4f16be0ad386e8d2aca2597324/href">https://medium.com/media/74079f4f16be0ad386e8d2aca2597324/href</a></iframe><pre>combined.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*mx0xGJPdknNRZmiZOv_VGg.png" /></figure><p>let’s define a function to get the columns that don’t have any missing values</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c021174c209be26f75c4be0dd229f72/href">https://medium.com/media/8c021174c209be26f75c4be0dd229f72/href</a></iframe><p>Get the columns that do not have any missing values .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9803907ae75e4de65bec03c1e4d8949e/href">https://medium.com/media/9803907ae75e4de65bec03c1e4d8949e/href</a></iframe><p>Let’s see how many columns we got</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1f0f495d92b3ace0200bcc34c84ca8c/href">https://medium.com/media/b1f0f495d92b3ace0200bcc34c84ca8c/href</a></iframe><pre>[out]:<br>Number of numerical columns with no nan values : 25 <br>Number of nun-numerical columns with no nan values : 20</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d65e167f81695523e9196b6bfc70f2e/href">https://medium.com/media/5d65e167f81695523e9196b6bfc70f2e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*cBbEbSv-BWn1BCJg0c7fPw.png" /><figcaption>Histogram of the features</figcaption></figure><p><strong>The correlation between the features</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3ed302f304a5cf5af247cc54669a33b/href">https://medium.com/media/b3ed302f304a5cf5af247cc54669a33b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*mhgimekf-wVw4gvFQr3Ecg.png" /></figure><p>From the correlation heat map above, we see that about 15 features are highly correlated with the target.</p><p><strong>One Hot Encode The Categorical Features :</strong></p><p>We will encode the categorical features using one hot encoding.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3b4f4ee54dbf5f43f351d88fd41adf1/href">https://medium.com/media/a3b4f4ee54dbf5f43f351d88fd41adf1/href</a></iframe><pre>[out]:<br>There were 45 columns before encoding categorical features <br>There are 149 columns after encoding categorical features</pre><p>Now, split back combined dataFrame to training data and test data</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81f63e7e65c70060758a307339ec98db/href">https://medium.com/media/81f63e7e65c70060758a307339ec98db/href</a></iframe><h3>Second : Make the Deep Neural Network</h3><ul><li>Define a sequential model</li><li>Add some dense layers</li><li>Use ‘<strong>relu</strong>’ as the activation function for the hidden layers</li><li>Use a ‘<strong>normal</strong>’ initializer as the kernal_intializer</li></ul><blockquote>Initializers define the way to set the initial random weights of Keras layers.</blockquote><ul><li>We will use mean_absolute_error as a loss function</li><li>Define the output layer with only one node</li><li>Use ‘<strong>linear</strong> ’as the activation function for the output layer</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e1117f942b466a5e040a9044956781c/href">https://medium.com/media/7e1117f942b466a5e040a9044956781c/href</a></iframe><pre>[Out]:<br>_________________________________________________________________ Layer (type)                 Output Shape              Param #    ================================================================= dense_1 (Dense)              (None, 128)               19200      _________________________________________________________________ dense_2 (Dense)              (None, 256)               33024      _________________________________________________________________ dense_3 (Dense)              (None, 256)               65792      _________________________________________________________________ dense_4 (Dense)              (None, 256)               65792      _________________________________________________________________ dense_5 (Dense)              (None, 1)                 257        ================================================================= Total params: 184,065 Trainable params: 184,065 Non-trainable params: 0 _________________________________________________________________</pre><p><strong>Define a checkpoint callback :</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca09b652fbb1249d03a0fe61041f299c/href">https://medium.com/media/ca09b652fbb1249d03a0fe61041f299c/href</a></iframe><h3>Third : Train the model :</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/775326dac4d60113a9cac206295d99d9/href">https://medium.com/media/775326dac4d60113a9cac206295d99d9/href</a></iframe><pre>[out]:<br>Train on 1168 samples, validate on 292 samples<br>Epoch 1/500<br>1168/1168 [==============================] - 0s 266us/step - loss: 19251.8903 - mean_absolute_error: 19251.8903 - val_loss: 23041.8968 - val_mean_absolute_error: 23041.8968  <br>Epoch 00001: val_loss did not improve from 21730.93555 <br>Epoch 2/500<br> 1168/1168 [==============================] - 0s 268us/step - loss: 18180.4985 - mean_absolute_error: 18180.4985 - val_loss: 22197.7991 - val_mean_absolute_error: 22197.7991  <br>Epoch 00002: val_loss did not improve from 21730.93555<br>.<br>.<br>.<br>Epoch 00500: val_loss did not improve from 18738.19831</pre><pre>&lt;keras.callbacks.History at 0x7f4324aa80b8&gt;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19deb04e60483f19184d177cbf20f6a2/href">https://medium.com/media/19deb04e60483f19184d177cbf20f6a2/href</a></iframe><p>We see that the validation loss of the best model is 18738.19</p><h3>Fourth : Test the model</h3><p>We will submit the predictions on the test data to Kaggle and see how good our model is.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1651eb80da6d4b34a652e9f7c5e61646/href">https://medium.com/media/1651eb80da6d4b34a652e9f7c5e61646/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*mXbUrGB9yB9RrBscwugP9g.png" /><figcaption>The result of the deep neural network’s submission on Kaggle</figcaption></figure><p>Not bad at all, with some more preprocessing, and more training, we can do better.</p><h3>Fifth: Try another ML algorithms :</h3><p>Now, let us try another ML algorithm to compare the results.</p><p>We will use random forest regressor and XGBRegressor.</p><p><strong>Split training data to training and validation data</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d117b5b0522e6d2eb5ae8c7899367c0e/href">https://medium.com/media/d117b5b0522e6d2eb5ae8c7899367c0e/href</a></iframe><p><strong>We will try Random forest model first:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/138b1513f179e019b2276dd7df6caee7/href">https://medium.com/media/138b1513f179e019b2276dd7df6caee7/href</a></iframe><pre>Random forest validation MAE =  19089.71589041096</pre><p><strong>Make a submission file and submit it to Kaggle to see the result :</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7358faff9bfc037525b1b56ba1cba6b2/href">https://medium.com/media/7358faff9bfc037525b1b56ba1cba6b2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*wcJqKzBsbLARqMjwvv0Xjw.png" /><figcaption>The result of random forest’s submission on Kaggle</figcaption></figure><p><strong>Now, let us try XGBoost model :</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc4bde7a1981e0c41d3862b7e781d65f/href">https://medium.com/media/cc4bde7a1981e0c41d3862b7e781d65f/href</a></iframe><pre>[out]: <br>XGBoost validation MAE =  17869.75410958904</pre><p><strong>Make a submission file and submit it to Kaggle to see the result :</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a133db89f0f05f934845841b98fbb67c/href">https://medium.com/media/a133db89f0f05f934845841b98fbb67c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*PO0jxykz1hv-aSN5kkjItg.png" /><figcaption>The result of XGBoost’s submission on Kaggle</figcaption></figure><p>Isn’t that a surprise, I really did not think that neural networks will beat random forests and XGBoost algorithms, but let us try not to be too optimistic, remember that we did not configure any hyperparameters on random forest and XGBoost models, I believe if we did so, these two models would outscore neural networks.</p><h4>To summarize what we did :</h4><ul><li>We load and processed the dataset</li><li>We got familiar with the dataset by plotting some histograms and a correlation heat map of the features</li><li>We used a deep neural network with three hidden layers each one has 256 nodes.</li><li>We used a linear activation function on the output layer</li><li>We trained the model then test it on Kaggle.</li><li>We also tested two other models</li><li>Our deep neural network was able to outscore these two models</li><li>We believe that these two models could beat the deep neural network model if we tweak their hyperparameters.</li></ul><h3>Next Steps :</h3><ul><li>Try to put more effort on processing the dataset</li><li>Try other types of neural networks</li><li>Try to tweak the hyperparameters of the two models that we used</li><li>If you really want to get better at regression problems, follow this tutorial:</li></ul><p>[<a href="https://www.kaggle.com/serigne/stacked-regressions-top-4-on-leaderboard">Stacked Regressions : Top 4% on LeaderBoard | Kaggle</a>]</p><h3>References :</h3><ul><li><a href="https://machinelearningmastery.com/regression-tutorial-keras-deep-learning-library-python/">Regression Tutorial with the Keras Deep Learning Library in Python</a></li></ul><p>You can follow me on Twitter <a href="https://twitter.com/ModMaamari">@ModMaamari</a></p><h4>You may also like :</h4><ul><li><a href="https://blog.goodaudience.com/ai-generates-taylor-swifts-song-lyrics-6fd92a03ef7e"><strong>AI Generates Taylor Swift’s Song Lyrics</strong></a></li><li><a href="https://medium.com/datadriveninvestor/introduction-to-random-forest-algorithm-with-python-9efd1d8f0157"><strong>Introduction to Random Forest Algorithm with Python</strong></a></li><li><a href="https://medium.com/@mamarih1/machine-learning-crash-course-with-tensorflow-apis-summary-524e0fa0a606"><strong>Machine Learning Crash Course with TensorFlow APIs Summary</strong></a></li><li><a href="https://medium.com/@mamarih1/how-to-make-a-cnn-using-tensorflow-and-keras-dd0aaaed8ab4"><strong>How To Make A CNN Using Tensorflow and Keras</strong></a><strong> ?</strong></li><li><a href="https://medium.com/@mamarih1/how-to-choose-the-best-machine-learning-model-e1dbb46bdd4d"><strong>How to Choose the Best Machine Learning Model ?</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81321897ca33" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deep-neural-networks-for-regression-problems-81321897ca33">Deep Neural Networks for Regression Problems</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[Introduction to Random Forest Algorithm with Python]]></title>
            <link>https://medium.com/good-audience/introduction-to-random-forest-algorithm-with-python-9efd1d8f0157?source=rss-6238d4ba3932------2</link>
            <guid isPermaLink="false">https://medium.com/p/9efd1d8f0157</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[kaggle-competition]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mohammed AL-Ma'amari]]></dc:creator>
            <pubDate>Tue, 25 Sep 2018 19:53:16 GMT</pubDate>
            <atom:updated>2018-11-17T20:46:35.633Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iIx75bixLRbE45mXkH2oCg.png" /></figure><p>Random forest algorithm has become the most common algorithm to be used in ML competitions like Kaggle competitions, If you ever search for an easy to use and accurate ML algorithm, you will absolutely get random forest in the top results. To understand Random forest algorithm you have to be familiar with decision trees at first .</p><h3>What are Decision Trees?</h3><ul><li>Decision trees are predictive models that use a set of binary rules to calculate a target value.</li><li>There are two types of decision trees are classification and regression trees.</li><li>Classification trees are used to create categorical data sets such as land cover classification</li><li>Regression trees are used to create continuous data sets such as biomass and percent tree cover.</li><li>Each individual tree is a fairly simple model that has branches, nodes and leaves.</li><li>The nodes contain the attributes the objective function depends on.</li></ul><p>Now after you got familiar with decision trees, you are ready to understand random forest.</p><h3>What is Random Forest?</h3><p>As <strong>Leo Breiman </strong>defined it in the <a href="https://www.stat.berkeley.edu/~breiman/randomforest2001.pdf">research paper</a>, “ Random forests are a combination of tree predictors such that each tree depends on the values of a random vector sampled independently and with the same distribution for all trees in the forest ”</p><p>Another definition “A random forest is a classifier consisting of a collection of tree structured classifiers {h(x,Θk ), k=1, …} where the {Θk} are independent identically distributed random vectors and each tree casts a unit vote for the most popular class at input x ” Briefly, Random forest builds multiple decision trees and merges them together to get a more accurate and stable prediction.</p><h3>Advantages of Random Forests</h3><ul><li>It can be used for both classification and regression problems</li><li>Reduction in overfitting: by averaging several trees, there is a significantly lower risk of overfitting.</li><li>Random forests make a wrong prediction only when more than half of the base classifiers are wrong</li><li>It is very easy to measure the relative importance of each feature on the prediction. Sklearn as example has powerful library to do that.</li></ul><p>Because of that, it is more accurate than most of the other algorithms.</p><h3>Disadvantages of Random Forests</h3><ul><li>Random forests have been observed to overfit for some datasets with noisy classification/regression tasks.</li><li>It’s more complex and computationally expensive than decision tree algorithm.</li></ul><h3>Important Terminology related to Decision Trees <a href="https://www.analyticsvidhya.com/blog/2016/04/complete-tutorial-tree-based-modeling-scratch-in-python/">[1]</a></h3><p>Let’s look at the basic terminology used with decision trees and random forests :</p><ol><li><strong>Root Node</strong>: It represents entire population or sample and this further gets divided into two or more homogeneous sets.</li><li><strong>Splitting</strong>: It is a process of dividing a node into two or more sub-nodes.</li><li><strong>Decision Node</strong>: When a sub-node splits into further sub-nodes, then it is called decision node.</li><li><strong>Leaf/ Terminal Node</strong>: Nodes do not split is called Leaf or Terminal node.</li><li><strong>Pruning</strong>: When we remove sub-nodes of a decision node, this process is called pruning. You can say opposite process of splitting.</li><li><strong>Branch / Sub-Tree</strong>: A sub section of entire tree is called branch or sub-tree.</li><li><strong>Parent and Child Node</strong>: A node, which is divided into sub-nodes is called parent node of sub-nodes where as sub-nodes are the child of parent node.</li></ol><p>After we got to know some essentials about random forests, let us use this algorithm in some dataset, In our case we will use <a href="https://www.kaggle.com/c/titanic/data">Kaggle’s titanic survivors dataset</a> that I preprocessed before</p><p>And then we will use a neural network to compare the results.</p><p>I recommend you to try running the code yourself in this[<a href="https://colab.research.google.com/drive/1GLioV8YoeJtjuSWS6FD0GHfgSnluov1R">Colab Notebook</a>]</p><h4>Import needed dependencies :</h4><pre>from sklearn.model_selection import train_test_split<br>import pandas as pd<br>import numpy as np<br>from keras.models import Sequential<br>from keras.layers import Dense, Activation, Flatten<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import f1_score<br>from sklearn.metrics import accuracy_score<br>from keras.callbacks import ModelCheckpoint<br>from sklearn.metrics import accuracy_score</pre><h4>Load the preprocessed dataset:</h4><p>Download the preprocessed dataset [ <a href="https://drive.google.com/file/d/1rzbDYv3tYLQ7J-P3cgG7mHVwxWzgBwdr/view">Here</a>]</p><pre>dataset =pd.read_csv(&#39;TitanicPreprocessed.csv&#39;)<br>dataset.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*DD4Az5g3W1uKrdPJ0zI_2g.png" /></figure><pre>y = dataset[&#39;Survived&#39;]<br>X = dataset.drop([&#39;Survived&#39;], axis = 1)</pre><pre># Split the dataset to trainand test data<br>train_X, test_X, train_y, test_y = train_test_split(X, y, test_size=0.25, random_state=0)</pre><h4>Set the parameters for the random forest model :</h4><pre>parameters = {&#39;bootstrap&#39;: True,<br>              &#39;min_samples_leaf&#39;: 3,<br>              &#39;n_estimators&#39;: 50, <br>              &#39;min_samples_split&#39;: 10,<br>              &#39;max_features&#39;: &#39;sqrt&#39;,<br>              &#39;max_depth&#39;: 6,<br>              &#39;max_leaf_nodes&#39;: None}</pre><h3>Hyperparameters of Sklearn Random forest classifier<a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">[2]</a> :</h3><p><strong>bootstrap</strong> : boolean, optional (default=True)</p><ul><li>Whether bootstrap samples are used when building trees.</li></ul><p><strong>min_samples_leaf</strong> : int, float, optional (default=1)</p><p><em>The minimum number of samples required to be at a leaf node:</em></p><ul><li>If int, then consider min_samples_leaf as the minimum number.</li><li>If float, then min_samples_leaf is a percentage and ceil(min_samples_leaf * n_samples) are the minimum number of samples for each node.</li></ul><p><strong>n_estimators</strong> : integer, optional (default=10)</p><ul><li>The number of trees in the forest.</li></ul><p><strong>min_samples_split</strong> : int, float, optional (default=2)</p><p>The minimum number of samples required to split an internal node:</p><ul><li>If int, then consider min_samples_split as the minimum number.</li><li>If float, then min_samples_split is a percentage and ceil(min_samples_split * n_samples) are the minimum number of samples for each split.</li></ul><p><strong>max_features</strong> : int, float, string or None, optional (default=”auto”)</p><p>The number of features to consider when looking for the best split:</p><ul><li>If int, then consider max_features features at each split. -If float, then max_features is a percentage and int(max_features * n_features) features are considered at each split.</li><li>If “auto”, then max_features=sqrt(n_features).</li><li>If “sqrt”, then max_features=sqrt(n_features) (same as “auto”).</li><li>If “log2”, then max_features=log2(n_features).</li><li>If None, then max_features=n_features.</li></ul><p><strong>max_depth</strong> : integer or None, optional (default=None)</p><ul><li>The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples.</li></ul><p><strong>max_leaf_nodes</strong> : int or None, optional (default=None)</p><ul><li>Grow trees with max_leaf_nodes in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes.</li></ul><p>If you want to learn more about the rest of hyperparameters , check out <a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">sklearn.ensemble.RandomForestClassifier</a></p><h4>Define the model :</h4><pre>RF_model = RandomForestClassifier(**parameters)</pre><h4>Train the model :</h4><pre>RF_model.fit(train_X, train_y)</pre><h4>Test the trained model on test data :</h4><pre>RF_predictions = RF_model.predict(test_X)</pre><pre>score = accuracy_score(test_y ,RF_predictions)<br>print(score)</pre><blockquote>0.82511</blockquote><p>We see that the model’s accuracy is 82%, not bad at all.</p><h3>Using Neural Networks:</h3><h4>Define the model :</h4><pre># Build a neural network :<br>NN_model = Sequential()</pre><pre>NN_model.add(Dense(128, input_dim = 68, activation=&#39;relu&#39;))<br>NN_model.add(Dense(256, activation=&#39;relu&#39;))<br>NN_model.add(Dense(256, activation=&#39;relu&#39;))<br>NN_model.add(Dense(256, activation=&#39;relu&#39;))<br>NN_model.add(Dense(1, activation=&#39;sigmoid&#39;))<br>NN_model.compile(loss=&#39;binary_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])</pre><p>Define a checkpoint callback :</p><pre>checkpoint_name = &#39;Weights-{epoch:03d}-{val_acc:.5f}.hdf5&#39; <br>checkpoint = ModelCheckpoint(checkpoint_name, monitor=&#39;val_acc&#39;, verbose = 1, save_best_only = True, mode =&#39;max&#39;)<br>callbacks_list = [checkpoint]</pre><h4>Train the model :</h4><pre>NN_model.fit(train_X, train_y, epochs=150, batch_size=64, validation_split = 0.2, callbacks=callbacks_list)</pre><p>The training process :</p><pre>Epoch 00044: val_acc did not improve from 0.88060 Epoch 45/150 534/534 [==============================] - 0s 149us/step - loss: 0.3196 - acc: 0.8652 - val_loss: 0.4231 - val_acc: 0.8433  Epoch 00045: val_acc did not improve from 0.88060 Epoch 46/150 534/534 [==============================] - 0s 134us/step - loss: 0.3156 - acc: 0.8670 - val_loss: 0.4175 - val_acc: 0.8358  Epoch 00046: val_acc did not improve from 0.88060 Epoch 47/150 534/534 [==============================] - 0s 144us/step - loss: 0.3031 - acc: 0.8689 - val_loss: 0.4214 - val_acc: 0.8433  Epoch 00047: val_acc did not improve from 0.88060 Epoch 48/150 534/534 [==============================] - 0s 131us/step - loss: 0.3117 - acc: 0.8689 - val_loss: 0.4095 - val_acc: 0.8582</pre><pre>.<br>.<br>.</pre><pre>Epoch 00148: val_acc did not improve from 0.88060<br>Epoch 149/150<br>534/534 [==============================] - 0s 146us/step - loss: 0.1599 - acc: 0.9382 - val_loss: 1.0482 - val_acc: 0.7761<br><br>Epoch 00149: val_acc did not improve from 0.88060<br>Epoch 150/150<br>534/534 [==============================] - 0s 133us/step - loss: 0.1612 - acc: 0.9307 - val_loss: 1.1589 - val_acc: 0.7836<br><br>Epoch 00150: val_acc did not improve from 0.88060<br>&lt;keras.callbacks.History at 0x7f47cb549320&gt;</pre><p>Load wights file of the best model :</p><pre>wights_file = &#39;./Weights-016-0.88060.hdf5&#39; # choose the best checkpoint <br>NN_model.load_weights(wights_file) # load it<br>NN_model.compile(loss=&#39;binary_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])</pre><h4>Test the trained model on test data :</h4><pre>predictions = NN_model.predict(test_X)<br># round predictions<br>rounded = [round(x[0]) for x in predictions]<br>predictions = rounded<br>score = accuracy_score(test_y ,predictions)<br>print(score)</pre><blockquote>0.81165</blockquote><p>The accuracy of this neural network model is 81%, we notice that using random forest gives us a higher accuracy.</p><p><strong>To recap:</strong></p><ul><li>We learned some essentials about decisions trees and random forests.</li><li>We discussed the advantages and disadvantages of using random forests.</li><li>We talked about some important terminologies related to decision trees and random forests.</li><li>We applied both random forest algorithm and neural networks to a dataset, and we compared the accuracy of the two models.</li><li>Random forests outscored neural networks in the problem of predicting titanic survivors.</li></ul><h3>References :</h3><ul><li><a href="https://towardsdatascience.com/the-random-forest-algorithm-d457d499ffcd">The Random Forest Algorithm</a></li><li><a href="https://www.quora.com/What-are-some-advantages-of-using-a-random-forest-over-a-decision-tree-given-that-a-decision-tree-is-simpler">What are some advantages of using a random forest over a decision tree given that a decision tree is simpler?</a></li><li><a href="https://www.analyticsvidhya.com/blog/2016/04/complete-tutorial-tree-based-modeling-scratch-in-python/">A Complete Tutorial on Tree Based Modeling from Scratch</a></li><li><a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">Sklearn documents of random forest</a></li><li><a href="https://cdn5.vectorstock.com/i/1000x1000/88/99/city-and-forest-vector-1078899.jpg">Image Source</a></li></ul><p>You can follow me on Twitter <a href="https://twitter.com/ModMaamari">@ModMaamari</a></p><h4><strong>You may also like :</strong></h4><ul><li><a href="https://blog.goodaudience.com/ai-generates-taylor-swifts-song-lyrics-6fd92a03ef7e"><strong>AI Generates Taylor Swift’s Song Lyrics</strong></a></li><li><a href="https://medium.com/@mamarih1/deep-neural-networks-for-regression-problems-81321897ca33"><strong>Deep Neural Networks for Regression Problems</strong></a></li><li><a href="https://medium.com/@mamarih1/machine-learning-crash-course-with-tensorflow-apis-summary-524e0fa0a606"><strong>Machine Learning Crash Course with TensorFlow APIs Summary</strong></a></li><li><a href="https://medium.com/@mamarih1/how-to-make-a-cnn-using-tensorflow-and-keras-dd0aaaed8ab4"><strong>How To Make A CNN Using Tensorflow and Keras</strong></a></li><li><a href="https://medium.com/@mamarih1/how-to-choose-the-best-machine-learning-model-e1dbb46bdd4d"><strong>How to Choose the Best Machine Learning Model ?</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9efd1d8f0157" width="1" height="1" alt=""><hr><p><a href="https://medium.com/good-audience/introduction-to-random-forest-algorithm-with-python-9efd1d8f0157">Introduction to Random Forest Algorithm with Python</a> was originally published in <a href="https://medium.com/good-audience">Good Audience</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>