<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Examples and Exercises from Think Stats, 2nd Edition
http
Step1:  Analytic methods
If we know the parameters of the sampling distribution, we can compute confidence intervals and p-values analytically, which is computationally faster than resampling.
Step2:  Here's the confidence interval for the estimated mean.
Step3:  normal.py provides a Normal class that encapsulates what we know about arithmetic operations on normal distributions.
Step4:  We can use it to compute the sampling distribution of the mean.
Step5:  And then compute a confidence interval.
Step7:  Central Limit Theorem
If you add up independent variates from a distribution with finite mean and variance, the sum converges on a normal distribution.
The following function generates samples with difference sizes from an exponential distribution.
Step9:  This function generates normal probability plots for samples with various sizes.
Step10:  The following plot shows how the sum of exponential variates converges to normal as sample size increases.
Step12:  The lognormal distribution has higher variance, so it requires a larger sample size before it converges to normal.
Step14:  The Pareto distribution has infinite variance, and sometimes infinite mean, depending on the parameters.  It violates the requirements of the CLT and does not generally converge to normal.
Step18:  If the random variates are correlated, that also violates the CLT, so the sums don't generally converge.
To generate correlated values, we generate correlated normal values and then transform to whatever distribution we want.
Step19:  Difference in means
Let's use analytic methods to compute a CI and p-value for an observed difference in means.
The distribution of pregnancy length is not normal, but it has finite mean and variance, so the sum (or mean) of a few thousand samples is very close to normal.
Step21:  The following function computes the sampling distribution of the mean for a set of values and a given sample size.
Step22:  Here are the sampling distributions for the means of the two groups under the null hypothesis.
Step23:  And the sampling distribution for the difference in means.
Step24:  Under the null hypothesis, here's the chance of exceeding the observed difference.
Step25:  And the chance of falling below the negated difference.
Step27:  The sum of these probabilities is the two-sided p-value.
Testing a correlation
Under the null hypothesis (that there is no correlation), the sampling distribution of the observed correlation (suitably transformed) is a "Student t" distribution.
Step30:  The following is a HypothesisTest that uses permutation to estimate the sampling distribution of a correlation.
Step32:  Now we can estimate the sampling distribution by permutation and compare it to the Student t distribution.
Step33:  That confirms the analytic result.  Now we can use the CDF of the Student t distribution to compute a p-value.
Step35:  Chi-squared test
The reason the chi-squared statistic is useful is that we can compute its distribution under the null hypothesis analytically.
Step36:  Again, we can confirm the analytic result by comparing values generated by simulation with the analytic distribution.
Step37:  And then we can use the analytic distribution to compute p-values.
Step38:  Exercises
Exercise
Step39:  Exercise
Step40:  Exercise
<ASSISTANT_TASK:>
Python Code:
from __future__ import print_function, division
%matplotlib inline
import numpy as np
import pandas as pd
import random
import thinkstats2
import thinkplot
Explanation: Examples and Exercises from Think Stats, 2nd Edition
http://thinkstats2.com
Copyright 2016 Allen B. Downey
MIT License: https://opensource.org/licenses/MIT
End of explanation
import scipy.stats
def EvalNormalCdfInverse(p, mu=0, sigma=1):
    return scipy.stats.norm.ppf(p, loc=mu, scale=sigma)
Explanation: Analytic methods
If we know the parameters of the sampling distribution, we can compute confidence intervals and p-values analytically, which is computationally faster than resampling.
End of explanation
EvalNormalCdfInverse(0.05, mu=90, sigma=2.5)
EvalNormalCdfInverse(0.95, mu=90, sigma=2.5)
Explanation: Here's the confidence interval for the estimated mean.
End of explanation
from normal import Normal
dist = Normal(90, 7.5**2)
dist
Explanation: normal.py provides a Normal class that encapsulates what we know about arithmetic operations on normal distributions.
End of explanation
dist_xbar = dist.Sum(9) / 9
dist_xbar.sigma
Explanation: We can use it to compute the sampling distribution of the mean.
End of explanation
dist_xbar.Percentile(5), dist_xbar.Percentile(95)
Explanation: And then compute a confidence interval.
End of explanation
def MakeExpoSamples(beta=2.0, iters=1000):
    Generates samples from an exponential distribution.
    beta: parameter
    iters: number of samples to generate for each size
    returns: list of samples
    
    samples = []
    for n in [1, 10, 100]:
        sample = [np.sum(np.random.exponential(beta, n))
                  for _ in range(iters)]
        samples.append((n, sample))
    return samples
