# Inferential Statistics Ib - Frequentism

## Learning objectives

Welcome to the second Frequentist inference mini-project! Over the course of working on this mini-project and the previous frequentist mini-project, you'll learn the fundamental concepts associated with frequentist inference. The following list includes the topics you will become familiar with as you work through these two mini-projects:
* the _z_-statistic
* the _t_-statistic
* the difference and relationship between the two
* the Central Limit Theorem, its assumptions and consequences
* how to estimate the population mean and standard deviation from a sample
* the concept of a sampling distribution of a test statistic, particularly for the mean
* how to combine these concepts to calculate confidence intervals and p-values
* how those confidence intervals and p-values allow you to perform hypothesis (or A/B) tests

## Prerequisites

* what a random variable is
* what a probability density function (pdf) is
* what the cumulative density function is
* a high-level sense of what the Normal distribution

If these concepts are new to you, please take a few moments to Google these topics in order to get a sense of what they are and how you might use them.

These two notebooks were designed to bridge the gap between having a basic understanding of probability and random variables and being able to apply these concepts in Python. This second frequentist inference mini-project focuses on a real-world application of this type of inference to give you further practice using these concepts. 

In the previous notebook, we used only data from a known normal distribution. You'll now tackle real data, rather than simulated data, and answer some relevant real-world business problems using the data.

## Hospital medical charges

Imagine that a hospital has hired you as their data analyst. An administrator is working on the hospital's business operations plan and needs you to help them answer some business questions. This mini-project, as well as the bootstrap and Bayesian inference mini-projects also found in this unit are designed to illustrate how each of the inferential statistics methods have their uses for different use cases. In this assignment notebook, you're going to use frequentist statistical inference on a data sample to answer the questions:
* has the hospital's revenue stream fallen below a key threshold?
* are patients with insurance really charged different amounts than those without?
Answering that last question with a frequentist approach makes some assumptions, or requires some knowledge, about the two groups. In the next mini-project, you'll use bootstrapping to test that assumption. And in the final mini-project of the unit, you're going to create a model for simulating _individual_ charges (not a sampling distribution) that the hospital can use to model a range of scenarios.

