<?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 whoisslimshady on Medium]]></title>
        <description><![CDATA[Stories by whoisslimshady on Medium]]></description>
        <link>https://medium.com/@whoisslimshady?source=rss-3c0cd74a4676------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*apN1MS3ZwRaWtKOH1bETBA.png</url>
            <title>Stories by whoisslimshady on Medium</title>
            <link>https://medium.com/@whoisslimshady?source=rss-3c0cd74a4676------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:09:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@whoisslimshady/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[Ai created a movie]]></title>
            <link>https://medium.com/geekculture/ai-created-a-movie-f97f897bd244?source=rss-3c0cd74a4676------2</link>
            <guid isPermaLink="false">https://medium.com/p/f97f897bd244</guid>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[movies]]></category>
            <category><![CDATA[gpt]]></category>
            <dc:creator><![CDATA[whoisslimshady]]></dc:creator>
            <pubDate>Wed, 13 Oct 2021 12:50:27 GMT</pubDate>
            <atom:updated>2021-10-14T07:23:25.736Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G5pgV1-32d8M5nqxCQUJSA.jpeg" /></figure><p>In this blog i am going to show some of the results and the process of the project i was working on, in which i had to assemble a video fully made by deep learning techniques</p><p>Before solving this problem we need to know what are the requirements to create a movie</p><p>few basic needs are actors, music, script</p><p>now with this knowledge we are equipped to produce a movie</p><h3>Script</h3><p>To produce the script for the movie i am going to use GPT-J-6B model name 6B cause it has 6 billion parameters and thanks to all the researcher of <a href="https://www.eleuther.ai/">EleutherAI</a> they open source the model for public</p><p>so to produce a script i had to input a context text then GPT-6B will take care of the script</p><blockquote>man — its too dark here i wouldn’t able to find light if i wanted to.</blockquote><blockquote>man — why you got very late.</blockquote><blockquote>Women replied — the weather was cold and harsh.</blockquote><p>this is the what i input into model after many trial error i got a script which make little bit of sense so now we done with script</p><h3>Actors</h3><p>We need someone to actually perform on our script for this i turned to StyleGAN which was released by the nvidia which makes easy for us to recruit actor so after trial and error i finalise to cast two actors who don’t exist</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cclSim_OFgQsAsj4ddUDfA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A49oyFZi1-r40fcHqA5n1A.png" /></figure><p>One for women actor and other for man but these are only images how they gonna perform then</p><p>to overcome this problem i ended up with First-order-model which easily solves this problem you can check the official repo <a href="https://github.com/AliaksandrSiarohin/first-order-model">https://github.com/AliaksandrSiarohin/first-order-model</a> here</p><h3>Music</h3><p>How can we have movie without music so to produce music i ended up with musegan which can actually produce good sound you can check out their repo <a href="https://github.com/salu133445/musegan">https://github.com/salu133445/musegan</a> so we got the the music now its time to assemble the whole thing in one video which is totally machine l genrated</p><p>for cinematic shots i used gaugan</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFTi_49k9-Go%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFTi_49k9-Go&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FFTi_49k9-Go%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/1e3f9e4683ec082d5e1319f1c32a40ba/href">https://medium.com/media/1e3f9e4683ec082d5e1319f1c32a40ba/href</a></iframe><p><a href="https://youtu.be/FTi_49k9-Go"><strong>https://youtu.be/FTi_49k9-Go</strong></a></p><p>here is the final result of the project hope you like it</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f97f897bd244" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/ai-created-a-movie-f97f897bd244">Ai created a movie</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[General approach for Custom Object Detection with Tensorflow 2]]></title>
            <link>https://whoisslimshady.medium.com/general-approach-for-custom-object-detection-with-tensorflow-2-61593a67a02d?source=rss-3c0cd74a4676------2</link>
            <guid isPermaLink="false">https://medium.com/p/61593a67a02d</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[whoisslimshady]]></dc:creator>
            <pubDate>Mon, 30 Aug 2021 07:27:42 GMT</pubDate>
            <atom:updated>2021-08-30T09:03:26.877Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3H9iEvN65L0FBNfKRQVUPg.png" /></figure><p>In this blog, I walk you through how you can train your own custom object detector with Tensorflow 2. This won’t be Tutorial to do certain type of detection but more of a common approach which we can take to detect anything.</p><p>To train a custom object detection model with the Tensorflow object Detection API, you need to go through the following steps:</p><ul><li>Download the Tensorflow Object Detection API</li><li>Get data</li><li>Prepare data for the OD API</li><li>Hyperparameter tuning</li><li>Train model</li><li>Save model</li><li>Test model</li></ul><h3>Installation</h3><p>You can install the TensorFlow Object Detection API either with Python Package Installer (pip) or <a href="https://www.docker.com/">Docker</a>, an open-source platform for deploying and managing containerized applications. For running the Tensorflow Object Detection API locally, Docker is recommended. If you aren’t familiar with Docker though, it might be easier to install it using pip.</p><p>First clone the master branch of the Tensorflow Models repository:</p><pre>git clone <a href="https://github.com/tensorflow/models.git">https://github.com/tensorflow/models.git</a></pre><h3>Docker Installation</h3><pre># From the root of the git repository (inside the models directory)<br>docker build -f research/object_detection/dockerfiles/tf2/Dockerfile -t od .<br>docker run -it od</pre><h3>Python Package Installation</h3><pre>cd models/research<br># Compile protos.<br>protoc object_detection/protos/*.proto --python_out=.<br># Install TensorFlow Object Detection API.<br>cp object_detection/packages/tf2/setup.py .<br>python -m pip install .</pre><pre>import os<br>import sys<br>args = sys.argv<br>directory = args[1]<br>protoc_path = args[2]<br>for file in os.listdir(directory):<br>    if file.endswith(&quot;.proto&quot;):<br>        os.system(protoc_path+&quot; &quot;+directory+&quot;/&quot;+file+&quot; --python_out=.&quot;)</pre><pre>python use_protobuf.py &lt;path to directory&gt; &lt;path to protoc file&gt;</pre><p>To test the installation run:</p><pre>python object_detection/builders/model_builder_tf2_test.py</pre><p>If everything installed correctly you should see something like:</p><pre>...<br>[       OK ] ModelBuilderTF2Test.test_create_ssd_models_from_config<br>[ RUN      ] ModelBuilderTF2Test.test_invalid_faster_rcnn_batchnorm_update<br>[       OK ] ModelBuilderTF2Test.test_invalid_faster_rcnn_batchnorm_update<br>[ RUN      ] ModelBuilderTF2Test.test_invalid_first_stage_nms_iou_threshold<br>[       OK ] ModelBuilderTF2Test.test_invalid_first_stage_nms_iou_threshold<br>[ RUN      ] ModelBuilderTF2Test.test_invalid_model_config_proto<br>[       OK ] ModelBuilderTF2Test.test_invalid_model_config_proto<br>[ RUN      ] ModelBuilderTF2Test.test_invalid_second_stage_batch_size<br>[       OK ] ModelBuilderTF2Test.test_invalid_second_stage_batch_size<br>[ RUN      ] ModelBuilderTF2Test.test_session<br>[  SKIPPED ] ModelBuilderTF2Test.test_session<br>[ RUN      ] ModelBuilderTF2Test.test_unknown_faster_rcnn_feature_extractor<br>[       OK ] ModelBuilderTF2Test.test_unknown_faster_rcnn_feature_extractor<br>[ RUN      ] ModelBuilderTF2Test.test_unknown_meta_architecture<br>[       OK ] ModelBuilderTF2Test.test_unknown_meta_architecture<br>[ RUN      ] ModelBuilderTF2Test.test_unknown_ssd_feature_extractor<br>[       OK ] ModelBuilderTF2Test.test_unknown_ssd_feature_extractor<br>----------------------------------------------------------------------<br>Ran 20 tests in 91.767s</pre><pre>OK (skipped=1)</pre><h3>To get data</h3><p>Before you can get started building your object detector, you need some data. If you already have a labelled data-set, you can skip this section and move directly to preparing your data for the Tensorflow OD API.</p><h3>Public data-sets</h3><p>If you’re more interested in the process of building and using a object detection model, it’s a good idea to make use of an already labelled public data-set.</p><ul><li><a href="https://gilberttanner.com/">Kaggle</a></li><li>github</li></ul><h3>Collect data</h3><p>If you want to create your own data-set, you first need to get some pictures. To train a robust model, the pictures should be as diverse as possible. So they should have different backgrounds,different viewing angle,varying lighting conditions, and unrelated random objects in them .</p><p>You can either take pictures yourself, or you can download pictures from the internet. For my helmet detector, I am using kaggle dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*iI2SEQCisX6fIvBj8jfSFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*8aCJXAyUQpKEAiJEussoxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*7JwefaVE7QTPZdNN1u0-Mw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Kf4Ct-8d0wnsNslz7ZQpbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*CJ-nOnjSK2HIwdClkDN-CA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*6oGoT_rkWMGcdmnNDyoRPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*cE8DhPzxiJwLrGppmUErjA.png" /></figure><p>After that you have all the images, move about 90% to the object_detection/images/train directory and the other 10% to the object_detection/images/test directory. Make sure that the images in both directories have a good variety of classes.</p><h3>Label data</h3><p>If you are using your own dataset you need to label the images. There are many free, open-source labeling tools that can help you with that.</p><p>To get started, I recommend using <a href="https://github.com/tzutalin/labelImg">LabelImg</a> as it can be easily downloaded and used, but there are many other great tools, including <a href="http://www.robots.ox.ac.uk/~vgg/software/via/">VGG Image Annotation Tool</a> and <a href="https://github.com/microsoft/VoTT">VoTT (Visual Object Tagging Tool)</a>.</p><h3>Prepare data for the Object Detection API</h3><p>With the data labelled, it’s time to convert it to a format the Tensorflow can use. The API works with files in the <a href="https://www.tensorflow.org/tutorials/load_data/tfrecord">TFRecod format</a>, a simple format for storing a sequence of binary records.</p><p>The process of converting your data to the TFRecord format will vary for different label formats. In this article, I’ll show you how to work with Pascal VOC format, the format LabelImg produces. You can find files to convert other data formats inside the <a href="https://github.com/tensorflow/models/tree/master/research/object_detection/dataset_tools">object_detection/dataset_tools directory</a>.</p><p>For the Pascal VOC format, first convert all the xml files into a single csv file using the <a href="https://github.com/TannerGilbert/Tensorflow-Object-Detection-API-Train-Model/blob/master/xml_to_csv.py">xml_to_csv.py</a> file from my Github.</p><pre>python xml_to_csv.py</pre><p>Next, download and open the <a href="https://github.com/TannerGilbert/Tensorflow-Object-Detection-API-Train-Model/blob/master/generate_tfrecord.py">generate_tfrecord.py</a> file and replace the labelmap inside the class_text_to_int method with your own label map.</p><p>For my data-set, the class_text_to_int method looks as follows:</p><pre>def class_text_to_int(row_label):<br>    if row_label == &#39;With Helmet&#39;:<br>        return 1<br>    elif row_label == &#39;Without Helmet&#39;:<br>        return 2<br>    else:<br>        return None</pre><p>Now the TFRecords can be generated by typing:</p><pre>python generate_tfrecord.py --csv_input=images/train_labels.csv --image_dir=images/train --output_path=train.record<br>python generate_tfrecord.py --csv_input=images/test_labels.csv --image_dir=images/test --output_path=test.record</pre><p>After executing the above commands, you should have a train.record and test.record file inside the object_detection folder.</p><h3>Configure training</h3><p>The last thing you need to do before training is to create a label map and a training configuration file.</p><h3>Labelmap</h3><p>The label map maps an id to a name. The labelmap for my detector can be seen below.</p><pre>item {<br>    id: 1<br>    name: &#39;With Helmet&#39;<br>}<br>item {<br>    id: 2<br>    name: &#39;Without Helmet&#39;<br>}</pre><p>The mapping from id to name should be the same as in the generate_tfrecord.py file.</p><h3>Training configuration</h3><p>Next, you need to create a training configuration file based on your model of choice.</p><p>In this article, I will use mobilenetv2_fnite— a recent family of SOTA models discovered with the help of Neural Architecture Search. You can find a list of all available models for Tensorflow 2 in the <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md">TensorFlow 2 Object Detection model zoo</a>.</p><p>The <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/configs/tf2/ssd_efficientdet_d0_512x512_coco17_tpu-8.config">base </a>for the model can be found inside the <a href="https://github.com/tensorflow/models/tree/master/research/object_detection/configs/tf2">configs/tf2 folder</a> in model github repo. It needs to be changed to point to the custom data and pretrained weights. Some training parameters also need to be changed.</p><p>The changes look as follows:</p><ul><li>Change the number of classes to number of objects you want to detect (4 in my case)</li><li>Change fine_tune_checkpoint to the path of the model.ckpt file.</li></ul><pre>fine_tune_checkpoint: &quot;&lt;path&gt;/<a href="http://download.tensorflow.org/models/object_detection/tf2/20200711/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8.tar.gz">SSD MobileNet V2 FPNLite 320x320</a>/checkpoint/ckpt-0&quot;</pre><ul><li>Change fine_tune_checkpoint_type to detection</li><li>Change input_path of the train_input_reader to the path of the train.record file:</li></ul><pre>input_path: &quot;&lt;path&gt;/train.record&quot;</pre><ul><li>Change input_path of the eval_input_reader to the path of the test.record file:</li></ul><pre>input_path: &quot;&lt;path&gt;/test.record&quot;</pre><ul><li>Change label_map_path to the path of the label map:</li></ul><pre>label_map_path: &quot;&lt;path&gt;/label_map.pbtxt&quot;</pre><ul><li>Change batch_size to a number appropriate for your hardware, like 4, 8, or 16.</li></ul><h3>Train model</h3><p>To train the model, execute the following command in the command line:</p><pre>python model_main_tf2.py \<br>    --pipeline_config_path=training/ssd_efficientdet_d0_512x512_coco17_tpu-8.config \<br>    --model_dir=training \<br>    --alsologtostderr</pre><p>If everything was setup correctly, the training should begin shortly, and you should see something like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYRaRtjJBE2wB1Lp2aJSnQ.png" /></figure><p>Every few minutes, the current state gets logged to Tensorboard. Open Tensorboard by opening a second command line, navigating to the object_detection folder and typing:</p><pre>tensorboard --logdir=training/train</pre><p>This will open a webpage at localhost:6006.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*2cXqAJAZhvFt3lOs5g-7-w.png" /></figure><p>The training script saves checkpoints every few minutes. Train the model until it reaches a satisfying loss, then you can terminate the training process by pressing Ctrl+C.</p><h3>Export inference graph</h3><p>To make it easier to use and deploy your model, I recommend converting it to a frozen graph file. This can be done using the exporter_main_v2.py script.</p><pre>python exporter_main_v2.py \<br>    --trained_checkpoint_dir=training \<br>    --pipeline_config_path=training/ssd<a href="http://download.tensorflow.org/models/object_detection/tf2/20200711/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8.tar.gz"> MobileNet V2 FPNLite</a>_tpu-8.config \<br>    --output_directory inference_graph</pre><h3>Test model</h3><p>Now that you have trained your model and exported it to an inference graph, you can use it for inference. You can find an inference example at the end of the training with the help of open cv</p><p>Figure : Predictions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*lffbdY1aHP4OCNkNlUb3DQ.jpeg" /></figure><h3>Resources</h3><ul><li><a href="https://github.com/tensorflow/models/tree/master/research/object_detection">Tensorflow Object Detection API Repository</a></li><li><a href="https://github.com/tensorflow/models/tree/master/research/object_detection/g3doc">Tensorflow Object Detection API Documentation</a></li><li><a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md">Model Zoo</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61593a67a02d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Reinforcement Learning]]></title>
            <link>https://whoisslimshady.medium.com/introduction-to-reinforcement-learning-8ea35f30dec3?source=rss-3c0cd74a4676------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ea35f30dec3</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[deep-q-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[whoisslimshady]]></dc:creator>
            <pubDate>Sat, 12 Jun 2021 17:59:21 GMT</pubDate>
            <atom:updated>2021-06-12T17:59:21.536Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GsnmCgGsPyQMVLFEsvMHYw.jpeg" /></figure><p>This article will covers <em>Reinforcement Learning</em>. This technique is different than many of the other machine learning techniques we have and has many applications in training agents (an AI) to interact with environments like games. Rather than feeding our machine learning model millions of examples we let our model come up with its own examples by exploring an environemt.</p><p>The concept is simple. Humans learn by exploring and learning from mistakes and past experiences so let’s have our computer do the same.</p><h3>Terminology</h3><p>Before we dive into explaining reinforcement learning we need to define a few key pieces of terminology.</p><p><strong>Environment</strong> In reinforcement learning tasks we have a notion of the environment. This is what our <em>agent</em> will explore. An example of an environment in the case of training an AI to play say a game of mario would be the level we are training the agent on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zKvQWW05zfSaCfSEHviayA.png" /></figure><p><strong>Agent</strong> an agent is an entity that is exploring the environment. Our agent will interact and take different actions within the environment. In our mario example the mario character within the game would be our agent.</p><p><strong>State</strong> always our agent will be in what we call a <em>state</em>. The state simply tells us about the status of the agent. The most common example of a state is the location of the agent within the environment. Moving locations would change the agents state.</p><p><strong>Action</strong> any interaction between the agent and environment would be considered an action. For example, moving to the left or jumping would be an action. An action may or may not change the current <em>state</em> of the agent. In fact, the act of doing nothing is an action as well! The action of say not pressing a key if we are using our mario example.</p><p><strong>Reward</strong> every action that our agent takes will result in a reward of some magnitude (positive or negative). The goal of our agent will be to maximize its reward in an environment. Sometimes the reward will be clear, for example if an agent performs an action which increases their score in the environment we could say they’ve recieved a positive reward. If the agent were to perform an action which results in them losing score or possibly dying in the environment then they would <strong>receive </strong>a negative reward.</p><p>The most important part of reinforcement learning is determining how to reward the agent. After all, the goal of the agent is to maximize its rewards. This means we should reward the agent appropriately such that it reaches the desired goal.</p><h3>Q-Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nbRc5xTpCvRFIJJ9Na317Q.png" /></figure><p>Now that we have a vague idea of how reinforcement learning works it’s time to talk about a specific technique in reinforcement learning called <em>Q-Learning</em>.</p><p>Q-Learning is a simple yet quite powerful technique in machine learning that involves learning a matrix of action-reward values. This matrix is often referred to as a Q-Table or Q-Matrix. The matrix is in shape (number of possible states, number of possible actions) where each value at matrix[n, m] represents the agents expected reward given they are in state n and take action m. The Q-learning algorithm defines the way we update the values in the matrix and decide what action to take at each state. The idea is that after a <strong>successful </strong>training/learning of this Q-Table/matrix we can determine the action an agent should take in any state by looking at that states row in the matrix and taking the maximum value column as the action.</p><p><strong>Consider this example.</strong></p><p>Let’s say A1-A4 are the possible actions and we have 3 states represented by each row (state 1 — state 3).</p><pre>A1  A2  A3  A4</pre><pre> 0   0   10  5<br> 5  10    0  0<br>10   5    0  0</pre><p>If that was our Q-Table/matrix then the following would be the prefer actions in each state.</p><blockquote><em>State 1: A3</em></blockquote><blockquote><em>State 2: A2</em></blockquote><blockquote><em>State 3: A1</em></blockquote><p>We can see that this is because the values in each of those columns are the highest for those states!</p><h3>Learning the Q-Table</h3><p>So that’s simple, right? Now how do we create this table and find those values. Well this is where we will discuss how the Q-Learning algorithm updates the values in our Q-Table.</p><p>I’ll start by noting that our Q-Table starts of with all 0 values. This is because the agent has yet to learn anything about the environment.</p><p>Our agent learns by exploring the enviornment and observing the outcome/reward from each action it takes in each state. But how does it know what action to take in each state? There are two ways that our agent can decide on which action to take.</p><ul><li>Randomly picking a valid action</li><li>Using the current Q-Table to find the best action.</li></ul><p>Near the beginning of our agents learning it will mostly take random actions in order to explore the environment and enter many different states. As it starts to explore more of the environment it will start to gradually rely more on it’s learned values (Q-Table) to take actions. This means that as our agent explores more of the environment it will develop a better understanding and start to take “correct” or better actions more often. It’s important that the agent has a good balance of taking random actions and using learned values to ensure it does get trapped in a local maximum.</p><p>After each new action our agent wil record the new state (if any) that it has entered and the reward that it recieved from taking that action. These values will be used to update the Q-Table. The agent will stop taking new actions only once a certain time limit is reached or it has acheived the goal or reached the end of the enviornment.</p><h4>Updating Q-Values</h4><p>The formula for updating the Q-Table after each action is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*EjMS1I8P3kYa7pTkp8Ug0Q.png" /></figure><ul><li>α stands for the <strong>Learning Rate</strong></li><li>γ stands for the <strong>Discount Factor</strong></li></ul><h4>Learning Rate α</h4><p>The learning rate α is a numeric constant that defines how much change is permitted on each QTable update. A high learning rate means that each update will introduce a large change to the current state-action value. A small learning rate means that each update has a more subtle change. Modifying the learning rate will change how the agent explores the environment and how quickly it determines the final values in the QTable.</p><h4>Discount Factor γ</h4><p>Discount factor also know as gamma (γ) is used to balance how much focus is put on the current and future reward. A high discount factor means that future rewards will be considered more heavily.</p><p>To perform updates on this table we will let the agent explpore the enviornment for a certain period of time and use each of its actions to make an update. Slowly we should start to notice the agent learning and choosing better actions.</p><h3>Q-Learning Example</h3><p>For this example we will use the Q-Learning algorithm to train an agent to navigate a popular enviornment from the <a href="https://gym.openai.com/">Open AI Gym</a>. The Open AI Gym was developed so programmers could practice machine learning using unique enviornments. Intersting fact, Elon Musk is one of the founders of OpenAI!</p><p>Let’s start by looking at what Open AI Gym is.</p><pre>import gym # all you have to do to import and use open ai gym!</pre><p>Once you import gym you can load an environmentusing the line</p><pre>gym.make(&quot;environment&quot;).</pre><pre>env = gym.make(‘FrozenLake-v0’) # we are going to use the FrozenLake enviornment</pre><p>There are a few other commands that can be used to interact and get information about the environment.</p><pre>print(env.observation_space.n) # get number of states</pre><pre>print(env.action_space.n) # get number of actions</pre><pre><br>env.reset() # reset enviornment to default state</pre><pre>action = env.action_space.sample() # get a random action</pre><pre>new_state, reward, done, info = env.step(action) # take action, notice it returns information about the action</pre><pre>env.render() # render the GUI for the environment</pre><h3>Frozen Lake Environment</h3><p>Now that we have a basic understanding of how the gym environment works it’s time to discuss the specific problem we will be solving.</p><p>The environment we loaded above FrozenLake-v0 is one of the simplest environment in Open AI Gym. The goal of the agent is to navigate a frozen lake and find the Goal without falling through the ice (render the environment above to see an example).</p><p>There are:</p><ul><li>16 states (one for each square)</li><li>4 possible actions (LEFT, RIGHT, DOWN, UP)</li><li>4 different types of blocks (F: frozen, H: hole, S: start, G: goal)</li></ul><h3>Building the Q-Table</h3><p>The first thing we need to do is build an empty Q-Table that we can use to store and update our values.</p><pre>import gym</pre><pre>import numpy as np</pre><pre>import time</pre><pre>env = gym.make(‘FrozenLake-v0’)</pre><pre>STATES = env.observation_space.n</pre><pre>ACTIONS = env.action_space.n</pre><pre>Q = np.zeros((STATES, ACTIONS)) # create a matrix with all 0 values Q</pre><h3>Constants</h3><p>As we discussed we need to define some constants that will be used to update our Q-Table and tell our agent when to stop training.</p><pre>EPISODES = 2000 # how many times to run the environment from the beginning</pre><pre>MAX_STEPS = 100 # max number of steps allowed for each run of enviornment</pre><pre>LEARNING_RATE = 0.81 # learning rate</pre><pre>GAMMA = 0.96</pre><h3>Picking an Action</h3><p>Remember that we can pick an action using one of two methods:</p><ul><li>Randomly picking a valid action</li><li>Using the current Q-Table to find the best action.</li></ul><p>Here we will define a new value ϵ that will tell us the probabillity of selecting a random action. This value will start off very high and slowly decrease as the agent learns more about the environment.</p><pre>epsilon = 0.9 # start with a 90% chance of picking a random action</pre><p>code to pick action</p><pre>if np.random.uniform(0, 1) &lt; epsilon: # we will check if a randomly selected value is less than epsilon.</pre><pre>action = env.action_space.sample() # take random action</pre><pre>else:</pre><pre>action = np.argmax(Q[state, :]) # use Q table to pick best action based on current values</pre><h3>Updating Q Values</h3><p>The code below implements the formula discussed above.</p><pre>Q[state, action] = Q[state, action] + LEARNING_RATE * (reward + GAMMA * np.max(Q[new_state, :]) — Q[state, action])</pre><h3>Putting it Together</h3><p>Now that we know how to do some basic things we can combine these together to create our Q-Learning algorithm,</p><pre>import gym</pre><pre>import numpy as np</pre><pre>import time</pre><pre>env = gym.make(‘FrozenLake-v0’)</pre><pre>STATES = env.observation_space.n</pre><pre>ACTIONS = env.action_space.n</pre><pre>Q = np.zeros((STATES, ACTIONS))</pre><pre>EPISODES = 1500 # how many times to run the enviornment from the beginning</pre><pre>MAX_STEPS = 100 # max number of steps allowed for each run of enviornment</pre><pre>LEARNING_RATE = 0.81 # learning rate</pre><pre>GAMMA = 0.96</pre><pre>RENDER = False # if you want to see training set to true</pre><pre>epsilon = 0.9</pre><pre>[ ]</pre><pre>rewards = []</pre><pre>for episode in range(EPISODES):</pre><pre>state = env.reset()</pre><pre>for _ in range(MAX_STEPS):</pre><pre>if RENDER:</pre><pre>env.render()</pre><pre>if np.random.uniform(0, 1) &lt; epsilon:</pre><pre>action = env.action_space.sample()</pre><pre>else:</pre><pre>action = np.argmax(Q[state, :])</pre><pre>next_state, reward, done, _ = env.step(action)</pre><pre>Q[state, action] = Q[state, action] + LEARNING_RATE * (reward + GAMMA * np.max(Q[next_state, :]) — Q[state, action])</pre><pre>state = next_state</pre><pre>if done:</pre><pre>rewards.append(reward)</pre><pre>epsilon -= 0.001</pre><pre>break # reached goal</pre><pre>print(Q)</pre><pre>print(f”Average reward: {sum(rewards)/len(rewards)}:”)</pre><pre># and now we can see our Q values!</pre><pre>[ ]</pre><pre># we can plot the training progress and see how the agent improved</pre><pre>import matplotlib.pyplot as plt</pre><pre>def get_average(values):</pre><pre>return sum(values)/len(values)</pre><pre>avg_rewards = []</pre><pre>for i in range(0, len(rewards), 100):</pre><pre>avg_rewards.append(get_average(rewards[i:i+100]))</pre><pre>plt.plot(avg_rewards)</pre><pre>plt.ylabel(‘average reward’)</pre><pre>plt.xlabel(‘episodes (100\’s)’)</pre><pre>plt.show()</pre><p>well we can do more than this like implementing Ai in some classic games like flappy bird and mario and others but that’s too much for the blog but if you are interested you can checkout the github repo to play with the code</p><h3>Sources</h3><ul><li>Openai. “Openai/Gym.” GitHub, <a href="https://github.com/openai/gym/wiki/FrozenLake-v0">https://github.com/openai/gym/wiki/FrozenLake-v0</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ea35f30dec3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brief Overview of Natural Language Processing with tensorflow2.0]]></title>
            <link>https://medium.com/geekculture/natural-language-processing-ed48334f80be?source=rss-3c0cd74a4676------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed48334f80be</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[whoisslimshady]]></dc:creator>
            <pubDate>Mon, 31 May 2021 12:58:15 GMT</pubDate>
            <atom:updated>2021-05-31T14:12:09.434Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UsFIEny149WPIRqNaR2MaQ.jpeg" /></figure><p>Natural Language Processing (or NLP for short) is a discipline in computing that deals with the communication between natural (human) languages and computer languages. A common example of NLP is something like spellcheck or autocomplete. Essentially NLP is the field that focuses on how computers can understand and/or process natural/human languages.</p><h3>Recurrent Neural Networks</h3><p>In this tutorial we will introduce a new kind of neural network that is much more capable of processing sequential data such as text or characters called a <strong>recurrent neural network</strong> (RNN for short).</p><p>We will learn how to use a reccurent neural network to do the following:</p><ul><li>Sentiment Analysis</li><li>Character Generation</li></ul><p>RNN’s are complex and come in many different forms so in this tutorial we wil focus on how they work and the kind of problems they are best suited for.</p><h3>Sequence Data</h3><p>In the previous blog we focused on data that we could represent as one static data point where the notion of time or step was irrelevant. Take for example our image data, it was simply a tensor of shape (width, height, channels). That data doesn’t change or care about the notion of time.</p><p>In this blog we will look at sequences of text and learn how we can encode them in a meaningful way. Unlike images, sequence data such as long chains of text, weather patterns, videos and really anything where the notion of a step or time is relevant needs to be processed and handled in a special way.</p><p>But what do I mean by sequences and why is text data a sequence? Well that’s a good question. Since textual data contains many words that follow in a very specific and meaningful order, we need to be able to keep track of each word and when it occurs in the data. Simply encoding say an entire paragraph of text into one data point wouldn’t give us a very meaningful picture of the data and would be very difficult to do anything with. This is why we treat text as a sequence and process one word at a time. We will keep track of where each of these words appear and use that information to try to understand the meaning of pieces of text.</p><h3>Encoding Text</h3><p>As we know machine learning models and neural networks don’t take raw text data as an input. This means we must somehow encode our textual data to numeric values that our models can understand. There are many different ways of doing this and we will look at a few examples below.</p><p>Before we get into the different encoding/preprocessing methods let’s understand the information we can get from textual data by looking at the following two movie reviews.</p><p>I thought the movie was going to be bad, but it was actually amazing!</p><p>I thought the movie was going to be amazing, but it was actually bad!</p><p>Although these two setences are very similar we know that they have very different meanings. This is because of the <strong>ordering</strong> of words, a very important property of textual data.</p><p>Now keep that in mind while we consider some different ways of encoding our textual data.</p><h3>Bag of Words</h3><p>The first and simplest way to encode our data is to use something called <strong>bag of words</strong>. This is a pretty easy technique where each word in a sentence is encoded with an integer and thrown into a collection that does not maintain the order of the words but does keep track of the frequency. Have a look at the python function below that encodes a string of text into bag of words.</p><pre>vocab = {} # maps word to integer representing it</pre><pre>word_encoding = 1</pre><pre>def bag_of_words(text):</pre><pre>global word_encoding</pre><pre>words = text.lower().split(“ “) # create a list of all of the words in the text, well assume there is no grammar in our text for this example</pre><pre>bag = {} # stores all of the encodings and their frequency</pre><pre>for word in words:</pre><pre>if word in vocab:</pre><pre>encoding = vocab[word] # get encoding from vocab</pre><pre>else:</pre><pre>vocab[word] = word_encoding</pre><pre>encoding = word_encoding</pre><pre>word_encoding += 1</pre><pre>if encoding in bag:</pre><pre>bag[encoding] += 1</pre><pre>else:</pre><pre>bag[encoding] = 1</pre><pre>return bag</pre><pre>text = “this is a test to see if this test will work is is test a a”</pre><pre>bag = bag_of_words(text)</pre><pre>print(bag)</pre><pre>print(vocab)</pre><p>This isn’t really the way we would do this in practice, but I hope it gives you an idea of how bag of words works. Notice that we’ve lost the order in which words appear. In fact, let’s look at how this encoding works for the two sentences we showed above.</p><pre>positive_review = “I thought the movie was going to be bad but it was actually amazing”</pre><pre>negative_review = “I thought the movie was going to be amazing but it was actually bad”</pre><pre>pos_bag = bag_of_words(positive_review)</pre><pre>neg_bag = bag_of_words(negative_review)</pre><pre>print(“Positive:”, pos_bag)</pre><pre>print(“Negative:”, neg_bag)</pre><p>We can see that even though these sentences have a very different meaning they are encoded exaclty the same way. Obviously, this isn’t going to fly. Let’s look at some other methods.</p><h3>Integer Encoding</h3><p>The next technique we will look at is called <strong>integer encoding</strong>. This involves representing each word or character in a sentence as a unique integer and maintaining the order of these words. This should hopefully fix the problem we saw before were we lost the order of words.vocab = {}</p><pre>word_encoding = 1</pre><pre>def one_hot_encoding(text):</pre><pre>global word_encoding</pre><pre>words = text.lower().split(“ “)</pre><pre>encoding = []</pre><pre>for word in words:</pre><pre>if word in vocab:</pre><pre>code = vocab[word]</pre><pre>encoding.append(code)</pre><pre>else:</pre><pre>vocab[word] = word_encoding</pre><pre>encoding.append(word_encoding)</pre><pre>word_encoding += 1</pre><pre>return encoding</pre><pre>text = “this is a test to see if this test will work is is test a a”</pre><pre>encoding = one_hot_encoding(text)</pre><pre>print(encoding)</pre><pre>print(vocab)</pre><pre>And now let’s have a look at one hot encoding on our movie reviews.</pre><pre>positive_review = “I thought the movie was going to be bad but it was actually amazing”</pre><pre>negative_review = “I thought the movie was going to be amazing but it was actually bad”</pre><pre>pos_encode = one_hot_encoding(positive_review)</pre><pre>neg_encode = one_hot_encoding(negative_review)</pre><pre>print(“Positive:”, pos_encode)</pre><pre>print(“Negative:”, neg_encode)</pre><p>Much better, now we are keeping track of the order of words and we can tell where each occurs. But this still has a few issues with it. Ideally when we encode words, we would like similar words to have similar labels and different words to have very different labels. For example, the words happy and joyful should probably have very similar labels so we can determine that they are similar. While words like horrible and amazing should probably have very different labels. The method we looked at above won’t be able to do something like this for us. This could mean that the model will have a very difficult time determing if two words are similar or not which could result in some pretty drastic performace impacts.</p><h3>Word Embeddings</h3><p>Luckily there is a third method that is far superior, <strong>word embeddings</strong>. This method keeps the order of words intact as well as encodes similar words with very similar labels. It attempts to not only encode the frequency and order of words but the meaning of those words in the sentence. It encodes each word as a dense vector that represents its context in the sentence.</p><p>Unlike the previous techniques word embeddings are learned by looking at many different training examples. You can add what’s called an <em>embedding layer</em> to the beggining of your model and while your model trains your embedding layer will learn the correct embeddings for words. You can also use pretrained embedding layers.</p><p>This is the technique we will use for our examples and its implementation will be showed later on.</p><h3>Recurrent Neural Networks (RNN’s)</h3><p>Now that we’ve learned a little bit about how we can encode text it’s time to dive into recurrent neural networks. Up until this point we have been using something called <strong>feed-forward</strong> neural networks. This simply means that all our data is fed forwards (all at once) from left to right through the network. This was fine for the problems we considered before but won’t work very well for processing text. After all, even we (humans) don’t process text all at once. We read word by word from left to right and keep track of the current meaning of the sentence so we can understand the meaning of the next word. Well this is exaclty what a recurrent neural network is designed to do. When we say recurrent neural network all we really mean is a network that contains a loop. A RNN will process one word at a time while maintaining an internal memory of what it’s already seen. This will allow it to treat words differently based on their order in a sentence and to slowly build an understanding of the entire input, one word at a time.</p><p>This is why we are treating our text data as a sequence! So that we can pass one word at a time to the RNN.</p><p>Let’s have a look at what a recurrent layer might look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E4AGtlEFD2GSCKjV.png" /></figure><p><em>Source: </em><a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/"><em>https://colah.github.io/posts/2015-08-Understanding-LSTMs/</em></a></p><p>Let’s define what all these variables stand for before we get into the explination.</p><p><strong>ht</strong> output at time t</p><p><strong>xt</strong> input at time t</p><p><strong>A</strong> Recurrent Layer (loop)</p><p>What this diagram is trying to illustrate is that a recurrent layer processes words or input one at a time in a combination with the output from the previous iteration. So, as we progress further in the input sequence, we build a more complex understanding of the text as a whole.</p><p>What we’ve just looked at is called a <strong>simple RNN layer</strong>. It can be effective at processing shorter sequences of text for simple problems but has many downfalls associated with it. One of them being the fact that as text sequences get longer it gets increasingly difficult for the network to understand the text properly.</p><h3>LSTM</h3><p>The layer we dicussed in depth above was called a <em>simpleRNN</em>. However, there does exist some other recurrent layers (layers that contain a loop) that work much better than a simple RNN layer. The one we will talk about here is called LSTM (Long Short-Term Memory). This layer works very similarily to the simpleRNN layer but adds a way to access inputs from any timestep in the past. Whereas in our simple RNN layer input from previous timestamps gradually disappeared as we got further through the input. With a LSTM we have a long-term memory data structure storing all the previously seen inputs as well as when we saw them. This allows for us to access any previous value we want at any point in time. This adds to the complexity of our network and allows it to discover more useful relationships between inputs and when they appear.</p><p>For the purpose of this course we will refrain from going any further into the math or details behind how these layers work.</p><h3>LSTM</h3><p>And now time to see a recurrent neural network in action. For this example, we are going to do something called sentiment analysis.</p><p>The formal definition of this term from Wikipedia is as follows:</p><p><em>the process of computationally identifying and categorizing opinions expressed in a piece of text, especially in order to determine whether the writer’s attitude towards a particular topic, product, etc. is positive, negative, or neutral.</em></p><p>The example we’ll use here is classifying movie reviews as either postive, negative or neutral.</p><p><em>This guide is based on the following tensorflow tutorial: </em><a href="https://www.tensorflow.org/tutorials/text/text_classification_rnn"><em>https://www.tensorflow.org/tutorials/text/text_classification_rnn</em></a></p><h3>Sentiment Analysis</h3><p>Well start by loading in the IMDB movie review dataset from keras. This dataset contains 25,000 reviews from IMDB where each one is already preprocessed and has a label as either positive or negative. Each review is encoded by integers that represents how common a word is in the entire dataset. For example, a word encoded by the integer 3 means that it is the 3rd most common word in the dataset.</p><pre>%tensorflow_version 2.x # this line is not required unless you are in a notebook</pre><pre>from keras.datasets import imdb</pre><pre>from keras.preprocessing import sequence</pre><pre>import keras</pre><pre>import tensorflow as tf</pre><pre>import os</pre><pre>import numpy as np</pre><pre>VOCAB_SIZE = 88584</pre><pre>MAXLEN = 250</pre><pre>BATCH_SIZE = 64</pre><pre>(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words = VOCAB_SIZE)</pre><pre>[ ]</pre><pre># Lets look at one review</pre><pre>train_data[1]</pre><h3>More Preprocessing</h3><p>If we have a look at some of our loaded in reviews, we’ll notice that they are different lengths. This is an issue. We cannot pass different length data into our neural network. Therefore, we must make each review the same length. To do this we will follow the procedure below:</p><ul><li>if the review is greater than 250 words then trim off the extra words</li><li>if the review is less than 250 words add the necessary amount of 0’s to make it equal to 250.</li></ul><p>Luckily for us keras has a function that can do this for us:</p><pre>train_data = sequence.pad_sequences(train_data, MAXLEN)</pre><pre>test_data = sequence.pad_sequences(test_data, MAXLEN)</pre><h3>Creating the Model</h3><p>Now it’s time to create the model. We’ll use a word embedding layer as the first layer in our model and add a LSTM layer afterwards that feeds into a dense node to get our predicted sentiment.</p><p>32 stands for the output dimension of the vectors generated by the embedding layer. We can change this value if we’d like!</p><pre>model = tf.keras.Sequential([</pre><pre>tf.keras.layers.Embedding(VOCAB_SIZE, 32),</pre><pre>tf.keras.layers.LSTM(32),</pre><pre>tf.keras.layers.Dense(1, activation=”sigmoid”)</pre><pre>])</pre><pre>model.summary()</pre><h3>Training</h3><p>Now it’s time to compile and train the model.</p><pre>model.compile(loss=”binary_crossentropy”,optimizer=”rmsprop”,metrics=[‘acc’])</pre><pre>history = model.fit(train_data, train_labels, epochs=10, validation_split=0.2)</pre><p>And we’ll evaluate the model on our training data to see how well it performs.</p><pre>results = model.evaluate(test_data, test_labels)</pre><pre>print(results)</pre><p>So we’re scoring somewhere in the mid-high 80’s. Not bad for a simple recurrent network.</p><h3>Making Predictions</h3><p>Now let’s use our network to make predictions on our own reviews.</p><p>Since our reviews are encoded well need to convert any review that we write into that form so the network can understand it. To do that well load the encodings from the dataset and use them to encode our own data.</p><pre>word_index = imdb.get_word_index()</pre><pre>def encode_text(text):</pre><pre>tokens = keras.preprocessing.text.text_to_word_sequence(text)</pre><pre>tokens = [word_index[word] if word in word_index else 0 for word in tokens]</pre><pre>return sequence.pad_sequences([tokens], MAXLEN)[0]</pre><pre>text = “that movie was just amazing, so amazing”</pre><pre>encoded = encode_text(text)</pre><pre>print(encoded)</pre><p>while were at it lets make a decode function</p><pre>reverse_word_index = {value: key for (key, value) in word_index.items()}</pre><pre>def decode_integers(integers):</pre><pre>PAD = 0</pre><pre>text = “”</pre><pre>for num in integers:</pre><pre>if num != PAD:</pre><pre>text += reverse_word_index[num] + “ “</pre><pre>return text[:-1]</pre><pre>print(decode_integers(encoded))</pre><p>now time to make a prediction</p><pre>def predict(text):</pre><pre>encoded_text = encode_text(text)</pre><pre>pred = np.zeros((1,250))</pre><pre>pred[0] = encoded_text</pre><pre>result = model.predict(pred)</pre><pre>print(result[0])</pre><pre>positive_review = “That movie was! really loved it and would great watch it again because it was amazingly great”</pre><pre>predict(positive_review)</pre><pre>negative_review = “that movie really sucked. I hated it and wouldn’t watch it again. Was one of the worst things I’ve ever watched”</pre><pre>predict(negative_review)</pre><h3>RNN Play Generator</h3><p>Now time for one of the coolest examples we’ve seen so far. We are going to use a RNN to generate a play. We will simply show the RNN an example of something we want it to recreate and it will learn how to write a version of it on its own. We’ll do this using a character predictive model that will take as input a variable length sequence and predict the next character. We can use the model many times in a row with the output from the last predicition as the input for the next call to generate a sequence.</p><p><em>This guide is based on the following: </em><a href="https://www.tensorflow.org/tutorials/text/text_generation"><em>https://www.tensorflow.org/tutorials/text/text_generation</em></a></p><pre>%tensorflow_version 2.x # this line is not required unless you are in a notebook</pre><pre>from keras.preprocessing import sequence</pre><pre>import keras</pre><pre>import tensorflow as tf</pre><pre>import os</pre><pre>import numpy as np</pre><h3>Dataset</h3><p>For this example, we only need one peice of training data. In fact, we can write our own poem or play and pass that to the network for training if we’d like. However, to make things easy we’ll use an extract from a shakesphere play.</p><pre>path_to_file = tf.keras.utils.get_file(‘shakespeare.txt’, ‘https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt&#39;)</pre><h3>Loading Your Own Data</h3><p>To load your own data, you’ll need to upload a file in google colab.Then you’ll need to follow the steps from above but load in this new file instead.</p><pre>from google.colab import files</pre><pre>path_to_file = list(files.upload().keys())[0]</pre><h3>Read Contents of File</h3><p>Let’s look at the contents of the file.</p><pre># Read, then decode for py2 compat.</pre><pre>text = open(path_to_file, ‘rb’).read().decode(encoding=’utf-8&#39;)</pre><pre># length of text is the number of characters in it</pre><pre>print (‘Length of text: {} characters’.format(len(text)))</pre><pre>[ ]</pre><pre># Take a look at the first 250 characters in text</pre><pre>print(text[:250])</pre><h3>Encoding</h3><p>Since this text isn’t encoded yet well need to do that ourselves. We are going to encode each unique character as a different integer.</p><pre>vocab = sorted(set(text))</pre><pre># Creating a mapping from unique characters to indices</pre><pre>char2idx = {u:i for i, u in enumerate(vocab)}</pre><pre>idx2char = np.array(vocab)</pre><pre>def text_to_int(text):</pre><pre>return np.array([char2idx[c] for c in text])</pre><pre>text_as_int = text_to_int(text)</pre><pre># lets look at how part of our text is encoded</pre><pre>print(“Text:”, text[:13])</pre><pre>print(“Encoded:”, text_to_int(text[:13]))</pre><p>And here we will make a function that can convert our numeric values to text.</p><pre>def int_to_text(ints):</pre><pre>try:</pre><pre>ints = ints.numpy()</pre><pre>except:</pre><pre>pass</pre><pre>return ‘’.join(idx2char[ints])</pre><pre>print(int_to_text(text_as_int[:13]))</pre><h3>Creating Training Examples</h3><p>Remember our task is to feed the model a sequence and have it return to us the next character. This means we need to split our text data from above into many shorter sequences that we can pass to the model as training examples.</p><p>The training examples we will prepapre will use a <em>seq_length</em> sequence as input and a <em>seq_length</em> sequence as the output where that sequence is the original sequence shifted one letter to the right. For example:</p><p>input: Hell | output: ello</p><p>Our first step will be to create a stream of characters from our text data.</p><pre>seq_length = 100 # length of sequence for a training example</pre><pre>examples_per_epoch = len(text)//(seq_length+1)</pre><pre># Create training examples / targets</pre><pre>char_dataset = tf.data.Dataset.from_tensor_slices(text_as_int)</pre><p>Next we can use the batch method to turn this stream of characters into batches of desired length.</p><pre>sequences = char_dataset.batch(seq_length+1, drop_remainder=True)</pre><p>Now we need to use these sequences of length 101 and split them into input and output.</p><pre>def split_input_target(chunk): # for the example: hello</pre><pre>input_text = chunk[:-1] # hell</pre><pre>target_text = chunk[1:] # ello</pre><pre>return input_text, target_text # hell, ello</pre><pre>dataset = sequences.map(split_input_target) # we use map to apply the above function to every entry</pre><pre>[ ]</pre><pre>for x, y in dataset.take(2):</pre><pre>print(“\n\nEXAMPLE\n”)</pre><pre>print(“INPUT”)</pre><pre>print(int_to_text(x))</pre><pre>print(“\nOUTPUT”)</pre><pre>print(int_to_text(y))</pre><p>Finally we need to make training batches.</p><pre>BATCH_SIZE = 64</pre><pre>VOCAB_SIZE = len(vocab) # vocab is number of unique characters</pre><pre>EMBEDDING_DIM = 256</pre><pre>RNN_UNITS = 1024</pre><pre># Buffer size to shuffle the dataset</pre><pre># (TF data is designed to work with possibly infinite sequences,</pre><pre># so it doesn’t attempt to shuffle the entire sequence in memory. Instead,</pre><pre># it maintains a buffer in which it shuffles elements).</pre><pre>BUFFER_SIZE = 10000</pre><pre>data = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True)</pre><h3>Building the Model</h3><p>Now it is time to build the model. We will use an embedding layer a LSTM and one dense layer that contains a node for each unique character in our training data. The dense layer will give us a probability distribution over all nodes.</p><pre>def build_model(vocab_size, embedding_dim, rnn_units, batch_size):</pre><pre>model = tf.keras.Sequential([</pre><pre>tf.keras.layers.Embedding(vocab_size, embedding_dim,</pre><pre>batch_input_shape=[batch_size, None]),</pre><pre>tf.keras.layers.LSTM(rnn_units,</pre><pre>return_sequences=True,</pre><pre>stateful=True,</pre><pre>recurrent_initializer=’glorot_uniform’),</pre><pre>tf.keras.layers.Dense(vocab_size)</pre><pre>])</pre><pre>return model</pre><pre>model = build_model(VOCAB_SIZE,EMBEDDING_DIM, RNN_UNITS, BATCH_SIZE)</pre><pre>model.summary()</pre><h3>Creating a Loss Function</h3><p>Now we are going to create our own loss function for this problem. This is because our model will output a (64, sequence_length, 65) shaped tensor that represents the probability distribution of each character at each timestep for every sequence in the batch.</p><p>However, before we do that let’s have a look at a sample input and the output from our untrained model. This is so we can understand what the model is giving us.</p><pre>for input_example_batch, target_example_batch in data.take(1):</pre><pre>example_batch_predictions = model(input_example_batch) # ask our model for a prediction on our first batch of training data (64 entries)</pre><pre>print(example_batch_predictions.shape, “# (batch_size, sequence_length, vocab_size)”) # print out the output shape</pre><pre># we can see that the predicition is an array of 64 arrays, one for each entry in the batch</pre><pre>print(len(example_batch_predictions))</pre><pre>print(example_batch_predictions)</pre><pre># lets examine one prediction</pre><pre>pred = example_batch_predictions[0]</pre><pre>print(len(pred))</pre><pre>print(pred)</pre><p>notice this is a 2d array of length 100, where each interior array is the prediction for the next character at each time step</p><pre># and finally well look at a prediction at the first timestep</pre><pre>time_pred = pred[0]</pre><pre>print(len(time_pred))</pre><pre>print(time_pred)</pre><pre># and of course its 65 values representing the probabillity of each character occuring next</pre><p>If we want to determine the predicted character we need to sample the output distribution (pick a value based on probabillity)</p><pre>sampled_indices = tf.random.categorical(pred, num_samples=1)</pre><p>now we can reshape that array and convert all the integers to numbers to see the actual characters</p><pre>sampled_indices = np.reshape(sampled_indices, (1, -1))[0]</pre><pre>predicted_chars = int_to_text(sampled_indices)</pre><pre>predicted_chars # and this is what the model predicted for training sequence 1</pre><p>So now we need to create a loss function that can compare that output to the expected output and give us some numeric value representing how close the two were.</p><pre>def loss(labels, logits):</pre><pre>return tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True)</pre><h3>Compiling the Model</h3><p>At this point we can think of our problem as a classification problem where the model predicts the probabillity of each unique letter coming next.</p><pre>model.compile(optimizer=’adam’, loss=loss)</pre><h3>Creating Checkpoints</h3><p>Now we are going to setup and configure our model to save checkpoinst as it trains. This will allow us to load our model from a checkpoint and continue training it.</p><pre># Directory where the checkpoints will be saved</pre><pre>checkpoint_dir = ‘./training_checkpoints’</pre><pre># Name of the checkpoint files</pre><pre>checkpoint_prefix = os.path.join(checkpoint_dir, “ckpt_{epoch}”)</pre><pre>checkpoint_callback=tf.keras.callbacks.ModelCheckpoint(</pre><pre>filepath=checkpoint_prefix,</pre><pre>save_weights_only=True)</pre><h3>Training</h3><p>Finally, we will start training the model.</p><p><strong>If this is taking a while go to Runtime &gt; Change Runtime Type and choose “GPU” under hardware accelerator.</strong></p><pre>history = model.fit(data, epochs=50, callbacks=[checkpoint_callback])</pre><h3>Loading the Model</h3><p>We’ll rebuild the model from a checkpoint using a batch_size of 1 so that we can feed one peice of text to the model and have it make a prediction.</p><pre>model = build_model(VOCAB_SIZE, EMBEDDING_DIM, RNN_UNITS, batch_size=1)</pre><p>Once the model is finished training, we can find the <strong>lastest checkpoint</strong> that stores the models weights using the following line.</p><pre>model.load_weights(tf.train.latest_checkpoint(checkpoint_dir))</pre><pre>model.build(tf.TensorShape([1, None]))</pre><p>We can load <strong>any checkpoint</strong> we want by specifying the exact file to load.</p><pre>checkpoint_num = 10</pre><pre>model.load_weights(tf.train.load_checkpoint(“./training_checkpoints/ckpt_” + str(checkpoint_num)))</pre><pre>model.build(tf.TensorShape([1, None]))</pre><h3>Generating Text</h3><p>Now we can use the lovely function provided by tensorflow to generate some text using any starting string we’d like.</p><pre>def generate_text(model, start_string):</pre><pre># Evaluation step (generating text using the learned model)</pre><pre># Number of characters to generate</pre><pre>num_generate = 800</pre><pre># Converting our start string to numbers (vectorizing)</pre><pre>input_eval = [char2idx[s] for s in start_string]</pre><pre>input_eval = tf.expand_dims(input_eval, 0)</pre><pre># Empty string to store our results</pre><pre>text_generated = []</pre><pre># Low temperatures results in more predictable text.</pre><pre># Higher temperatures results in more surprising text.</pre><pre># Experiment to find the best setting.</pre><pre>temperature = 1.0</pre><pre># Here batch size == 1</pre><pre>model.reset_states()</pre><pre>for i in range(num_generate):</pre><pre>predictions = model(input_eval)</pre><pre># remove the batch dimension</pre><pre>predictions = tf.squeeze(predictions, 0)</pre><pre># using a categorical distribution to predict the character returned by the model</pre><pre>predictions = predictions / temperature</pre><pre>predicted_id = tf.random.categorical(predictions, num_samples=1)[-1,0].numpy()</pre><pre># We pass the predicted character as the next input to the model</pre><pre># along with the previous hidden state</pre><pre>input_eval = tf.expand_dims([predicted_id], 0)</pre><pre>text_generated.append(idx2char[predicted_id])</pre><pre>return (start_string + ‘’.join(text_generated))</pre><pre>inp = input(“Type a starting string: “)</pre><pre>print(generate_text(model, inp))</pre><p><em>And</em> that’s pretty much it for this module! I highly reccomend messing with the model we just created and seeing what you can get it to do!</p><h3>Sources</h3><ul><li>Chollet François. Deep Learning with Python. Manning Publications Co., 2018.</li><li>“Text Classification with an RNN : TensorFlow Core.” TensorFlow, <a href="http://www.tensorflow.org/tutorials/text/text_classification_rnn">www.tensorflow.org/tutorials/text/text_classification_rnn</a>.</li><li>“Text Generation with an RNN : TensorFlow Core.” TensorFlow, <a href="http://www.tensorflow.org/tutorials/text/text_generation">www.tensorflow.org/tutorials/text/text_generation</a>.</li><li>“Understanding LSTM Networks.” Understanding LSTM Networks — Colah’s Blog, <a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">https://colah.github.io/posts/2015-08-Understanding-LSTMs/</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed48334f80be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/natural-language-processing-ed48334f80be">Brief Overview of Natural Language Processing with tensorflow2.0</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</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 Deep Convolutional GAN’s Using Tensorflow and Keras]]></title>
            <link>https://medium.com/geekculture/introduction-to-deep-convolutional-gans-using-tensorflow-and-keras-3af58f5b2696?source=rss-3c0cd74a4676------2</link>
            <guid isPermaLink="false">https://medium.com/p/3af58f5b2696</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[whoisslimshady]]></dc:creator>
            <pubDate>Sun, 11 Apr 2021 12:11:33 GMT</pubDate>
            <atom:updated>2021-04-12T03:57:42.635Z</atom:updated>
            <content:encoded><![CDATA[<p>This tutorial demonstrates how to generate images of handwritten digits using a <a href="https://arxiv.org/pdf/1511.06434.pdf">Deep Convolutional Generative Adversarial Network</a> (DCGAN). The code is written using the <a href="https://www.tensorflow.org/guide/keras">Keras Sequential API</a> with a <a href="https://www.tensorflow.org/api_docs/python/tf/GradientTape">tf.GradientTape</a> training loop.</p><h3>What are GANs?</h3><p><a href="https://arxiv.org/abs/1406.2661">Generative Adversarial Networks</a> (GANs) are one of the most interesting ideas in computer science today. Two models are trained simultaneously by an adversarial process. A <em>generator</em> (“the artist”) learns to create images that look real, while a <em>discriminator</em> (“the art critic”) learns to tell real images apart from fakes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5YXn4KgSoBPCpMXZRfPmqg.png" /></figure><p>During training, the <em>generator</em> progressively becomes better at creating images that look real, while the <em>discriminator</em> becomes better at telling them apart. The process reaches equilibrium when the <em>discriminator</em> can no longer distinguish real images from fakes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0DPjyVo0i8hx78kpAadJAA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-PbIK0qLvGGCFnO7v8E7mQ.jpeg" /></figure><p>The best analogy is to imagine genrator as a artist who just started and don’t know what he is doing and discriminator as a art critic who also stared his job both try to win on each other and also learn from each other.</p><p>This tutorial demonstrates this process on the MNIST dataset. The following animation shows a series of images produced by the <em>generator</em> as it was trained for 50 epochs. The images begin as random noise, and increasingly resemble hand written digits over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/0*2TeoH9APyhnjSIEJ.gif" /></figure><p>what i told you is just tip of the iceberg is what Generative Adversarial Networks</p><h3>Setup</h3><pre>import tensorflow as tf</pre><pre>tf.__version__<br>&#39;2.4.1&#39;</pre><pre># To generate GIFs<br>pip install -q imageio<br>pip install -q git+https://github.com/tensorflow/docs</pre><pre>import glob<br>import imageio<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import os<br>import PIL<br>from tensorflow.keras import layers<br>import time</pre><pre>from IPython import display</pre><h3>Load and prepare the dataset</h3><p>You will use the MNIST dataset to train the generator and the discriminator. The generator will generate handwritten digits resembling the MNIST data.</p><pre>(train_images, train_labels), (_, _) = tf.keras.datasets.mnist.load_data()</pre><pre>Downloading data from <a href="https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz">https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz</a><br>11493376/11490434 [==============================] - 0s 0us/step</pre><pre>train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype(&#39;float32&#39;)<br>train_images = (train_images - 127.5) / 127.5  # Normalize the images to [-1, 1]</pre><pre>BUFFER_SIZE = 60000<br>BATCH_SIZE = 256</pre><pre># Batch and shuffle the data<br>train_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)</pre><h3>Create the models</h3><p>Both the generator and discriminator are defined using the <a href="https://www.tensorflow.org/guide/keras#sequential_model">Keras Sequential API</a>.</p><h3>The Generator</h3><p>The generator uses <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2DTranspose">tf.keras.layers.Conv2DTranspose</a> (upsampling) layers to produce an image from a seed (random noise). Start with a Dense layer that takes this seed as input, then upsample several times until you reach the desired image size of 28x28x1. Notice the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/LeakyReLU">tf.keras.layers.LeakyReLU</a> activation for each layer, except the output layer which uses tanh.</p><pre>def make_generator_model():<br>    model = tf.keras.Sequential()<br>    model.add(layers.Dense(7*7*256, use_bias=False, input_shape=(100,)))<br>    model.add(layers.BatchNormalization())<br>    model.add(layers.LeakyReLU())</pre><pre>    model.add(layers.Reshape((7, 7, 256)))<br>    assert model.output_shape == (None, 7, 7, 256)  # Note: None is the batch size</pre><pre>    model.add(layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding=&#39;same&#39;, use_bias=False))<br>    assert model.output_shape == (None, 7, 7, 128)<br>    model.add(layers.BatchNormalization())<br>    model.add(layers.LeakyReLU())</pre><pre>    model.add(layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding=&#39;same&#39;, use_bias=False))<br>    assert model.output_shape == (None, 14, 14, 64)<br>    model.add(layers.BatchNormalization())<br>    model.add(layers.LeakyReLU())</pre><pre>    model.add(layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding=&#39;same&#39;, use_bias=False, activation=&#39;tanh&#39;))<br>    assert model.output_shape == (None, 28, 28, 1)</pre><pre>    return model</pre><p>Use the (as yet untrained) generator to create an image.</p><pre>generator = make_generator_model()</pre><pre>noise = tf.random.normal([1, 100])<br>generated_image = generator(noise, training=False)</pre><pre>plt.imshow(generated_image[0, :, :, 0], cmap=&#39;gray&#39;)</pre><pre>&lt;matplotlib.image.AxesImage at 0x7f3740747390&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/0*dd4M5XEkbm5I1Ixo.png" /></figure><h3>The Discriminator</h3><p>The discriminator is a CNN-based image classifier.</p><pre>def make_discriminator_model():<br>    model = tf.keras.Sequential()<br>    model.add(layers.Conv2D(64, (5, 5), strides=(2, 2), padding=&#39;same&#39;,<br>                                     input_shape=[28, 28, 1]))<br>    model.add(layers.LeakyReLU())<br>    model.add(layers.Dropout(0.3))</pre><pre>    model.add(layers.Conv2D(128, (5, 5), strides=(2, 2), padding=&#39;same&#39;))<br>    model.add(layers.LeakyReLU())<br>    model.add(layers.Dropout(0.3))</pre><pre>    model.add(layers.Flatten())<br>    model.add(layers.Dense(1))</pre><pre>    return model</pre><p>Use the (as yet untrained) discriminator to classify the generated images as real or fake. The model will be trained to output positive values for real images, and negative values for fake images.</p><pre>discriminator = make_discriminator_model()<br>decision = discriminator(generated_image)<br>print (decision)</pre><pre>tf.Tensor([[-0.00033125]], shape=(1, 1), dtype=float32)</pre><h3>Define the loss and optimizers</h3><p>Define loss functions and optimizers for both models.</p><pre># This method returns a helper function to compute cross entropy loss<br>cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)</pre><h3>Discriminator loss</h3><p>This method quantifies how well the discriminator is able to distinguish real images from fakes. It compares the discriminator’s predictions on real images to an array of 1s, and the discriminator’s predictions on fake (generated) images to an array of 0s.</p><pre>def discriminator_loss(real_output, fake_output):<br>    real_loss = cross_entropy(tf.ones_like(real_output), real_output)<br>    fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)<br>    total_loss = real_loss + fake_loss<br>    return total_loss</pre><h3>Generator loss</h3><p>The generator’s loss quantifies how well it was able to trick the discriminator. Intuitively, if the generator is performing well, the discriminator will classify the fake images as real (or 1). Here, compare the discriminators decisions on the generated images to an array of 1s.</p><pre>def generator_loss(fake_output):<br>    return cross_entropy(tf.ones_like(fake_output), fake_output)</pre><p>The discriminator and the generator optimizers are different since you will train two networks separately.</p><pre>generator_optimizer = tf.keras.optimizers.Adam(1e-4)<br>discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)</pre><h3>Save checkpoints</h3><p>This notebook also demonstrates how to save and restore models, which can be helpful in case a long running training task is interrupted.</p><pre>checkpoint_dir = &#39;./training_checkpoints&#39;<br>checkpoint_prefix = os.path.join(checkpoint_dir, &quot;ckpt&quot;)<br>checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,<br>                                 discriminator_optimizer=discriminator_optimizer,<br>                                 generator=generator,<br>                                 discriminator=discriminator)</pre><h3>Define the training loop</h3><pre>EPOCHS = 50<br>noise_dim = 100<br>num_examples_to_generate = 16</pre><pre># You will reuse this seed overtime (so it&#39;s easier)<br># to visualize progress in the animated GIF)<br>seed = tf.random.normal([num_examples_to_generate, noise_dim])</pre><p>The training loop begins with generator receiving a random seed as input. That seed is used to produce an image. The discriminator is then used to classify real images (drawn from the training set) and fakes images (produced by the generator). The loss is calculated for each of these models, and the gradients are used to update the generator and discriminator.</p><pre># Notice the use of `tf.function`<br># This annotation causes the function to be &quot;compiled&quot;.<br>@tf.function<br>def train_step(images):<br>    noise = tf.random.normal([BATCH_SIZE, noise_dim])</pre><pre>    with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:<br>      generated_images = generator(noise, training=True)</pre><pre>      real_output = discriminator(images, training=True)<br>      fake_output = discriminator(generated_images, training=True)</pre><pre>      gen_loss = generator_loss(fake_output)<br>      disc_loss = discriminator_loss(real_output, fake_output)</pre><pre>    gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)<br>    gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)</pre><pre>    generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))<br>    discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))</pre><pre>def train(dataset, epochs):<br>  for epoch in range(epochs):<br>    start = time.time()</pre><pre>    for image_batch in dataset:<br>      train_step(image_batch)</pre><pre>    # Produce images for the GIF as you go<br>    display.clear_output(wait=True)<br>    generate_and_save_images(generator,<br>                             epoch + 1,<br>                             seed)</pre><pre>    # Save the model every 15 epochs<br>    if (epoch + 1) % 15 == 0:<br>      checkpoint.save(file_prefix = checkpoint_prefix)</pre><pre>    print (&#39;Time for epoch {} is {} sec&#39;.format(epoch + 1, time.time()-start))</pre><pre>  # Generate after the final epoch<br>  display.clear_output(wait=True)<br>  generate_and_save_images(generator,<br>                           epochs,<br>                           seed)</pre><p><strong>Generate and save images</strong></p><pre>def generate_and_save_images(model, epoch, test_input):<br>  # Notice `training` is set to False.<br>  # This is so all layers run in inference mode (batchnorm).<br>  predictions = model(test_input, training=False)</pre><pre>  fig = plt.figure(figsize=(4, 4))</pre><pre>  for i in range(predictions.shape[0]):<br>      plt.subplot(4, 4, i+1)<br>      plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap=&#39;gray&#39;)<br>      plt.axis(&#39;off&#39;)</pre><pre>  plt.savefig(&#39;image_at_epoch_{:04d}.png&#39;.format(epoch))<br>  plt.show()</pre><h3>Train the model</h3><p>Call the train() method defined above to train the generator and discriminator simultaneously. Note, training GANs can be tricky. It&#39;s important that the generator and discriminator do not overpower each other (e.g., that they train at a similar rate).</p><p>At the beginning of the training, the generated images look like random noise. As training progresses, the generated digits will look increasingly real. After about 50 epochs, they resemble MNIST digits. This may take about one minute / epoch with the default settings on Colab.</p><pre>train(train_dataset, EPOCHS)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/0*31aHY7kvzon75rEn.png" /></figure><p>Restore the latest checkpoint.</p><pre>checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))</pre><pre>&lt;tensorflow.python.training.tracking.util.CheckpointLoadStatus at 0x7f371f792c88&gt;</pre><h3>Create a GIF</h3><pre># Display a single image using the epoch number<br>def display_image(epoch_no):<br>  return PIL.Image.open(&#39;image_at_epoch_{:04d}.png&#39;.format(epoch_no))</pre><pre>display_image(EPOCHS)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/0*GqZ34quWyfInuXB1.png" /></figure><p>Use imageio to create an animated gif using the images saved during training.</p><pre>anim_file = &#39;dcgan.gif&#39;</pre><pre>with imageio.get_writer(anim_file, mode=&#39;I&#39;) as writer:<br>  filenames = glob.glob(&#39;image*.png&#39;)<br>  filenames = sorted(filenames)<br>  for filename in filenames:<br>    image = imageio.imread(filename)<br>    writer.append_data(image)<br>  image = imageio.imread(filename)<br>  writer.append_data(image)</pre><pre>import tensorflow_docs.vis.embed as embed<br>embed.embed_file(anim_file)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/0*UclyZFuh0NM1Hr-7.gif" /></figure><p>source: tensorflow, wike, google :”)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3af58f5b2696" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/introduction-to-deep-convolutional-gans-using-tensorflow-and-keras-3af58f5b2696">Introduction to Deep Convolutional GAN’s Using Tensorflow and Keras</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[800+ Machine Learning Resources 2021]]></title>
            <link>https://whoisslimshady.medium.com/800-machine-learning-resources-2021-8018aaa0d1f5?source=rss-3c0cd74a4676------2</link>
            <guid isPermaLink="false">https://medium.com/p/8018aaa0d1f5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[whoisslimshady]]></dc:creator>
            <pubDate>Thu, 08 Apr 2021 08:16:02 GMT</pubDate>
            <atom:updated>2021-04-08T08:26:12.808Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*y5gdr1hwPPpAlooWbY9Huw.jpeg" /></figure><p>This article contains 800+ of resources at one place these resources are scattered on the internet but here I will give you all of them at one place starting from concepts of machine learning ,blogs ,tutorials many deep learning concepts</p><h3>Concepts of machine learning</h3><p><a href="https://blog.insightdatascience.com/how-to-deliver-on-machine-learning-projects-c8d82ce642b0">How to deliver on Machine Learning projects — Insight Data</a></p><p><a href="https://aeon.co/ideas/the-body-is-the-missing-link-for-truly-intelligent-machines">The body is the missing link for truly intelligent machines | Aeon Ideas</a></p><p><a href="https://www.altviz.co/article/machine-learning-guide">An Executive’s Primer On Machine Learning</a></p><p><a href="https://techcrunch.com/2016/10/26/the-darker-side-of-machine-learning/">The darker side of machine learning | TechCrunch</a></p><p><a href="https://medium.com/machine-learning-for-humans/supervised-learning-2-5c1c23f3560d">Machine Learning for Humans, Part 2.2: Supervised Learning II</a></p><p><a href="https://medium.com/@rchang/getting-better-at-machine-learning-16b4dd913a1f">Getting Better at Machine Learning — Robert Chang — Medium</a></p><p><a href="https://aeon.co/essays/the-complexity-of-social-problems-is-outsmarting-the-human-brain">The complexity of social problems is outsmarting the human brain | Aeon Essays</a></p><p><a href="https://qz.com/1005275/language-matters-more-than-ever-in-the-age-of-ai/">Language matters more than ever in the age of AI — Quartz</a></p><p><a href="http://waitbutwhy.com/2017/04/neuralink.html">Neuralink and the Brain’s Magical Future — Wait But Why</a></p><p><a href="https://hbr.org/cover-story/2017/07/the-business-of-artificial-intelligence">The Business of Artificial Intelligence</a></p><p><a href="https://www.mckinsey.com/business-functions/mckinsey-analytics/our-insights/an-executives-guide-to-ai">An executive’s guide to AI | McKinsey</a></p><p><a href="https://www.propublica.org/article/machine-bias-risk-assessments-in-criminal-sentencing">Machine Bias — ProPublica</a></p><p><a href="http://nautil.us/issue/55/trust/are-algorithms-building-the-new-infrastructure-of-racism">We Are Running Out of Time to Make Algorithms Fair</a></p><p><a href="http://www.fast.ai/2018/08/07/hbr-bias-algorithms/?utm_campaign=Data_Elixir&amp;utm_medium=email&amp;utm_source=Data_Elixir_195">What HBR Gets Wrong About Algorithms and Bias · fast.ai</a></p><p><a href="https://hackernoon.com/rethinking-fast-and-slow-in-data-science-b2ce18d5b054?mkt_tok=eyJpIjoiWmpWaFkyUTNZMlZrTldJeiIsInQiOiJ3Qms4dmU3TklzVW9VQ0dWbWYyVmZ4UVJvR3ZBXC9ERStvd3NLRzVwNTBXXC9cL3gwQ3hHNHV6a0Y5b1Zsb3NUT1Ira0x0cTB5RGZtemViYTNHY0VDVjlwOURNQU40YUhFbitkakpSTXNZVlpjZGFyTDRuUDNnOTBaUkdcLzJzOEQwYWoifQ%3D%3D">Rethinking Fast and Slow in Data Science — Hacker Noon</a></p><p><a href="https://www.youtube.com/watch?v=lsizZGqDszc">An overview of Machine learning and Deep Learning (Lecture at Harvard Business School) — YouTube</a></p><p><a href="https://eng.uber.com/forecasting-introduction/">Forecasting at Uber: An Introduction</a></p><p><a href="https://eng.uber.com/michelangelo/">Meet Michelangelo: Uber’s Machine Learning Platform</a></p><p><a href="https://www.oreilly.com/ideas/mlflow-a-platform-for-managing-the-machine-learning-lifecycle?utm_medium=email&amp;utm_source=topic+optin&amp;utm_campaign=awareness&amp;utm_content=20180725+data+nl&amp;mkt_tok=eyJpIjoiTlRnMVptVTRZakprTmpZeiIsInQiOiJvRGlBY2kxNkJyWVdYVlN6R21adHgwQnFOM05URDdKdlNyMmtnOXl4UFwvdFwvcURmcEx1eFhPbzJMWHoyWTdtNHo0OUEwZ2FabVhSaUR5UXdRSWE2SXhSRWVocEEwbUhsYjB0N2JydWlpTFp2ZVN4R3N2REZHTmN6Mm5VNFN2VDB1In0%3D">MLflow: A platform for managing the machine learning lifecycle — O’Reilly Media</a></p><p><a href="https://www.oreilly.com/ideas/the-five-cs?utm_medium=email&amp;utm_source=topic+optin&amp;utm_campaign=awareness&amp;utm_content=20180725+data+nl&amp;mkt_tok=eyJpIjoiTlRnMVptVTRZakprTmpZeiIsInQiOiJvRGlBY2kxNkJyWVdYVlN6R21adHgwQnFOM05URDdKdlNyMmtnOXl4UFwvdFwvcURmcEx1eFhPbzJMWHoyWTdtNHo0OUEwZ2FabVhSaUR5UXdRSWE2SXhSRWVocEEwbUhsYjB0N2JydWlpTFp2ZVN4R3N2REZHTmN6Mm5VNFN2VDB1In0%3D">The five Cs — O’Reilly Media</a></p><p><a href="https://www.oreilly.com/ideas/how-to-take-machine-learning-from-exploration-to-implementation?utm_medium=email&amp;utm_source=topic+optin&amp;utm_campaign=awareness&amp;utm_content=20180725+data+nl&amp;mkt_tok=eyJpIjoiTlRnMVptVTRZakprTmpZeiIsInQiOiJvRGlBY2kxNkJyWVdYVlN6R21adHgwQnFOM05URDdKdlNyMmtnOXl4UFwvdFwvcURmcEx1eFhPbzJMWHoyWTdtNHo0OUEwZ2FabVhSaUR5UXdRSWE2SXhSRWVocEEwbUhsYjB0N2JydWlpTFp2ZVN4R3N2REZHTmN6Mm5VNFN2VDB1In0%3D">How to take machine learning from exploration to implementation — O’Reilly Media</a></p><p><a href="https://www.oreilly.com/ideas/of-oaths-and-checklists?utm_medium=email&amp;utm_source=topic+optin&amp;utm_campaign=awareness&amp;utm_content=20180725+data+nl&amp;mkt_tok=eyJpIjoiTlRnMVptVTRZakprTmpZeiIsInQiOiJvRGlBY2kxNkJyWVdYVlN6R21adHgwQnFOM05URDdKdlNyMmtnOXl4UFwvdFwvcURmcEx1eFhPbzJMWHoyWTdtNHo0OUEwZ2FabVhSaUR5UXdRSWE2SXhSRWVocEEwbUhsYjB0N2JydWlpTFp2ZVN4R3N2REZHTmN6Mm5VNFN2VDB1In0%3D">Of oaths and checklists — O’Reilly Media</a></p><p><a href="https://hbr.org/2018/07/want-less-biased-decisions-use-algorithms">Want Less-Biased Decisions? Use Algorithms.</a></p><p><a href="https://blogs.technet.microsoft.com/machinelearning/2015/04/14/permutation-feature-importance/">Permutation Feature Importance | Machine Learning Blog</a></p><p><a href="https://www.forbes.com/sites/louiscolumbus/2018/08/26/25-machine-learning-startups-to-watch-in-2018/?utm_campaign=Data_Elixir&amp;utm_medium=email&amp;utm_source=Data_Elixir_197#7c5a97ca6f99">25 Machine Learning Startups To Watch in 2018</a></p><p><a href="https://medium.com/the-lever/no-machine-learning-in-your-product-start-here-2df776d10a5c">No Machine Learning in your product? Start here — The Lever — Medium</a></p><p><a href="https://hackernoon.com/building-ai-software-data-driven-vs-model-driven-ai-and-why-we-need-an-ai-specific-software-640f74aaf78f">Building AI software: Data-driven vs model-driven AI and why we need an AI-specific software…</a></p><p><a href="https://blog.ycombinator.com/learning-math-for-machine-learning/">Learning Math for Machine Learning</a></p><p><a href="http://www.unofficialgoogledatascience.com/2016/10/practical-advice-for-analysis-of-large.html">Practical advice for analysis of large, complex data sets</a></p><p><a href="https://medium.com/datadriveninvestor/a-curated-list-of-artificial-intelligence-ai-courses-books-video-lectures-and-papers-d2f584ca14f8">A curated list of Artificial Intelligence (AI) courses, books, video lectures and papers.</a></p><p><a href="https://theconversation.com/neuralink-wants-to-wire-your-brain-to-the-internet-what-could-possibly-go-wrong-76180">Neuralink wants to wire your brain to the internet — what could possibly go wrong?</a></p><p><a href="https://www.wired.com/story/inside-microsofts-ai-comeback?mbid=social_fb">Inside Microsoft’s Artificial Intelligence Comeback | WIRED</a></p><p><a href="https://unsupervisedmethods.com/my-curated-list-of-ai-and-machine-learning-resources-from-around-the-web-9a97823b8524">My Curated List of AI and Machine Learning Resources from Around the Web</a></p><p><a href="https://www.fastcodesign.com/90132632/ai-is-inventing-its-own-perfect-languages-should-we-let-it?utm_content=buffer3d120&amp;utm_medium=social&amp;utm_source=facebook.com&amp;utm_campaign=buffer">AI Is Inventing Languages Humans Can’t Understand. Should We Stop It?</a></p><p><a href="https://blog.playment.io/list-top-ai-data-science-machine-learning-resources/">List of Top AI, Data Science and Machine Learning Resources</a></p><p><a href="http://news.efinancialcareers.com/uk-en/285249/machine-learning-and-big-data-j-p-morgan">JPMorgan’s massive guide to machine learning jobs in finance</a></p><p><a href="https://elitedatascience.com/machine-learning-algorithms">Modern Machine Learning Algorithms: Strengths and Weaknesses</a></p><p><a href="https://towardsdatascience.com/which-machine-learning-algo-will-continue-to-be-in-use-in-year-2118-59d0461160f3">Which Machine Learning Algo will continue to be in use in year 2118?</a></p><p><a href="https://blog.h2o.ai/2018/03/driverless-ai-prevents-overfitting-leakage/">How Driverless AI Prevents Overfitting and Leakage — H2O.ai Blog</a></p><p><a href="https://medium.com/@YvesMulkers/10-machine-learning-algorithms-you-should-know-to-become-a-data-scientist-91ea637f5b57?mkt_tok=eyJpIjoiTlRkbE1USTVPRE0xWVdFNCIsInQiOiJBRVdXXC9pMExGM0dvaTB1SUdjUUFQZkZpdUpFdU4rUFNjdExkQjZtXC9hOHhXVFRZb3BKMWNlelFrRjV0S2RTZWE3YUpCNHhvN0RKSUVIM29ZekVkXC9jMjNzWFFcL0tOcnA5MUV1NXdQSU5PRWhyZ1FhZGsyUW5yK1d4UWdDRmdlZmsifQ%3D%3D">10 Machine Learning Algorithms You Should Know to Become a Data Scientist</a></p><p><a href="https://blogs.sas.com/content/subconsciousmusings/2017/04/12/machine-learning-algorithm-use/">Which machine learning algorithm should I use? — Subconscious Musings</a></p><p><a href="https://towardsdatascience.com/7-use-cases-for-data-science-and-predictive-analytics-e3616e9331f9">7 Use Cases For Data Science And Predictive Analytics</a></p><p><a href="http://martin.zinkevich.org/rules_of_ml/rules_of_ml.pdf">Rules of ML</a></p><p><a href="https://ujjwalkarn.me/2016/08/09/quick-intro-neural-networks/">A Quick Introduction to Neural Networks — the data science blog</a></p><p><a href="https://hbr.org/2018/02/you-dont-have-to-be-a-data-scientist-to-fill-this-must-have-analytics-role?imm_mid=0fb29a&amp;cmp=em-data-na-na-newsltr_20180214">You Don’t Have to Be a Data Scientist to Fill This Must-Have Analytics Role</a></p><p><a href="https://hbr.org/2018/07/most-of-ais-business-uses-will-be-in-two-areas">Most of AI’s Business Uses Will Be in Two Areas</a></p><p><a href="https://developers.google.com/machine-learning/guides/rules-of-ml/">Rules of Machine Learning: | ML Universal Guides | Google Developers</a></p><p><a href="https://medium.com/@bhushanshewale45/approach-towards-machine-learning-problem-bb17fdf0a187">Approaching Machine learning problem — Bhushan Shewale — Medium</a></p><p><a href="http://ai.stanford.edu/~zayd/why-is-machine-learning-hard.html?utm_medium=email&amp;utm_source=topic+optin&amp;utm_campaign=awareness&amp;utm_content=20180523+data+nl&amp;mkt_tok=eyJpIjoiTW1Ka1lqRTVNakJtWm1KayIsInQiOiJhbWxZNitLSGlYN1FsSUtwR2FFYkNJbHNlNTd4cDNnTnNVbW5XR1lrZTdiYWxCaDRCUzZcLytcL01CNVlJaW9FQ3hOMDlnR3cweXFVQjhIeEY4WEZnMkRHSVJVNmpqUUJaTUFiSVpma2k0ZGpLaWtZakZLWCtUN09pbk5sSG1CM2JrIn0%3D">Zayd’s Blog — Why is machine learning ‘hard’?</a></p><p><a href="https://medium.com/airbnb-engineering/airflow-a-workflow-management-platform-46318b977fd8">Airflow: a workflow management platform — Airbnb Engineering &amp; Data Science — Medium</a></p><h3>Blogs &amp; Tutorials</h3><p><a href="https://medium.com/machine-learning-in-practice/over-200-of-the-best-machine-learning-nlp-and-python-tutorials-2018-edition-dd8cf53cb7dc">Over 200 of the Best Machine Learning, NLP, and Python Tutorials — 2018 Edition</a></p><p><a href="https://www.analyticsvidhya.com/blog/2017/01/the-most-comprehensive-data-science-learning-plan-for-2017/">The most comprehensive Data Science learning plan for 2017</a></p><p><a href="https://developers.google.com/machine-learning/glossary/">Machine Learning | Google Developers</a></p><p><a href="https://medium.com/@ageitgey/machine-learning-is-fun-80ea3ec3c471">Machine Learning is Fun! — Medium</a></p><p><a href="https://github.com/ageron/handson-ml?utm_content=buffere416a&amp;utm_medium=social&amp;utm_source=twitter.com&amp;utm_campaign=buffer">A series of Jupyter notebooks that walk you through the fundamentals of Machine Learning and Deep Learning in python using Scikit-Learn and TensorFlow.</a></p><p><a href="https://towardsdatascience.com/a-complete-machine-learning-walk-through-in-python-part-one-c62152f39420">A Complete Machine Learning Walk-Through in Python: Part One</a></p><p><a href="https://unsupervisedmethods.com/learning-machine-learning-and-nlp-from-185-quora-questions-cebe42e47da8">Learning Machine Learning and NLP from 187 Quora Questions</a></p><p><a href="https://www.r-bloggers.com/in-depth-introduction-to-machine-learning-in-15-hours-of-expert-videos/">In-depth introduction to machine learning in 15 hours of expert videos | R-bloggers</a></p><p><a href="https://pythonprogramming.net/data-visualization-application-dash-python-tutorial-introduction/">Python Programming Tutorials</a></p><p><a href="https://spandan-madan.github.io/DeepLearningProject/">Deep_Learning_Project</a></p><p><a href="https://developers.google.com/machine-learning/crash-course/ml-intro">Introduction to Machine Learning | Machine Learning Crash Course | Google Developers</a></p><p><a href="https://towardsdatascience.com/a-data-science-for-good-machine-learning-project-walk-through-in-python-part-one-1977dd701dbc">A “Data Science for Good“ Machine Learning Project Walk-Through in Python: Part One</a></p><p><a href="https://towardsdatascience.com/a-complete-machine-learning-walk-through-in-python-part-one-c62152f39420">A Complete Machine Learning Walk-Through in Python: Part One</a></p><p><a href="https://www.analyticsindiamag.com/5-best-data-science-resources-that-beginners-can-download-for-free/">5 Best Data Science Resources That Beginners Can Download For Free</a></p><p><a href="https://chrisalbon.com/">Chris Albon</a></p><p><a href="http://course.fast.ai/index.html">Deep Learning For Coders — 36 hours of lessons for free</a></p><p><a href="https://www.kdnuggets.com/2018/09/essential-math-data-science.html#.W6JSciNOdtw.twitter">Essential Math for Data Science: ‘Why’ and ‘How’</a></p><p><a href="https://blog.sicara.com/bokeh-dash-best-dashboard-framework-python-shiny-alternative-c5b576375f7f">Bokeh vs Dash — Which is the Best Dashboard Framework for Python?</a></p><p><a href="https://startupsventurecapital.com/essential-cheat-sheets-for-machine-learning-and-deep-learning-researchers-efb6a8ebd2e5">Essential Cheat Sheets for Machine Learning and Deep Learning Engineers</a></p><p><a href="https://www.youtube.com/watch?v=h0e2HAPTGF4">(9) 11. Introduction to Machine Learning — YouTube</a></p><p><a href="https://www.analyticsvidhya.com/blog/2016/01/guide-data-exploration/">A Complete Tutorial which teaches Data Exploration in detail</a></p><p><a href="https://github.com/jupyter/jupyter/wiki/A-gallery-of-interesting-Jupyter-Notebooks">A gallery of interesting Jupyter Notebooks · jupyter/jupyter Wiki · GitHub</a></p><p><a href="http://cs229.stanford.edu/notes/cs229-notes1.pdf">Andrew Ng — Supervised learning notes</a></p><p><a href="http://ufldl.stanford.edu/tutorial/supervised/LogisticRegression/">Unsupervised Feature Learning and Deep Learning Tutorial</a></p><p><a href="https://github.com/donnemartin/data-science-ipython-notebooks/blob/master/README.md">data-science-ipython-notebooks/README.md at master · donnemartin/data-science-ipython-notebooks · GitHub</a></p><p><a href="https://www.slideshare.net/TessFerrandez/notes-from-coursera-deep-learning-courses-by-andrew-ng">Notes from Coursera Deep Learning courses by Andrew Ng</a></p><p><a href="https://github.com/rasbt/python-machine-learning-book">rasbt/python-machine-learning-book: The “Python Machine Learning (1st edition)” book code repository and info resource</a></p><p><a href="https://github.com/ageron/handson-ml">ageron/handson-ml: A series of Jupyter notebooks that walk you through the fundamentals of Machine Learning and Deep Learning in python using Scikit-Learn and TensorFlow.</a></p><p><a href="https://github.com/ujjwalkarn/Machine-Learning-Tutorials">ujjwalkarn/Machine-Learning-Tutorials: machine learning and deep learning tutorials, articles and other resources</a></p><p><a href="https://github.com/josephmisiti/awesome-machine-learning">josephmisiti/awesome-machine-learning: A curated list of awesome Machine Learning frameworks, libraries and software.</a></p><p><a href="https://github.com/ujjwalkarn/Machine-Learning-Tutorials#interview">ujjwalkarn/Machine-Learning-Tutorials: machine learning and deep learning tutorials, articles and other resources</a></p><p><a href="https://github.com/ujjwalkarn/DataSciencePython">ujjwalkarn/DataSciencePython: common data analysis and machine learning tasks using python</a></p><p><a href="https://medium.com/open-machine-learning-course">Open Machine Learning Course — Medium</a></p><p><a href="https://www.kaggle.com/kanncaa1/data-sciencetutorial-for-beginners">Data ScienceTutorial for Beginners | Kaggle</a> <a href="https://towardsdatascience.com/a-complete-machine-learning-walk-through-in-python-part-three-388834e8804b">A Complete Machine Learning Walk-Through in Python: Part Three</a></p><p><a href="https://work.caltech.edu/telecourse.html">Learning From Data — Online Course (MOOC)</a></p><p><a href="https://github.com/ShuaiW/ml-cheatsheet">GitHub — ShuaiW/ml-cheatsheet: A constantly updated python machine learning cheatsheet</a></p><p><a href="https://www.autonlab.org/tutorials">tutorials [Auton Lab]</a> <a href="https://www.analyticsvidhya.com/blog/2016/01/complete-tutorial-ridge-lasso-regression-python/">A Complete Tutorial on Ridge and Lasso Regression in Python</a></p><p><a href="http://www-bcf.usc.edu/~gareth/ISL/">Introduction to Statistical Learning</a></p><p><a href="https://github.com/silvabrian/tech-talk-datatable/blob/master/Data%20Table%20Tech%20Talk.Rmd">tech-talk-datatable/Data Table Tech Talk.Rmd at master · silvabrian/tech-talk-datatable</a></p><p><a href="https://www.analyticsvidhya.com/blog/2018/06/comprehensive-data-science-machine-learning-interview-guide/?utm_source=feedburner&amp;utm_medium=email&amp;utm_campaign=Feed%3A+AnalyticsVidhya+%28Analytics+Vidhya%29">Comprehensive Data Science, Machine Learning Interview Guide</a></p><h3>Publications/Interesting websites etc</h3><p><a href="https://juliasilge.com/">Julia Silge</a></p><p><a href="https://dss.iq.harvard.edu/">Data Science Services</a> <a href="http://www.unofficialgoogledatascience.com/">The Unofficial Google Data Science Blog</a></p><p><a href="http://fivethirtyeight.com/">FiveThirtyEight | Nate Silver’s FiveThirtyEight uses statistical analysis — hard numbers — to tell compelling stories about politics, sports, science, economics and culture.</a></p><p><a href="http://www.datasciencecentral.com/profiles/blogs/25-timeless-data-science-articles">25 Timeless Data Science Articles — Data Science Central</a> <a href="https://blog.exploratory.io/">learn data science</a></p><p><a href="http://datavizproject.com/">Data Viz Project | Collection of data visualizations to get inspired and finding the right type.</a></p><p><a href="https://sebastianraschka.com/">Sebastian Raschka’s Website</a></p><p><a href="http://dogdogfish.com/">DogDogFish — Data Science, amongst other things.</a></p><p><a href="https://medium.com/@DataSciencePick">TDS Team — Medium</a> <a href="https://sebastiansauer.github.io/">Latest Posts — Sebastian Sauer Stats Blog</a></p><p><a href="https://www.youtube.com/channel/UCWN3xxRkmTPmbKwht9FuE5A">Siraj Raval — YouTube — YouTube</a></p><p><a href="https://www.dataquest.io/blog/build-a-data-science-portfolio/">The key to building a data science portfolio that will get you a job</a></p><p><a href="https://www.datasciencecentral.com/">Data Science Central</a> <a href="https://www.datasciencecentral.com/profiles/blogs/hitchhiker-s-guide-to-data-science-machine-learning-r-python">Hitchhiker’s Guide to Data Science, Machine Learning, R, Python — Data Science Central</a></p><p><a href="https://blog.udacity.com/2018/01/top-5-data-science-publications.html?%3Futm_source=facebook&amp;utm_medium=ads&amp;utm_campaign=fb-ads-3Q_FB_Acquisition_DataFoundations">Top 5 Data Science Publications You Should Read In 2018 | Udacity</a></p><p><a href="https://www.youtube.com/channel/UC3tFZR3eL1bDY8CqZDOQh-w">Ben Lambert — YouTube — YouTube</a></p><p><a href="https://towardsdatascience.com/the-best-data-science-learning-resources-out-there-and-my-journey-into-data-science-81c5a6ec67bc">The best data science learning resources out there and my journey into data science-</a></p><p><a href="https://drivendata.github.io/cookiecutter-data-science/?lipi=urn%3Ali%3Apage%3Ad_flagship3_feed%3BPmjjcAhOR8izyHDMiv3PdA%3D%3D">Cookiecutter Data Science</a></p><p><a href="https://towardsdatascience.com/data-curious-2017-year-in-review-my-favourite-data-stories-datasets-and-visualisations-from-last-4214bf634f56">Data Curious 2017 Year in Review: My favourite data stories, datasets and visualisations from last…</a></p><p><a href="https://towardsdatascience.com/how-to-create-value-with-your-data-science-projects-62460db3bb4f">How to Create Value with Your Data Science Projects</a> <a href="http://www.countingcalculi.com/explanations/google_sheets_and_jupyter_notebooks/">Integrate Google Sheets and Jupyter Notebooks</a></p><p><a href="http://flowingdata.com/">FlowingData</a></p><p><a href="http://www.claoudml.co/?lipi=urn%3Ali%3Apage%3Ad_flagship3_feed%3BlsRfZJe%2BT5GOgppX2tgphw%3D%3D">ClaoudML</a></p><p><a href="https://towardsdatascience.com/list-of-must-read-free-data-science-books-bfae4c5c5a16">List of Must — Read Free Data Science Books —</a></p><p><a href="https://towardsdatascience.com/list-of-must-read-free-data-science-books-bfae4c5c5a16">Towards Data Science</a></p><p><a href="https://elitedatascience.com/page/3">EliteDataScience — Page 3 of 4 — Supercharge your data science career.</a></p><p><a href="https://simmachines.com/">Machine Learning Software Company | simMachines</a></p><p><a href="http://www1.nyc.gov/site/analytics/index.page">NYC Analytics</a> <a href="https://www.drivendata.org/partners/">DrivenData</a></p><p><a href="https://medium.com/datadriveninvestor/the-50-best-public-datasets-for-machine-learning-d80e9f030279">The 50 Best Public Datasets for Machine Learning — Data Driven Investor — Medium</a></p><p><a href="https://trello.com/b/rbpEfMld/data-science">Data Science | Trello</a> <a href="https://www.alsharif.info/iom530">Modern Statistical Learning Methods</a></p><p><a href="https://elitedatascience.com/python-cheat-sheet">Python Cheat Sheet for Data Science</a></p><p><a href="https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Scikit_Learn_Cheat_Sheet_Python.pdf">Scikit_Learn_Cheat_Sheet_Python.pdf</a></p><p><a href="https://statsbot.co/blog/data-scientist-resume-projects/">Data Scientist Resume Projects | Statsbot Blog</a></p><p><a href="https://www.kaggle.com/shivamb/data-science-glossary-on-kaggle?utm_campaign=Data_Elixir&amp;utm_medium=email&amp;utm_source=Data_Elixir_190">Data Science Glossary on Kaggle !</a></p><p><a href="https://medium.com/towards-data-science/our-data-science-workflow-b974f30a124d">Our Data Science Workflow — Towards Data Science — Medium</a></p><p><a href="https://www.youtube.com/watch?v=8onB7rPG4Pk&amp;feature=youtu.be">Mathematics of Machine Learning — YouTube</a></p><h3>Data Science concepts</h3><h3>PCA</h3><p><a href="https://medium.com/data-design/how-to-not-be-dumb-at-applying-principal-component-analysis-pca-6c14de5b3c9d">How to not be dumb at applying Principal Component Analysis (PCA)?</a></p><p><a href="http://setosa.io/ev/principal-component-analysis/">Principal Component Analysis explained visually</a></p><p><a href="https://medium.com/towards-data-science/a-one-stop-shop-for-principal-component-analysis-5582fb7e0a9c">A One-Stop Shop for Principal Component Analysis — Towards Data Science — Medium</a></p><p><a href="https://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues">pca — Making sense of principal component analysis, eigenvectors &amp; eigenvalues — Cross Validated</a> <a href="https://stats.stackexchange.com/questions/144508/conclusions-from-output-of-a-principal-component-analysis">Conclusions from output of a principal component analysis — Cross Validated</a></p><p><a href="https://stats.stackexchange.com/questions/238538/are-there-cases-where-pca-is-more-suitable-than-t-sne">tsne — Are there cases where PCA is more suitable than t-SNE? — Cross Validated</a></p><p><a href="https://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues">Making sense of principal component analysis, eigenvectors &amp; eigenvalues — Cross Validated</a></p><p><a href="https://www.youtube.com/watch?v=ZqXnPcyIAL8">Dimensionality Reduction: Principal Components Analysis, Part 1 — YouTube</a></p><p><a href="http://www.cerebralmastication.com/2010/09/principal-component-analysis-pca-vs-ordinary-least-squares-ols-a-visual-explination/">Cerebral Mastication » Blog Archive » Principal Component Analysis (PCA) vs Ordinary Least Squares (OLS): A Visual Explanation</a></p><p><a href="https://medium.com/@aptrishu/understanding-principle-component-analysis-e32be0253ef0">Understanding Principal Component Analysis — Hacker Noon</a> <a href="http://sebastianraschka.com/Articles/2015_pca_in_3_steps.html">Principal Component Analysis</a></p><p><a href="https://medium.com/district-data-labs/principal-component-analysis-with-python-4962cd026465">Principal Component Analysis with Python — District Data Labs — Medium</a></p><p><a href="https://medium.com/@luckylwk/visualising-high-dimensional-datasets-using-pca-and-t-sne-in-python-8ef87e7915b">Visualising high-dimensional datasets using PCA and t-SNE in Python</a></p><h3>Missing data</h3><p><a href="https://chrisalbon.com/python/data_wrangling/pandas_missing_data/">Missing Data In pandas Dataframes</a> <a href="https://towardsdatascience.com/the-tale-of-missing-values-in-python-c96beb0e8a9d">The tale of missing values in Python —</a></p><p><a href="https://towardsdatascience.com/the-tale-of-missing-values-in-python-c96beb0e8a9d">Towards Data Science</a> <a href="https://machinelearningmastery.com/handle-missing-data-python/">How to Handle Missing Data with Python</a> <a href="https://pandas.pydata.org/pandas-docs/version/0.22/missing_data.html">Working with missing data — pandas 0.22.0 documentation</a></p><p><a href="https://www.quora.com/How-can-I-deal-with-missing-values-in-a-predictive-model/answer/Claudia-Perlich?share=569f82a1&amp;srid=idBZ">Claudia Perlich’s answer to How can I deal with missing values in a predictive model? — Quora</a></p><h3>Feature Engineering</h3><p><a href="https://towardsdatascience.com/automated-feature-engineering-in-python-99baf11cc219">Automated Feature Engineering in Python — Towards Data Science</a> <a href="https://jakevdp.github.io/PythonDataScienceHandbook/05.04-feature-engineering.html">Feature</a></p><p><a href="https://jakevdp.github.io/PythonDataScienceHandbook/05.04-feature-engineering.html">Engineering | Python Data Science Handbook</a></p><p><a href="https://towardsdatascience.com/why-automated-feature-engineering-will-change-the-way-you-do-machine-learning-5c15bf188b96">Why Automated Feature Engineering Will Change the Way You Do Machine Learning</a></p><p><a href="https://github.com/Featuretools/Automated-Manual-Comparison">GitHub — Featuretools/Automated-Manual-Comparison: Automated vs Manual Feature Engineering Comparison. Implemented using Featuretools.</a></p><p><a href="https://medium.com/the-artificial-impostor/feature-importance-measures-for-tree-models-part-i-47f187c1a2c3">Feature Importance Measures for Tree Models — Part I</a> <a href="https://www.featurelabs.com/blog/deep-feature-synthesis/?__hstc=166560673.3a055595ac7d7612c52e6b00061c9c1c.1519627491743.1519627491743.1519627491743.1&amp;__hssc=166560673.6.1519627491744&amp;__hsfp=3980689711">Deep Feature Synthesis: How Automated Feature Engineering Works | Feature Labs</a> <a href="https://towardsdatascience.com/understanding-feature-engineering-part-1-continuous-numeric-data-da4e47099a7b">Understanding Feature</a></p><p><a href="https://towardsdatascience.com/understanding-feature-engineering-part-1-continuous-numeric-data-da4e47099a7b">Engineering (Part 1) — Continuous Numeric Data</a> <a href="https://towardsdatascience.com/automated-feature-engineering-in-python-99baf11cc219">Automated Feature</a></p><p><a href="https://towardsdatascience.com/automated-feature-engineering-in-python-99baf11cc219">Engineering in Python — Towards Data Science</a></p><h3>Regression</h3><p><a href="https://hbr.org/2015/11/a-refresher-on-regression-analysis">A Refresher on Regression Analysis</a></p><p><a href="https://brohrer.github.io/how_linear_regression_works.html">How linear regression works</a></p><p><a href="https://towardsdatascience.com/linear-regression-detailed-view-ea73175f6e86">Linear Regression — Detailed View — Towards Data Science</a> <a href="https://heartbeat.fritz.ai/5-regression-loss-functions-all-machine-learners-should-know-4fb140e9d4b0">5 Regression Loss Functions All Machine Learners Should Know</a></p><p><a href="http://www.r-tutor.com/elementary-statistics/hypothesis-testing">Hypothesis Testing | R Tutorial</a> <a href="http://statistics.berkeley.edu/computing/r-t-tests">Using t-tests in R | Department of Statistics</a></p><p><a href="http://blog.minitab.com/blog/adventures-in-statistics-2/regression-analysis-how-do-i-interpret-r-squared-and-assess-the-goodness-of-fit">Regression Analysis: How Do I Interpret R-squared and Assess the Goodness-of-Fit?</a></p><p><a href="http://blog.minitab.com/blog/adventures-in-statistics-2/why-you-need-to-check-your-residual-plots-for-regression-analysis">Why You Need to Check Your Residual Plots for Regression Analysis: Or, To Err is Human, To Err Randomly is Statistically Divine | Minitab</a></p><p><a href="http://blog.minitab.com/blog/adventures-in-statistics-2/how-to-interpret-regression-analysis-results-p-values-and-coefficients">How to Interpret Regression Analysis Results: P-values and Coefficients | Minitab</a></p><p><a href="http://statisticsbyjim.com/regression/how-high-r-squared/">How High Does R-squared Need to Be? — Statistics By Jim</a></p><p><a href="http://nbviewer.jupyter.org/github/justmarkham/DAT4/blob/master/notebooks/08_linear_regression.ipynb">Linear regression — Python</a></p><p><a href="http://statisticsbyjim.com/hypothesis-testing/comparing-hypothesis-tests-data-types/">Comparing Hypothesis Tests for Continuous, Binary, and Count Data — Statistics By Jim</a></p><p><a href="https://www.analyticsvidhya.com/blog/2018/01/anova-analysis-of-variance/?utm_source=sendinblue&amp;utm_campaign=February_2018&amp;utm_medium=email">A Simple Introduction to ANOVA (with applications in Excel)</a></p><p><a href="https://saylordotorg.github.io/text_introductory-statistics/index.html">Introductory Statistics — Table of Contents</a> <a href="https://towardsdatascience.com/statistics-for-people-in-a-hurry-a9613c0ed0b?mkt_tok=eyJpIjoiTVdOa1pEVXhObVppTkRSbSIsInQiOiJ0YUtRdU5Ea0RFUWZrM24xcXhQRGFDbFpjZ1JFQ1JcLzVPWFwvaGQ1RHZkWkVPblVxZ1JIYU5MVXBWQ21NOHU5RllNU2xpb3BCWDA0K21pV0VmVDhtSEJEdXptaGY3SVZqakVjYllJVXZveFwva2pGbFhCTzhQTmVMRnRPVmI2YzYxUyJ9">Statistics for people in a hurry — Towards Data Science</a></p><h3>NLP</h3><p><a href="https://www.kdnuggets.com/2017/12/general-approach-preprocessing-text-data.html">A General Approach to Preprocessing Text Data</a></p><p><a href="https://medium.com/@ageitgey/natural-language-processing-is-fun-9a0bff37854e">Natural Language Processing is Fun! — Adam Geitgey — Medium</a></p><p><a href="https://www.analyticsvidhya.com/blog/2017/01/ultimate-guide-to-understand-implement-natural-language-processing-codes-in-python/">Ultimate Guide to Understand &amp; Implement Natural Language Processing</a> <a href="https://www.analyticsvidhya.com/blog/2018/02/natural-language-processing-for-beginners-using-textblob/?utm_source=feedburner&amp;utm_medium=email&amp;utm_campaign=Feed%3A+AnalyticsVidhya+%28Analytics+Vidhya%29">Natural Language Processing for Beginners: Using TextBlob</a></p><p><a href="https://medium.com/@ageitgey/natural-language-processing-is-fun-9a0bff37854e">m</a><a href="https://github.com/JasonKessler/scattertext">GitHub — JasonKessler/scattertext: Beautiful visualizations of how language differs among document types.</a></p><p><a href="http://www.mien.in/2017/10/02/visual-text-analytics-with-python/">Visual Text Analytics With Python | The Mien Blog</a></p><p><a href="http://pythondata.com/working-large-csv-files-python/">Working with large CSV files in Python</a></p><p><a href="https://github.com/zeeshanu/learn-regex">Learn regex the easy way</a></p><p><a href="https://www.analyticsvidhya.com/blog/2018/02/the-different-methods-deal-text-data-predictive-python/?utm_source=feedburner&amp;utm_medium=email&amp;utm_campaign=Feed%3A+AnalyticsVidhya+%28Analytics+Vidhya%29">Ultimate guide to deal with Text Data (using Python) — for Data Scientists &amp; Engineers</a></p><p><a href="https://blog.insightdatascience.com/how-to-solve-90-of-nlp-problems-a-step-by-step-guide-fda605278e4e">How to solve 90% of NLP problems: a step-by-step guide</a></p><p><a href="https://github.com/hundredblocks/concrete_NLP_tutorial/blob/master/NLP_notebook.ipynb">concrete_NLP_tutorial/NLP_notebook.ipynb at master · hundredblocks/concrete_NLP_tutorial</a></p><p><a href="https://dzone.com/articles/nlp-tutorial-using-python-nltk-simple-examples">NLP Tutorial Using Python NLTK (Simple Examples) — DZone AI</a></p><p><a href="http://www.rexegg.com/regex-quickstart.html">Regex Cheat Sheet</a></p><h3>LDA</h3><p><a href="https://radimrehurek.com/gensim/">gensim: Topic modelling for humans</a></p><p><a href="https://tedunderwood.com/2012/04/07/topic-modeling-made-just-simple-enough/">Topic modeling made just simple enough. | The Stone and the Shell</a></p><p><a href="https://eight2late.wordpress.com/2015/09/29/a-gentle-introduction-to-topic-modeling-using-r/">A gentle introduction to topic modeling using R | Eight to Late</a></p><p><a href="https://www.analyticsvidhya.com/blog/2016/08/beginners-guide-to-topic-modeling-in-python/">Beginners Guide to Topic Modeling in Python</a></p><p><a href="http://blog.echen.me/2011/08/22/introduction-to-latent-dirichlet-allocation/">Introduction to Latent Dirichlet Allocation</a></p><p><a href="https://shuaiw.github.io/2016/12/22/topic-modeling-and-tsne-visualzation.html">Topic Modeling and t-SNE Visualization</a></p><h3>Clustering</h3><p><a href="https://www.youtube.com/watch?v=DLfh8pv4-yQ">Overview of Clustering | Mining of Massive Datasets | Stanford University — YouTube</a></p><p><a href="https://www.analyticsvidhya.com/blog/2016/11/an-introduction-to-clustering-and-different-methods-of-clustering/">An Introduction to Clustering &amp; different methods of clustering</a></p><p><a href="https://towardsdatascience.com/the-5-clustering-algorithms-data-scientists-need-to-know-a36d136ef68">The 5 Clustering Algorithms Data Scientists Need to Know</a></p><p><a href="https://towardsdatascience.com/the-5-clustering-algorithms-data-scientists-need-to-know-a36d136ef68">The 5 Clustering Algorithms Data Scientists Need to Know</a> <a href="https://blog.biolab.si/2015/12/02/hierarchical-clustering-a-simple-explanation/">Hierarchical Clustering: A Simple Explanation | Orange Blog</a></p><h3>Model Evaluation</h3><p><a href="http://blog.exsilio.com/all/accuracy-precision-recall-f1-score-interpretation-of-performance-measures/">Accuracy, Precision, Recall &amp; F1 Score: Interpretation of Performance Measures — Exsilio Blog</a></p><p><a href="http://www.dataschool.io/simple-guide-to-confusion-matrix-terminology/">Simple guide to confusion matrix terminology</a></p><p><a href="http://www.navan.name/roc/">Understanding ROC curves</a></p><p><a href="https://stats.stackexchange.com/questions/65128/nested-cross-validation-for-model-selection">Nested cross validation for model selection — Cross Validated</a></p><p><a href="https://stats.stackexchange.com/questions/52274/how-to-choose-a-predictive-model-after-k-fold-cross-validation">How to choose a predictive model after k-fold cross-validation? — Cross Validated</a></p><p><a href="http://scikit-learn.org/stable/auto_examples/model_selection/plot_nested_cross_validation_iris.html">Nested versus non-nested cross-validation — scikit-learn 0.19.0 documentation</a></p><p><a href="https://www.kdnuggets.com/2018/04/right-metric-evaluating-machine-learning-models-1.html">Choosing the Right Metric for Evaluating Machine Learning Models — Part 1</a></p><p><a href="https://cheevahagadog.github.io/posts/model_explanations/?utm_medium=email&amp;utm_source=optin&amp;utm_campaign=awareness&amp;utm_content=20180502+data+nl&amp;mkt_tok=eyJpIjoiT0RJNFpEZ3daVFpsT1dJNCIsInQiOiJmeStrSFwvVlwvMmpCZXBJREgzc2lyb1JZaWprR2E5ck9nOGhKME5qQmR3SlluTnA3SVlQMWRiME9KYm1adG1yK3g1Q2JyaGdxSlI3aStYOE1yaDJ6c0djMHJvSSsrcXl5b1wvc0dCWTBlQUxhMEVKeWxzUlN1ZGtHUHY1WGlXMTgxbiJ9">Finding out which features contributed to each row’s prediction</a></p><p><a href="https://towardsdatascience.com/beyond-accuracy-precision-and-recall-3da06bea9f6c">Beyond Accuracy: Precision and Recall — Towards Data Science</a></p><p><a href="https://stats.stackexchange.com/questions/132777/what-does-auc-stand-for-and-what-is-it">classification — What does AUC stand for and what is it? — Cross Validated</a></p><p><a href="https://medium.com/towards-data-science/train-test-split-and-cross-validation-in-python-80b61beca4b6">Train/Test Split and Cross Validation in Python — Towards Data Science — Medium</a></p><p><a href="https://elitedatascience.com/imbalanced-classes">How to Handle Imbalanced Classes in Machine Learning</a></p><h3>AB Testing</h3><p><a href="http://hookedondata.org/Guidelines-for-AB-Testing/?utm_medium=email&amp;utm_source=topic+optin&amp;utm_campaign=awareness&amp;utm_content=20180829+data+nl&amp;mkt_tok=eyJpIjoiWXpRM05tRmtNek5sTkRVNCIsInQiOiJleXBZc0ZNWHlRWTMzbTYzNkIzU2ZuVGxiU01TbXhpbDR1WnZrOEVDVml4bjhEeFRsQnJcL3FXYUtrS2tXUmVmdUtZdU05djhGTDNxN3M0SVNTNGR1SkY0MkpBSXlVOVBqSzBaZHNTNXExdldLUWpvUUMxZFBWMWoyN0lPWFdnY0EifQ%3D%3D">Guidelines For Ab Testing — Hooked on Data</a></p><p><a href="https://juliasilge.com/blog/ab-testing/">Julia Silge — From Power Calculations to P-Values: A/B Testing at Stack Overflow</a></p><p><a href="https://eng.uber.com/xp/">Under the Hood of Uber’s Experimentation Platform</a></p><p><a href="https://www.datascience.com/blog/5-alternatives-to-ab-testing">5 Tricks When A/B Testing Is Off The Table</a></p><h3>Ensemble Learning</h3><p><a href="https://www.analyticsvidhya.com/blog/2016/02/complete-guide-parameter-tuning-gradient-boosting-gbm-python/">Complete Guide to Parameter Tuning in Gradient Boosting (GBM) in Python</a></p><p><a href="https://www.kaggle.com/arthurtok/introduction-to-ensembling-stacking-in-python">Introduction to Ensembling/Stacking in Python | Kaggle</a></p><p><a href="https://machinelearningmastery.com/gentle-introduction-gradient-boosting-algorithm-machine-learning/">A Gentle Introduction to the Gradient Boosting Algorithm for Machine Learning — Machine Learning Mastery</a></p><p><a href="https://medium.com/mlreview/gradient-boosting-from-scratch-1e317ae4587d">Gradient Boosting from scratch — ML Review — Medium</a></p><p><a href="http://blog.kaggle.com/2017/01/23/a-kaggle-master-explains-gradient-boosting/">A Kaggle Master Explains Gradient Boosting | No Free Hunch</a> <a href="https://www.youtube.com/watch?v=sRktKszFmSk">(33) Ensembles (3): Gradient Boosting — YouTube</a></p><p><a href="https://www.analyticsvidhya.com/blog/2016/02/complete-guide-parameter-tuning-gradient-boosting-gbm-python/">Complete Guide to Parameter Tuning in Gradient Boosting (GBM) in Python</a></p><p><a href="https://www.kaggle.com/arthurtok/introduction-to-ensembling-stacking-in-python">Introduction to Ensembling/Stacking in Python | Kaggle</a></p><p><a href="https://machinelearningmastery.com/gentle-introduction-gradient-boosting-algorithm-machine-learning/">A Gentle Introduction to the Gradient Boosting Algorithm for Machine Learning — Machine Learning Mastery</a></p><p><a href="https://medium.com/mlreview/gradient-boosting-from-scratch-1e317ae4587d">Gradient Boosting from scratch — ML Review — Medium</a></p><p><a href="http://blog.kaggle.com/2017/01/23/a-kaggle-master-explains-gradient-boosting/">A Kaggle Master Explains Gradient Boosting | No Free Hunch</a> <a href="https://www.youtube.com/watch?v=sRktKszFmSk">(33) Ensembles (3): Gradient Boosting — YouTube</a><a href="http://xgboost.readthedocs.io/en/latest/model.html#">Introduction to Boosted Trees — xgboost 0.71 documentation</a></p><p><a href="https://medium.com/diogo-menezes-borges/ensemble-learning-when-everybody-takes-a-guess-i-guess-ec35f6cb4600">Ensemble Learning: When everybody takes a guess…I guess!</a></p><p><a href="https://medium.com/diogo-menezes-borges/boosting-with-adaboost-and-gradient-boosting-9cbab2a1af81">Boosting with AdaBoost and Gradient Boosting — The Making Of… a Data Scientist — Medium</a></p><p><a href="https://towardsdatascience.com/an-implementation-and-explanation-of-the-random-forest-in-python-77bf308a9b76">An Implementation and Explanation of the Random Forest in Python</a></p><p><a href="http://danielhnyk.cz/how-to-use-xgboost-in-python/">How to use XGBoost in Python</a></p><p><a href="https://medium.com/open-machine-learning-course/open-machine-learning-course-topic-5-ensembles-of-algorithms-and-random-forest-8e05246cbba7">Open Machine Learning Course. Topic 5. Bagging and Random Forest</a></p><p><a href="https://www.analyticsvidhya.com/blog/2015/11/quick-introduction-boosting-algorithms-machine-learning/">Quick Guide to Boosting Algorithms in Machine Learning</a></p><p><a href="https://www.analyticsvidhya.com/blog/2016/03/complete-guide-parameter-tuning-xgboost-with-codes-python/">Complete Guide to Parameter Tuning in XGBoost (with codes in Python)</a></p><p><a href="https://medium.com/diogo-menezes-borges/what-is-gradient-descent-235a6c8d26b0">What in god’s name is Gradient Descent? — The Making Of… a Data Scientist — Medium</a></p><h3>Association Rules</h3><p><a href="http://michael.hahsler.net/research/arules_RUG_2015/demo/">arules: Association Rule Mining with R — A Tutorial</a></p><p><a href="https://medium.com/towards-data-science/a-gentle-introduction-on-market-basket-analysis-association-rules-fa4b986a40ce">A Gentle Introduction on Market Basket Analysis — Association Rules</a> <a href="http://mhahsler.github.io/arulesViz/reference/plot.html">Visualize Association Rules and Itemsets — plot • arulesViz</a></p><p><a href="https://gist.github.com/jyfeather/7460079">Association Rules Demo Using arulesViz · GitHub</a></p><p><a href="http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=7757158">IEEE Xplore Full-Text PDF:</a> <a href="http://michael.hahsler.net/research/Interface2011/arulesViz_talk/Interface11_arulesViz.pdf">Visualizing Association Rules in Hierarchical Groups</a></p><p><a href="http://www.salemmarafi.com/code/market-basket-analysis-with-r/">Market Basket Analysis with R : Salem Marafi</a> <a href="http://www.rdatamining.com/examples/association-rules">Association Rules — RDataMining.com: R and Data Mining</a></p><p><a href="https://datascienceplus.com/implementing-apriori-algorithm-in-r/">Implementing Apriori Algorithm in R | DataScience+</a></p><h3>Scaling data</h3><p><a href="http://blog.minitab.com/blog/adventures-in-statistics-2/when-is-it-crucial-to-standardize-the-variables-in-a-regression-model">When Is It Crucial to Standardize the Variables in a Regression Model?</a></p><p><a href="http://sebastianraschka.com/Articles/2014_about_feature_scaling.html">Feature Scaling and Normalization</a></p><p><a href="https://stats.stackexchange.com/questions/48360/is-standardization-needed-before-fitting-logistic-regression">Is standardization needed before fitting logistic regression? — Cross Validated</a></p><p><a href="https://www.theanalysisfactor.com/changing-the-scale-of-predictor-variables/">Interpreting Regression Coefficients: Changing the scale of predictor variables</a></p><p><a href="https://stackoverflow.com/questions/25481331/how-to-use-scale-in-logistic-regression-correctly">r — How to use scale in logistic regression correctly — Stack Overflow</a></p><h3>Anomaly Detection</h3><p><a href="https://a-little-book-of-r-for-time-series.readthedocs.io/en/latest/src/timeseries.html">Using R for Time Series Analysis — Time Series 0.2 documentation</a></p><p><a href="https://flowingdata.com/2008/02/15/how-to-read-and-use-a-box-and-whisker-plot/">How to Read and Use a Box-and-Whisker Plot | FlowingData</a></p><h3>Logistic Regression</h3><p><a href="https://medium.com/towards-data-science/building-a-logistic-regression-in-python-step-by-step-becd4d56c9c8">Building A Logistic Regression in Python, Step by Step</a></p><p><a href="https://towardsdatascience.com/the-logistic-regression-algorithm-75fe48e21cfa">The Logistic Regression Algorithm — Towards Data Science</a></p><p><a href="https://towardsdatascience.com/5-reasons-logistic-regression-should-be-the-first-thing-you-learn-when-become-a-data-scientist-fcaae46605c4">5 Reasons “Logistic Regression” should be the first thing you learn when becoming a Data Scientist</a></p><p><a href="https://www.youtube.com/playlist?list=PLnnr1O8OWc6YxlVX_qT_YOtgVVGAtzGY5">Logistic Regression Series</a></p><h3>SVM</h3><p><a href="http://www.kdnuggets.com/2016/07/support-vector-machines-simple-explanation.html">Support Vector Machines: A Simple Explanation</a></p><p><a href="https://www.reddit.com/r/MachineLearning/comments/15zrpp/please_explain_support_vector_machines_svm_like_i/">Please explain Support Vector Machines (SVM) like I am a 5 year old. : MachineLearning</a></p><p><a href="https://www.youtube.com/watch?time_continue=712&amp;v=-Z4aojJ-pdg">How Support Vector Machines work / How to open a black box — YouTube</a></p><p><a href="https://www.analyticsvidhya.com/blog/2017/09/understaing-support-vector-machine-example-code/">Understanding Support Vector Machine algorithm from examples (along with code)</a></p><p><a href="http://web.mit.edu/6.034/wwwbob/svm-notes-long-08.pdf">svmrecita.ppt</a></p><p><a href="http://bytesizebio.net/2014/02/05/support-vector-machines-explained-well/">Support Vector Machines explained well | Byte Size Biology</a></p><p><a href="https://www.youtube.com/watch?v=3Xw6FKYP7e4">Kernel Trick — YouTube</a></p><h3>Decision Trees</h3><p><a href="https://medium.com/greyatom/decision-tree-intuition-a38669005cb7">Decision tree Intuition — GreyAtom — Medium</a></p><p><a href="https://rstudio-pubs-static.s3.amazonaws.com/123908_3df6d25c8ad04030a2a429661125a59b.html#/13">Intro to Decision Trees with R Example</a></p><p><a href="https://towardsdatascience.com/decision-trees-and-random-forests-for-classification-and-regression-pt-1-dbb65a458df">Decision Trees and Random Forests for Classification and Regression pt.1</a></p><h3>Dimensionality Reduction</h3><p><a href="https://www.analyticsvidhya.com/blog/2015/07/dimension-reduction-methods/">Beginners Guide To Learn Dimension Reduction Techniques</a></p><p><a href="https://www.kdnuggets.com/2015/05/7-methods-data-dimensionality-reduction.html">Seven Techniques for Data Dimensionality Reduction</a></p><p><a href="https://www.quora.com/Is-having-a-very-large-number-of-features-in-Machine-Learning-ever-a-bad-thing">(2/1) Is having a very large number of features in Machine Learning ever a bad thing? — Quora</a></p><p><a href="https://towardsdatascience.com/a-feature-selection-tool-for-machine-learning-in-python-b64dd23710f0">A Feature Selection Tool for Machine Learning in Python</a></p><p><a href="https://www.kaggle.com/pmarcelino/data-analysis-and-feature-extraction-with-python">Data analysis and feature extraction with Python | Kaggle</a></p><p><a href="https://www.kaggle.com/pmarcelino/data-analysis-and-feature-extraction-with-python/notebook">Data analysis and feature extraction with Python | Kaggle</a></p><h3>Time series forecasting</h3><p><a href="http://ucanalytics.com/blogs/forecasting-time-series-analysis-manufacturing-case-study-example-part-1/">Forecasting &amp; Time Series Analysis — Manufacturing Case Study Example</a></p><p><a href="https://www.analyticsvidhya.com/blog/2015/12/complete-tutorial-time-series-modeling/">A Complete Tutorial on Time Series Modeling in R</a></p><p><a href="https://www.analyticsvidhya.com/blog/2016/02/time-series-forecasting-codes-python/">Complete guide to create a Time Series Forecast (with Codes in Python)</a></p><p><a href="http://ucanalytics.com/blogs/forecasting-time-series-analysis-manufacturing-case-study-example-part-1/">(Part 1) — YOU CANalytics</a></p><p><a href="http://ucanalytics.com/blogs/step-by-step-graphic-guide-to-forecasting-through-arima-modeling-in-r-manufacturing-case-study-example/">Step-by-Step Graphic Guide to Forecasting through ARIMA</a></p><p><a href="https://www.youtube.com/watch?v=FYwTl9s4lVc">ARIMA estimation in R — YouTube</a> <a href="https://www.datascience.com/blog/introduction-to-forecasting-with-arima-in-r-learn-data-science-tutorials">Introduction to Forecasting with ARIMA in R</a></p><p><a href="https://www.youtube.com/watch?v=Aw77aMLj9uM&amp;t=1657s">(31) Time Series Forecasting Theory | AR, MA, ARMA, ARIMA | Data Science — YouTube</a></p><p><a href="https://machinelearningmastery.com/gentle-introduction-autocorrelation-partial-autocorrelation/">A Gentle Introduction to Autocorrelation and Partial Autocorrelation — Machine Learning Mastery</a></p><h3>Others</h3><p><a href="https://medium.com/towards-data-science/data-science-simplified-part-10-an-introduction-to-classification-models-82490f6c171f">An Introduction to Classification Models</a></p><p><a href="https://medium.com/@sifium/machine-learning-types-of-classification-9497bd4f2e14">Types of classification algorithms in Machine Learning</a></p><p><a href="https://github.com/dssg/MLforPublicPolicy">GitHub — dssg/MLforPublicPolicy: Class resources for CAPP 30254 (Machine Learning for Public Policy)</a></p><p><a href="https://www.kdnuggets.com/2017/12/managing-machine-learning-workflows-scikit-learn-pipelines-part-1.html">Managing Machine Learning Workflows with Scikit-learn Pipelines Part 1: A Gentle Introduction</a></p><p><a href="https://towardsdatascience.com/regularization-the-path-to-bias-variance-trade-off-b7a7088b4577">Regularization: the path to bias-variance trade-off</a></p><p><a href="https://www.analyticsvidhya.com/blog/2017/09/common-machine-learning-algorithms/">Essentials of Machine Learning Algorithms (with Python and R Codes)</a></p><p><a href="https://cs.uwaterloo.ca/~ppoupart/teaching/cs485-winter16/">CS485/685 Homepage</a> <a href="https://towardsdatascience.com/data-science-interview-guide-4ee9f5dc778">Data Science Interview Guide — Towards Data Science</a></p><p><a href="http://automl.github.io/auto-sklearn/stable/index.html">auto-sklearn — AutoSklearn 0.3.0 documentation</a></p><p><a href="http://www.fharrell.com/post/stat-ml/?utm_campaign=Data_Elixir&amp;utm_medium=email&amp;utm_source=Data_Elixir_181&amp;utm_medium=email&amp;utm_source=topic+optin&amp;utm_campaign=awareness&amp;utm_content=20180523+data+nl&amp;mkt_tok=eyJpIjoiTW1Ka1lqRTVNakJtWm1KayIsInQiOiJhbWxZNitLSGlYN1FsSUtwR2FFYkNJbHNlNTd4cDNnTnNVbW5XR1lrZTdiYWxCaDRCUzZcLytcL01CNVlJaW9FQ3hOMDlnR3cweXFVQjhIeEY4WEZnMkRHSVJVNmpqUUJaTUFiSVpma2k0ZGpLaWtZakZLWCtUN09pbk5sSG1CM2JrIn0%3D">Road Map for Choosing Between Statistical Modeling and Machine Learning | Statistical Thinking</a></p><p><a href="https://www.kaggle.com/learn/deep-learning">Learn | Kaggle</a> <a href="https://www.kaggle.com/dansbecker/intro-to-deep-learning-and-computer-vision">Intro to Deep Learning and Computer Vision | Kaggle</a></p><p><a href="https://github.com/Squarespace/datasheets">Squarespace/datasheets: Read data from, write data to, and modify the formatting of Google Sheets</a></p><p><a href="https://towardsdatascience.com/interpretability-in-machine-learning-70c30694a05f">Interpreting machine learning models — Towards Data Science</a></p><p><a href="https://github.com/marcotcr/lime">marcotcr/lime: Lime: Explaining the predictions of any machine learning classifier</a></p><h3>Data Visualization</h3><p><a href="https://towardsdatascience.com/february-edition-data-visualization-ee524ca64416">February Edition: Data Visualization — Towards Data Science</a></p><p><a href="https://hbr.org/2016/06/visualizations-that-really-work">Visualizations That Really Work</a></p><p><a href="http://www.storytellingwithdata.com/">storytelling with data</a></p><p><a href="https://www.ted.com/talks/david_mccandless_the_beauty_of_data_visualization">David McCandless: The beauty of data visualization | TED Talk | TED.com</a></p><p><a href="https://towardsdatascience.com/beautiful-data-science-presentations-9e9d8fd91446">Beautiful Data Science Presentations — Towards Data Science</a></p><p><a href="https://towardsdatascience.com/15-stunning-data-visualizations-and-what-you-can-learn-from-them-fc5b78f21fb8">15 Stunning Data Visualizations (And What You Can Learn From Them)</a></p><p><a href="https://terrytangyuan.github.io/2018/02/12/autoplotly-intro/">autoplotly — One Line of R Code to Build Interactive Visualizations for Popular Statistical Results — Yuan’s Blog</a></p><p><a href="http://www.noamross.net/blog/2012/10/5/ggplot-introduction.html">Noam Ross | A quick introduction to ggplot()</a></p><p><a href="https://www.analyticsvidhya.com/blog/2017/07/data-visualisation-made-easy/">Tableau for Beginners — Data Visualisation made easy</a></p><p><a href="https://www.analyticsvidhya.com/blog/2018/01/tableau-for-intermediate-data-science/">Intermediate Tableau guide for data science, business intelligence pros</a></p><p><a href="https://www.analyticsvidhya.com/blog/2018/03/tableau-for-advanced-users-easy-expertise-in-data-visualisation/?utm_source=feedburner&amp;utm_medium=email&amp;utm_campaign=Feed%3A+AnalyticsVidhya+%28Analytics+Vidhya%29">A Step-by-Step Guide to learn Advanced Tableau — for Data Science and Business Intelligence Professionals — Analytics Vidhya</a></p><p><a href="https://flowingdata.com/2016/09/08/beeswarm-plot-in-r-to-show-distributions/">Beeswarm Plot in R to Show Distributions | FlowingData</a></p><p><a href="https://leanpub.com/D3-Tips-and-Tricks">D3 Tips and Tricks… by Malcolm Maclean [Leanpub PDF/iPad/Kindle]</a></p><p><a href="http://dimplejs.org/">dimple — A simple charting API for d3 data visualisations</a></p><p><a href="https://github.com/bloomberg/bqplot">bloomberg/bqplot: Plotting library for IPython/Jupyter Notebooks</a></p><p><a href="https://towardsdatascience.com/data-visualization-with-bokeh-in-python-part-iii-a-complete-dashboard-dc6a86aa6e23">Data Visualization with Bokeh in Python, Part III: Making a Complete Dashboard</a></p><p><a href="https://xeno.graphics/">Xenographics — Weird but (sometimes) useful charts</a></p><p><a href="https://medium.com/@plotlygraphs/introducing-dash-5ecf7191b503">🌟 Introducing Dash 🌟 — plotly — Medium</a></p><p><a href="http://projects.susielu.com/viz-palette?colors=[%22#ffd700%22,%22#ffb14e%22,%22#fa8775%22,%22#ea5f94%22,%22#cd34b5%22,%22#9d02d7%22,%22#0000ff%22]&amp;backgroundColor=%22white%22&amp;fontColor=%22black%22">Viz Palette</a></p><p><a href="https://github.com/mathisonian/awesome-visualization-research?utm_campaign=Data_Elixir&amp;utm_medium=email&amp;utm_source=Data_Elixir_190">mathisonian/awesome-visualization-research: A list of recommended research papers and other readings on data visualization</a></p><p><a href="http://www.biologyforlife.com/interpreting-error-bars.html">Interpreting Error Bars — BIOLOGY FOR LIFE</a></p><p><a href="https://www.data-to-viz.com/caveats.html?utm_campaign=Data_Elixir&amp;utm_medium=email&amp;utm_source=Data_Elixir_191&amp;utm_medium=email&amp;utm_source=topic+optin&amp;utm_campaign=awareness&amp;utm_content=20180801+data+nl&amp;mkt_tok=eyJpIjoiTlRFNFkyVmpaRFV3TmpkaCIsInQiOiJXVzRIOW5tcDhDNmNmbzRmamJaREtxZmlVYjhLZDh2MitJaGROZFpSVCtMUFZGc0YwSThHZXBmSHJtYzdqRzcwdkdieit2NmFDUFwvXC8zMk9MQ2VTckhVZ2Q2dUE2ZkxMMHd1cVJzQk83aWorTSsxd000dU1GeFlEbGxTMFRXZWsrIn0%3D">Data to Viz | A collection of graphic pitfalls</a></p><p><a href="https://github.com/fasouto/awesome-dataviz">fasouto/awesome-dataviz: A curated list of awesome data visualization libraries and resources.</a></p><p><a href="https://policyviz.com/2018/08/07/dataviz-cheatsheet/?utm_medium=email&amp;utm_source=topic+optin&amp;utm_campaign=awareness&amp;utm_content=20180815+data+nl&amp;mkt_tok=eyJpIjoiWmpWaFkyUTNZMlZrTldJeiIsInQiOiJ3Qms4dmU3TklzVW9VQ0dWbWYyVmZ4UVJvR3ZBXC9ERStvd3NLRzVwNTBXXC9cL3gwQ3hHNHV6a0Y5b1Zsb3NUT1Ira0x0cTB5RGZtemViYTNHY0VDVjlwOURNQU40YUhFbitkakpSTXNZVlpjZGFyTDRuUDNnOTBaUkdcLzJzOEQwYWoifQ%3D%3D">DataViz Cheatsheet — Policy Viz</a></p><p><a href="https://towardsdatascience.com/a-comprehensive-guide-to-the-grammar-of-graphics-for-effective-visualization-of-multi-dimensional-1f92b4ed4149">A Comprehensive Guide to the Grammar of Graphics for Effective Visualization of Multi-dimensional…</a></p><p><a href="http://www.teradata.com/Other-Resources/ArtofAnalytics">Art of Analytics | Data Visualization Examples | Teradata</a></p><p><a href="https://jakevdp.github.io/PythonDataScienceHandbook/04.14-visualization-with-seaborn.html">Visualization with Seaborn | Python Data Science Handbook</a></p><h3>Exploratory Data Analysis</h3><p><a href="https://medium.com/district-data-labs/data-exploration-with-python-part-1-643fda933479">Data Exploration with Python, Part 1 — District Data Labs — Medium</a></p><p><a href="https://medium.com/@databrit/5-simple-techniques-for-powerful-data-storytelling-f70d52bcccaf">5 Simple Techniques for Powerful Data Storytelling — Brit Cava — Medium</a></p><p><a href="https://www.kaggle.com/pmarcelino/comprehensive-data-exploration-with-python">Comprehensive data exploration with Python | Kaggle</a></p><p><a href="https://www.r-bloggers.com/dataexplorer-fast-data-exploration-with-minimum-code/amp/">DataExplorer: Fast Data Exploration With Minimum Code | R-bloggers</a></p><p><a href="https://medium.com/topos-ai/the-next-wave-predicting-the-future-of-coffee-in-new-york-city-23a0c5d62000">The Next Wave: Predicting the future of coffee in New York City</a></p><p><a href="https://towardsdatascience.com/exploratory-data-analysis-8fc1cb20fd15">What is Exploratory Data Analysis? — Towards Data Science</a></p><p><a href="http://www.unofficialgoogledatascience.com/2016/10/practical-advice-for-analysis-of-large.html">Practical advice for analysis of large, complex data sets</a></p><p><a href="https://medium.freecodecamp.org/how-to-build-interactive-presentations-with-jupyter-notebook-and-reveal-js-c7e24f4bd9c5">How you can ditch PowerPoint and build better slides with Jupyter and Reveal.js</a></p><p><a href="http://lab.hakim.se/reveal-js/#/4">reveal.js — The HTML Presentation Framework</a> <a href="https://rpubs.com/luisa791222/219682">RPubs — Sun Country HW</a></p><p><a href="http://r4ds.had.co.nz/exploratory-data-analysis.html">R for Data Science</a> <a href="https://www.analyticsvidhya.com/blog/2018/01/tableau-for-intermediate-data-science/?utm_source=sendinblue&amp;utm_campaign=February_2018&amp;utm_medium=email">Intermediate Tableau guide for data science, business intelligence pros</a></p><p><a href="https://www.kaggle.com/kabure/extensive-eda-of-deal-probability">Extensive EDA of Deal Probability | Kaggle</a> <a href="http://nbviewer.jupyter.org/github/PBPatil/Exploratory_Data_Analysis-Wine_Quality_Dataset/blob/master/winequality_white.ipynb">Jupyter Notebook Viewer</a></p><h3>SQL</h3><p><a href="http://1keydata.com/">1Keydata — Free Online Programming Tutorials</a></p><p><a href="http://sqlzoo.net/">SQLZOO</a></p><p><a href="https://stackoverflow.com/questions/3308122/how-do-i-decide-when-to-use-right-joins-left-joins-or-inner-joins-or-how-to-dete">mysql — How do I decide when to use right joins/left joins or inner joins Or how to determine which table is on which side? — Stack Overflow</a></p><p><a href="https://www.linkedin.com/learning/advanced-sql-for-data-scientists">Advanced SQL for Data Scientists</a></p><p><a href="http://www.sqltutorial.org/sql-cheat-sheet/">SQL Cheat Sheet Download PDF it in PDF or PNG Format</a></p><h3>Data Engineering</h3><p><a href="https://highlyscalable.wordpress.com/2012/03/01/nosql-data-modeling-techniques/">NoSQL Data Modeling Techniques — Highly Scalable Blog</a></p><p><a href="https://towardsdatascience.com/designing-data-products-b6b93edf3d23">Designing Data Products — Towards Data Science</a> <a href="https://www.sitepoint.com/sql-vs-nosql-choose/">SQL vs NoSQL: How to Choose — SitePoint</a></p><p><a href="https://medium.com/@rchang/a-beginners-guide-to-data-engineering-part-i-4227c5c457d7">A Beginner’s Guide to Data Engineering — Part I — Robert Chang — Medium</a></p><p><a href="https://eng.uber.com/databook/">Databook: Turning Big Data into Knowledge with Metadata at Uber</a></p><p><a href="https://medium.com/@NetflixTechBlog/notebook-innovation-591ee3221233">Beyond Interactive: Notebook Innovation at Netflix — Netflix Technology Blog — Medium</a></p><p><a href="https://www.civisanalytics.com/blog/workflows-in-python-getting-data-ready-to-build-models/">Workflows in Python: Getting data ready to build models | Civis Analytics</a></p><h3>Software design</h3><p><a href="https://towardsdatascience.com/how-to-write-a-production-level-code-in-data-science-5d87bd75ced">How to write a production-level code in Data Science?</a></p><p><a href="https://towardsdatascience.com/how-docker-can-help-you-become-a-more-effective-data-scientist-7fc048ef91d5">How Docker Can Help You Become A More Effective Data Scientist</a></p><p><a href="https://engineering.videoblocks.com/web-architecture-101-a3224e126947">Web Architecture 101 — VideoBlocks Product &amp; Engineering</a></p><p><a href="https://medium.com/@severinperez/reflections-on-clean-code-8c9b683277ca">Reflections on Clean Code — Severin Perez — Medium</a></p><p><a href="https://medium.com/@julien.topcu/decoupling-your-technical-code-from-your-business-logic-with-the-hexagonal-architecture-hexarch-b4da7ba62079">Decoupling your technical code from your business logic with the Hexagonal Architecture (HexArch)</a></p><p><a href="https://www.locallyoptimistic.com/post/code-as-configuration/?utm_campaign=Data_Elixir&amp;utm_medium=email&amp;utm_source=Data_Elixir_200">Code as Configuration</a> <a href="https://www.designcouncil.org.uk/news-opinion/design-process-what-double-diamond">The Design Process: What is the Double Diamond? | Design Council</a></p><p><a href="https://simplystatistics.org/2018/09/14/divergent-and-convergent-phases-of-data-analysis/?utm_campaign=Data_Elixir&amp;utm_medium=email&amp;utm_source=Data_Elixir_200">Divergent and Convergent Phases of Data Analysis · Simply Statistics</a></p><p><a href="https://medium.com/datadriveninvestor/writing-flexible-code-with-the-single-responsibility-principle-b71c4f3f883f">Writing Flexible Code with the Single Responsibility Principle</a></p><p><a href="https://medium.com/@karpathy/software-2-0-a64152b37c35">Software 2.0 — Andrej Karpathy — Medium</a></p><p><a href="http://www.marknagelberg.com/workflow-to-deploy-and-maintain-a-web-app/">Workflow to Deploy and Maintain a Web App — Mark Nagelberg</a></p><p><a href="http://www.marknagelberg.com/digging-into-data-science-tools-docker/">Digging into Data Science Tools: Docker — Mark Nagelberg</a></p><p><a href="https://blogs.technet.microsoft.com/machinelearning/2018/03/15/demystifying-docker-for-data-scientists-a-docker-tutorial-for-your-deep-learning-projects/">Demystifying Docker for Data Scientists — A Docker Tutorial for Your Deep Learning Projects | Machine Learning Blog</a></p><p><a href="https://blog.insightdatascience.com/getting-started-with-aws-serverless-architecture-tutorial-on-kinesis-and-dynamodb-using-twitter-38a1352ca16d">Tutorial on AWS serverless architecture using Kinesis, DynamoDB and Twitter</a></p><p><a href="https://medium.com/@vladyslavhoncharenko/how-to-index-new-and-existing-amazon-dynamodb-content-with-amazon-elasticsearch-service-30c1bbc91365">How to index new and existing Amazon DynamoDB content with Amazon</a></p><p><a href="https://medium.com/@vladyslavhoncharenko/how-to-index-new-and-existing-amazon-dynamodb-content-with-amazon-elasticsearch-service-30c1bbc91365">Elasticsearch Service.</a> <a href="https://aws.amazon.com/blogs/compute/indexing-amazon-dynamodb-content-with-amazon-elasticsearch-service-using-aws-lambda/">Indexing Amazon DynamoDB Content with Amazon</a></p><p><a href="https://aws.amazon.com/blogs/compute/indexing-amazon-dynamodb-content-with-amazon-elasticsearch-service-using-aws-lambda/">Elasticsearch Service Using AWS Lambda | AWS Compute Blog</a></p><h3>Research</h3><p><a href="https://mlflow.org/">MLflow — A platform for the complete machine learning lifecycle | MLflow</a></p><p><a href="http://luigi.readthedocs.io/en/stable/index.html">Getting Started — Luigi 2.7.6 documentation</a></p><p><a href="https://towardsdatascience.com/deploying-a-machine-learning-model-as-a-rest-api-4a03b865c166">Deploying a Machine Learning Model as a REST API — Towards Data Science</a></p><p><a href="https://github.com/mwouts/jupytext?utm_campaign=Data_Elixir&amp;utm_medium=email&amp;utm_source=Data_Elixir_200">GitHub — mwouts/jupytext: Jupyter notebooks as Markdown documents, Julia, Python or R scripts</a></p><p><a href="https://anatomyof.ai/?utm_campaign=Data_Elixir&amp;utm_medium=email&amp;utm_source=Data_Elixir_200">Anatomy of an AI System</a></p><p><a href="https://superset.incubator.apache.org/">Apache Superset (incubating) — Apache Superset documentation</a></p><h3>Spark</h3><p><a href="https://blog.sicara.com/get-started-pyspark-jupyter-guide-tutorial-ae2fe84f594f">Get Started with PySpark and Jupyter Notebook in 3 Minutes</a></p><p><a href="https://www.datacamp.com/community/tutorials/apache-spark-python">Apache Spark in Python: Beginner’s Guide (article) — DataCamp</a></p><p><a href="https://changhsinlee.com/pyspark-udf/">How to Turn Python Functions into PySpark Functions (UDF) — Chang Hsin Lee — Commiting my thoughts to words.</a></p><p><a href="https://medium.com/civis-analytics/prediction-at-scale-with-scikit-learn-and-pyspark-pandas-udfs-51d5ebfb2cd8">Prediction at Scale with scikit-learn and PySpark Pandas UDFs</a></p><p><a href="https://creativedata.atlassian.net/wiki/spaces/SAP/pages/83237142/Pyspark+-+Tutorial+based+on+Titanic+Dataset">Pyspark — Tutorial based on Titanic Dataset — Saagie User Group Wiki — Saagie</a></p><p><a href="https://github.com/jadianes/spark-py-notebooks">GitHub — jadianes/spark-py-notebooks: Apache Spark &amp; Python (pySpark) tutorials for Big Data Analysis and Machine Learning as IPython / Jupyter notebooks</a></p><p><a href="https://github.com/mahmoudparsian/pyspark-tutorial">mahmoudparsian/pyspark-tutorial: PySpark-Tutorial provides basic algorithms using PySpark</a></p><p><a href="https://www.dezyre.com/article/top-50-spark-interview-questions-and-answers-for-2017/208">Top 50 Spark Interview Questions and Answers for 2017</a></p><h3>Python Resources</h3><h3>Pandas</h3><p><a href="https://medium.com/open-machine-learning-course/open-machine-learning-course-topic-1-exploratory-data-analysis-with-pandas-de57880f1a68">Open Machine Learning Course. Topic 1. Exploratory Data Analysis with Pandas</a></p><p><a href="https://github.com/TomAugspurger/effective-pandas">GitHub — TomAugspurger/effective-pandas: Source code for my collection of articles on using pandas.</a></p><p><a href="https://towardsdatascience.com/pandas-tips-and-tricks-33bcc8a40bb9">Pandas tips and tricks — Towards Data Science</a></p><p><a href="https://jalammar.github.io/visualizing-pandas-pivoting-and-reshaping/">Visualizing Pandas’ Pivoting and Reshaping Functions — Jay Alammar —</a></p><p><a href="https://jalammar.github.io/visualizing-pandas-pivoting-and-reshaping/">Visualizing machine learning one concept at a time</a></p><p><a href="http://pandas.pydata.org/">Pandas Documentation</a> <a href="https://pandas.pydata.org/pandas-docs/stable/10min.html">10 Minutes to pandas — pandas 0.20.3 documentation</a></p><p><a href="https://pandas.pydata.org/pandas-docs/stable/cookbook.html#cookbook">Cookbook — pandas 0.20.3 documentation</a></p><p><a href="https://pandas.pydata.org/pandas-docs/stable/api.html">Pandas API Reference</a></p><p><a href="http://pandas.pydata.org/pandas-docs/stable/merging.html">Merge, join, and concatenate — pandas 0.20.3 documentation</a></p><p><a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html">Reshaping and Pivot Tables — pandas 0.20.3 documentation</a></p><p><a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html">Group By: split-apply-combine — pandas 0.20.3 documentation</a></p><p><a href="http://pandas.pydata.org/pandas-docs/stable/basics.html#vectorized-string-methods">Essential Basic Functionality — pandas 0.20.3 documentation</a></p><p><a href="http://pandas.pydata.org/pandas-docs/version/0.19.2/comparison_with_sql.html">Comparison with SQL — pandas 0.19.2 documentation</a></p><p><a href="http://www.shanelynn.ie/summarising-aggregation-and-grouping-data-in-python-pandas/">Summarising, Aggregating, and Grouping data in Python Pandas | Shane Lynn</a> <a href="http://www.gregreda.com/2013/10/26/working-with-pandas-dataframes/">Working with DataFrames</a></p><p><a href="https://chrisalbon.com/python/pandas_apply_operations_to_groups.html">Apply Operations To Groups In Pandas — Python</a> <a href="https://pandas.pydata.org/pandas-docs/stable/api.html#datetimelike-properties">Datetime properties</a></p><p><a href="https://www.youtube.com/watch?v=OYZNk7Z9s6I">What do I need to know about the pandas index? (Part 1) — YouTube</a></p><p><a href="https://jeffdelaney.me/blog/useful-snippets-in-pandas/">19 Essential Snippets in Pandas</a></p><p><a href="https://docs.scipy.org/doc/numpy/reference/routines.statistics.html">Basic statistical functions</a> <a href="https://docs.scipy.org/doc/numpy/user/quickstart.html">Quickstart tutorial — NumPy v1.13 Manual</a> <a href="https://docs.scipy.org/doc/numpy/search.html">Search page</a></p><p><a href="https://learnpythonthehardway.org/book/ex39.html">Dictionary — Learn Python the hard way</a> <a href="https://www.python.org/dev/peps/pep-0265/">PEP 265 — Sorting Dictionaries by Value | Python.org</a></p><h3>Data viz</h3><p><a href="https://www.datacamp.com/community/tutorials/seaborn-python-tutorial">Python Seaborn Tutorial For Beginners (article) — DataCamp</a></p><p><a href="https://www.datacamp.com/community/tutorials/matplotlib-tutorial-python">Matplotlib Tutorial: Python Plotting (article) — DataCamp</a> <a href="https://stackoverflow.com/questions/22408237/named-colors-in-matplotlib">python — Named colors in matplotlib — Stack Overflow</a></p><p><a href="https://elitedatascience.com/python-seaborn-tutorial">The Ultimate Python Seaborn Tutorial: Gotta Catch ’Em All</a></p><p><a href="https://github.com/ioam/holoviews">GitHub — ioam/holoviews: Stop plotting your data — annotate your data and let it visualize itself.</a></p><p><a href="https://python-graph-gallery.com/">The Python Graph Gallery — Visualizing data — with Python</a></p><p><a href="https://www.dataquest.io/blog/making-538-plots/">How to Generate FiveThirtyEight Graphs in Python</a></p><p><a href="http://explained.ai/decision-tree-viz/index.html?utm_campaign=Data_Elixir&amp;utm_medium=email&amp;utm_source=Data_Elixir_202">How to visualize decision trees</a> <a href="https://medium.com/@enjalot/machine-learning-for-visualization-927a9dff1cab">Machine Learning for Visualization — Ian Johnson — Medium</a></p><h3>Matplotlib</h3><p><a href="https://stackoverflow.com/questions/34162443/why-do-many-examples-use-fig-ax-plt-subplots-in-matplotlib-pyplot-python">Why do many examples use “fig, ax = plt.subplots()” in Matplotlib/pyplot/python — Stack Overflow</a></p><p><a href="https://matplotlib.org/api/pyplot_api.html">pyplot — Matplotlib 2.0.2 documentation</a></p><p><a href="https://matplotlib.org/2.0.2/api/index.html">The Matplotlib API — Matplotlib 2.0.2 documentation</a></p><p><a href="http://matplotlib.org/users/pyplot_tutorial.html">Pyplot tutorial — Matplotlib 2.0.2 documentation</a></p><p><a href="https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.plot.html#matplotlib.axes.Axes.plot">matplotlib.axes.Axes.plot — Matplotlib 2.0.2 documentation</a></p><p><a href="http://www.labri.fr/perso/nrougier/teaching/matplotlib/">Matplotlib tutorial</a></p><h3>Beautiful Soup</h3><p><a href="http://srome.github.io/Parsing-HTML-Tables-in-Python-with-BeautifulSoup-and-pandas/">Parsing HTML Tables in Python with BeautifulSoup and pandas — Scott Rome — Math Ph.D. who works in Machine Learning</a></p><p><a href="https://www.dataquest.io/blog/web-scraping-tutorial-python/">Python Web Scraping Tutorial using BeautifulSoup</a></p><p><a href="http://savvastjortjoglou.com/nba-draft-part01-scraping.html">Learning Python: Part 1 — Scraping and Cleaning the NBA Draft — Savvas Tjortjoglou</a></p><p><a href="https://chrisalbon.com/python/beautiful_soup_scrape_table.html">Scraping a HTML with Beauitful Soup — Python</a></p><p><a href="https://chihacknight.org/blog/2014/11/26/an-intro-to-web-scraping-with-python.html">An Intro to Web Scraping with Python — Chi Hack Night — Chicago’s weekly event to build, share, and learn about civic tech.</a></p><h3>Other interesting stuff</h3><p><a href="https://medium.freecodecamp.org/an-a-z-of-useful-python-tricks-b467524ee747?mkt_tok=eyJpIjoiT1RFeE9EUmlNVFV5WW1GaiIsInQiOiJaeitaeFB3TVJcL1dzZWFKamdLVHAyMTZ5dzNGVnJKMzdsQmFNd1IzWndWNjRIdmozMFwvdk90MnNpNTVHT3NmTU5XSEU5Y2tuaXlVNXA3SjBDNXpxbFFVVGU3VjZDclNqb1JET25lR241QXJwYWtJMG5SVk93WFJBektuODhcL1ZWdCJ9">An A-Z of useful Python tricks — freeCodeCamp.org</a></p><p><a href="https://towardsdatascience.com/trying-out-dask-dataframes-in-python-for-fast-data-analysis-in-parallel-aa960c18a915">How to Run Parallel Data Analysis in Python using Dask Dataframes</a></p><p><a href="http://deon.drivendata.org/?utm_campaign=Data_Elixir&amp;utm_medium=email&amp;utm_source=Data_Elixir_199">About — Deon</a></p><p><a href="https://dask.pydata.org/en/latest/docs.html">Dask — Dask 0.18.2 documentation</a></p><p><a href="https://medium.com/@rodkey/deploying-a-flask-application-on-aws-a72daba6bb80">Deploying a Flask application on AWS — Scott Rodkey — Medium</a> <a href="https://flaskbook.com/">FlaskBook.com</a> <a href="http://exploreflask.com/en/latest/index.html">Explore Flask — Explore Flask 1.0 documentation</a></p><p><a href="https://github.com/Acrotrend/awesome-dash">GitHub — Acrotrend/awesome-dash: A curated list of awesome Dash (plotly) resources</a></p><p><a href="https://www.heatonresearch.com/content/oracle.html">Installing Oracle (cx_Oracle) for Python | Heaton Research</a> <a href="https://www.oracle.com/technetwork/articles/dsl/prez-python-queries-101587.html">Mastering Oracle+Python, Part 1: Querying Best Practices</a></p><p><a href="https://github.com/krzjoa/awesome-python-datascience">GitHub — krzjoa/awesome-python-datascience: Curated list of data science software in Python</a></p><p><a href="https://github.com/cmawer/pycon-2017-eda-tutorial/blob/master/notebooks/1-RedCard-EDA/2-Redcard-Players.ipynb">pycon-2017-eda-tutorial/2-Redcard-Players.ipynb at master · cmawer/pycon-2017-eda-tutorial · GitHub</a></p><p><a href="https://github.com/EpistasisLab/tpot">GitHub — EpistasisLab/tpot: A Python Automated Machine Learning tool that optimizes machine learning pipelines using genetic programming.</a></p><p><a href="https://docs.python.org/2/">Python 2.7.13 documentation</a></p><p><a href="https://elitedatascience.com/python-seaborn-tutorial">The Ultimate Python Seaborn Tutorial: Gotta Catch ’Em All</a></p><p><a href="https://docs.python.org/2/library/functions.html">Built-in Functions — Python 2.7.13 documentation</a></p><p><a href="http://www.greenteapress.com/thinkpython/html/index.html">Think Python</a></p><p><a href="https://pandas.pydata.org/pandas-docs/stable/timedeltas.html">Time Deltas</a></p><h3>R Resources</h3><p><a href="http://www.stat.cmu.edu/~cshalizi/rmarkdown/">Using R Markdown for Class Reports</a> <a href="https://www.youtube.com/watch?v=DNS7i2m4sB0">(6) R Markdown with RStudio — YouTube</a></p><p><a href="http://blog.hackerearth.com/beginners-tutorial-apriori-algorithm-data-mining-r-implementation">A beginner’s tutorial on the apriori algorithm in data mining with R implementation | HackerEarth Blog</a></p><p><a href="http://r-statistics.co/Top50-Ggplot2-Visualizations-MasterList-R-Code.html#top">Top 50 ggplot2 Visualizations — The Master List (With Full R Code)</a></p><p><a href="https://blog.exploratory.io/filter-with-text-data-952df792c2ba">Filter with Text data — learn data science</a></p><h3>dplyr</h3><p><a href="http://nbviewer.jupyter.org/gist/TomAugspurger/6e052140eaa5fdb6e8c0">Dplyr vs Pandas</a></p><p><a href="https://campus.datacamp.com/courses/data-visualization-with-ggplot2-1/chapter-2-data?ex=4">base package and ggplot2, part 3 | R</a></p><p><a href="https://github.com/justmarkham/dplyr-tutorial/blob/master/dplyr-tutorial.Rmd">dplyr-tutorial/dplyr-tutorial.Rmd at master · justmarkham/dplyr-tutorial · GitHub</a></p><p><a href="https://www.yellowdig.com/downloadfiles.php?filename=Gm3jnKR-d4l9ctH-HuuNZDkD459V3dUHblCeIgda6N8&amp;path=upS_ze1Eh2MDRiUbRV8C6QG5dWt1FmRWAXI5omj9jok&amp;uid=-XLTeDg4xovOI4_znPzSXrmDe7VcVUBLvBDajuc8eNo&amp;pid=cIeBAeZcJiFgycPKAMIEZM_26eDXPXHg0Cm6eNpPMv8">data-wrangling-cheatsheet</a></p><p><a href="http://sharpsightlabs.com/blog/data-analysis-example-r-supercars-part2/">Data exploration with ggplot2 and dplyr (code and tutorial)</a></p><p><a href="http://tclavelle.github.io/dplyr-tidyr-tutorial/">Dplyr-tidyr-tutorial by tclavelle</a></p><p><a href="http://r4ds.had.co.nz/tidy-data.html">R for Data Science</a> <a href="https://rpubs.com/bradleyboehmke/data_wrangling">RPubs — Data Processing with dplyr &amp;amp; tidyr</a></p><p><a href="http://rpubs.com/justmarkham/dplyr-tutorial">RPubs — Introduction to dplyr for Faster Data Manipulation in R</a></p><p><a href="https://sesync-ci.github.io/data-manipulation-in-R-lesson/2016/07/26/">Data manipulation with tidyr and dplyr</a></p><p><a href="https://cran.rstudio.com/web/packages/dplyr/vignettes/dplyr.html">Introduction to dplyr</a></p><p><a href="https://github.com/susanli2016/Data-Analysis-with-R">GitHub — susanli2016/Data-Analysis-with-R: Using gglot2, tidyr, dplyr, ggmap, choroplethr, shiny, logistic regression, clustering models and more</a></p><p><a href="https://blog.exploratory.io/working-with-json-data-in-very-simple-way-ad7ebcc0bb89">Working with JSON data in very simple way — learn data science</a></p><p><a href="http://tutorials.iq.harvard.edu/R/Rgraphics/Rgraphics.html">Introduction to R Graphics with &lt;code&gt;ggplot2&lt;/code&gt;</a></p><p><a href="https://www.computerworld.com/article/2935394/business-intelligence/my-ggplot2-cheat-sheet-search-by-task.html">My ggplot2 cheat sheet: Search by task | Computerworld</a></p><p><a href="https://www.rstudio.com/resources/cheatsheets/">Cheatsheets — RStudio</a> <a href="https://github.com/jrnold/ggthemes">GitHub — jrnold/ggthemes: ggplot themes and scales</a> <a href="https://www.rstudio.com/wp-content/uploads/2015/03/ggplot2-cheatsheet.pdf">ggplot2-cheatsheet</a></p><p><a href="http://shiny.stat.ubc.ca/r-graph-catalog/">R Graph Catalog</a> <a href="http://seananderson.ca/ggplot2-FISH554/">seananderson.ca/ggplot2-FISH554/</a></p><p><a href="https://www.analyticsvidhya.com/blog/2016/08/practicing-machine-learning-techniques-in-r-with-mlr-package/">Practicing Machine Learning Techniques in R with MLR Package</a></p><p><a href="http://l2r.cs.uiuc.edu/~danr/Teaching/CS446-17/lectures.html">UIUC Notes</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8018aaa0d1f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Convolutional Neural Network With Tensorflow and Keras]]></title>
            <link>https://medium.com/geekculture/introduction-to-convolutional-neural-network-with-tensorflow-and-keras-cb52cdc66eaf?source=rss-3c0cd74a4676------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb52cdc66eaf</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[whoisslimshady]]></dc:creator>
            <pubDate>Fri, 12 Mar 2021 15:05:22 GMT</pubDate>
            <atom:updated>2021-03-14T09:17:17.549Z</atom:updated>
            <content:encoded><![CDATA[<h3>Convolutional Neural Network With Tensorflow and Keras</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AwajNAlAEAJCD1lFYN-5Xw.jpeg" /></figure><p>In this guide we will learn how to peform <em>image classification and object detection/recognition</em> using <strong>convolutional neural network</strong>. with something called a computer vision</p><p>The goal of our convolutional neural networks will be to classify and detect images or specific objects from within the image. We will be using image data as our features and a label for those images as our label or output.</p><p>We already know how neural networks work so we can skip through the basics and move right into explaining the following concepts.</p><ul><li>Image Data</li><li>Convolutional Layer</li><li>Pooling Layer</li><li>CNN Architectures</li></ul><p>The major differences we are about to see in these types of neural networks are the layers that make them up.</p><h3>Image Data</h3><p>Now we are about to deal with image data that is usually made up of 3 dimensions. These 3 dimensions are as follows:</p><ul><li>image height</li><li>image width</li><li>color channels</li></ul><p>The only item in the list above you may not understand is <strong>color channels</strong>. The number of color channels represents the depth of an image and coorelates to the colors used in it. For example, an image with three channels is likely made up of rgb (red, green, blue) pixels. So, for each pixel we have three numeric values in the range 0–255 that define its color. For an image of color depth 1 we would likely have a greyscale image with one value defining each pixel, again in the range of 0–255.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*VZ2D3BS9avtqzOMvj-9vbQ.png" /><figcaption>Keep this in mind as we discuss how our network works and the input/output of each layer.</figcaption></figure><h3>Convolutional Neural Network</h3><p><strong>Note:</strong> I will use the term <em>convnet</em> and convolutional neural network interchangeably.</p><p>Each convolutional neural network is made up of one or many convolutional layers. These layers are different than the <em>dense</em> layers we have seen previously. Their goal is to find patterns from within images that can be used to classify the image or parts of it. But this may sound familiar to what our densely connected neural network in the previous section was doing, well that’s because it is.</p><p>The fundamental difference between a dense layer and a convolutional layer is that dense layers detect patterns globally while convolutional layers detect patterns locally. When we have a densly connected layer each node in that layer sees all the data from the previous layer. This means that this layer is looking at all the information and is only capable of analyzing the data in a global capacity. Our convolutional layer however will not be densly connected, this means it can detect local patterns using part of the input data to that layer.</p><p><em>Let’s have a look at how a densely connected layer would look at an image vs how a convolutional layer would.</em></p><p>This is our image; the goal of our network will be to determine whether this image is a cat or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rAbCk0T4rksShBcPQjWC0A.gif" /></figure><p><strong>Dense Layer:</strong> A dense layer will consider the ENTIRE image. It will look at all the pixels and use that information to generate some output.</p><p><strong>Convolutional Layer:</strong> The convolutional layer will look at specific parts of the image. In this example let’s say it analyzes the highlighted parts below and detects patterns there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o56wiQbp8HySiLGVXxqXQA.png" /></figure><p>Can you see why this might make these networks more useful?</p><h3>How They Work</h3><p>A dense neural network learns patterns that are present in one specific area of an image. This means if a pattern that the network knows is present in a different area of the image it will have to learn the pattern again in that new area to be able to detect it.</p><p><em>Let’s use an example to better illustrate this.</em></p><p>We’ll consider that we have a dense neural network that has learned what an eye looks like from a sample of dog images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NYNnG1afCYYEXMQV_-g89A.png" /></figure><p>Let’s say it’s determined that an image is likely to be a dog if an eye is present in the boxed off locations of the image above.</p><p>Now let’s flip the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pDLDlrLTcccO43NtNMBAJw.png" /></figure><p>Since our densely connected network has only recognized patterns globally it will look where it thinks the eyes should be present. Clearly it does not find them there and therefore would likely determine this image is not a dog. Even though the pattern of the eyes is present, it’s just in a different location.</p><p>Since convolutional layers learn and detect patterns from different areas of the image, they don’t have problems with the example we just illustrated. They know what an eye looks like and by analyzing different parts of the image can find where it is present.</p><h3>Multiple Convolutional Layers</h3><p>In our models it is quite common to have more than one convolutional layer. Even the basic example we will use in this guide will be made up of 3 convolutional layers. These layers work together by increasing complexity and abstraction at each subsequent layer. The first layer might be responsible for picking up edges and short lines, while the second layer will take as input these lines and start forming shapes or polygons. Finally, the last layer might take these shapes and determine which combinations make up a specific image.</p><h3>Feature Maps</h3><p>You may see me use the term <em>feature map</em> throughout this tutorial. This term simply stands for a 3D tensor with two special axes (width and height) and one depth axis. Our convolutional layers take feature maps as their input and return a new feature map that reprsents the prescence of spcific filters from the previous feature map. These are what we call <em>response maps</em>.</p><h3>Layer Parameters</h3><p>A convolutional layer is defined by two key parameters.</p><h4>Filters</h4><p>A filter is a m x n pattern of pixels that we are looking for in an image. The number of filters in a convolutional layer represents how many patterns each layer is looking for and what the depth of our response map will be. If we are looking for 32 different patterns/filters than our output feature map (aka the response map) will have a depth of 32. Each one of the 32 layers of depth will be a matrix of some size containing values indicating if the filter was present at that location or not.</p><p>Here’s a great illustration from the book “Deep Learning with Python” by Francois Chollet (pg 124).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqDHVFg7VJgpwHe60zJIkA.png" /></figure><h4>Sample Size</h4><p>This isn’t really the best term to describe this, but each convolutional layer is going to examine n x m blocks of pixels in each image. Typically, we’ll consider 3x3 or 5x5 blocks. In the example above we use a 3x3 “sample size”. This size will be the same as the size of our filter.</p><p>Our layers work by sliding these filters of n x m pixels over every possible position in our image and populating a new feature map/response map indicating whether the filter is present at each location.</p><h3>Borders and Padding</h3><p>The more mathematical of you may have realized that if we slide a filter of let’s say size 3x3 over our image well consider less positions for our filter than pixels in our input. Look at the example below.</p><p><em>Image from “Deep Learning with Python” by Francois Chollet (pg 126).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OOABoO6uP2K8kjWwpbeUDg.png" /></figure><p>This means our response map will have a slightly smaller width and height than our original image. This is fine but sometimes we want our response map to have the same dimensions. We can accomplish this by using something called <em>padding</em>.</p><p><strong>Padding</strong> is simply the addition of the appropriate number of rows and/or columns to your input data such that each pixel can be centered by the filter.</p><h3>Strides</h3><p>In the previous sections we assumed that the filters would be slid continously through the image such that it covered every possible position. This is common but sometimes we introduce the idea of a <strong>stride</strong> to our convolutional layer. The stride size reprsents how many rows/cols we will move the filter each time. These are not used very frequently so we’ll move on.</p><h3>Pooling</h3><p>You may recall that our convnets are made up of a stack of convolution and pooling layers.</p><p>The idea behind a pooling layer is to down sample our feature maps and reduce their dimensions. They work in a similar way to convolutional layers where they extract windows from the feature map and return a response map of the max, min or average values of each channel. Pooling is usually done using windows of size 2x2 and a stride of 2. This will reduce the size of the feature map by a factor of two and return a response map that is 2x smaller.</p><h3>A More Detailed Look</h3><p>Please refer to the video of legend andrew ng to learn how all of this happens at the lower level!</p><h3>Creating a Convnet</h3><p>Now it is time to create our first convnet! This example is for the purpose of getting familiar with CNN architectures, we will talk about how to improves its performance later.</p><p><em>This tutorial is based on the following guide from the TensorFlow documentation: </em><a href="https://www.tensorflow.org/tutorials/images/cnn"><em>https://www.tensorflow.org/tutorials/images/cnn</em></a></p><h3>Dataset</h3><p>The problem we will consider here is classifying 10 different everyday objects. The dataset we will use is built into tensorflow and called the <a href="https://www.cs.toronto.edu/~kriz/cifar.html"><strong>CIFAR Image Dataset.</strong></a> It contains 60,000 32x32 color images with 6000 images of each class.</p><p>The labels in this dataset are the following:</p><ul><li>Airplane</li><li>Automobile</li><li>Bird</li><li>Cat</li><li>Deer</li><li>Dog</li><li>Frog</li><li>Horse</li><li>Ship</li><li>Truck</li></ul><p>We’ll load the dataset and have a look at some of the images below.</p><pre>%tensorflow_version 2.x  # this line is not required unless you are in a notebook</pre><pre>import tensorflow as tf</pre><pre>from tensorflow.keras import datasets, layers, models</pre><pre>import matplotlib.pyplot as plt</pre><pre>#  LOAD AND SPLIT DATASET</pre><pre>(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()</pre><pre># Normalize pixel values to be between 0 and 1</pre><pre>train_images, test_images = train_images / 255.0, test_images / 255.0</pre><pre>class_names = [&#39;airplane&#39;, &#39;automobile&#39;, &#39;bird&#39;, &#39;cat&#39;, &#39;deer&#39;,&#39;dog&#39;, &#39;frog&#39;, &#39;horse&#39;, &#39;ship&#39;, &#39;truck&#39;]<br>IMG_INDEX = 7  # change this to look at other images</pre><pre>plt.imshow(train_images[IMG_INDEX] ,cmap=plt.cm.binary)</pre><pre>plt.xlabel(class_names[train_labels[IMG_INDEX][0]])</pre><pre>plt.show()</pre><h3>CNN Architecture</h3><p>A common architecture for a CNN is a stack of Conv2D and MaxPooling2D layers followed by a few densely connected layers. To idea is that the stack of convolutional and maxPooling layers extract the features from the image. Then these features are flattened and fed to densely connected layers that determine the class of an image based on the presence of features.</p><p>We will start by building the <strong>Convolutional Base</strong>.</p><pre>model = models.Sequential()</pre><pre>model.add(layers.Conv2D(32, (3, 3), activation=’relu’, input_shape=(32, 32, 3)))</pre><pre>model.add(layers.MaxPooling2D((2, 2)))</pre><pre>model.add(layers.Conv2D(64, (3, 3), activation=’relu’))</pre><pre>model.add(layers.MaxPooling2D((2, 2)))</pre><pre>model.add(layers.Conv2D(64, (3, 3), activation=’relu’))</pre><p><strong>Layer 1</strong></p><p>The input shape of our data will be 32, 32, 3 and we will process 32 filters of size 3x3 over our input data. We will also apply the activation function relu to the output of each convolution operation.</p><p><strong>Layer 2</strong></p><p>This layer will perform the max pooling operation using 2x2 samples and a stride of 2.</p><p><strong>Other Layers</strong></p><p>The next set of layers do very similar things but take as input the feature map from the previous layer. They also increase the frequency of filters from 32 to 64. We can do this as our data shrinks in special dimensions as it passed through the layers, meaning we can afford (computationally) to add more depth.</p><pre>model.summary() # let’s have a look at our model so far</pre><p>After looking at the summary you should notice that the depth of our image increases but the special dimensions reduce drastically.</p><h3>Adding Dense Layers</h3><p>So far, we have just completed the <strong>convolutional base</strong>. Now we need to take these extracted features and add a way to classify them. This is why we add the following layers to our model.</p><pre>model.add(layers.Flatten())</pre><pre>model.add(layers.Dense(64, activation=’relu’))</pre><pre>model.add(layers.Dense(10))<br>model.summary()</pre><p>We can see that the flatten layer changes the shape of our data so that we can feed it to the 64-node dense layer, followed by the final output layer of 10 neurons (one for each class).</p><h3>Training</h3><p>Now we will train and compile the model using the recommended hyper paramaters from tensorflow.</p><p><em>Note: This will take much longer than previous models!</em></p><pre>model.compile(optimizer=’adam’,</pre><pre>loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),</pre><pre>metrics=[‘accuracy’])</pre><pre>history = model.fit(train_images, train_labels, epochs=4,</pre><pre>validation_data=(test_images, test_labels))</pre><h3>Evaluating the Model</h3><p>We can determine how well the model performed by looking at it’s performance on the test data set</p><pre>est_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)</pre><pre>print(test_acc)</pre><p>You should be getting an accuracy of about 70%. This isn’t bad for a simple model like this, but we’ll dive into some better approaches for computer vision below.</p><h3>Working with Small Datasets</h3><p>In the situation where you don’t have millions of images it is difficult to train a CNN from scratch that performs very well. This is why we will learn about a few techniques we can use to train CNN’s on small datasets of just a few thousand images.</p><h3>Data Augmentation</h3><p>To avoid overfitting and create a larger dataset from a smaller one we can use a technique called data augmentation. This is simply performing random transformations on our images so that our model can generalize better. These transformations can be things like compressions, rotations, stretches and even color changes.</p><p>Fortunately, keras can help us do this. Look at the code below to an example of data augmentation.</p><pre>from keras.preprocessing import image</pre><pre>from keras.preprocessing.image import ImageDataGenerator</pre><pre># creates a data generator object that transforms images</pre><pre>datagen = ImageDataGenerator(</pre><pre>rotation_range=40,</pre><pre>width_shift_range=0.2,</pre><pre>height_shift_range=0.2,</pre><pre>shear_range=0.2,</pre><pre>zoom_range=0.2,</pre><pre>horizontal_flip=True,</pre><pre>fill_mode=’nearest’)</pre><pre># pick an image to transform</pre><pre>test_img = train_images[20]</pre><pre>img = image.img_to_array(test_img) # convert image to numpy arry</pre><pre>img = img.reshape((1,) + img.shape) # reshape image</pre><pre>i = 0</pre><pre>for batch in datagen.flow(img, save_prefix=’test’, save_format=’jpeg’): # this loops runs forever until we break, saving images to current directory with specified prefix</pre><pre>plt.figure(i)</pre><pre>plot = plt.imshow(image.img_to_array(batch[0]))</pre><pre>i += 1</pre><pre>if i &gt; 4: # show 4 images</pre><pre>break</pre><pre>plt.show()</pre><h3>Tansfer learning</h3><p>You would have noticed that the model above takes a few minutes to train and only gives an accuaracy of ~70%. This is okay but surely there is a way to improve on this.</p><p>In this section we will talk about using a pretrained CNN as apart of our own custom network to improve the accuracy of our model. We know that CNN’s alone (with no dense layers) don’t do anything other than map the presence of features from our input. This means we can use a pretrained CNN, one trained on millions of images, as the start of our model. This will allow us to have a very good convolutional base before adding our own dense layered classifier at the end. In fact, by using this techique we can train a very good classifier for a realtively small dataset (&lt; 10,000 images). This is because the convnet already has a very good idea of what features to look for in an image and can find them very effectively. So, if we can determine the presence of features all the rest of the model needs to do is determine which combination of features makes a specific image.</p><h3>Fine Tuning</h3><p>When we employ the technique defined above, we will often want to tweak the final layers in our convolutional base to work better for our specific problem. This involves not touching or retraining the earlier layers in our convolutional base but only adjusting the final few. We do this because the first layers in our base are very good at extracting low level features lile lines and edges, things that are similar for any kind of image. Where the later layers are better at picking up very specific features like shapes or even eyes. If we adjust the final layers than we can look for only features relevant to our very specific problem.</p><h3>Using a Pretrained Model</h3><p>In this section we will combine the tecniques we learned above and use a pretrained model and fine tuning to classify images of dogs and cats using a small dataset.</p><p><em>This tutorial is based on the following guide from the TensorFlow documentation: </em><a href="https://www.tensorflow.org/tutorials/images/transfer_learning"><em>https://www.tensorflow.org/tutorials/images/transfer_learning</em></a></p><pre>#Imports</pre><pre>import os</pre><pre>import numpy as np</pre><pre>import matplotlib.pyplot as plt</pre><pre>import tensorflow as tf</pre><pre>keras = tf.keras</pre><h3>Dataset</h3><p>We will load the <em>cats_vs_dogs</em> dataset from the modoule tensorflow_datatsets.</p><p>This dataset contains (image, label) pairs where images have different dimensions and 3 color channels.</p><pre>import tensorflow_datasets as tfds</pre><pre>tfds.disable_progress_bar()</pre><pre># split the data manually into 80% training, 10% testing, 10% validation</pre><pre>(raw_train, raw_validation, raw_test), metadata = tfds.load(</pre><pre>‘cats_vs_dogs’,</pre><pre>split=[‘train[:80%]’, ‘train[80%:90%]’, ‘train[90%:]’],</pre><pre>with_info=True,</pre><pre>as_supervised=True,<br>)</pre><pre>get_label_name = metadata.features[&#39;label&#39;].int2str  # creates a function object that we can use to get labels</pre><pre># display 2 images from the dataset</pre><pre>for image, label in raw_train.take(5):</pre><pre>plt.figure()</pre><pre>plt.imshow(image)</pre><pre>plt.title(get_label_name(label))</pre><h3>Data Preprocessing</h3><p>Since the sizes of our images are all different, we need to convert them all to the same size. We can create a function that will do that for us below.</p><pre>IMG_SIZE = 160 # All images will be resized to 160x160</pre><pre>def format_example(image, label):</pre><pre>“””</pre><pre>returns an image that is reshaped to IMG_SIZE</pre><pre>“””</pre><pre>image = tf.cast(image, tf.float32)</pre><pre>image = (image/127.5) — 1</pre><pre>image = tf.image.resize(image, (IMG_SIZE, IMG_SIZE))</pre><pre>return image, label</pre><p>Now we can apply this function to all our images using .map().</p><pre>train = raw_train.map(format_example)</pre><pre>validation = raw_validation.map(format_example)</pre><pre>test = raw_test.map(format_example)</pre><p>Let’s have a look at our images now.</p><p>[ ]</p><p>for image, label in train.take(2):</p><pre>plt.figure()</pre><pre>plt.imshow(image)</pre><pre>plt.title(get_label_name(label))</pre><pre>Finally we will shuffle and batch the images.</pre><pre>[ ]</pre><pre>BATCH_SIZE = 32</pre><pre>SHUFFLE_BUFFER_SIZE = 1000</pre><pre>train_batches = train.shuffle(SHUFFLE_BUFFER_SIZE).batch(BATCH_SIZE)</pre><pre>validation_batches = validation.batch(BATCH_SIZE)</pre><pre>test_batches = test.batch(BATCH_SIZE)</pre><p>Now if we look at the shape of an original image vs the new image we will see it has been changed.</p><p>[ ]</p><pre>for img, label in raw_train.take(2):</pre><pre>print(“Original shape:”, img.shape)</pre><pre>for img, label in train.take(2):</pre><pre>print(“New shape:”, img.shape)</pre><h3>Picking a Pretrained Model</h3><p>The model we are going to use as the convolutional base for our model is the <strong>MobileNet V2</strong> developed at Google. This model is trained on 1.4 million images and has 1000 different classes.</p><p>We want to use this model but only its convolutional base. So, when we load in the model, we’ll specify that we don’t want to load the top (classification) layer. We’ll tell the model what input shape to expect and to use the predetermined weights from <em>imagenet</em> (Googles dataset).</p><pre>IMG_SHAPE = (IMG_SIZE, IMG_SIZE, 3)</pre><pre># Create the base model from the pre-trained model MobileNet V2</pre><pre>base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,</pre><pre>include_top=False,</pre><pre>weights=’imagenet’)</pre><pre>base_model.summary()</pre><p>At this point this <em>base_model</em> will simply output a shape (32, 5, 5, 1280) tensor that is a feature extraction from our original (1, 160, 160, 3) image. The 32 means that we have 32 layers of differnt filters/features.</p><pre>for image, _ in train_batches.take(1):</pre><pre>pass</pre><pre>feature_batch = base_model(image)</pre><pre>print(feature_batch.shape)</pre><h3>Freezing the Base</h3><p>The term <strong>freezing</strong> refers to disabling the training property of a layer. It simply means we won’t make any changes to the weights of any layers that are frozen during training. This is important as we don’t want to change the convolutional base that already has learned weights.</p><pre>base_model.trainable = False</pre><pre>base_model.summary()</pre><h3>Adding our Classifier</h3><p>Now that we have our base layer setup, we can add the classifier. Instead of flattening the feature map of the base layer we will use a global average pooling layer that will average the entire 5x5 area of each 2D feature map and return to us a single 1280 element vector per filter.</p><pre>global_average_layer = tf.keras.layers.GlobalAveragePooling2D()</pre><p>Finally, we will add the predicition layer that will be a single dense neuron. We can do this because we only have two classes to predict for.</p><pre>prediction_layer = keras.layers.Dense(1)</pre><p>Now we will combine these layers together in a model.</p><pre>model = tf.keras.Sequential([</pre><pre>base_model,</pre><pre>global_average_layer,</pre><pre>prediction_layer</pre><pre>])</pre><pre>model.summary()</pre><h3>Training the Model</h3><p>Now we will train and compile the model. We will use a very small learning rate to ensure that the model does not have any major changes made to it.</p><pre>base_learning_rate = 0.0001</pre><pre>model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=base_learning_rate),</pre><pre>loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),</pre><pre>metrics=[‘accuracy’])</pre><pre># We can evaluate the model right now to see how it does before training it on our new images</pre><pre>initial_epochs = 3</pre><pre>validation_steps=20</pre><pre>loss0,accuracy0 = model.evaluate(validation_batches, steps = validation_steps)</pre><pre># Now we can train it on our images</pre><pre>history = model.fit(train_batches,</pre><pre>epochs=initial_epochs,</pre><pre>validation_data=validation_batches)</pre><pre>acc = history.history[‘accuracy’]</pre><pre>print(acc)</pre><pre>model.save(“dogs_vs_cats.h5”) # we can save the model and reload it at anytime in the future</pre><pre>new_model = tf.keras.models.load_model(‘dogs_vs_cats.h5’)</pre><p>And that’s it for this section on computer vision!</p><h3>Object Detection</h3><p>If you’d like to learn how you can perform object detection and recognition with tensorflow check out the guide below.</p><p><a href="https://github.com/tensorflow/models/tree/master/research/object_detection">https://github.com/tensorflow/models/tree/master/research/object_detection</a></p><h3>Sources</h3><ul><li>“Convolutional Neural Network (CNN) : TensorFlow Core.” TensorFlow, <a href="http://www.tensorflow.org/tutorials/images/cnn">www.tensorflow.org/tutorials/images/cnn</a>.</li><li>“Transfer Learning with a Pretrained ConvNet : TensorFlow Core.” TensorFlow, <a href="http://www.tensorflow.org/tutorials/images/transfer_learning">www.tensorflow.org/tutorials/images/transfer_learning</a>.</li><li>Chollet François. Deep Learning with Python. Manning Publications Co., 2018.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb52cdc66eaf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/introduction-to-convolutional-neural-network-with-tensorflow-and-keras-cb52cdc66eaf">Introduction to Convolutional Neural Network With Tensorflow and Keras</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quake III’s or Fast InvSqrt() or 0x5F3759DF Algorithm]]></title>
            <link>https://whoisslimshady.medium.com/quake-iiis-or-fast-invsqrt-or-0x5f3759df-algorithm-47e6bf5bfa35?source=rss-3c0cd74a4676------2</link>
            <guid isPermaLink="false">https://medium.com/p/47e6bf5bfa35</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c]]></category>
            <dc:creator><![CDATA[whoisslimshady]]></dc:creator>
            <pubDate>Mon, 08 Mar 2021 07:57:39 GMT</pubDate>
            <atom:updated>2021-08-08T07:13:36.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*azvjkGNLs1hDeYsgGV9WoA.jpeg" /></figure><p>In 2005, a game company open-sourced the engine software for their video game Quake 3 arena and after looking in that source code fans of the game discovered an algorithm that was so ingenious it quickly became famous, and the only thing this algorithm does</p><p>IS to calculate the inverse of a square root if I had to write a piece of code that would calculate the inverse of a square root this is how</p><p>I would do it here I’m using the c programming language the same programming language used for quake 3 but to be fair I wouldn’t write the square root in there myself because the design has already figured out how to calculate the square root and the provided algorithm to us in math.h file that we programmers can then just include in our program so what could possibly be so interesting about the quake 3 algorithm</p><p>how does its software calculate inverse square roots at first glance</p><p>it doesn’t seem to make any sense where does this number 0x5f3759df come from what does this have to do with taking square roots and why is there a disgusting curse word in the second comment</p><h3>Prerequisite</h3><p>C, Number system, Newton method, IEEE 754 standards, and basic mathematical skills<br>I will show you how with some cool bit manipulation you can take in for square roots and the algorithm<br> The name fast inverse square root, first of all, why would the game engine want to calculate 1/(x)¹/2<br>if you want to implement physics and lighting or reflections in your game engine</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8MBQ8M5bF4t8Y19vE46lNQ.jpeg" /></figure><p>doing this will helps if the vectors you’re calculating with are normalized to have length 1 because otherwise, your vectors might be too short or too long and when you do physics with the things can go wrong as all of you know the length of a vector is sqrt(x² + y² + z²) <br>And if you don’t happen to notice I think you’ve seen this for two dimensions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dIYWN_JxfcRQ-mgR-zfaxA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqVOqhtFzQ-o_uu1h7AHPg.jpeg" /></figure><p>it’s just Pythagoras theorem so if we want to normalize the vector’s length to 1 we value have to scale everything down by the length of the vector,</p><p>it’s just Pythagoras theorem so if we want to normalize the vector’s length to 1 we value have to scale everything down by the length of the vector,<br>I mean obviously because, if we divide the length of the vector by the length of the vector we obviously get one<br>So all that’s left for us to do is to divide x, y, and z by the length</p><p>x/sqrt(x² + y² + z²), y/sqrt(x² + y² + z²) and z/sqrt(x² + y² + z²)</p><p>Or similarly, multiply by one divided by the length<br>x*(1/sqrt(x² + y² + z²))<br>y*(1/sqrt(x² + y² + z²))</p><p>z*(1/sqrt(x² + y² + z²))</p><p>You might already see where this is going calculating sqrt(x² + y² + z²) is easy and more importantly is how fast in code, you would implement</p><p>x*(1/sqrt(x² + y² + z²))</p><p>All it is is just three multiplications summed up additions and multiplications are common operations that have been designed to be very fast the square root on the other hand is a terribly slow operation and division is not much better this is not good if we have several thousands of surfaces where each has a vector that needs to be normalized but this also means that here we have an opportunity for speed improvements</p><p>If we can find even just an approximation of (1/sqrt(x) as long as it’s fast we can save precious time, So the fast inverse square root is such an approximation with only an error of at most 1% while being three times as fast</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*azvjkGNLs1hDeYsgGV9WoA.jpeg" /></figure><p>Looking at the code again we can see that the beginning is pretty harmless</p><p>we are given a number called number as input the number we’re supposed to take the inverse square root of<br>first with the variable i.<br>we declare a 32-bit number then we declare two 32-bit decimal numbers naming x2 and y and then we store 1.5 into the variable with the obvious name three halves.<br>The next two lines simply copy half of the input into x2.<br>The whole input into y.<br>But it’s after that where the magic happens, take a moment to look at it again well the longer you look at it the less it makes sense and the comments on the right, are not helpful either but they do hint that there are three steps to this algorithm puzzling together these three steps will show us the brilliancy of this algorithm but before we start with these three steps let’s first take a look at binary numbers we said that in the first line</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*jvLH70X2AtXDA6yDCQO-7Q.jpeg" /></figure><p>we declare a 32-bit integer in a c programming language called long,<br>That means we’re given 32 bits and we can represent the number with it but, I think you all know how to do that, but in the next line we declare two decimal numbers in c called float again we’re given 32 bits and we have to represent the decimal number with it how would you do that if you and I were designing decimal numbers this is probably</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k46pfQunCiaJJfgY4v00dw.jpeg" /></figure><p>One way we would do it, To just put a decimal point in the middle, and in front of the decimal point we count in the usual way 1 2 3 4 and so on and after the decimal point, There are no surprises either just remind yourself that this is binary so instead of tenths hundredths and thousands and we have halves fourths eights sixteens and any combination of them like a half and a fourth give you three-fourths also known as 0.75, but this idea is actually terrible we’ve decimated the range of numbers we can represent before we could represent numbers to around 2 billion now only to about 32 000.</p><p>Luckily people much smarter than us have found a better way to make use of those 32 bits they took inspiration from scientific notation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*UKPvI2_dO15zRbAd5AtNsw.jpeg" /></figure><p>the same way we can systematically represent numbers like 23 000 as 2.3 times 10 raised to the 4 and .0034 as 3.4 times 10 raised to the minus 3.</p><p>we can also represent them in a binary system where here for example 1 1 0 0 0 could for example be 1.1 times 2 raised to the 4.</p><p>The standard they came up with takes the name IEEE 754 standard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZOl1JMmcmvqrWooyBwQcw.jpeg" /></figure><p>The IEEE 754 defines the following</p><p>We are as usual given 32 bits the first bit is the sign bit if it is 0 the number is positive and if it is 1 the number is negative, but the numbers quake 3 provides the fast inverse square root is always positive.</p><p>I mean obviously, they’re positive if we would have to calculate 1 divided by the square root of negative 5 something definitely has gone wrong so for the rest of this we ignore the sign bit as it is always 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*AHbrmBYGCiVH0wKTK7aNhA.jpeg" /></figure><p>Then the next 8 bits define the exponent that means 2 raised to the 1 or 2 raised to the 2 or 2 raised to the 3 or 2 raised to the 4 and so on with 8 bits we can represent numbers between 0 and 255, but that’s not exactly what we need we also want negative exponents this is why everything is actually shifted down by 127.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*T4khY24HVSmxiDcQoWn8mg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*SJrbfpqKLW4PZzC9aM-ziQ.jpeg" /></figure><p>So instead of 2 raised to the 4, we actually have 2 raised to the minuses 127, So if we actually want the exponent to be 4, the bits need to be set to 131 because 131 minus 127 is 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iPOBAXCtLX_ifMHgWiP_Hw.jpeg" /></figure><p>The last 23 bits are the mantissa as usual in scientific notation, we want to denote one digit followed by the comma followed by the decimal places but with 23 bits we can represent numbers from 0 to 23, but not including 2 to the 23.</p><p>Again that’s not exactly what we need for scientific notation we need the mantissa to go from 1 to 10 or in binary scientific notation to go from one to two so we could do something that we’ve already done before putting a comma after the first bit this automatically gives us numbers from one to two but this native approach is wasteful.</p><p>As you see the people that designed standard 754 realized that in binary something happens that happens in no other base, look at the first digit in scientific notation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VmDjY7ASea5G001-JyXgFA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7KVPe-8czE3PbieY0UO81A.jpeg" /></figure><p>The first digit is by definition always non-zero but in binary, there is only one digit that is not zero one and, if we know that the first digit will always be a one there is no need to store it thus we can save one bit by moving the comma one digit to the left and fixing an extra one in the number it represents now our mantissa is between one and two even though 23 bits gave us numbers between 0 and 2 to the 23, we scaled them down to get numbers between 0 and 1 and then we added an extra 1 to get numbers between 1 and 2.</p><p>And this already is the main part of IEEE standard 754, but just the so-called normalized numbers the informed viewer knows that the standard also includes denormalized numbers, not a number infinities and two zeros but we won’t go into those because in quake 3 it just happens that these are never inputs into our algorithm otherwise something definitely has gone wrong anyway at no point should our game engine have to normalize a vector with the infinite length, for this algorithm and the rest of this it will be useful to think of the mantissa and exponent as the binary numbers they are if we are given two numbers one being the mantissa and 1 being the exponent 23 bits and 8 bits respectively</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*zQpIYBRTMSoZyKjK8jue1Q.jpeg" /></figure><p>we can get a bit of representation with 2 to the 23 times e plus m</p><p>If you think about it because multiplying e by 2 raised to the 23 just shifts e by 23 digits, so that’s how one could write the bits but we get the actual number behind the bits with this formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*lUvK8yzw33WYWIZ46Biy2w.jpeg" /></figure><p>This should seem familiar to you, here we have the exponent with 127 subtracted from it and here we have the mantissa with the extra one in front but now something completely different for no obvious reason at all let’s take the logarithm of that expression since we’re doing computer science here we take the logarithm base 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*vYjIAuP__1J9axrVhtC1Iw.jpeg" /></figure><p>we simplify take as much as we can take out the exponent, but then we get stuck but not so the creators of quake developer Gary tabouli,</p><p>he knew a trick to get rid of the logarithm you see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*HmuyviKLckbYaA_FHgkj5Q.jpeg" /></figure><p>The trick is an approximation to the log (1+x) for small values of x log(1+x) is approximately equal to x,</p><p>if you think about it this approximation is actually correct for x equals zero and x equals one but we’ll add term mu this correction term can be chosen freely again with mu equal to zero this approximation is correct at zero and one but it turns out that setting mu to number 0.0430 gives the smallest error on average for numbers between zero and one so going back to our formula we apply our trick as (m/2²³) is indeed a value between 0 and 1.</p><p>we rearrange a little bit more and we finally see why we did all those calculations m + e* (1/2²³) appears that’s our bit representation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*wTZGeQLdk3wUgssbXcTaqw.jpeg" /></figure><p>so let’s think about what we just did, we applied the logarithm to our formula and got the bit representation just scaled and shifted by some constants so in some sense the bit represent and the ratio of a number is its own logarithm armed with this knowledge we can finally start with the three steps of the fast inverse square root</p><h3>First step</h3><p>the first step is actually not complicated it just looks complicated because it’s memory address trickery so we stored our number into y, and now we want to do cool bit manipulation tricks with floats, unfortunately, c doesn’t come with the tools we need to do bit manipulation the reason you cannot do bit manipulation on floats is that they were never designed to do so floats are inherently tied to the IEEE standard 754</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*lu2e85ibvhBcl52BLpZm-A.jpeg" /></figure><p>Longs on the other hand were designed to do bit manipulation on them for example here’s one trick bit shifting along to the left doubles it and bit shifting it to the right halves it and, yes if your number is odd you do end up rounding but hey we’re willing to accept such inaccuracies as long as this means that our algorithm is fast in c as pretty much all programming languages</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*knpzRJgJjDORX6Jz22I61A.jpeg" /></figure><p>This does provide a way to convert from a float to a long this conversion does what most programmers needed to do namely convert from a decimal number to an ordinary integer as best as it can do so if we give it float like 3.33 it converts it to an integer in this case 3 but this is not the conversion we need here, first of all, we don’t care about the resulting integer number we want to somehow keep our float and secondly the bits that lie behind our number get all messed up we don’t want this conversion to mess with our bits the only thing we want to do is to put the bits one to one into a long.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*G0exkl3KrtYic6zIzG6vTg.jpeg" /></figure><p>The way you achieve this is to convert the memory address not the number first we get the address of y, this is the address of a float then you convert that address from a float address to a long’s address,</p><p>the address itself doesn’t change but c now thinks that the number living at that address is now long so then you read what’s written at that address, because c now thinks that this is an address of a long, it will read the number at that address as if it were long like this we tricked c by lifting the conversion away from the number itself to the address of that number and that’s how we get the bits of a number into I don’t know what else to say that’s just how c works</p><h3><strong>Second step</strong></h3><p>so let’s just go to the next step the intuition behind the second step is the following remind yourself bit shifting a number to the left doubles it and shifting it to the right halves it, but what would happen if we did something like this to an exponent doubling an exponent square the number and halving the exponent gives us the square root, but now also negating the exponent gives us 1 divided by the square root of x that’s exactly what we need, so let’s remind ourselves what our goal is here we have our numbers stored into y and our goal was to calculate 1/sqrt(y)</p><p>As I’ve already said calculating this directly is too hard and too expensive but we’ve extracted the bits from y and we’ve seen with the IEEE standard 754 that the bits of a number are in some sense its own logarithm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*Gm3mVND1w1uKq8Kv37-A5A.jpeg" /></figure><p>that means in variable i , we have stored log of y up to some scaling and shifting variable i claim that our problem becomes way easier if we work with logs instead of trying so hard to calculate 1/sqrt(y) we instead calculate the log(1/sqrt(y)).</p><p>we rewrite this to log (y)raised to the power of negative 1/2,</p><p>so we can take out the exponent calculating, this is stupidly easy you might think oh no we have a division in there didn’t you say in the beginning that divisions are slow well yes but remember that we can do bit shifts now instead of dividing by 2, we just bit shift once to the right this already explains why we do minus,i bit shifted the ones to the right but why is this number 0x5f37590f here again in the code, well because our logarithm is actually scaled and shifted</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*mzvXzZ3TDsd77Nzb1NJyrQ.jpeg" /></figure><p>so let’s calculate and understand where it comes from, let gamma be our solution then we know that log of gamma equals to the log (y)raised to the power minus a half which equals to minus a half times the log of y</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*9_0K4ZxeILQkAhPVUnoFnQ.jpeg" /></figure><p>now we replace the logarithm with the bit representation and then we just solve for the bits of gamma I’ll spare us the details but</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*GFeUzg7XwFwlfu55mlStwQ.jpeg" /></figure><p>this is the result</p><p>the magic number turns out to be the remnants of the error term mu the scaling factor and the shifting now we have the bits of resolution and we can just reverse the steps from the evil bit hack to get back the actual solution from those bits well actually not the exact solution just an approximation this is why we need the third step</p><h3>Third step — Newton’s method</h3><p>After the previous step, we have a pretty decent approximation but we did pick up some error terms here and there, but thanks to newton’s method we can make a really good approximation out of a decent one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*glGTjxDGyZS_KpKrHLLLYw.jpeg" /></figure><p>newton’s method is a technique that finds a root for a given function meaning it finds an x for which f( x) equals zero, it does so by taking an approximation and returning a better approximation and usually you repeat this process until you’re close enough to the actual solution, but it turns out that here we are already close enough to the actual solution that one iteration suffices to get an error within one percent,</p><p>the only things newton’s method needs is the function and its derivative and what newton’s method does is that it takes an x value and tries to guess by how much it is off from being a root it does so by calculating f of x and its derivative</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*zBvVFazyyZi1p5NTkHGr1w.jpeg" /></figure><p>we can write f of x as y and the derivative as d y over dx we have the ratio between y and the x offset and y itself so to get the x offset we just divide y by the ratio so then we simply subtract this offset to get our new x the informed viewer can now verify that the last line is one such newton iteration applied to the function f of y equals 1 divided by y squared minus x notice that y being a root of this function I equivalent to y being the inverse square root of x</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSNS0nWrCbkLL7h5aOoJlw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmrOO8C_BQPMek9nKJuSyg.jpeg" /></figure><p>I really encourage you to verify this last line of code since it’s really surprising that even though both the function and newton’s method have a division in them the code does not which means that our algorithm is and stays fast now we finally understand the fast inverse square root it only took us the knowledge of the IEEE standard 754 a trick to outsmart the c programming language magic bit operations and the calculus behind newton’s method you</p><p>Source -Youtube and Wikipedia</p><p>As always thanks for reading………………</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47e6bf5bfa35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Neural Networks]]></title>
            <link>https://medium.com/geekculture/introduction-to-neural-networks-4decf5e749a9?source=rss-3c0cd74a4676------2</link>
            <guid isPermaLink="false">https://medium.com/p/4decf5e749a9</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[whoisslimshady]]></dc:creator>
            <pubDate>Sun, 07 Mar 2021 05:42:02 GMT</pubDate>
            <atom:updated>2021-04-05T22:31:04.528Z</atom:updated>
            <content:encoded><![CDATA[<p>In this notebook, you will learn how to create and use a neural network to classify articles of clothing. To achieve this, we will use a sub-module of TensorFlow called <em>keras</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*jQl51GpSWzKS3xwcV_P90Q.png" /></figure><p>Keras</p><p>Before we dive in and start discussing neural networks, I’d like to give a breif introduction to keras.</p><p>From the keras official documentation (<a href="https://keras.io/">https://keras.io/</a>) keras is described as follows.</p><p>“Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano. It was developed with a focus on enabling fast experimentation.</p><p>Use Keras if you need a deep learning library that:</p><ul><li>Allows for easy and fast prototyping (through user friendliness, modularity, and extensibility).</li><li>Supports both convolutional networks and recurrent networks, as well as combinations of the two.</li><li>Runs seamlessly on CPU and GPU.”</li></ul><p>Keras is a very powerful module that allows us to avoid having to build neural networks from scratch. It also hides a lot of mathematical complexity (that otherwise we would have to implement) inside of helpful packages, modules and methods.</p><p>In this guide we will use keras to quickly develop neural networks.</p><h3>What is a Neural Network</h3><p>So, what are these magical things that have been beating chess grandmasters, driving cars, detecting cancer cells and winning video games?</p><p>A deep neural network is a layered representation of data. The term “deep” refers to the presence of multiple layers. Recall that in our core learning algorithms (like linear regression) data was not transformed or modified within the model, it simply existed in one layer. We passed some features to our model, some math was done, an answer was returned. The data was not changed or transformed throughout this process. A neural network processes our data differently. It attempts to represent our data in different ways and in different dimensions by applying specific operations to transform our data at each layer. Another way to express this is that at each layer our data is transformed in order to learn more about it. By performing these transformations, the model can better understand our data and therefore provide a better prediction.</p><h3>How it Works</h3><p>Before going into too much detail I will provide a very surface level explination of how neural networks work on a mathematical level. All the terms and concepts I discuss will be defined and explained in more detail below.</p><p>On a lower level neural networks are simply a combination of elementry math operations and some more advanced linear algebra. Each neural network consists of a sequence of layers in which data passes through. These layers are made up on neurons and the neurons of one layer are connected to the next (see below). These connections are defined by what we call a weight (some numeric value). Each layer also has something called a bias, this is simply an extra neuron that has no connections and holds a single numeric value. Data starts at the input layer and is trasnformed as it passes through subsequent layers. The data at each subsequent neuron is defined as the following</p><p>The equation you just read is called a weighed sum. We will take this weighted sum at each and every neuron as we pass information through the network. Then we will add what’s called a bias to this sum. The bias allows us to shift the network up or down by a constant value. It is like the y-intercept of a line.</p><p>But that equation is the not complete one! We forgot a crucial part, <strong>the activation function</strong>. This is a function that we apply to the equation seen above to add complexity and dimensionality to our network. Our new equation with the addition of an activation function F(x) is seen below.</p><p>Y=(∑ni=0wixi)+b</p><p>w stands for the weight of each connection to the neuron</p><p>x stands for the value of the connected neuron from the previous value</p><p>b stands for the bias at each layer, this is a constant</p><p>n is the number of connections</p><p>Y is the output of the current neuron</p><p>∑ stands for sum</p><p>The equation you just read is called a weighed sum. We will take this weighted sum at each and every neuron as we pass information through the network. Then we will add what’s called a bias to this sum. The bias allows us to shift the network up or down by a constant value. It is like the y-intercept of a line.</p><p>But that equation is the not complete one! We forgot a crucial part, <strong>the activation function</strong>. This is a function that we apply to the equation seen above to add complexity and dimensionality to our network. Our new equation with the addition of an activation function F(x) is seen below.</p><blockquote><em>Y=F((∑ni=0wixi)+b)</em></blockquote><h3>Breaking Down The Neural Network!</h3><p>Before we dive into any code lets break down how a neural network works and what it does.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*A45QNFTWQdGewSN1anYVJA.png" /></figure><h3>Data</h3><p>The type of data a neural network processes varies drastically based on the problem being solved. When we build a neural network, we define what shape and kind of data it can accept. It may sometimes be neccessary to modify our dataset so that it can be passed to our neural network.</p><p>Some common types of data a neural network uses are listed below.</p><ul><li>Vector Data (2D)</li><li>Timeseries or Sequence (3D)</li><li>Image Data (4D)</li><li>Video Data (5D)</li></ul><p>There are of course many different types or data, but these are the main categories.</p><h3>Layers</h3><p>As we mentioned earlier each neural network consists of multiple layers. At each layer a different transformation of data occurs. Our initial input data is fed through the layers and eventually arrives at the output layer where we will obtain the result.</p><h4>Input Layer</h4><p>The input layer is the layer that our initial data is passed to. It is the first layer in our neural network.</p><h4>Output Layer</h4><p>The output layer is the layer that we will retrive our results from. Once the data has passed through all other layers it will arrive here.</p><h4>Hidden Layer(s)</h4><p>All the other layers in our neural network are called “hidden layers”. This is because they are hidden to us, we cannot observe them. Most neural networks consist of at least one hidden layer but can have an unlimited amount. Typically, the more complex the model the more hidden layers.</p><h4>Neurons</h4><p>Each layer is made up of what are called neurons. Neurons have a few different properties that we will discuss later. The important aspect to understand now is that each neuron is responsible for generating/holding/passing ONE numeric value.</p><p>This means that in the case of our input layer it will have as many neurons as we have input information. For example, say we want to pass an image that is 28x28 pixels, thats 784 pixels. We would need 784 neurons in our input layer to capture each of these pixels.</p><p>This also means that our output layer will have as many neurons as we have output information. The output is a little more complicated to understand so I’ll refrain from an example right now but hopefully you’re getting the idea.</p><p>But what about our hidden layers? Well these have as many neurons as we decide. We’ll discuss how we can pick these values later but understand a hidden layer can have any number of neurons.</p><h4>Connected Layers</h4><p>So how are all these layers connected? Well the neurons in one layer will be connected to neurons in the subsequent layer. However, the neurons can be connected in a variety of different ways.</p><p>Take for example <em>Figure 1</em> (look above). Each neuron in one layer is connected to every neuron in the next layer. This is called a <strong>dense</strong> layer. There are many other ways of connecting layers but well discuss those as we see them.</p><h3>Weights</h3><p>Weights are associated with each connection in our neural network. Every pair of connected nodes will have one weight that denotes the strength of the connection between them. These are vital to the inner workings of a neural network and will be tweaked as the neural network is trained. The model will try to determine what these weights should be to achieve the best result. Weights start out at a constant or random value and will change as the network sees training data.</p><h3>Biases</h3><p>Biases are another important part of neural networks and will also be tweaked as the model is trained. A bias is simply a constant value associated with each layer. It can be thought of as an extra neuron that has no connections. The purpose of a bias is to shift an entire activation function by a constant value. This allows a lot more flexibllity when it comes to choosing an activation and training the network. There is one bias for each layer.</p><h3>Activation Function</h3><p>Activation functions are simply a function that is applied to the weighed sum of a neuron. They can be anything we want but are typically higher order/degree functions that aim to add a higher dimension to our data. We would want to do this to introduce more comolexity to our model. By transforming our data to a higher dimension, we can typically make better, more complex predictions.</p><p>A list of some common activation functions and their graphs can be seen below.</p><ul><li>Relu (Rectified Linear Unit)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*LIXbgz7JuR7sczx-ZNCm6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*BwZmaMBaVW8f8lBAQUoytw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*FixIQ1pKLkKoFEbXE3prbA.gif" /></figure><h3>Backpropagation</h3><p>Backpropagation is the fundemental algorithm behind training neural networks. It is what changes the weights and biases of our network. To fully explain this process, we need to start by discussing something called a cost/loss function.</p><h4>Loss/Cost Function</h4><p>As we now know our neural network feeds information through the layers until it eventually reaches an output layer. This layer contains the results that we look at to determine the prediciton from our network. In the training phase it is likely that our network will make many mistakes and poor predicitions. In fact, at the start of training our network doesn’t know anything (it has random weights and biases)!</p><p>We need some way of evaluating if the network is doing well and how well it is doing. For our training data we have the features (input) and the labels (expected output), because of this we can compare the output from our network to the expected output. Based on the difference between these values we can determine if our network has done a good job or poor job. If the network has done a good job, we’ll make minor changes to the weights and biases. If it has done a poor job our changes may be more drastic.</p><p>So, this is where the cost/loss function comes in. This function is responsible for determining how well the network did. We pass it the output and the expected output, and it returns to us some value representing the cost/loss of the network. This effectively makes the networks job to optimize this cost function, trying to make it as low as possible.</p><p>Some common loss/cost functions include.</p><ul><li>Mean Squared Error</li><li>Mean Absolute Error</li><li>Hinge Loss</li></ul><h4>Gradient Descent</h4><p>Gradient descent and backpropagation are closely related. Gradient descent is the algorithm used to find the optimal paramaters (weights and biases) for our network, while backpropagation is the process of calculating the gradient that is used in the gradient descent step.</p><p>Gradient descent requires some pretty advanced calculus and linear algebra to understand so we’ll stay away from that for now. Let’s just read the formal definition for now.</p><p>“Gradient descent is an optimization algorithm used to minimize some function by iteratively moving in the direction of steepest descent as defined by the negative of the gradient. In machine learning, we use gradient descent to update the parameters of our model.” (<a href="https://ml-cheatsheet.readthedocs.io/en/latest/gradient_descent.html">https://ml-cheatsheet.readthedocs.io/en/latest/gradient_descent.html</a>)</p><p>And that’s all we really need to know for now. I’ll direct you to the video for a more in depth explination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*SzVGKaga11mEwpJ1EpQJOw.png" /></figure><h3>Optimizer</h3><p>You may sometimes see the term optimizer or optimization function. This is simply the function that implements the backpropagation algorithm described above. Here’s a list of a few common ones.</p><ul><li>Gradient Descent</li><li>Stochastic Gradient Descent</li><li>Mini-Batch Gradient Descent</li><li>Momentum</li><li>Nesterov Accelerated Gradient</li></ul><p><em>This article explains them quite well is where I’ve pulled this list from.</em></p><p>(<a href="https://medium.com/@sdoshi579/optimizers-for-training-neural-network-59450d71caf6">https://medium.com/@sdoshi579/optimizers-for-training-neural-network-59450d71caf6</a>)</p><h3>Creating a Neural Network</h3><p>Okay now you have reached the exciting part of this tutorial! No more math and complex explinations. Time to get hands on and train a very basic neural network.</p><p><em>As stated earlier this guide is based off of the following TensorFlow tutorial.</em> <a href="https://www.tensorflow.org/tutorials/keras/classification">https://www.tensorflow.org/tutorials/keras/classification</a></p><pre>%tensorflow_version 2.x # this line is not required unless you are in a notebook</pre><pre># TensorFlow and tf.keras</pre><pre>import tensorflow as tf</pre><pre>from tensorflow import keras</pre><pre># Helper libraries</pre><pre>import numpy as np</pre><pre>import matplotlib.pyplot as plt</pre><h3>Dataset</h3><p>For this tutorial we will use the MNIST Fashion Dataset. This is a dataset that is included in keras.</p><p>This dataset includes 60,000 images for training and 10,000 images for validation/testing.</p><pre>fashion_mnist = keras.datasets.fashion_mnist # load dataset</pre><pre>(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() # split into tetsing and training</pre><p>Let&#39;s have a look at this data to see what we are working with.</p><pre> train_images.shape</pre><p>So we’ve got 60,000 images that are made up of 28x28 pixels (784 in total).</p><pre>train_images[0,23,23] # let’s have a look at one pixel</pre><p>Our pixel values are between 0 and 255, 0 being black and 255 being white. This means we have a grayscale image as there are no color channels.</p><pre>train_labels[:10] # let’s have a look at the first 10 training labels</pre><p>Our labels are integers ranging from 0 - 9. Each integer represents a specific article of clothing. We&#39;ll create an array of label names to indicate which is which.</p><pre>class_names = [‘T-shirt/top’, ‘Trouser’, ‘Pullover’, ‘Dress’, ‘Coat’,</pre><pre>‘Sandal’, ‘Shirt’, ‘Sneaker’, ‘Bag’, ‘Ankle boot’]</pre><p>Fianlly let&#39;s look at what some of these images look like!</p><pre>plt.figure()</pre><pre>plt.imshow(train_images[1])</pre><pre>plt.colorbar()</pre><pre>plt.grid(False)</pre><pre>plt.show()<br></pre><h3>Data Preprocessing</h3><p>The last step before creating our model is to <em>preprocess</em> our data. This simply means applying some prior transformations to our data before feeding it the model. In this case we will simply scale all our greyscale pixel values (0–255) to be between 0 and 1. We can do this by dividing each value in the training and testing sets by 255.0. We do this because smaller values will make it easier for the model to process our values.</p><pre>train_images = train_images / 255.0</pre><pre>test_images = test_images / 255.0</pre><h3>Building the Model</h3><p>Now it’s time to build the model! We are going to use a keras <em>sequential</em> model with three different layers. This model represents a feed-forward neural network (one that passes values from left to right). We’ll break down each layer and its architecture below.</p><pre>model = keras.Sequential([</pre><pre>keras.layers.Flatten(input_shape=(28, 28)), # input layer (1)</pre><pre>keras.layers.Dense(128, activation=’relu’), # hidden layer (2)</pre><pre>keras.layers.Dense(10, activation=’softmax’) # output layer (3)</pre><p><strong>Layer 1:</strong> This is our input layer and it will conist of 784 neurons. We use the flatten layer with an input shape of (28,28) to denote that our input should come in in that shape. The flatten means that our layer will reshape the shape (28,28) array into a vector of 784 neurons so that each pixel will be associated with one neuron.</p><p><strong>Layer 2:</strong> This is our first and only hidden layer. The <em>dense</em> denotes that this layer will be fully connected and each neuron from the previous layer connects to each neuron of this layer. It has 128 neurons and uses the rectify linear unit activation function.</p><p><strong>Layer 3:</strong> This is our output later and is also a dense layer. It has 10 neurons that we will look at to determine our models output. Each neuron represnts the probabillity of a given image being one of the 10 different classes. The activation function <em>softmax</em> is used on this layer to calculate a probabillity distribution for each class. This means the value of any neuron in this layer will be between 0 and 1, where 1 represents a high probabillity of the image being that class.</p><h3>Compile the Model</h3><p>The last step in building the model is to define the loss function, optimizer and metrics we would like to track. I won’t go into detail about why we chose each of these right now.</p><pre>model.compile(optimizer=’adam’,</pre><pre>loss=’sparse_categorical_crossentropy’,</pre><pre>metrics=[‘accuracy’])</pre><h3>Training the Model</h3><p>Now it’s finally time to train the model. Since we’ve already done all the work on our data this step is as easy as calling a single method.</p><pre>model.fit(train_images, train_labels, epochs=10)  # we pass the data, labels and epochs and watch the magic!</pre><h3>Evaluating the Model</h3><p>Now it’s time to test/evaluate the model. We can do this quite easily using another builtin method from keras.</p><p>The <em>verbose</em> argument is defined from the keras documentation as: “verbose: 0 or 1. Verbosity mode. 0 = silent, 1 = progress bar.” (<a href="https://keras.io/models/sequential/">https://keras.io/models/sequential/</a>)</p><pre>test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=1)</pre><pre>print(‘Test accuracy:’, test_acc)</pre><p>You’ll likely notice that the accuracy here is lower than when training the model. This difference is reffered to as <strong>overfitting</strong>.</p><p>And now we have a trained model that’s ready to use to predict some values!</p><h3>Making Predictions</h3><p>To make predictions we simply need to pass an array of data in the form we’ve specified in the input layer to .predict() method</p><pre>predictions = model.predict(test_images)</pre><p>This method returns to us an array of predictions for each image we passed it. Let’s have a look at the predictions for image 1.</p><pre>predictions[0]</pre><p>If we wan’t to get the value with the highest score we can use a useful function from numpy called argmax(). This simply returns the index of the maximium value from a numpy array.</p><pre>np.argmax(predictions[0])</pre><p>And we can check if this is correct by looking at the value of the cooresponding test label.</p><pre>test_labels[0]</pre><h3>Verifying Predictions</h3><p>I’ve written a small function here to help us verify predictions with some simple visuals.]</p><pre>COLOR = &#39;white&#39;</pre><pre>plt.rcParams[&#39;text.color&#39;] = COLOR</pre><pre>plt.rcParams[&#39;axes.labelcolor&#39;] = COLOR</pre><pre>def predict(model, image, correct_label):</pre><pre>class_names = [&#39;T-shirt/top&#39;, &#39;Trouser&#39;, &#39;Pullover&#39;, &#39;Dress&#39;, &#39;Coat&#39;,</pre><pre>&#39;Sandal&#39;, &#39;Shirt&#39;, &#39;Sneaker&#39;, &#39;Bag&#39;, &#39;Ankle boot&#39;]</pre><pre>prediction = model.predict(np.array([image]))</pre><pre>predicted_class = class_names[np.argmax(prediction)]</pre><pre>show_image(image, class_names[correct_label], predicted_class)</pre><pre>def show_image(img, label, guess):</pre><pre>plt.figure()</pre><pre>plt.imshow(img, cmap=plt.cm.binary)</pre><pre>plt.title(&quot;Excpected: &quot; + label)</pre><pre>plt.xlabel(&quot;Guess: &quot; + guess)</pre><pre>plt.colorbar()</pre><pre>plt.grid(False)</pre><pre>plt.show()</pre><pre>def get_number():</pre><pre>while True:</pre><pre>num = input(&quot;Pick a number: &quot;)</pre><pre>if num.isdigit():</pre><pre>num = int(num)</pre><pre>if 0 &lt;= num &lt;= 1000:</pre><pre>return int(num)</pre><pre>else:</pre><pre>print(&quot;Try again...&quot;)</pre><pre>num = get_number()</pre><pre>image = test_images[num]</pre><pre>label = test_labels[num]</pre><pre>predict(model, image, label)</pre><p>And that’s pretty much it for an introduction to neural networks!</p><p>“Basic Classification: Classify Images of Clothing : TensorFlow Core.” TensorFlow, <a href="http://www.tensorflow.org/tutorials/keras/classification">www.tensorflow.org/tutorials/keras/classification</a>.</p><p>“Gradient Descent¶.” Gradient Descent — ML Glossary Documentation, <a href="http://www.ml-cheatsheet.readthedocs.io/en/latest/gradient_descent.html">www.ml-cheatsheet.readthedocs.io/en/latest/gradient_descent.html</a>.Chollet François. Deep Learning with Python. Manning Publications Co., 2018.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4decf5e749a9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/introduction-to-neural-networks-4decf5e749a9">Introduction to Neural Networks</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</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 TensorFlow 2.0]]></title>
            <link>https://whoisslimshady.medium.com/introduction-to-tensorflow-2-0-a4d277b89168?source=rss-3c0cd74a4676------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4d277b89168</guid>
            <dc:creator><![CDATA[whoisslimshady]]></dc:creator>
            <pubDate>Fri, 05 Mar 2021 17:51:26 GMT</pubDate>
            <atom:updated>2021-03-05T17:51:26.124Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Czct01dBHTaUJEev-T04IQ.jpeg" /></figure><p>In introduction to TensorFlow 2.0. We will walk through the following topics within the TensorFlow module:</p><ul><li>TensorFlow Install and Setup</li><li>Representing Tensors</li><li>Tensor Shape and Rank</li><li>Types of Tensors</li></ul><p>If you’d like to follow along without installing TensorFlow on your machine you can use <strong>Google Collaboratory</strong>. Collaboratory is a free Jupyter notebook environment that requires no setup and runs entirely in the cloud.</p><h3>Installing TensorFlow</h3><p>To install TensorFlow on your local machine you can use pip.</p><pre>pip install tensorflow</pre><p>If you have a CUDA enabled GPU you can install the GPU version of TensorFlow. You will also need to install some other software which can be found here: <a href="https://www.tensorflow.org/install/gpu">https://www.tensorflow.org/install/gpu</a></p><pre>pip install tensorflow-gpu</pre><h3>Importing TensorFlow</h3><p>The first step here is going to be to select the correct version of TensorFlow from within collabratory!</p><pre>%tensorflow_version 2.x # this line is not required unless you are in a notebook</pre><pre>import tensorflow as tf # now import the tensorflow module</pre><pre>print(tf.version) # make sure the version is 2.x</pre><h3>Tensors</h3><p>“A tensor is a generalization of vectors and matrices to potentially higher dimensions. Internally, TensorFlow represents tensors as n-dimensional arrays of base datatypes.” (<a href="https://www.tensorflow.org/guide/tensor">https://www.tensorflow.org/guide/tensor</a>)</p><p>It should’t surprise you that tensors are a fundemental apsect of TensorFlow. They are the main objects that are passed around and manipluated throughout the program. Each tensor represents a partialy defined computation that will eventually produce a value. TensorFlow programs work by building a graph of Tensor objects that details how tensors are related. Running different parts of the graph allow results to be generated.</p><p>Each tensor has a data type and a shape.</p><p><strong>Data Types Include</strong>: float32, int32, string and others.</p><p><strong>Shape</strong>: Represents the dimension of data.</p><p>Just like vectors and matrices tensors can have operations applied to them like addition, subtraction, dot product, cross product etc.</p><p>In the next sections we will discuss some different properties of tensors. This is to make you more familiar with how tensorflow represnts data and how you can manipulate this data.</p><p>Below is an example of how to create some different tensors.</p><p>You simply define the value of the tensor and the datatype and you are good to go! It’s worth mentioning that usually we deal with tensors of numeric data, it is quite rare to see string tensors.</p><p>For a full list of datatypes please refer to the following guide.</p><p><a href="https://www.tensorflow.org/api_docs/python/tf/dtypes/DType?version=stable">tf.dtypes.DType | TensorFlow Core v2.4.1</a></p><pre>string = tf.Variable(“this is a string”, tf.string)</pre><pre>number = tf.Variable(324, tf.int16)</pre><pre>floating = tf.Variable(3.567, tf.float64)</pre><h3>Rank/Degree of Tensors</h3><p>Another word for rank is degree, these terms simply mean the number of dimensions involved in the tensor. What we created above is a <em>tensor of rank 0</em>, also known as a scalar.</p><p>Now we’ll create some tensors of higher degrees/ranks.</p><pre>rank1_tensor = tf.Variable([“Test”], tf.string)</pre><pre>rank2_tensor = tf.Variable([[“test”, “ok”], [“test”, “yes”]], tf.string)</pre><p><strong>To determine the rank</strong> of a tensor we can call the following method.</p><pre>tf.rank(rank2_tensor)</pre><pre>&lt;tf.Tensor: shape=(), dtype=int32, numpy=2&gt;</pre><p>The rank of a tensor is direclty related to the deepest level of nested lists. You can see in the first example [&quot;Test&quot;] is a rank 1 tensor as the deepest level of nesting is 1. Where in the second example [[&quot;test&quot;, &quot;ok&quot;], [&quot;test&quot;, &quot;yes&quot;]] is a rank 2 tensor as the deepest level of nesting is 2.</p><h3>Shape of Tensors</h3><p>Now that we’ve talked about the rank of tensors it’s time to talk about the shape. The shape of a tensor is simply the number of elements that exist in each dimension. TensorFlow will try to determine the shape of a tensor but sometimes it may be unknown.</p><p>To <strong>get the shape</strong> of a tensor we use the shape attribute.</p><pre>rank2_tensor.shape</pre><h3>Changing Shape</h3><p>The number of elements of a tensor is the product of the sizes of all its shapes. There are often many shapes that have the same number of elements, making it convient to be able to change the shape of a tensor.</p><p>The example below shows how to change the shape of a tensor.</p><pre>tensor1 = tf.ones([1,2,3]) # tf.ones() creates a shape [1,2,3] tensor full of ones</pre><pre>tensor2 = tf.reshape(tensor1, [2,3,1]) # reshape existing data to shape [2,3,1]</pre><pre>tensor3 = tf.reshape(tensor2, [3, -1]) # -1 tells the tensor to calculate the size of the dimension in that place</pre><pre># this will reshape the tensor to [3,3]</pre><pre># The numer of elements in the reshaped tensor MUST match the number in the original</pre><p>Now let’s have a look at our different tensors.</p><pre>print(tensor1)</pre><pre>print(tensor2)</pre><pre>print(tensor3)</pre><pre># Notice the changes in shape</pre><h3>Slicing Tensors</h3><p>You may be familiar with the term “slice” in python and its use on lists, tuples etc. Well the slice operator can be used on tensors to select specific axes or elements.</p><p>When we slice or select elements from a tensor, we can use comma seperated values inside the set of square brackets. Each subsequent value refrences a different dimension of the tensor.</p><p>Ex: tensor[dim1, dim2, dim3]</p><p>I’ve included a few examples that will hopefully help illustrate how we can manipulate tensors with the slice operator.</p><pre># Creating a 2D tensor</pre><pre>matrix = [[1,2,3,4,5],</pre><pre>[6,7,8,9,10],</pre><pre>[11,12,13,14,15],</pre><pre>[16,17,18,19,20]]</pre><pre>tensor = tf.Variable(matrix, dtype=tf.int32)</pre><pre>print(tf.rank(tensor))</pre><pre>print(tensor.shape)</pre><pre>three = tensor[0,2] # selects the 3rd element from the 1st row</pre><pre>print(three) # -&gt; 3</pre><pre>row1 = tensor[0] # selects the first row</pre><pre>print(row1)</pre><pre>column1 = tensor[:, 0] # selects the first column</pre><pre>print(column1)</pre><pre>row_2_and_4 = tensor[1::2] # selects second and fourth row</pre><pre>print(row2and4)</pre><pre>column_1_in_row_2_and_3 = tensor[1:3, 0]</pre><pre>print(column_1_in_row_2_and_3)</pre><h3>Types of Tensors</h3><p>Before we go to far, I will mention that there are diffrent types of tensors. These are the most used and we will talk more in depth about each as they are used.</p><ul><li>Variable</li><li>Constant</li><li>Placeholder</li><li>SparseTensor</li></ul><p>With the execption of Variable all these tensors are immuttable, meaning their value may not change during execution.</p><p>For now, it is enough to understand that we use the Variable tensor when we want to potentially change the value of our tensor.</p><p>thanks for reading……</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4d277b89168" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>