Explanation: Central Limit Theorem
If you add up independent variates from a distribution with finite mean and variance, the sum converges on a normal distribution.
The following function generates samples with difference sizes from an exponential distribution.
End of explanation
def NormalPlotSamples(samples, plot=1, ylabel=''):
    Makes normal probability plots for samples.
    samples: list of samples
    label: string
    
    for n, sample in samples:
        thinkplot.SubPlot(plot)
        thinkstats2.NormalProbabilityPlot(sample)
        thinkplot.Config(title='n=%d' % n,
                         legend=False,
                         xticks=[],
                         yticks=[],
                         xlabel='random normal variate',
                         ylabel=ylabel)
        plot += 1
Explanation: This function generates normal probability plots for samples with various sizes.
End of explanation
thinkplot.PrePlot(num=3, rows=2, cols=3)
samples = MakeExpoSamples()
NormalPlotSamples(samples, plot=1,
                  ylabel='sum of expo values')
Explanation: The following plot shows how the sum of exponential variates converges to normal as sample size increases.
End of explanation
def MakeLognormalSamples(mu=1.0, sigma=1.0, iters=1000):
    Generates samples from a lognormal distribution.
    mu: parmeter
    sigma: parameter
    iters: number of samples to generate for each size
    returns: list of samples
    
    samples = []
    for n in [1, 10, 100]:
        sample = [np.sum(np.random.lognormal(mu, sigma, n))
                  for _ in range(iters)]
        samples.append((n, sample))
    return samples
thinkplot.PrePlot(num=3, rows=2, cols=3)
samples = MakeLognormalSamples()
NormalPlotSamples(samples, ylabel='sum of lognormal values')
Explanation: The lognormal distribution has higher variance, so it requires a larger sample size before it converges to normal.
End of explanation
def MakeParetoSamples(alpha=1.0, iters=1000):
    Generates samples from a Pareto distribution.
    alpha: parameter
    iters: number of samples to generate for each size
    returns: list of samples
    
    samples = []
    for n in [1, 10, 100]:
        sample = [np.sum(np.random.pareto(alpha, n))
                  for _ in range(iters)]
        samples.append((n, sample))
    return samples
thinkplot.PrePlot(num=3, rows=2, cols=3)
samples = MakeParetoSamples()
NormalPlotSamples(samples, ylabel='sum of Pareto values')
Explanation: The Pareto distribution has infinite variance, and sometimes infinite mean, depending on the parameters.  It violates the requirements of the CLT and does not generally converge to normal.
End of explanation
def GenerateCorrelated(rho, n):
    Generates a sequence of correlated values from a standard normal dist.
    
    rho: coefficient of correlation
    n: length of sequence
    returns: iterator
    
    x = random.gauss(0, 1)
    yield x
    sigma = np.sqrt(1 - rho**2)
    for _ in range(n-1):
        x = random.gauss(x * rho, sigma)
        yield x
def GenerateExpoCorrelated(rho, n):
    Generates a sequence of correlated values from an exponential dist.
    rho: coefficient of correlation
    n: length of sequence
    returns: NumPy array
    
    normal = list(GenerateCorrelated(rho, n))
    uniform = scipy.stats.norm.cdf(normal)
    expo = scipy.stats.expon.ppf(uniform)
    return expo
