<?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 Qasim Riaz on Medium]]></title>
        <description><![CDATA[Stories by Qasim Riaz on Medium]]></description>
        <link>https://medium.com/@qasimr.1097?source=rss-53c011e34528------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y5JeB8q8an738Go4q9teAg.jpeg</url>
            <title>Stories by Qasim Riaz on Medium</title>
            <link>https://medium.com/@qasimr.1097?source=rss-53c011e34528------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 20:53:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@qasimr.1097/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[Journeying through Fastai: Building an Image Classifier using Kaggle Data]]></title>
            <link>https://medium.com/@qasimr.1097/journeying-through-fastai-building-an-image-classifier-using-kaggle-data-9bc5762fe676?source=rss-53c011e34528------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bc5762fe676</guid>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[fastai]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Qasim Riaz]]></dc:creator>
            <pubDate>Fri, 15 Oct 2021 15:42:17 GMT</pubDate>
            <atom:updated>2022-03-01T17:57:58.091Z</atom:updated>
            <content:encoded><![CDATA[<p>The paradox of choice.</p><p>As an enthusiastic beginner to the field of Deep Learning, I have been inundated by the flood of resources scattered across the internet, each claimed as being ‘the best’.</p><ul><li>PyTorch vs TensorFlow?</li><li>Math vs Coding?</li><li>Coursera vs Udemy?</li></ul><p>If you’re a novice like me, I imagine at some stage in your journey, you must have gone through a similar experience as well — not knowing where to start, not making any progress. Having felt this annoyance, I finally decided to opt for one of the courses I found, and stick with it until completion.</p><p>This course is called Fastai, and it is taught by the wonderful <em>Jeremy Howard.</em></p><h3>What is Fastai?</h3><p>Fastai is a library built on top of PyTorch that provides both high and low-level functionality, simplifying the building and training of state-of-the-art neural networks. Fastai aims to make deep learning accessible to an increasing number of people and encourage them to make use of this technology in clever, creative ways.</p><p>In this article, we will look at just how easy it is to get started with this library and build deep learning models for personal projects.</p><p><a href="https://course.fast.ai/">Practical Deep Learning for Coders - Practical Deep Learning</a></p><h3>Project Scope and Motivation</h3><p>The aim of our project is to build an image classifier, using a pre-trained Convolutional Neural Network. This network should distinguish between the different classes of images by extracting the most important features in each of these class images.</p><p>We will break this process down into digestible chunks for easier understanding.</p><p>Note that the aim of this blogpost is not to teach how convolutional neural networks work or how data augmentation helps improve our model, there are multiple posts that already do a great job at that. Instead, the goal here is to show you the practical applications of fastai, the ease with which they can be achieved, and inspire you, the reader, to run wild with your ideas.</p><p>Let’s get started with our project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*OIbsa7QY1oYegOvYw1vEUg.jpeg" /></figure><h3>Data Collection</h3><p>Data collection and cleaning is one of the most fundamental, and yet so often overlooked part of the deep learning pipeline. There are multiple ways to curate your custom dataset, and fastai even provides methods to <a href="https://course.fast.ai/images">download images</a>.</p><p>For this project, I used Kaggle to find a relevant and interesting dataset: The American Sign Language Alphabet Image data set.</p><p><a href="https://www.kaggle.com/grassknoted/asl-alphabet">ASL Alphabet</a></p><p>As outlined in the dataset description:</p><blockquote>The training data set contains 87,000 images which are 200x200 pixels. There are 29 classes, of which 26 are for the letters A-Z and 3 classes for SPACE, DELETE and NOTHING.</blockquote><blockquote>The test data set contains a mere 28 images, to encourage the use of real-world test images.</blockquote><p>I downloaded the data as a zip file, and then uploaded it on to Google Drive to use it in my model application.</p><h3>Platform</h3><p>Deep learning projects require a GPU to process large amounts of data. For beginner-level projects, I highly recommend the use of <a href="https://research.google.com/colaboratory/">Google Colab</a> for this purpose.</p><p>Fastai provides a tutorial to set up their library in Colab <a href="https://course.fast.ai/start_colab">here</a>. Just make sure to change your hardware accelerator to GPU after connecting. This is done by clicking on Runtime → Change runtime type → Hardware accelerator → GPU.</p><p>If you are not familiar with Colab, you can get an overview of its features through their <a href="https://colab.research.google.com/notebooks/basic_features_overview.ipynb">official tutorial</a>.</p><h3>Code</h3><p>Now we get to the heart of the project.</p><h4>Preparing the Data</h4><p>First, we need to link Google Drive to our Colab Notebook to use the dataset we downloaded.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fddfd7a244bec10f0b9c2169e975e804/href">https://medium.com/media/fddfd7a244bec10f0b9c2169e975e804/href</a></iframe><p>When you run this code, Google will ask you to authenticate your sign in to mount Google Drive onto Colab.</p><p>Once we have our drive mounted, we can install and import the required libraries and unzip the dataset that was uploaded earlier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70b3187048d37d5ba7e73c39bcb3697b/href">https://medium.com/media/70b3187048d37d5ba7e73c39bcb3697b/href</a></iframe><p>Since the data set was fairly large, I chose to unzip the images on the Colab disk rather than on my Google Drive storage. Even though unzipping in this manner is much faster, it means that I will have to repeat this process every time I want to run my model.</p><p>On the flipside, you could choose to unzip the images once to your directory of choice on your drive, by appending the command as follows:</p><pre>!unzip &lt;your zip file directory&gt; -d &lt;target directory&gt;</pre><p>If you follow the same steps as I did, you should note the test and train image folders added to your disk/custom directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*b-bHFLtJhIoQ8lmXfKCEYA.png" /><figcaption>train-test image directories</figcaption></figure><p>The structure of this directory is crucial. Notice how the train folder (and test folder) contains subfolders, each appropriately named according to the class label, and containing the relevant images. Following such a directory structure is highly recommended and makes processing our data much easier.</p><h4>DataBlocks and DataLoaders</h4><p>A DataBlock is essentially a pipeline for assembling your data — describing all the processes that need to be applied to the data to get it ready for ‘loading’. It is used to specify exactly how we want our data to be structured.</p><p>On the flipside, a DataLoader is what actually loads and works with the data in the context of training a machine learning model. This includes allocating the batch size, applying all the processes defined in the DataBlock, allocating memory and much more.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b907f8b43ed28c4d58e17f2b88496e02/href">https://medium.com/media/b907f8b43ed28c4d58e17f2b88496e02/href</a></iframe><p>Multiple parameters are used inside a DataBlock:</p><blockquote>blocks: this is where you define the different types of data that your model will work with. Typically, you pass your input and output data type in a tuple. Since our inputs are images and outputs are classes, our ‘blocks’ are ImageBlock and CategoryBlocks respectively.</blockquote><blockquote>get_items: this function is used to actually pick up the images, from the specified path, when required.</blockquote><blockquote>splitter: defines how the data needs to be split into training and validation. RandomSplitter is just one specific type of splitter method. You can define how much of the data to keep for validation purposes (20% in my case). A seed value may be specified for replicability.</blockquote><blockquote>get_y: defines how to extract the target label from the data. Since all of our images are inside their respective class folders, we use the parent_label method to specify that the target variable for each image is just its respective parent folder name. This is also why storing the data in the file structured defined earlier was so important.</blockquote><blockquote>item_tfms: item transforms is an optional argument used to specify any additional processing that needs to be carried out on each image, when we flow our data through. Details on the exact transformations may be read in the official documentation <a href="https://fastai1.fast.ai/vision.transform.html">here</a>.</blockquote><blockquote>batch_tfms: uses fast.ai’s aug_transforms method to apply a variety of image transformations on each batch of data. This is what is known as data augmentation and is used to generate more variety in the training data and help our model become more generalizable.</blockquote><p>Having defined the specifications of structuring, categorizing and processing the data, we then feed it into our DataLoader by passing it the path to our training images and a batch size of 32.</p><h4>Data Visualization</h4><p>Once we have loaded in our data, we can begin to visualize what it looks like.</p><p>First, we view the distribution of our classes — specifically in our validation set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9243580ace94eb30de0ba1b970eb8a9/href">https://medium.com/media/e9243580ace94eb30de0ba1b970eb8a9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bOWiT1HOW_hSuSaLZLFkcg.png" /></figure><p>Notice that the distribution of the images in the validation dataset is fairly well-balanced. This is a key point in our model training pipeline, as an imbalanced dataset is likely to cause significant issues in model training and validation.</p><blockquote>Tip: path is an object of Python’s <em>pathlib</em> class, which provides convenient methods to deal with filesystem paths.</blockquote><p>Furthermore, we can also view a sample of our training images by calling fast.ai’s handy show_batch method on our dataloader object.</p><pre>dls.show_batch(max_n=9)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*2xSFD5WzRituGsGnf8hR1Q.png" /></figure><p>We can see how our data augmentation steps defined above (in the batch_tfms parameter) have transformed the data.</p><h4>Model Training</h4><p>Now, we will build and train our neural network to classify these images. In the domain of fast.ai, the model being trained is termed as a “learner”. For our purposes, we will use a cnn_learner, modelled on the ResNet34 architecture.</p><blockquote>ResNet34 is a pre-trained model, trained on the popular <a href="https://www.image-net.org/">ImageNet</a> data set. We will apply this model on our data, making use of the parameters that the model has already learned, and fine-tuning them to acclimatize to our data set. This approach is termed <strong><em>transfer learning</em></strong>, and it lies at the heart of fast.ai’s model-building approach.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7e63474c29c0bf7535f2f3e740ddff3/href">https://medium.com/media/b7e63474c29c0bf7535f2f3e740ddff3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*QEBqRTo1wNMViJqcmyzXSw.png" /></figure><p>Calling the fit_one_cycle() method trains the model on our data set for 4 epochs (as specified). The output shows the training and validation losses along with the accuracy which was specified as our metric of choice above.</p><p>First, note that with just four epochs of training, our model is able to achieve <strong>near perfect accuracy of 99.9%! </strong>on the validation data set. The ease with which such accuracy is achieved is one of the key selling points of fast.ai.</p><p>Another interesting thing evident in these results is the loss values. On first glance, it seems strange that the validation loss is far lower than the training loss, even though the model is trained on the training images and is specifically designed to reduce the loss on those images.</p><p>However, this is where some insight comes into play. By default, fast.ai applies our specified image transformations (other than RandomResizedCrop) on the training data, and not on the validation data. This means that the images in the training data set are far trickier and varied than those in the validation data, making it more difficult for the model to classify them.</p><p>We can view this difference by viewing a sample of the validation images only.</p><pre>dls.valid.show_batch(max_n=8, nrows=2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*QD-o4t9UL5Q00C4w5n1yLQ.png" /></figure><p>These images are exactly those provided in the original data set, with just the RandomResizedCrop transformation applied to them, making some of them look more ‘zoomed in’. However, these images are much more straightforward than those depicted earlier, which had gone through multiple batch transformations.</p><p>You can read more about this detail in the resource below:</p><p><a href="https://www.pyimagesearch.com/2019/10/14/why-is-my-validation-loss-lower-than-my-training-loss/">Why is my validation loss lower than my training loss? - PyImageSearch</a></p><p>Finally, once we have trained our model and are happy with its results, we can export its meta data as a .pkl file, and then load it later for inference when required. This means that we won’t have to train our model every time we want to make an inference.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cab85efa8706f1bf1c6ab4fe87ba71c3/href">https://medium.com/media/cab85efa8706f1bf1c6ab4fe87ba71c3/href</a></iframe><h4>Predictions and Results</h4><p>We are now in a position to test the competency of our model on the test data that we had kept aside all this time.</p><p>To make predictions on our test data, we specify the path to the test images and use the get_preds method to generate our model’s predictions on these images.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71c23dbe9e5b1ba3bd792de4f8ed2fdd/href">https://medium.com/media/71c23dbe9e5b1ba3bd792de4f8ed2fdd/href</a></iframe><p>Recall that in our example, the test data set only contains 28 images, each belonging to the classes A — Z and a further two corresponding to ‘nothing’, and ‘space’. This relates to the fact that our preds tensor has 28 rows in total. Moreover, each row has 29 values. This is because our model was trained on 29 classes, and so each value in a particular row represents the probability that our model believes the image belongs to that particular class.</p><p>For instance, the fourth value in the fifth row of preds shows the probability that the model believes the image belongs to class ‘D’, when it actually belongs to class ‘E’.</p><p>Since preds just contains the probabilities associated with each class, we would like to figure out what class has the highest probability for each test image. We do this by using the o2i method provided by fast.ai, which maps the class of an object with its index. Since we have the indices instead, we need to make use of the reverse mapping.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/843eace389e6abf54689384d74a141e3/href">https://medium.com/media/843eace389e6abf54689384d74a141e3/href</a></iframe><p>We can now compare our predictions with the actual test labels. Since get_images_sorted returns the paths of each image, we will have to extract the label of each image manually.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59c456f4450a0f9aea69d7da7ba2463c/href">https://medium.com/media/59c456f4450a0f9aea69d7da7ba2463c/href</a></iframe><p>Since the sum of our comparison list returns 28, this means that our model has achieved <strong>100% </strong>accuracy on the test set. Perfection.</p><p>However, because there are only 28 images in the test set, we can create our own test images and use our model to predict them instead. We can achieve this using the magic of python widgets.</p><p>You can create a simple upload button to load your own image.A</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*EL1B0cm9RckkYRVLMIpn8Q.png" /><figcaption>Widget for uploading custom image</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76b2ea4e2cf1e6f0ba95cc5adce44392/href">https://medium.com/media/76b2ea4e2cf1e6f0ba95cc5adce44392/href</a></iframe><p>The predict method will return a tuple containing the actual class prediction of the model as well as a tensor of probabilities associated with each class — very useful for analyzing and improving the model.</p><h3>Review and Looking Ahead</h3><p>The purpose of this post was to give you a glimpse of the ease with which anyone can get up and running with building deep learning models using fast.ai. The library provides a powerful tool for both beginners and advanced users with its high and low-level usage.</p><p>In this article, we looked at a particular use case of classifying images into the American Sign Language letters they correspond to. We looked at structuring and visualizing the data, model training using transfer learning, and inference on both the provided and custom test sets, whilst achieving state-of-the-art results.</p><p>Looking ahead, we will discuss how to improve our models for real-world applications. Even though our model perfectly predicts the classes of the provided test data set, it makes some mistakes with custom images. Therefore, we can look into making improvements to our model through fine-tuning more of our model parameters, finding better learning rates, or perhaps in our case, using more, varied data for model training.</p><p>Deep learning is an exciting field, and there is room for all of us to learn more about it and produce creative and useful applications. I hope that my post has inspired you to do just that.</p><h3>References</h3><p>You can view the entire code, with comments, on my github:</p><ul><li><a href="https://github.com/qasimr17/fastai/tree/main/asl">fastai/asl at main · qasimr17/fastai</a></li><li><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bc5762fe676" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Intuitive Introduction to Monte Carlo Simulations]]></title>
            <link>https://medium.com/@qasimr.1097/an-intuitive-introduction-to-monte-carlo-simulations-b5f1aabb2d14?source=rss-53c011e34528------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5f1aabb2d14</guid>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[monte-carlo-method]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Qasim Riaz]]></dc:creator>
            <pubDate>Sun, 26 Jul 2020 22:07:22 GMT</pubDate>
            <atom:updated>2020-07-26T22:49:03.287Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SGzZqZCDBrGPchx5" /><figcaption>Photo by <a href="https://unsplash.com/@stevesawusch?utm_source=medium&amp;utm_medium=referral">Steve Sawusch</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A Monte Carlo simulation is simply a method of estimating the value of an unknown quantity using the principles of inferential statistics. In this article, we’ll strip away the complexities from this term and look a little bit at the history, usage and some R code to understand these simulations from an intuitive lens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jtI3dMVU8gvCgOY9K58E6Q.jpeg" /><figcaption>Source: Getty Images</figcaption></figure><h3>History</h3><p>The history and consequent usage of the Monte Carlo Simulations stem from a man’s rather simple desire to win a computer game.</p><p>The Polish scientist, Stanislaw Ulam, while recovering from an illness, was playing a lot of Solitaire, and like most <em>normal </em>people, wanted to establish the odds of winning. Speaking on the chances of winning a standard game, Ulam mentioned <em>“… After spending a lot of time trying to estimate them by pure combinatorial calculations, I wondered whether a more practical method than “abstract thinking” might not be to lay it out say one hundred times and simply observe and count the number of successful plays”. </em>In order to play out these simulations, Ulam collaborated with John Von Neumann, and later worked successfully on the Manhattan project as well. Herein lay the foundations of the simulations that were to become an integral part of statistics.</p><p>These simulations were, rather aptly, named after the gambling hot spot in Monaco — where games of chance, random outcomes and high stakes are the talk of the town.</p><h3>Usage</h3><p>The uses of MC simulations are wide ranging; from statistical physics to finance, there’s a place for Monte Carlo everywhere. However, wherever this technique may be used, the underlying foundation remains the same: <strong>Simulation of random numbers to solve a deterministic process</strong>.</p><blockquote>Randomness → Reality</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vjL1Su99AscZo9yIVhWWLg.jpeg" /><figcaption>Source: <a href="https://projector-video-pdf-converter.datacamp.com/14568/chapter1.pdf">https://projector-video-pdf-converter.datacamp.com/14568/chapter1.pdf</a></figcaption></figure><p>Imagine you had to estimate the probability of obtaining heads from a particular coin, when there is no guarantee that the coin is fair.</p><p>One way to go about it would be to <em>simulate </em>the process of coin-flipping. You could flip the coin twice and might obtain one head and one tail…would you be confident enough to call the coin fair? Probably not. But the idea is to repeat this experiment multiple times. Simulating this a 100, 1000, 10,000 times with the notion that as the number of flips →<strong> ∞</strong>, the fraction of heads observed in the experiment will get closer and closer to the true probability of heads that we’re trying to estimate. Sound familiar?</p><p>This concept of a sample estimate being equal to the true value in the limit is one of the cornerstones of inferential statistics, the all-familiar:</p><blockquote><em>Law of Large Numbers</em><strong><em><br></em></strong><a href="https://www.youtube.com/watch?v=OgO1gpXSUzU">In repeated, independent tests with the same actual probability<strong><em> </em>p<em> </em></strong>of a particular outcome in each test, the chance that the fraction of times that outcome occurs differs from <strong>p<em> </em></strong>converges to zero as the number of trials goes to infinity.</a></blockquote><p>Psst…it is a common, <strong>and incorrect</strong>, misconception to equate this law with the <a href="https://en.wikipedia.org/wiki/Gambler%27s_fallacy">Gambler’s Fallacy</a>.</p><h3>Some Code</h3><p>Now that we have laid the foundations of MC simulations, it is time to turn our attention towards some practical applications.</p><p>Remember <strong>Pi</strong>? What do we know about it? Well, for one, we know that Pi is the ratio of a circle’s circumference to its diameter. Great! But what is Pi’s use here? <br>Well, there’s another way of looking at Pi as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*S09VJzORDiR4TaMyM79rNA.jpeg" /><figcaption>Source: <a href="https://geometryhelp.net/circle-inscribed-square/">https://geometryhelp.net/circle-inscribed-square/</a></figcaption></figure><p>The figure above depicts a circle, with radius <em>r, </em>inscribed within a square. <br>The area of the square is <em>length * length = 2r * 2r = </em><strong><em>4r²</em></strong><em>.<br></em>Meanwhile, the area of the inscribed circle is <strong>πr²</strong>.</p><p>The ratio of the area of the circle to that of the square is thus:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*whe_M-i5-rayPA_YPV1oHg.png" /></figure><blockquote>This means that if we multiply the ratio of the area of a circle inscribed in a square to that of the area of the square by 4, we would obtain the value of pi. Simple enough?</blockquote><p>But there’s a problem. We can’t compute the area of the circle without knowing the value of pi, and we can’t compute the value of pi without knowing the area of the circle…recursion?</p><p>Here’s where Monte Carlo simulations come in. We can obtain an <em>estimate </em>of the value of pi without having to compute any areas at all. Random Sampling!</p><blockquote>The idea is to pick a plethora of random points within the square, and divide the number of points that lie within the circle by the total number of points to obtain an estimate for pi. This estimate will get better as the number of points we pick gets bigger…remember the Law of Large Numbers?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*YSVG2ftAVHMYe0Cixbcyzw.png" /></figure><p>You can simulate this in a program to get a better understanding. Here’s some R code for this purpose.</p><pre>library(animation) # To knit the plots together as a gif<br>library(ggplot2)</pre><pre>n &lt;- c(100,1000,10000,100000,1000000)</pre><pre>saveGIF(<br>for (num in n){</pre><pre>  x &lt;- matrix(runif(num), nrow = num/2)<br>  ins &lt;- x[(x[,1]-0.5)**2 + (x[,2]-0.5)**2 &lt; 0.5**2,] <br>  ins &lt;- as.data.frame(ins)<br>  x &lt;- as.data.frame(x)<br>  estimate &lt;- 4*length(ins$V1)/length(x$V1)</pre><pre>  plot &lt;- ggplot() + geom_point(data=x,aes(V1,V2),color=&#39;red&#39;) +     geom_point(data=ins,aes(V1,V2),color = &#39;blue&#39;)</pre><pre>  plot &lt;- plot + labs(title = &quot;Approximating Pi Using Monte Carlo Simulation&quot;, <br>subtitle = sprintf(&quot;Pi Estimate with %s datapoints is:  %s&quot;,num/2,estimate), x= NULL, y = NULL) <br>  print(plot)<br>}<br>)</pre><p>And the result is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ckZra3HHC1wLoIxWiTbzgQ.gif" /><figcaption>GIF created by author</figcaption></figure><p>Notice how the estimate for Pi gets closer and closer to the actual value as the number of data points increases!</p><blockquote>Monte Carlo simulations are an incredibly powerful tool that can be made use of in a wide range of fields. One particular use case is in the computation of integrals. In situations where an equation is too complex to be integrated easily, the MC method may be applied to estimate this value by calculating areas/volumes in a manner not too dissimilar as the one discussed above. In this, and many more similar cases, finding numerical solutions may well be a far better and quicker method than computing analytical solutions especially in cases where the latter is impossible to find.</blockquote><p>The link below provides an intuitive understanding of MC methods, especially in the context of the example above.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fq6gJ2T0NSwM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dq6gJ2T0NSwM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fq6gJ2T0NSwM%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/0eba120aad9adedf444da3c89ba0abd7/href">https://medium.com/media/0eba120aad9adedf444da3c89ba0abd7/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5f1aabb2d14" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>