<?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 Hussain Anwaar on Medium]]></title>
        <description><![CDATA[Stories by Hussain Anwaar on Medium]]></description>
        <link>https://medium.com/@hussain.anwaar?source=rss-3ff4996b15b5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*N7q088ybWt1zWt20TCKYtA.jpeg</url>
            <title>Stories by Hussain Anwaar on Medium</title>
            <link>https://medium.com/@hussain.anwaar?source=rss-3ff4996b15b5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:17:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hussain.anwaar/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[Intro to Statistical Inference — Part 3: Confidence Interval for Proportion]]></title>
            <link>https://medium.com/intro-to-statistical-inference/intro-to-statistical-inference-part-3-confidence-interval-for-proportion-e45d4776a7b7?source=rss-3ff4996b15b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e45d4776a7b7</guid>
            <category><![CDATA[confidence-interval]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[inferential-statistics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Hussain Anwaar]]></dc:creator>
            <pubDate>Sat, 09 Sep 2023 22:40:37 GMT</pubDate>
            <atom:updated>2023-09-09T22:40:37.553Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro to Statistical Inference — Part 3: Confidence Interval for Proportion</h3><p>By now we know a thing or two about the word “confidence interval” and it’s significance in the world of statistical inference. Last time we discussed how to build a confidence interval if the variable of interest is a continuous variable (<strong>revenue per user</strong> in the grocery store analysis example we worked on previously). We also discussed why do we even need the confidence interval for reporting different stats in the grocery store example for decision making.</p><p>If you need a quick recap on C.I for Means, i highly recommend reading the last article.</p><p><a href="https://medium.com/intro-to-statistical-inference/intro-to-statistical-inference-part-2-confidence-interval-for-mean-and-proportion-2e9befbd191c">Intro to Statistical Inference — Part 2: Confidence Interval for Mean and Proportion</a></p><p>Today we’ll discuss cases where the parameter of interest is not continuous rather it is binary — meaning it takes only two values either a “0” or a “1”. Now if your variable looks something like this, how would you report it?</p><p>Let’s follow the example of grocery store from our last blog where you are working as a data analyst at a local grocery store and you record some data regarding sales daily. Here’s the data you have collected today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*LyUcCVzZnuNOc-bd9-syhg.png" /></figure><p>Revenue is simply “sales per customer”, and the buy flag is whether the customer bought at least one product. So, it would be zero if the customer did not buy anything. Let’s say your manager asked you to report an important metric of “Proportion of people who buy at-least one product during their visit” — It could help you analyze the health of the business where if you track this metric every day and look at it over weeks or months, you would want to see it increasing, if the business is growing and the % of shoppers with at-least one product bought is increasing. This relates directly to revenue growth aswell.</p><p>Here is an example plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sD672nlHIxWhUN9RhqCr2w.png" /></figure><p>Let’s say you gathered the data and calculated the proportion of people who atleast bought one product and it comes out to be 60%, which we know is the point estimate. By this time we know that the point estimate is not enough to make an informed decision, we have to define the variability around the point estimate using confidence interval. And this is what we would learn next.</p><p>Before moving to C.I, i want to introduce an important concept of <strong>Bernoulli Distribution, Bernoulli Trials and The Binomial Distribution.</strong></p><p>Let’s start with the estimate of the metric we have got from data, which is 60%. You see this metric can also be explained as “There is 60% chance that a shopper will buy at least one product”, so we can think of this metric as the probability of buying at least one product. There are two things at play here.</p><ol><li>A binary variable is needed to explain whether a shopper will buy or not</li><li>There is a fixed probability of buying at least one product for every shopper</li></ol><p>Think of it like this, let’s say a new shopper enters your grocery store. If you had to guess whether they would buy a product or not, how would you do it? You would say there is a 60% chance they would buy a single product. In statistics we call this a <strong>Bernoulli trial</strong>, where there are only two outcomes of a trial, and is modeled using the <strong>Bernoulli Distribution</strong> with probability of success as P(Success) &amp; P(Failure) = 1 — P(Success), which in our case is P(Buy ≥ 1 Product) = 0.6 &amp; P(Buy nothing) = 1–0.6 = 0.4. Now imagine imagine you run the analysis one day later, where you have 50 new shoppers who came to the store today and now you have to report the metric. Here, you want to calculate out of 50 people how many successes you will have (meaning how many will buy ≥ 1 product). This is the case of <strong>Binomial Distribution — </strong>It’s a probability distribution used to model the <strong>“Number of Successes from N Bernoulli Trials”.</strong></p><p>In our case we have:</p><ol><li>50 people thus N = 50</li><li>Each can either buy or not buy anything (Hence Bernoulli Trial)</li><li>With some fixed probability of success — which we estimated from our analysis as P = 0.60</li></ol><p>Now you might be asking why this is important. Why did i take this detour of explaining some boring probability concepts. If you have been paying attention, We want to define the confidence interval around this metric P (Proportion of people buying ≥ 1 product = Probability of buying ≥ 1 Product). Above i explained that this “P” models the variable that follows Binomial Distribution. Now remember this as we do the proof of C.I for proportion.</p><p>If you went through the first article, where i explained that to build a confidence interval we need these things:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*Az3N2oOPZ3lS70AU-8O2DA.png" /></figure><p>Where I introduced the concept of sampling distribution and it’s importance. I also mentioned that:</p><p>Point Estimate is the Mean of sampling distribution, whereas the Standard Error is the variance of sampling distribution. If your knowledge on sampling distribution is a bit rusty, please go through this quick article which explains these concepts in detail.</p><p><a href="https://medium.com/intro-to-statistical-inference/intro-to-statistical-inference-part-1-what-is-statistical-inference-43a006c9a71">Intro to Statistical Inference — Part 1: What is Statistical Inference?</a></p><h4><strong>A little recap on how to build Confidence Interval</strong></h4><p>To build the confidence interval we need to build the sampling distribution, which in this case would be achieve by:</p><ul><li>Repeat N times:<br>- Take a sample of let’s say size n = 30, calculate the metric</li></ul><p>Now,</p><p><strong>Point Estimate</strong> = Mean (Metric of all N times we repeated the above experiment)</p><p><strong>Standard Error</strong> = Standard Deviation (Metric of all N times we repeated the above experiment)</p><p>It’s literally as simple as that. But since we made it a point in the first article that we don’t have luxury to draw samples “N” times. We usually only have one sample to draw our inference (Which is the whole point of statistical inference). Now follow this proof to see how we derive the quick and easy mathematical equations for C.I for proportions.</p><h4>Proof</h4><p>Let’s assume a random variable “X” which is used to model <strong>“Number of successes in n Bernoulli trials” —</strong> In simple words X can model situations like: If you toss your coin 10 times, how many time it would come up as heads <strong>OR</strong> If 100 customers visit your grocery stores how many of them buy atleast one thing from the store!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*Am5cwYz-BcAwDAN4Z7HVuA.png" /><figcaption>Proof of C.I for Proportion</figcaption></figure><p>The above proof was to show how we came up with the equations and formulas, i hope it all makes sense to you. Now, the final piece of the puzzle is, how do we calculate the alpha. We are going to use the help of Central Limit Theorem here. We saw in the first blog that if sample size if large enough (N ≥ 30) then sampling distribution of the mean of any random variable follows the normal distribution. There is a proof that shows how the mean of large number of random variables that follow binomial distribution can be estimated using normal distribution (Here’s the link for people who are interested). Thus, we can say that alpha can be estimated through standard normal distribution with given confidence level.</p><p>Here is the code snippet to calculate C.I of our proportion based metric from the data:</p><pre>from scipy.stats import norm<br>alpha = 0.95<br>p_hat = df.buy_flag.mean() # Sample Statistic<br>standard_error = np.sqrt(p_hat * (1-p_hat)/df.shape[0]) # Standard Error<br>critical_value = abs(norm.ppf((1-alpha)/2,0,1)) # Critical Value<br>C_I = [p_hat - critical_value*standard_error, p_hat + critical_value*standard_error]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*r2iV7tZRcjXgRtGueBbSBQ.png" /></figure><p>This means that we are 95% confident that on average the shopper conversion would be between 78% and 83%.</p><h4>Conclusion</h4><p>In this blog, we discussed the confidence intervals for ratio/proportion based metrics and we solved a real time example from a grocery store. We also looked at the significance of reporting confidence interval for these metrics.</p><p>In the next few articles i’ll dive into the realm of hypothesis testing and then finally in models like regression, anova and their significance.</p><p>Stay Tuned for next one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e45d4776a7b7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/intro-to-statistical-inference/intro-to-statistical-inference-part-3-confidence-interval-for-proportion-e45d4776a7b7">Intro to Statistical Inference — Part 3: Confidence Interval for Proportion</a> was originally published in <a href="https://medium.com/intro-to-statistical-inference">Intro to Statistical Inference</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to Probability Theory: What is Random Variable?]]></title>
            <link>https://medium.com/@hussain.anwaar/intro-to-probability-theory-what-is-random-variable-7956edd94f69?source=rss-3ff4996b15b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7956edd94f69</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[random-variable]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[discrete-random-variable]]></category>
            <dc:creator><![CDATA[Hussain Anwaar]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 03:42:40 GMT</pubDate>
            <atom:updated>2023-08-17T03:42:40.816Z</atom:updated>
            <content:encoded><![CDATA[<p>The random variable, probability distribution, sample space &amp; more!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tmBKfUPmNByNamrRyB8zw.jpeg" /><figcaption><a href="https://unsplash.com/photos/cQYNJe7kP6Q">https://unsplash.com/photos/cQYNJe7kP6Q</a></figcaption></figure><p>Statistics use probability theory and tricks to build methods that help us explain the structure of our data. If we look at any of the methods that are the backbone of modern day data analysis like Central Limit Theorem, Confidence Interval or Regression, we encounter words like random variable and probability distribution. Have we ever wondered what is “Random Variable, Probability or Distribution”. Why do we hear these terms all the time whenever we read any literature on statistics or probability theory. What do we mean when we say a random variable follows a certain distribution (or probability distribution)? — More importantly, why is it even important in the practical world of data?</p><p>In this post, i’ll explain what a random variable and probability distribution is. We’ll do an example from real data to demonstrate these concepts and do tiny bit of hands on coding for data analysis. Then we’ll dive into different types of random variables and distributions.</p><h4>What is a Random Variable?</h4><blockquote>It is a variable that is used to model the outcome of an experiment and can take any value from the set of sample space based on a probability distribution</blockquote><p>Not simple enough, huh!</p><p>Let’s try one more time. Anything that you observe in real life which can take a finite or infinite set of values and is associated to some phenomena is a “Random Variable”. Let’s start with the textbook example of a <strong>coin toss</strong>. If you want to observe the result of a coin toss, you model this using a random variable. why? Because anytime you throw a coin in the air, you can either get “Heads” or “Tails” with some chance (probability) associated to each of them. If i ask you “what is it gonna be, heads or tails” — what would you say? Probably, “I don’t know it could either be heads or tails with 50/50 chance right?”</p><p>Here I want to introduce a few terms that you might have heard of in probability courses.</p><ol><li><strong>Experiment </strong>— Any phenomena that you observe or want to observe is the experiment — <strong>“Observing the coin toss”</strong></li><li><strong>Outcome</strong> — The values that you can observe if you try to observe the phenomena at multiple points in time — <strong>“Observing the coin toss, where i can either see a head or a tail, so head and tail are the outcomes”</strong></li><li><strong>Sample Space</strong> — The set of all possible outcomes of your experiment is sample space — <strong>“Observing the coin toss, where i can either see a head or a tail, thus my sample space is: [Head, Tail]”</strong></li><li><strong>Probability</strong> — In inferential statistics, probability the long run average of the outcome of interest. In simple words what percentage of time we observe the outcome of interest if we repeat the experiment long enough — <strong>“If i do a coin toss a hundred time and count the number of times the head appears, then probability of head is 50/100 ~ 50%”</strong></li><li><strong>Probability Distribution</strong> — A distribution that assigns probability to each outcome of your experiment — <strong>“Observing the coin toss, where i can either see a head or a tail, thus my sample space is: [Head, Tail], where i can observe either of them with a 50%, 50% chance, thus probability distribution is [Prob of Head, Prob of Tail] ~ [50%, 50%]”</strong></li></ol><p>I hope by now the picture is a bit clearer. Since, we live in the world of data, so i’d want to follow an example from data and see what we can learn there.</p><p>Let’s say you work at a gym where you have this data available which contains member_id, their status (whether they are regular members or not) and height in inches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*CITAH-y90GHGihzpiQkvGQ.png" /></figure><p>This data could be from an experiment you ran where you just wanted to record member’s id, their gym status &amp; age. Now, let’s answer each of the above questions we answered with the coin toss example using this gym data.</p><p><strong>Q.1: What is the probability of Pr(status = ‘Regular Member/R’)?</strong><br>Remember that probability is the long run average of the outcomes. All we have to do is count the number of “regular” members out of all.</p><pre>print(f&quot;Regular Member count: {df[df.status == &#39;R&#39;].shape[0]}&quot;)<br>print(f&quot;Total Member count: {df.shape[0]}&quot;)<br>print(f&quot;Pr(Status = &#39;Regular Member - R&#39;) = {df[df.status == &#39;R&#39;].shape[0]/df.shape[0]}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*lSS3--3NKFqHYSBfIdC9-w.png" /></figure><p><strong>Q.2: What is the sample space for member’s status?<br></strong>Remember that sample space is the set all possible outcomes. Since we know that there are only “Regular or Non Regular Members” in the gym, thus sample space is: <strong>[‘R’, ‘NR’]</strong></p><p><strong>Q.3: What is the probability distribution for member’s status?<br></strong>Probability distribution is a distribution that assigns the probability (chance of occurrence) to each of the outcome in our experiment. To calculate this from our data, we just need to find the proportion (probability) of both “Regular and Non Regular Members”</p><pre>status_pdf = df.groupby(&quot;status&quot;).agg(counts = (&quot;status&quot;, &quot;count&quot;)).reset_index()<br>status_pdf[&#39;probability&#39;] = status_pdf[&#39;counts&#39;]/status_pdf[&#39;counts&#39;].sum()<br>status_pdf</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*19UGNq_SDZ-lXfW6flGLUQ.png" /></figure><pre>sns.barplot(data = status_pdf, x = &quot;status&quot;, y = &quot;probability&quot;)<br>plt.title(&quot;Probability Distribution of Gym status&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*S9zeeAGtibIBwZwky9Ff1w.png" /></figure><p>Now, we can use this information to make some inference about your gym. It seems like more of the members in your gym are “Non Regular” members, maybe you can strategize on helping members become more “regular” by introducing fitness programs or some other promotions to help with growing your business.</p><p>You see how probability, random variables and distributions are the backbone of simple data analysis. The above variable of “Member Status” is called <strong>“Discrete Random Variable”</strong> since it can only take a <strong>finite </strong>set of values, and the distribution used to describe is called <strong>“Discrete Probability Distribution”</strong>. If you noticed in the data, we had another variable called <strong>height, </strong>which is a continuous variable, meaning it can take infinitely possible values. E.g people can have a height of 55.6, 55.69, 56.2 inches and so on. Thus, these variables are called <strong>continuous random variables</strong> and the distributions used to represent these variables are called “C<strong>ontinuous Probability Distributions</strong>”.</p><p>In the next article, we will discuss the continuous probability distributions, some other terms that define the structure of a distribution like PDF (No not that PDF!), PMF and CDF.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7956edd94f69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to Statistical Inference — Part 2: Confidence Interval for Mean and Proportion]]></title>
            <link>https://medium.com/intro-to-statistical-inference/intro-to-statistical-inference-part-2-confidence-interval-for-mean-and-proportion-2e9befbd191c?source=rss-3ff4996b15b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e9befbd191c</guid>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[confidence-interval]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[statistical-inference]]></category>
            <dc:creator><![CDATA[Hussain Anwaar]]></dc:creator>
            <pubDate>Sun, 13 Aug 2023 21:28:44 GMT</pubDate>
            <atom:updated>2024-02-16T21:02:52.764Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro to Statistical Inference — Part 2: Confidence Interval for Mean</h3><p>In the last article we discussed what a confidence interval is and the intuition behind it. If you need to refresh your knowledge on “Confidence Interval and Central Limit Theorem” — please review this first blog i wrote in the series.</p><p><a href="https://medium.com/intro-to-statistical-inference/intro-to-statistical-inference-part-1-what-is-statistical-inference-43a006c9a71">Intro to Statistical Inference — Part 1: What is Statistical Inference?</a></p><p>Today, we’ll dive a bit more into:<br><strong>1. General details around confidence interval<br>2. Confidence Interval for Mean — Derivation &amp; Examples</strong></p><p>I’ll provide some practical examples and code snippets to run quick simulations to develop a strong understanding of the concept.</p><p>Let’s dive right into it!</p><h4>A few general details on Confidence Interval</h4><p>In the last article we explained that confidence interval is “a plausible range of values that contains true population parameter with some confidence”. Simply put, C.I quantifies the uncertainty (variability) around the sample statistic.</p><p>But why do we need C.I, why can’t we just report a single metric like average revenue per customer, avg. time spent reading on medium etc. I discussed this topic in detail in previous blog.</p><p>Now let’s focus on how to build the confidence interval. We need three things to build C.I for any metric.</p><ol><li>Point Estimate (Metric of Interest — avg. revenue etc)</li><li>Standard Error (Variance of Sampling Distribution) — Quantifies the variability around the point estimate (metric of interest)</li><li>Confidence (1 — alpha) — Shows how confident we are in the range we provided</li></ol><p>Thus, the complete equation look something like this:<br><strong>Point Estimate ± Confidence × Standard Error</strong></p><p><strong>Point estimate —</strong> relates to some metric you are trying to report/measure. It could be avg. revenue, avg. spend or even a proportion based metric like CVR (conversion rate — based on a binary metric).</p><p><strong>Standard Error —</strong> as explained in the last article is the variability around the metric.</p><p><strong>Confidence </strong>— quantifies the confidence you have in the range you produced using point estimate and standard error. Intuitively, this means that for a higher confidence value, the range of C.I would be larger and you would have a higher confidence — Meaning you’d be more confident in saying that the range you calculated (using C.I) would contain the true population parameter, whereas for a lower confidence, the range of C.I would be smaller (As suggested by the formula above). Now let’s look at this picture below from last article —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QH-FTWrn6rf6OYPKAUSeqQ.png" /></figure><p>Range of 1-sigma (one standard deviation) around the mean captures ~68% of variability, while as you increase the limit and move to 2-sigma, the percentage of variability captured increases. Thus, finding this 1, 2 or 3 in sigma, is where the significance of your confidence lies. If you want to be ~68% confident in your C.I, you can use “1”. If you want to be ~95% confident, you can use “2”.</p><p>I used confidence for simplicity here. In reality we use critical value which is defined by the confidence percentage. As in above example, 95% confidence relates to 2 for Standard Normal Distribution.</p><p>Enough with the theory already, let’s talk about some practical example. Usually there is a metric you always want to calculate the confidence interval for. Suppose you are the analyst at a grocery store — You could have different important metrics that you are tracking, E.g <strong>spend per customer</strong> (revenue per customer), <strong>customer conversion</strong> (% of total customer that at-least buy one product in a visit). The first metric is a continuous metric, meaning more of an average of some numbers, whereas the second metric is a percentage of a binary metric (Metric that take 1 or 0 value — whether the customer bought any item or not). Your analytics lead might have asked you to report these metrics in a meeting to analyze the store’s growth. Now you have already been following this series and know that it is always important to report the variability around the metric, so you want to make sure you report the Confidence Intervals for both metrics. Let’s see how we can do that!</p><h4>Confidence Interval for Means</h4><p>Whenever the point estimate is a continuous quantity, we’ll use confidence interval for means to report the metric and variability around it. The data you have is of each customer’s spend per visit and looks something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*wxtr3CPfKRKXutAiZITnDQ.png" /></figure><p>Since it is a continuous metric and the easiest way we can aggregate the Revenue/Spend is by taking it’s average and report it. Thus, you’d follow this process below:</p><ol><li>Calculate the average of the metric of interest, which in our case is revenue per customer:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*sVYfrWQuGiEVfUmSSP6__w.png" /></figure><p>2. Calculate the Standard Error for that metric:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*mFRckCZw1BQ6X2MuPbTXKQ.png" /></figure><p>3. Decide on Confidence Level to report on and calculate the critical value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*XZNHahpPxmvbYC9GX9QS_A.png" /></figure><p>Plug all the above into the formula below and you have the C.I for the metric:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*ZrGa3dDC_ZTzXSuuBiWmLA.png" /></figure><p>Now, there is a caveat in the above equation. If you see the formulation for standard error, it contains “sigma”. Which is the population standard deviation and not the sample one. However, in most cases we only have access to the sample only as in the case above. So, the question is how can we use sample standard deviation to estimate the standard error and what changes we need to make?</p><p>The good news is that we can use sample standard deviation and there not a whole lot we need to change. With the new formulation here is complete process (Don’t worry i’ll explain it all in a bit)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*kN54GROyOiwf7TcV8gYbYg.png" /></figure><p>If you take a deeper look at the formulation, not a whole lot changed. Except now we are talking about t-Distribution instead of the standard normal distribution to calculate the critical value. Why?</p><p>Here is a simple answer, because now we are estimating the standard error (variance of sampling distribution) using sample standard deviation. Thus, samples usually have more variability compared to population from which they are sampled from. Simply because we take a small chunk from a population and variability would be higher. To cater to that we use student t-distribution to simulate the sampling distribution instead of the standard normal distribution as we did in CLT proof in the last article. One of the major differences between a normal and t-distribution is that the latter has fatter tails so that it can be used to model some extra variance (which comes from the fact that we are using a sample standard deviation to estimate the sampling distribution’s variability (i.e Standard Error). From the POV of computation, not a whole lot changes. Previously we use the critical value table from standard normal distribution, now we’ll use the critical value from t-distribution. I’ll do a deeper dive on the differences between t-distribution and standard normal distribution. But for now just remember that they both are:</p><ol><li>Very similar to each other in shape</li><li>Both are centered around zero</li><li>larger the df (degrees of freedom — due to larger sample size), the more similar two distributions become</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*gHMat2fLs23ndIMPUfWP2g.png" /></figure><p>Now let’s look at some data and run some code to calculate the C.I for the Revenue per user.</p><p>I created a dummy dataset which has user_id’s and their spend from last day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*CB3rgSvv4PCwo96lqWKFeg.png" /></figure><p>Here is the code snippet to calculate the C.I from the data:</p><pre>from scipy.stats import t<br>alpha = 0.95<br>n = df.shape[0]<br>x_bar = df[&#39;revenue&#39;].mean()<br>s = df[&#39;revenue&#39;].std()<br>critical_value = t.ppf(alpha ,df = n - 1)<br>C_I = [x_bar - critical_value*(s/np.sqrt(n)), x_bar + critical_value*(s/np.sqrt(n))]</pre><p>Here’s the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*D_h53kLkbrwbpujPwuIlUA.png" /></figure><p>This means that we are 95% confident that the true avg. spend per customer would lie somewhere between $49.51 and $50.54. You can track this over days or weeks and analyze the growth of the store.</p><h4>Conclusion</h4><p>In this blog, we discussed the important facets of confidence intervals and how to calculate confidence intervals for means. We looked at a practical example of the user spend data and how to report avg. revenue per user like a pro using the confidence intervals.</p><p>In the next article we’ll look into the second metric of conversion meaning what % of users convert on their visit. This kind of metric can help us analyze why certain users are not buying anything from the store, which can later be used to find causes of why certain users do not buy anything from the store.</p><p>Stay Tuned for next one!</p><h4>Resources</h4><p><a href="https://github.com/mitu246/blogs/blob/main/CI%20for%20Mean.ipynb">Github code</a></p><h4>Connect with me</h4><p>I just started rewriting the blog series and share my knowledge along the way. My interests are Statistics, Causal Inference, Traditional Machine Learning, Reinforcement Learning</p><p>If any of the above topics interests you, i’d love to chat more and connect!</p><p>My LinkedIn: <a href="https://www.linkedin.com/in/hussainanwaar246/">hussain_anwaar</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e9befbd191c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/intro-to-statistical-inference/intro-to-statistical-inference-part-2-confidence-interval-for-mean-and-proportion-2e9befbd191c">Intro to Statistical Inference — Part 2: Confidence Interval for Mean and Proportion</a> was originally published in <a href="https://medium.com/intro-to-statistical-inference">Intro to Statistical Inference</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to Statistical Inference — Part 1: What is Statistical Inference?]]></title>
            <link>https://medium.com/intro-to-statistical-inference/intro-to-statistical-inference-part-1-what-is-statistical-inference-43a006c9a71?source=rss-3ff4996b15b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/43a006c9a71</guid>
            <category><![CDATA[confidence-interval]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[statistical-inference]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <dc:creator><![CDATA[Hussain Anwaar]]></dc:creator>
            <pubDate>Thu, 21 Oct 2021 21:56:17 GMT</pubDate>
            <atom:updated>2023-08-13T21:39:42.539Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro to Statistical Inference — Part 1: What is Statistical Inference?</h3><p>In this blog series, I will talk about the basics of Statistical Inference. I’ll start with what Statistical Inference is and what we mean when we say “Infer something about the population from the data we observe”, and in later parts I’ll talk about different Statistical Tests to decide the significance of effects we observe through the data (i.e. if these effects are true effects or just random noise). I’ll dive into the explanations of different types Statistical Tests used for different types of data (or should I say the type of population parameter in question). Most of the time I’ll try to keep things simple and basic, however I’ll be posting examples designed in R and Python to help understand the concept.</p><h3>What is Statistical Inference?</h3><p>By definition, it is the study of theory and methods used to form judgements regarding a “population” from the sample (data) that we observe, and measure the reliability of those judgements made from the sample data. In simple words, we can say that Inference is about generalizing something with a “certain degree of certainty” about a population by looking at a sample from that population.</p><p>For example, you may want to how many glasses of water people of your age usually drink everyday. Now, the easiest way to check that is by observing yourself and asking your friends (assuming they are your age) about the glasses of water they drink everyday. After asking two of your friends and observing yourself, you came up to a conclusion that “People of your age drink on average “X” many glass of water”. We’ll discuss the process of reaching this conclusion shortly, but the above statement is where you are inferring about the population (i.e. people of your age) that they drink a certain amount of water everyday.</p><p>Now you might ask — Why do we need to Infer something about the population, why can’t we exactly know how the population looks like and what is the value of it’s parameter of interest (Population Parameter). The answer is that in real time scenarios, population parameter of interest is unknown, because the complete population is mostly unobserved, e.g You can never ask every person of your age on earth, how many glasses of water they drink as it’s practically impossible. We can only make some inferences about population by observing a sample from the same population</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*9O_-82J62STps3IjMivzCA.png" /></figure><h3>Basic Terminologies</h3><p>Before diving deep into the example above I wanted to talk about the basic terminologies I’ll be using throughout this blog series.</p><h4>Population</h4><p>Complete set of Individuals/Objects under study is population. From the example above population is the all the people your age in this world.</p><h4>Parameter of Interest</h4><p>Parameter of Interest is the attribute you want to infer in regards to the population under study. Amount of water is the parameter of interest as you are inferring how much water people your age drink.</p><h4>Measuring the Parameter of Interest</h4><p>After deciding about the Parameter of Interest you need to decide on how would you quantify/measure the parameter of interest. In our case it is the number of glasses a person drink everyday.</p><h4>Population Parameter &amp; Sample Statistic</h4><p>The measure for Parameter we talked about in the previous section can be measured w.r.t both the population and sample. When it is measured w.r.t population, it is called Population Parameter and when measured for a sample, it’s called Sample Statistic. For example — Average glass of water that a person of your age drinks (Population) is a population parameter, while the average glass of water you and the sample of your two friends drink is the sample statistic. Population parameter is what is unknown mostly all the time, while sample statistic is what we can measure from our sample and use it to make an inference about population parameter.</p><p>From our example we discussed above — Let’s say you drink 5 glasses, your first friend drinks 3 and your second friend drinks 7 glasses of water everyday. The average of these numbers comes out as 5 which is the sample statistic in this case. You might be wondering, Well — I can infer each person of my age on average drinks 5 glasses of water, right? — Wrong! Because you did not account for the variability that would occur in terms of sample statistic if you were to take a different sample from what you just took. For example, you had asked two people from your neighborhood other than your two friends that you just asked, they might have answered that they drink 9 and 13 glasses of water everyday. Now if you average your 5 glasses of water, 9 and 13 from the above two people, you now have a sample statistic of average of 9 glasses per day. Now if you notice how different your sample statistic would be if you had chosen this sample instead of the last one.</p><p>This Variability in sample statistic due to difference in samples we collect is called Sampling Variability. We can use this variability and sample statistic to define the plausible range of values from which we can say the population parameter can lie with a certain degree of confidence.</p><h4>Sampling Distribution and Central Limit Theorem (CLT)</h4><p>It is the distribution of different (yet identical) values of sample statistic that can come from different samples of same size from a population. In our example above, your sample is of size n=3. Let’s say you decided to take 15 samples (each of size n=3, i.e three people — You decided to ask 15 groups of 3 people each) and you recorded the “Average Number of glasses for each sample. Here are the numbers Sn = 8,7,9,8,7,9,6,10,8,8,7,6,9,5,11 — Avg. Number of glasses per sample. Let’s plot them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_8s8VULSjQ0OCezsklyrw.jpeg" /></figure><p>If we assume that the underlying population is normal in our case, and you had kept on sampling and were able to sample the entire population, the curve shown above would start approaching a normal distribution with mean “mu — μ” and standard deviation (Sampling Variability or sometimes called Standard Error) as “σ/√n” (where “μ” population mean (population parameter) and “σ” is the standard deviation of the population). This essentially means that the sampling distribution of sample mean (<strong>x̄</strong>) ~ N(μ,σ²/n), given that the underlying population is normal. Even if the underlying population is not normal (i.e Binomial, Uniform Distribution etc), the sampling distribution will still be normal given the sample size is large enough. The description above most accurately describes what Central Limit Theorem is. Here is a short proof for all the things I have mentioned. This will form the basis for most types of Statistical Tests we’ll talk about in the next blogs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*mQTxiDUmOvle3e_4iiSgKw.png" /><figcaption>Please read the left page first and then move towards right</figcaption></figure><p>Here’s a simulation I ran in R that would help understand the CLT better. I took a uniform distribution with mean 0.5, and ran a simulation to show the sampling distribution based on different sample sizes. We can visualize that as the sample size increases, the sampling distribution appears to be more like normal distribution. As sample size approaches infinity the sampling distribution becomes exactly normal. Here’s how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OAe1qofd4KrBHYqRNii1WQ.png" /></figure><p>Here’s the code snippet to do it:</p><pre># CLT Proof:<br>x &lt;- runif(1000000,0,1)</pre><pre># We&#39;ll take a total of 100 samples of different sizes to show <br># how the sampling distribution looks like</pre><pre># Sample Sizes<br>n &lt;- c(10,50,100,150,200,1000)</pre><pre># Final Data Table:<br>final_dt &lt;- data.table()<br>for(n_ in n){<br>  x_bar_list &lt;- c()<br>  dt_ &lt;- data.table()<br>  for(i in 1:100){<br>    x_i &lt;- sample(x,n_,replace=T)<br>    x_bar &lt;- mean(x_i)<br>    <br>    x_bar_list &lt;- c(x_bar_list,x_bar)<br>  }<br>  dt_[,`:=`(sample_size=rep(n_,length(x_bar_list)),<br>            x_bar=x_bar_list)] <br>  final_dt &lt;- rbind(final_dt,dt_)<br>}<br># Plot the sampling distributions for different sample sizes:<br>final_dt$sample_size = as.character(final_dt$sample_size)<br>ggplot(final_dt)+geom_density(aes(x=x_bar,col=sample_size))</pre><h4>Confidence Interval</h4><p>Unfortunately, we don’t have the luxury or resources to sample a population completely and generate the whole sampling distribution. We mostly just have one sample from the population on the basis of which we have to infer something about the population. Now we would agree on the fact that due to sampling variability we cannot infer by only using sample statistic, we need to cater for the sampling variability, and we do that by generating a plausible range of values in which the true population parameter would lie with a certain degree of confidence. Why, we say with certain degree of confidence, let’s dive into it after we build some intuition using the normal probability curve. Let’s say we have a normal distribution following ~ N(μ,σ²).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iSUqv2yB94q9B3aDp37Ovw.jpeg" /></figure><p>From the above picture we see that 68% of the data lies within +/-1σ of mean, while 95% of the data lies within <strong>+/-2</strong>σ of mean, and the percentage increases as we increase the range around the mean. Now, think of it in terms of sample statistic mean and it’s standard deviation (Sampling Variability or Standard Error).</p><p>Following this analogy we can say that p% confidence interval can be built using this formula:<br><strong>x̄ +/- [critical_value(given p% confidence) * S.E]</strong></p><p>Now, if sample mean (sample statistic) follows a normal distribution then we can get the critical value for respective confidence percentage from the normal distribution defined above. For example, for 95% confidence we would use the critical value of 2. Sample mean can follow either normal distribution or T-Distribution depending upon how we estimate standard error. We’ll dive into the explanation for this in the next article.</p><p>Finally, I’d want to build some intuition behind Confidence Interval. Let’s assume we generated a p% C.I. This means that if we were to generate “x” number of these intervals from x different samples (coming from same population) then x*p% of these intervals would contain the true population parameter. For example, let’s say you generate x=10 different (yet identical) 95% Confidence Intervals by taking 10 samples from population, then about 9.5 (~ round down to 9) of these 10 C.I’s would contain the true unknown population parameter or 9.5 out of 10 times your Confidence Interval is solid!</p><p>In this article, I tried to explain the baseline idea behind statistical inference and the tools we use to infer something about a population by using a single sample from that population. In the next few articles, I’ll discuss how to build Confidence Intervals for different type of measurements (e.g mean and proportion) and we’ll discuss other concepts like Hypothesis Testing, Regression and Analysis of Variance in detail.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43a006c9a71" width="1" height="1" alt=""><hr><p><a href="https://medium.com/intro-to-statistical-inference/intro-to-statistical-inference-part-1-what-is-statistical-inference-43a006c9a71">Intro to Statistical Inference — Part 1: What is Statistical Inference?</a> was originally published in <a href="https://medium.com/intro-to-statistical-inference">Intro to Statistical Inference</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Action Recognition and Video Classification using Keras and Tensorflow]]></title>
            <link>https://medium.com/video-classification-using-keras-and-tensorflow/action-recognition-and-video-classification-using-keras-and-tensorflow-56badcbe5f77?source=rss-3ff4996b15b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/56badcbe5f77</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[action-recognition]]></category>
            <category><![CDATA[video-processing]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Hussain Anwaar]]></dc:creator>
            <pubDate>Fri, 17 Jul 2020 23:45:03 GMT</pubDate>
            <atom:updated>2020-07-17T23:45:03.106Z</atom:updated>
            <content:encoded><![CDATA[<h4>A beginner’s guide to using Neural Networks for Action Recognition and Classification in Videos</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wcDYgHFa4z_aKBr1YLCQGg.png" /><figcaption>Some Stretching Body Actions — Image Source: <a href="https://www.tfsportstherapist.co.uk/wp-content/uploads/2017/10/stretches.png">https://www.tfsportstherapist.co.uk/wp-content/uploads/2017/10/stretches.png</a></figcaption></figure><h3>Background</h3><p>Neural Networks are a vital part of the Deep Learning realm where we can use them in Computer Vision, Regression, Natural Language Processing, or Time Series Forecasting tasks. I employed Neural Networks for the first time when I worked on a project of Image Classification in my Machine Learning course during my master’s. I was baffled by the human brain-inspired structure of Neural Networks and how the task of “Image Processing and Classification” is being simplified through the use of Neural Networks. On top of that, the use of Keras Library in Python running on top of the Tensorflow platform makes it so easy to design any neural network and perform parallel processing on your GPU. Since then, I wanted to explore this area and its applications. I came across another project of Action Recognition and Classification through Videos during another course. That’s when I realized there were not many blogs and articles available for beginners to start using Neural Networks in Video Classification Tasks. Thus, I wanted to write one to help with that.</p><h3>Introduction</h3><p>I will start off with a quick intro to the project. The task was to design a neural network model that could detect a “Stretching Body” in videos. I took about 230 videos with an average length of 10-12 seconds where a person is performing some action needed to be classified as either “Stretching or No-Stretching”. For the sake of simplicity, I constrained myself to just one human object in a video. I used Keras Library in Python and did most of the work in Google Colab as I didn’t have a GPU on my machine. I tried different Deep Learning architecture that could be used for Processing Video Data.</p><p>The project had about 5 phases where I tried numerous different architectures from very basic to most complex ones. Here, I will just talk about the very basic strategy regarding how to read the data from videos and how to develop a very basic Deep Learning Architecture to perform video classification. Let’s dig a bit deeper here while avoiding technical jargon as much as possible.</p><p>The picture below would give you a birds-eye view of the whole process and a better intuition to understand the whole process. I’ll explain each step in detail as we move further along the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GNJgOHkMpers7aOvSQchcg.png" /><figcaption>A flowchart of Video Processing and Classification task</figcaption></figure><h3>Reading and Processing the Videos</h3><p>Basically, videos are just a set of images binned serially and you are looking at them continuously in the form of a video. Thus, reading a video is just like reading a number of images at once. This seems a bit intimidating at first — But, we have an OpenCV library in python for our rescue. With just a few lines of code, you can read the video files on your drive and set the “Number frames per second. Here, I wrote a function that would read 10 frames from each video (i.e 1 Frame per second for the sake of simplicity) and save them in another folder so that we can read them later for processing.</p><pre>import cv2<br>def video_capturing_function(dataset,folder_name):<br>    for i in np.arange(len(dataset)):<br>        video_name=dataset.video_name[i]<br>        video_read_path=os.path.join(video_directory,video_name)<br>        cap=cv2.VideoCapture(video_read_path)<br>        try:          os.mkdir(os.path.join(os.path.join(stretches_path,folder_name),<br>                                  video_name.split(&quot;.&quot;)[0]))<br>        except:<br>            print(&quot;File Already Created&quot;)<br>        <br>        train_write_file=os.path.join(os.path.join(stretches_path,folder_name),<br>                                  video_name.split(&quot;.&quot;)[0])<br>        cap.set(cv2.CAP_PROP_FPS, 1)<br>        frameRate=cap.get(5)<br>        x=1<br>        count=0<br>        while(cap.isOpened()):<br>            frameId = cap.get(1) #current frame number<br>            ret, frame = cap.read()<br>            if (ret != True):<br>                break<br>            if (frameId % math.floor(frameRate) == 0):<br>                filename =&quot;frame%d.jpg&quot; % count;count+=1<br>                frame_grey=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)<br>                cv2.imwrite(os.path.join(train_write_file,filename), frame_grey)<br>        cap.release()<br>    return print(&quot;All frames written in the: &quot;+folder_name+&quot; Folder&quot;)<br>    <br>video_capturing_function(train_set,&quot;Train_Videos&quot;)<br>video_capturing_function(test_set,&quot;Test_Videos&quot;)</pre><p>What this function above does is that it reads the name of each video file in “Train Set (A Dataframe containing the name and class label of the video) and Test Set” and then from the folder where that video is saved start reading the frames (Images) from that video with a specified fps (Frames per second). Here, for simplicity, I read 1 frame each second so that each video would have approximately 10 frames. As processing 10 frames are easier and less complex than processing a 10-second video with 30 fps that makes about 300 frames in each video.</p><p>After using this, you have a folder for each video containing 10 images of it in your drive. Now we can write a function that would read those images and create our Train and Test Datasets to be used in our Deep Learning Model.</p><pre>def data_load_function_10frames(dataset,directory):<br>    frames=[]<br>    for i in np.arange(len(dataset)):<br>        vid_name=dataset.video_name[i].split(&quot;.&quot;)[0]<br>        vid_dir_path=os.path.join(directory,vid_name)<br>        frames_to_select=[]<br>        for l in np.arange(0,10):<br>            frames_to_select.append(&#39;frame%d.jpg&#39; % l)<br>        vid_data=[]<br>        for frame in frames_to_select:<br>            image=Image.open(os.path.join(vid_dir_path,frame))<br>            image=image.resize((250, 250), Image.ANTIALIAS) <br>            datu=np.asarray(image)<br>            normu_dat=datu/255<br>            vid_data.append(normu_dat)<br>        vid_data=np.array(vid_data)<br>        frames.append(vid_data)<br>    return np.array(frames)</pre><p>The above function reads 10 images we saved in the folders created for each video when we employed the function explained previously. It creates a Numpy array with the dimensions (Number of Samples, Frames, Image Length, Image Width, Channels). Here the images are loaded in the forms of tensors and are normalized. As I don’t need color images, I have converted the images to a grey-scale through this function. So, all dimensions for frames would be 10, image size would be 250✕250 and the channel would be 1.</p><pre>test_dataset_new=data_load_function_10frames(test_set,test_dir_path)<br>train_dataset_new=data_load_function_10frames(train_vid_dat,train_dir_path)<br>validation_dataset_new=data_load_function_10frames(validation_vid_dat,train_dir_path)</pre><pre># Reshaping tensors to confirm with the model we are going to train:<br>test_dataset_new=test_dataset_new.reshape((60,10,250,250,1))<br>train_dataset_new=train_dataset_new.reshape((136,10,250,250,1))<br>validation_dataset_new=validation_dataset_new.reshape((34,10,250,250,1))</pre><p>As we can see till this point we have our data ready to be fed to the neural network. I used this technique of reading the Videos and converting them into tensors to be fed into the neural network because it’s easier to explain and is more intuitive. But if you have large Dataset and are reading longer videos, this technique is inefficient. There, you can use the “Generators” in Keras to process and load the video data into the model directly at training time. But I’ll leave that technique for other blogs.</p><h3>Model Architectures</h3><p>In image processing, we used to perform convolution on one image by building convolution layers and then using fully connected layers to classify the image. Here, we have multiple images (Frames) for one video to be processed and classified such that there is one classification for multiple frames of a video. There are many different architectures that have been proposed for processing multiple frames at a time as in the case of Videos, 3D-CNN (Convolutional Neural Network), CNN &amp; LSTM Layer, and many other more complex architectures. Here, I will just focus on explaining how to design a “CNN &amp; LSTM” architecture for Video Classification Task.</p><p>The figure below gives the first sketch of the model architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*h5HWw8lkq2xCxEySXDHzeA.png" /><figcaption>CNN &amp; LSTM Architecture</figcaption></figure><p>In the image processing first, we use the convolution layers to extract features from an image so that they can be further learned to classify the image. So, here as we have multiple frames, we want to apply convolution operation at the same time to all the 10 frames to learn features in each layer simultaneously, so that in the other deeper layers we learn other features on top of the previously learned features. Time Distributed Layer in Keras gives us the liberty to do just that. Here, are some insights regarding the Time Distributed Layer.</p><ul><li>It applies a layer (Convolution in our case) into “N” time dimensions (Temporally) given. For example, if we have 10 frames in a video. And we use a Convolution Layer to extract features from those 10 images, “Time Distributed Layer” would consider 10 frames as 10 timesteps and apply the Convolutional Layer onto those 10 frames keeping the temporal aspect intact.</li><li>Bottom line is that Time Distributed Layer applied with the Convolutional layer would learn different aspects temporally, e.g it would detect a person/body in the first frame and then would try to learn how the orientation of the body changes in the succeeding frames.</li></ul><p>I designed a very basic architecture (Sequential Architecture) to just beat the baseline accuracy (Random Guess) of 50% as out test dataset contains a total of 60 videos out of which 30 belong to “Stretching Class” and 30 belong to “No-Stretching Class”.</p><p>Here, is the code for basic architecture:</p><pre>from keras.layers import TimeDistributed, Conv2D, Dense, MaxPooling2D, Flatten, LSTM, Dropout, BatchNormalization<br>from keras import models<br>model_cnlst = models.Sequential()<br>model_cnlst.add(TimeDistributed(Conv2D(128, (3, 3), strides=(1,1),activation=&#39;relu&#39;),input_shape=(10, 250, 250, 1)))<br>model_cnlst.add(TimeDistributed(Conv2D(64, (3, 3), strides=(1,1),activation=&#39;relu&#39;)))<br>model_cnlst.add(TimeDistributed(MaxPooling2D(2,2)))<br>model_cnlst.add(TimeDistributed(Conv2D(64, (3, 3), strides=(1,1),activation=&#39;relu&#39;)))<br>model_cnlst.add(TimeDistributed(Conv2D(32, (3, 3), strides=(1,1),activation=&#39;relu&#39;)))<br>model_cnlst.add(TimeDistributed(MaxPooling2D(2,2)))<br>model_cnlst.add(TimeDistributed(BatchNormalization()))<br><br><br>model_cnlst.add(TimeDistributed(Flatten()))<br>model_cnlst.add(Dropout(0.2))<br><br>model_cnlst.add(LSTM(32,return_sequences=False,dropout=0.2)) # used 32 units<br><br>model_cnlst.add(Dense(64,activation=&#39;relu&#39;))<br>model_cnlst.add(Dense(32,activation=&#39;relu&#39;))<br>model_cnlst.add(Dropout(0.2))<br>model_cnlst.add(Dense(1, activation=&#39;sigmoid&#39;))<br>model_cnlst.summary()</pre><h3>Model Training and Compilation</h3><p>I used RMSprop as the optimizer in Keras and trained the model for 20 epochs with a batch size of 10.</p><pre>from keras import optimizers<br>callbacks_list_cnlst=[keras.callbacks.EarlyStopping(<br>monitor=&#39;acc&#39;,patience=3),<br>               keras.callbacks.ModelCheckpoint(<br>               filepath=&#39;cnn_lstm_model_new3.h5&#39;,<br>               monitor=&#39;val_loss&#39;,<br>               save_best_only=True),<br>                keras.callbacks.ReduceLROnPlateau(monitor = &quot;val_loss&quot;, factor = 0.1, patience = 3)<br>               ]<br><br><br>optimizer_new=optimizers.RMSprop(lr=0.01)<br>model_cnlst.compile(optimizer=optimizer_new,loss=&#39;binary_crossentropy&#39;,metrics=[&#39;acc&#39;])</pre><pre># Training:<br>history_new_cnlst=model_cnlst.fit(train_dataset_new,train_labels,batch_size=10,epochs=20,<br>                        validation_data=(validation_dataset_new,validation_labels),<br>                       callbacks=callbacks_list_cnlst)</pre><h3>Model Testing</h3><p>After training the model I used it to classify the 60 videos in our test dataset. It gave me an accuracy of 73.3% which beats the baseline accuracy of 50%. Hence, with this simple architecture, we processed the videos and classified them in two classes of “Stretching and No-Stretching”.</p><h3>Next Up</h3><p>In this article, I made a humble attempt to simplify and explain the intimidating process of Reading and Processing Video Data, Building and Training a Deep Learning Architecture for Video Classification in Python using Keras. It’s my first blog on medium, I would request you to give it a read and give me your feedback on how can I improve and what other topics I should write about. Next Up, I’ll expand on other complex architectures in Video Classification.</p><h3>Github Link</h3><p><a href="https://github.com/mitu246/Activity-Recognition-in-Videos-using-Keras">mitu246/Activity-Recognition-in-Videos-using-Keras</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56badcbe5f77" width="1" height="1" alt=""><hr><p><a href="https://medium.com/video-classification-using-keras-and-tensorflow/action-recognition-and-video-classification-using-keras-and-tensorflow-56badcbe5f77">Action Recognition and Video Classification using Keras and Tensorflow</a> was originally published in <a href="https://medium.com/video-classification-using-keras-and-tensorflow">Video Classification using Keras and Tensorflow</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>