def MakeCorrelatedSamples(rho=0.9, iters=1000):
    Generates samples from a correlated exponential distribution.
    rho: correlation
    iters: number of samples to generate for each size
    returns: list of samples
        
    samples = []
    for n in [1, 10, 100]:
        sample = [np.sum(GenerateExpoCorrelated(rho, n))
                  for _ in range(iters)]
        samples.append((n, sample))
    return samples
thinkplot.PrePlot(num=3, rows=2, cols=3)
samples = MakeCorrelatedSamples()
NormalPlotSamples(samples, ylabel='sum of correlated exponential values')
Explanation: If the random variates are correlated, that also violates the CLT, so the sums don't generally converge.
To generate correlated values, we generate correlated normal values and then transform to whatever distribution we want.
End of explanation
import first
live, firsts, others = first.MakeFrames()
delta = firsts.prglngth.mean() - others.prglngth.mean()
delta
Explanation: Difference in means
Let's use analytic methods to compute a CI and p-value for an observed difference in means.
The distribution of pregnancy length is not normal, but it has finite mean and variance, so the sum (or mean) of a few thousand samples is very close to normal.
End of explanation
def SamplingDistMean(data, n):
    Computes the sampling distribution of the mean.
    data: sequence of values representing the population
    n: sample size
    returns: Normal object
    
    mean, var = data.mean(), data.var()
    dist = Normal(mean, var)
    return dist.Sum(n) / n
Explanation: The following function computes the sampling distribution of the mean for a set of values and a given sample size.
End of explanation
dist1 = SamplingDistMean(live.prglngth, len(firsts))
dist2 = SamplingDistMean(live.prglngth, len(others))
Explanation: Here are the sampling distributions for the means of the two groups under the null hypothesis.
End of explanation
dist_diff = dist1 - dist2
dist
Explanation: And the sampling distribution for the difference in means.
End of explanation
1 - dist_diff.Prob(delta)
Explanation: Under the null hypothesis, here's the chance of exceeding the observed difference.
End of explanation
dist_diff.Prob(-delta)
Explanation: And the chance of falling below the negated difference.
End of explanation
def StudentCdf(n):
    Computes the CDF correlations from uncorrelated variables.
    n: sample size
    returns: Cdf
    
    ts = np.linspace(-3, 3, 101)
    ps = scipy.stats.t.cdf(ts, df=n-2)
    rs = ts / np.sqrt(n - 2 + ts**2)
    return thinkstats2.Cdf(rs, ps)
Explanation: The sum of these probabilities is the two-sided p-value.
Testing a correlation
Under the null hypothesis (that there is no correlation), the sampling distribution of the observed correlation (suitably transformed) is a "Student t" distribution.
End of explanation
import hypothesis
class CorrelationPermute(hypothesis.CorrelationPermute):
    Tests correlations by permutation.
    def TestStatistic(self, data):
        Computes the test statistic.
        data: tuple of xs and ys
        
        xs, ys = data
        return np.corrcoef(xs, ys)[0][1]
Explanation: The following is a HypothesisTest that uses permutation to estimate the sampling distribution of a correlation.
End of explanation
def ResampleCorrelations(live):
    Tests the correlation between birth weight and mother's age.
    live: DataFrame for live births
    returns: sample size, observed correlation, CDF of resampled correlations
    
    live2 = live.dropna(subset=['agepreg', 'totalwgt_lb'])
    data = live2.agepreg.values, live2.totalwgt_lb.values
    ht = CorrelationPermute(data)
    p_value = ht.PValue()
    return len(live2), ht.actual, ht.test_cdf
n, r, cdf = ResampleCorrelations(live)
model = StudentCdf(n)
thinkplot.Plot(model.xs, model.ps, color='gray',
               alpha=0.5, label='Student t')
thinkplot.Cdf(cdf, label='sample')
thinkplot.Config(xlabel='correlation',
                 ylabel='CDF',
                 legend=True, loc='lower right')
