# 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
import scipy.stats
from scipy.stats import t
from numpy.random import seed
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
# plot histogram of charges
_ = plt.hist(medical['charges'])
_ = plt.xlabel('patient charges')
_ = plt.ylabel('number of patients')
_ = plt.title('Distribution of patient charges ')
```


```python
# calculate the mean
mean_charges = np.mean(medical['charges'])
print(mean_charges)
```

    13270.422265141257



```python
# calculate the std
std_charges = np.std(medical['charges'], ddof=1)
print(std_charges)
```

    12110.011236693994


__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:__ We should calculate a confidence interval to determine whether the random sample's calculated mean falls below 12,000 when the margin of error is applied.  Because the true population standard deviation is unknown and the sample size is relatively small (1,338), we should use the t distribution to calculate the confidence interval.

__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:__ A one-sided confidence interval is appropriate given that the administrator is only concerned with the lower bound (i.e., data points below 12,000).  


```python
# calculate the 95% margin of error using t value

# Step 1 - calculate the critical t value
critical_t = t.ppf(1-0.05, 1337)
print('The t value is {}'.format(critical_t))

# Step 2 - find the standard error (std / sqrt of sample size)
std_error = std_charges / np.sqrt(1338)
print('The standard error is {}'.format(std_error))

# calculate margin of error (t * std_error)
moe = critical_t * std_error
print('The margin of error is {}'.format(moe))
```

    The t value is 1.6459941145571317
    The standard error is 331.06745431568226
    The margin of error is 544.9350813250251



```python
# calculate the 95% confidence interval for the mean
print(mean_charges - moe)
```

    12725.4871838


__A:__ Applying the 95% confidence interval gives us a mean value of 12,725.  The administrator therefore should be comfortable that the hospital's average charge is above 12,000.

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:__

__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:__ 

The null hypothesis is that the mean values of the no insurance claim charges and the insurance claim charges are equal.

The alternative hypothesis is that the two mean values are not equal.


```python
# create dataframe for no insurance claims
print('No Insurance Claims')
medical_no_ins = medical[medical['insuranceclaim'] == 0]
print('shape = {}'.format(medical_no_ins.shape))

# calculate the mean of no insurance claims charges
medical_no_ins_mean = np.mean(medical_no_ins['charges'])
print('mean = {}'.format(medical_no_ins_mean))

# calcluate the std of no insurance claims charges
medical_no_ins_std = np.std(medical_no_ins['charges'])
print('std = {}'.format(medical_no_ins_std))
```

    No Insurance Claims
    shape = (555, 8)
    mean = 8821.421892306294
    std = 6440.699841605233



```python
# create dataframe for insurance claims
print('Insured Claims')
medical_ins = medical[medical['insuranceclaim'] == 1]
print('shape = {}'.format(medical_ins.shape))

# calculate the mean of insurance claims charges
medical_ins_mean = np.mean(medical_ins['charges'])
print('mean = {}'.format(medical_ins_mean))

# calculate the std of insurance claims charges
medical_ins_std = np.std(medical_ins['charges'])
print('std = {}'.format(medical_ins_std))
```

    Insured Claims
    shape = (783, 8)
    mean = 16423.928276537663
    std = 14036.956250260411



```python
# calculate pooled std
pooled_std = np.sqrt(((554 * medical_no_ins_std**2) + (782 * medical_ins_std**2)) / (555 + 783 -2))
print(pooled_std)
```

    11512.2828992



```python
# calculate t test statistic
t_test = (medical_no_ins_mean - medical_ins_mean) / (pooled_std * np.sqrt((1/555 + 1/783)))
print(t_test)
```

    -11.9013069436



```python

```

Looking up the p-value on a t distribution chart shows that the p-value is going to be approaching 0%, which means that the null hypothesis is almost certainly incorrect and that insured claims likely charge a different amount than non-insured claims.


```python
# calculate the t test using scipy
t_test_scipy = scipy.stats.ttest_ind(medical_no_ins['charges'], medical_ins['charges'])
print(t_test_scipy)
```

    Ttest_indResult(statistic=-11.893299030876712, pvalue=4.4612302316207173e-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
# calculate the t test using scipy with unequal variances
scipy.stats.ttest_ind(medical_no_ins['charges'], medical_ins['charges'], 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.

__A:__  I do not see an equivalent test function in scipy.stats for a z-test. 

## 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

1c9da729bd926af9876324fd50b18bf25ff0a3cb
ipynb
Jupyter Notebook
jupyter-notebooks/other-online-courses/Chapter_8_Frequentist_Statistics/inferential_statistics_1b-Q6.25.ipynb
totalgood/dsdh
f74324543932c9c31cf0e1ffbde3f9c0562e23f0
MIT
jupyter-notebooks/other-online-courses/Chapter_8_Frequentist_Statistics/inferential_statistics_1b-Q6.25.ipynb
totalgood/dsdh
f74324543932c9c31cf0e1ffbde3f9c0562e23f0
MIT
jupyter-notebooks/other-online-courses/Chapter_8_Frequentist_Statistics/inferential_statistics_1b-Q6.25.ipynb
totalgood/dsdh
f74324543932c9c31cf0e1ffbde3f9c0562e23f0
MIT
2020-01-23T04:45:28.000Z
2020-01-23T04:45:28.000Z
Qwen/Qwen-72B
1. YES
2. YES