We are going to use some data on medical charges obtained from [Kaggle](https://www.kaggle.com/easonlai/sample-insurance-claim-prediction-dataset). For the purposes of this exercise, assume the observations are the result of random sampling from our one hospital. Recall in the previous assignment, we introduced the Central Limit Theorem (CLT), and how it tells us that the distributions of sample statistics approach a normal distribution as $n$ increases. The amazing thing about this is that it applies to the sampling distributions of statistics that have been calculated from even highly non-normal distributions of data. Remember, also, that hypothesis testing is very much based on making inferences about such sample statistics. You're going to rely heavily on the CLT to apply frequentist (parametric) tests to answer the questions in this notebook.


```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import t
from numpy.random import seed
import seaborn as sns
medical = pd.read_csv('data/insurance2.csv')
```


```python
medical.shape
```




    (1338, 8)




```python
medical.head()
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>age</th>
      <th>sex</th>
      <th>bmi</th>
      <th>children</th>
      <th>smoker</th>
      <th>region</th>
      <th>charges</th>
      <th>insuranceclaim</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>19</td>
      <td>0</td>
      <td>27.900</td>
      <td>0</td>
      <td>1</td>
      <td>3</td>
      <td>16884.92400</td>
      <td>1</td>
    </tr>
    <tr>
      <th>1</th>
      <td>18</td>
      <td>1</td>
      <td>33.770</td>
      <td>1</td>
      <td>0</td>
      <td>2</td>
      <td>1725.55230</td>
      <td>1</td>
    </tr>
    <tr>
      <th>2</th>
      <td>28</td>
      <td>1</td>
      <td>33.000</td>
      <td>3</td>
      <td>0</td>
      <td>2</td>
      <td>4449.46200</td>
      <td>0</td>
    </tr>
    <tr>
      <th>3</th>
      <td>33</td>
      <td>1</td>
      <td>22.705</td>
      <td>0</td>
      <td>0</td>
      <td>1</td>
      <td>21984.47061</td>
      <td>0</td>
    </tr>
    <tr>
      <th>4</th>
      <td>32</td>
      <td>1</td>
      <td>28.880</td>
      <td>0</td>
      <td>0</td>
      <td>1</td>
      <td>3866.85520</td>
      <td>1</td>
    </tr>
  </tbody>
</table>
</div>



__Q:__ Plot the histogram of charges and calculate the mean and standard deviation. Comment on the appropriateness of these statistics for the data.

__A:__


```python
# Let's look at the max value so we can use a number around it for our
# xticks
max(medical.charges)
```




    63770.42801




```python
sns.set()
plt.figure(figsize=[12,8])
plt.hist(medical.charges, bins = 50, color='C4')
plt.xlabel('Charges')
plt.ylabel('Count')
plt.title('Medical Charges and Counts')
plt.xticks(range(0,65000,2500), rotation = 'vertical')
plt.show()
```


```python
print('The mean of the medical charges is {} '.format(round(np.mean(medical.charges),2)))
print('The standard deviation of the medical charges is {} '.format(round(np.std(medical.charges),2)))
```

    The mean of the medical charges is 13270.42 
    The standard deviation of the medical charges is 12105.48 


 The combination of mean and standard deviation is appropriate. The median wouldn't be suitable as it looks like more people pay under 15000 for medical charges. Also, the distribution is not normal and skewed right.

__Q:__ The administrator is concerned that the actual average charge has fallen below 12000, threatening the hospital's operational model. On the assumption that these data represent a random sample of charges, how would you justify that these data allow you to answer that question? And what would be the most appropriate frequentist test, of the ones discussed so far, to apply?

__A:__ The data is not normally distributed and it looks like it is skewed to the right. We have a large sample size as well which means that the CLT should be ok to use. The mean is 13270.42 which isn't much higher than their concern average amount. Since we don't have the population mean in this example, I think the most appropriate frequentist test would be to use the CLT to resample the means and work toward a better distribution

__Q:__ Given the nature of the administrator's concern, what is the appropriate confidence interval in this case? A one-sided or two-sided interval? Calculate the critical value and the relevant 95% confidence interval for the mean and comment on whether the administrator should be concerned?

__A:__  I think this should be a one sided interval since we are concerned about the actual average charge fallen below 12000 and not concerned if it is over 12000. The mean is 13270.42 for the sample collected and should not be concerned at first glance.


```python
# Critical Value with sample size of 1338
n = len(medical.charges)
dof = n - 1
p = 0.95
critical_t = t.ppf(p, dof)
print('The critical t value for one tailed 95% confidence interval is: {} '.format(critical_t))
```

    The critical t value for one tailed 95% confidence interval is: 1.6459941145571317 



```python
# Standard Error of the Mean (a.k.a. the standard deviation of the sampling distribution of the sample mean!
se = (np.std(medical.charges)) / (np.sqrt(n))
moe = critical_t * se # Margin of Error
print('The Margin of error is: {} '.format(moe))
```

    The Margin of error is: 544.7314053390934 



```python
lower = (np.mean(medical.charges)) - moe
lower
#print('The lower is {}'.format(lower) + "\n""The administrator shouldn't be concerened as we are 95 percent confident it lies above {}".format(lower))
```




    12725.690859802164



The administrator shouldn't be concerened as we are 95% confident that the actual average charge is above 12725.690859802164

The administrator then wants to know whether people with insurance really are charged a different amount to those without.

__Q:__ State the null and alternative hypothesis here. Use the _t_-test for the difference between means where the pooled standard deviation of the two groups is given by
\begin{equation}
s_p = \sqrt{\frac{(n_0 - 1)s^2_0 + (n_1 - 1)s^2_1}{n_0 + n_1 - 2}}
\end{equation}

and the *t* test statistic is then given by

\begin{equation}
t = \frac{\bar{x}_0 - \bar{x}_1}{s_p \sqrt{1/n_0 + 1/n_1}}.
\end{equation}

What assumption about the variances of the two groups are we making here?

__A:__ 
1. The H0 would be that people with insurance are charged the same.
2. The Ha would be that they are NOT charged the same.

The null hypothesis (H0) is that there is no difference between people with insurance and people without insurance, that they are charged the same.

The alternative hypothesis is that the people with insurance are charged differently than those without insurance.

My assumptions are:

When we plot the data, we would see a normal distribution (bell-shaped distribution curve).
Equal variance exists when the standard deviations of samples are equal or approximately equal.

__Q:__ Perform this hypothesis test both manually, using the above formulae, and then using the appropriate function from [scipy.stats](https://docs.scipy.org/doc/scipy/reference/stats.html#statistical-tests) (hint, you're looking for a function to perform a _t_-test on two independent samples). For the manual approach, calculate the value of the test statistic and then its probability (the p-value). Verify you get the same results from both.

__A:__ 


```python
#print(medical.columns)
# This is a binary column so 1 means it has insurance claim 0 means it has no claims
#print(medical.insuranceclaim.head()) 
```


```python
insured_charges = medical.loc[medical['insuranceclaim'] == 1, 'charges']
uninsured_charges = medical.loc[medical['insuranceclaim'] == 0, 'charges']
n1 = sum(medical['insuranceclaim'] == 1)
x1 = (np.mean(insured_charges))
s1 = (np.std(insured_charges,ddof = 1))

n0 = sum(medical['insuranceclaim'] == 0)
x0 = (np.mean(uninsured_charges))
s0 = (np.std(uninsured_charges, ddof =1))

print('The Uninsured: \n','count', n0, 'mean', x0, 'standard deviation', s0)
print('The Insured: \n', 'count', n1, 'mean', x1, 'standard deviation', s1)
```

    The Uninsured: 
     count 555 mean 8821.421892306294 standard deviation 6446.510126811736
    The Insured: 
     count 783 mean 16423.928276537663 standard deviation 14045.928418802127



```python
# breaking down the formula

a = (n0 - 1) * s0 **2 # first part of the formula
b = (n1 - 1) * s1 **2 # second part of the formula

dof = (n0 + n1 - 2)

sp = np.sqrt((a + b)/dof) # pooled standard deviation

print('sp:', sp)

t_test = ((x0 - x1)/(sp*(np.sqrt(1/n0 + 1/n1))))

print('t test:', t_test)
```

    sp: 11520.034268775256
    t test: -11.89329903087671



```python
# For a two-sided test, if the value of the test statistic from your sample is negative, then the p-value is equal to 
# two times the p-value for the lower-tailed p-value (i.e. 2 * cdf(ts)) 
p_value = 2 * t.cdf(t_test, dof)
print(f'The p value is: ', p_value)
```

    The p value is:  4.461230231620972e-31


The p value is less than 0.05 so we reject the null hypothesis (H0). This means that people with insurance are charged differently!


```python
# Using the appropriate function from scipy.stats to Calculate the T-test for the means of two independent samples.
from scipy.stats import ttest_ind

# (stats.ttest_ind) This is a two-sided test for the null hypothesis that 2 independent samples have identical average 
# This test assumes that the populations have identical variances by default.
print(ttest_ind(uninsured,insured))


```

    Ttest_indResult(statistic=-11.893299030876712, pvalue=4.461230231620717e-31)


Congratulations! Hopefully you got the exact same numerical results. This shows that you correctly calculated the numbers by hand. Secondly, you used the correct function and saw that it's much easier to use. All you need to do pass your data to it.

__Q:__ In the above calculations, we assumed the sample variances were equal. We may well suspect they are not (we'll explore this in another assignment). The calculation becomes a little more complicated to do by hand in this case, but we now know of a helpful function. Check the documentation for the function to tell it not to assume equal variances and perform the test again.

__A:__


```python
# Let's not assume equal variances and perform this test again
print(ttest_ind(uninsured,insured, equal_var = False))
```

    Ttest_indResult(statistic=-13.298031957975649, pvalue=1.1105103216309125e-37)


__Q:__ Conceptual question: look through the documentation for statistical test functions in scipy.stats. You'll see the above _t_-test for a sample, but can you see an equivalent one for performing a *z*-test from a sample? Comment on your answer.


```python
#import scipy
#help(scipy.stats.zscore)

```

__A:__ The scipy.stats has a zscore method that we can use. 

zscore(a, axis=0, ddof=0)
    Calculate the z score of each value in the sample, relative to the
    sample mean and standard deviation.

## Learning outcomes

Having completed this project notebook, you now have good hands-on experience:
* using the central limit theorem to help you apply frequentist techniques to answer questions that pertain to very non-normally distributed data from the real world
* performing inference using such data to answer business questions
* forming a hypothesis and framing the null and alternative hypotheses
* testing this using a _t_-test

35fa5fde6b4d1544cdf47b91d87f2f99e0f95a95
ipynb
Jupyter Notebook
Python Statistics/Mini Projects/inferential_statistics_frequentist_mini-projects6.28.19/inferential_statistics_1b-Q6.25.ipynb
atalebizadeh/DS-Career-Track
8bf78ef11041aef94810a392022cd51b94462d9c
MIT
Python Statistics/Mini Projects/inferential_statistics_frequentist_mini-projects6.28.19/inferential_statistics_1b-Q6.25.ipynb
atalebizadeh/DS-Career-Track
8bf78ef11041aef94810a392022cd51b94462d9c
MIT
Python Statistics/Mini Projects/inferential_statistics_frequentist_mini-projects6.28.19/inferential_statistics_1b-Q6.25.ipynb
atalebizadeh/DS-Career-Track
8bf78ef11041aef94810a392022cd51b94462d9c
MIT
Qwen/Qwen-72B
1. YES
2. YES