Explanation: Now we can estimate the sampling distribution by permutation and compare it to the Student t distribution.
End of explanation
t = r * np.sqrt((n-2) / (1-r**2))
p_value = 1 - scipy.stats.t.cdf(t, df=n-2)
print(r, p_value)
Explanation: That confirms the analytic result.  Now we can use the CDF of the Student t distribution to compute a p-value.
End of explanation
def ChiSquaredCdf(n):
    Discrete approximation of the chi-squared CDF with df=n-1.
    n: sample size
    
    returns: Cdf
    
    xs = np.linspace(0, 25, 101)
    ps = scipy.stats.chi2.cdf(xs, df=n-1)
    return thinkstats2.Cdf(xs, ps)
Explanation: Chi-squared test
The reason the chi-squared statistic is useful is that we can compute its distribution under the null hypothesis analytically.
End of explanation
data = [8, 9, 19, 5, 8, 11]
dt = hypothesis.DiceChiTest(data)
p_value = dt.PValue(iters=1000)
n, chi2, cdf = len(data), dt.actual, dt.test_cdf
model = ChiSquaredCdf(n)
thinkplot.Plot(model.xs, model.ps, color='gray',
                   alpha=0.3, label='chi squared')
thinkplot.Cdf(cdf, label='sample')
thinkplot.Config(xlabel='chi-squared statistic',
                 ylabel='CDF',
                 loc='lower right')
Explanation: Again, we can confirm the analytic result by comparing values generated by simulation with the analytic distribution.
End of explanation
p_value = 1 - scipy.stats.chi2.cdf(chi2, df=n-1)
print(chi2, p_value)
Explanation: And then we can use the analytic distribution to compute p-values.
End of explanation
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here
Explanation: Exercises
Exercise:    In Section 5.4, we saw that the distribution of adult weights is approximately lognormal. One possible explanation is that the weight a person gains each year is proportional to their current weight. In that case, adult weight is the product of a large number of multiplicative factors:
w = w0 f1 f2 ... fn  
where w is adult weight, w0 is birth weight, and fi is the weight gain factor for year i.
The log of a product is the sum of the logs of the factors:
logw = logw0 + logf1 + logf2 + ... + logfn 
So by the Central Limit Theorem, the distribution of logw is approximately normal for large n, which implies that the distribution of w is lognormal.
To model this phenomenon, choose a distribution for f that seems reasonable, then generate a sample of adult weights by choosing a random value from the distribution of birth weights, choosing a sequence of factors from the distribution of f, and computing the product. What value of n is needed to converge to a lognormal distribution?
End of explanation
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here
Explanation: Exercise: In Section 14.6 we used the Central Limit Theorem to find the sampling distribution of the difference in means, δ, under the null hypothesis that both samples are drawn from the same population.
We can also use this distribution to find the standard error of the estimate and confidence intervals, but that would only be approximately correct. To be more precise, we should compute the sampling distribution of δ under the alternate hypothesis that the samples are drawn from different populations.
Compute this distribution and use it to calculate the standard error and a 90% confidence interval for the difference in means.
End of explanation
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here
Explanation: Exercise: In a recent paper, Stein et al. investigate the effects of an intervention intended to mitigate gender-stereotypical task allocation within student engineering teams.
Before and after the intervention, students responded to a survey that asked them to rate their contribution to each aspect of class projects on a 7-point scale.
Before the intervention, male students reported higher scores for the programming aspect of the project than female students; on average men reported a score of 3.57 with standard error 0.28. Women reported 1.91, on average, with standard error 0.32.
Compute the sampling distribution of the gender gap (the difference in means), and test whether it is statistically significant. Because you are given standard errors for the estimated means, you don’t need to know the sample size to figure out the sampling distributions.
After the intervention, the gender gap was smaller: the average score for men was 3.44 (SE 0.16); the average score for women was 3.18 (SE 0.16). Again, compute the sampling distribution of the gender gap and test it.
Finally, estimate the change in gender gap; what is the sampling distribution of this change, and is it statistically significant?
End of explanation
<END_TASK>