Gå til indholdet

Hypotesetest

Sessionsmateriale:

Ross: 8.1, 8.2, 8.3, 8.4 og 8.6. Afsnit 8.5 (test af varians med \(\chi^2\)) og 8.7 (Poisson) indgår ikke i pensum.

Python tutorial
Se Tutorial 8: Hypotesetest

Download tutorial som notebook (.ipynb)

Se tutorial som markdown

Recap og øvelser

Sessionnoter

Sessionsmateriale

Video Materiale:

Der er to playlister med hhv. 16 og 8 videoer. Videoerne gennemgår de grundlæggende begreber og metoder for hypotesetest; tests for to stikprøver og parret t-test. Test for andelse gennemgås ikke i videoerne, men her henvises til tutorialen og sessionens øvelser.

Hypotesetest

Inference for Two Population Means


Sessionbeskrivelse

I session 6 så vi stikprøvefordelinger, og i session 7 brugte vi dem til intervalestimation og konfidensintervaller. I denne session går vi skridtet videre til hypotesetest: vi stiller et præcist spørgsmål om en populationsparameter (formuleret som en nullhypotese \(H_0\) mod en alternativ hypotese \(H_1\)), beregner en teststørrelse ud fra data og træffer en beslutning ud fra enten et forkastelsesområde (kritiske værdier) eller en p-værdi sammenlignet med et valgt signifikansniveau \(\alpha\).

I denne session gennemgår vi de grundlæggende begreber inden for hypotesetest, herunder type I- og type II-fejl. Vi ser på tests for middelværdien i én normalpopulation (\(z\)-test når \(\sigma\) er kendt; \(t\)-test når \(\sigma\) estimeres med \(s\)) og i to populationer (uafhængige stikprøver og parrede observationer, jf. Ross 8.4). Desuden arbejder vi med test for én andel og forskel mellem to andele (stor-stikprøve-\(z\), Ross 8.6). Test af varians med \(\chi^2\) (Ross 8.5) og Poisson (8.7) indgår ikke. Mange metoder har en tæt forbindelse til konfidensintervallerne fra session 7.

Centrale begreber

  • Nullhypotese \(H_0\) og alternativ hypotese \(H_1\): hvad vi antager under testen, og hvad data skal tale imod
  • Ensidet vs. tosidet test: retning af alternativet og valg af kritisk område / p-værdi
  • Teststørrelse, kritisk værdi og forkastelsesområde: standardiseret mål og beslutningsregel ved fast \(\alpha\)
  • p-værdi: observeret “ekstremitet” under \(H_0\); sammenligning med \(\alpha\)
  • Signifikansniveau \(\alpha\) og type I-fejl: risiko for at forkaste en sand \(H_0\)
  • Type II-fejl: risiko for ikke at forkaste en falsk \(H_0\)
  • \(z\)-test og \(t\)-test for \(\mu\) (én population): normalmodel med kendt hhv. ukendt \(\sigma\)
  • To stikprøver / uafhængige grupper: sammenligning af to middelværdier (\(t\)-test med fælles/pooled varians eller Welchs \(t\)-test ved ulige varianser)
  • Parrede data: test af middel forskel som \(t\)-test på differenser
  • Test for andel \(p\): stor-stikprøve-\(z\) for én population (binomialgrundlag)

Læringsmål

  • Kunne opstille \(H_0\) og \(H_1\), skelne mellem ensidet og tosidet test og fortolke signifikansniveau og p-værdi korrekt.
  • Kunne gennemføre og fortolke \(z\)-test for populationsmiddelværdi når \(\sigma\) er kendt, og \(t\)-test når \(\sigma\) estimeres med \(s\).
  • Kunne gennemføre og fortolke \(t\)-test for to uafhængige normalstikprøver (sammenligning af to middelværdier) og parret \(t\)-test på differenser.
  • Kunne gennemføre stor-stikprøve-test for én populationsandel og for forskellen mellem to andele, og relatere til konfidensintervaller for \(p\).
  • Kunne forklare type I- og type II-fejl på et intuitivt niveau.

Øvelser

Øvelse 1

Cloud seeding has been studied for many decades as a weather modification procedure (for an interesting study of this subject, see the article in Technometrics, "A Bayesian Analysis of a Multiplicative Treatment Effect in Weather Modification," 1975 , Vol. 17, pp. 161-166). The rainfall in acre-feet from 20 clouds that were selected at random and seeded with silver nitrate follows: 18.0,30.7,19.8,27.1,22.3,18.8,31.8,23.4, 21.2,27.9,31.9,27.1,25.0,24.7,26.9,21.8,29.2,34.8,26.7, and 31.6.

  1. Can you support a claim that mean rainfall from seeded clouds exceeds 25 acre-feet? Use \(\alpha=0.01\). Find the \(P\)-value.
  2. Check that rainfall is normally distributed.
  3. Explain how the question in part (a) could be answered by constructing a one-sided confidence bound on the mean diameter.
 
  1. 1) The parameter of interest is the true mean rainfall, \(\mu\).

    2) \(H_0: \mu = 25\)

    3) \(H_1: \mu > 25\).

    4) \(\mathrm{t}_0=\frac{\bar{x}-\mu}{s / \sqrt{n}}\)

    5) Reject \(\mathrm{H}_0\) if \(\mathrm{t}_0>\mathrm{t}_{\alpha, \mathrm{n}-1}\) where \(\alpha=0.01\) and \(\mathrm{t}_{0.01,19}=2.539\) for \(\mathrm{n}=20\)

    6) \(\overline{\mathrm{x}}=26.04 \mathrm{~s}=4.78 \mathrm{n}=20\)

    \[ \mathrm{t}_0=\frac{26.04-25}{4.78 / \sqrt{20}}=0.97 \]

    7) Because \(0.97<2.539\) fail to reject the null hypothesis. There is insufficient evidence to conclude that the true mean rainfall is greater than 25 acre-feet at \(\alpha=0.01\). The \(0.10<\mathrm{P}\)-value \(<0.25\).

  2. The data on the normal probability plot falls along a line. Therefore, the normality assumption is reasonable.

  3. \(99 \%\) lower confidence bound on the mean diameter

    \[ \begin{aligned} & \bar{x}-t_{0.01,19}\left(\frac{s}{\sqrt{n}}\right) \leq \mu \\ & 26.04-2.539\left(\frac{4.78}{\sqrt{20}}\right) \leq \mu \\ & 23.326 \leq \mu \end{aligned} \]

    Because the lower limit of the CI is less than 25 there is insufficient evidence to conclude that the true mean rainfall is greater than 25 acre-feet at \(\alpha=0.01\).

Øvelse 2

A 1992 article in the Journal of the American Medical Association ("A Critical Appraisal of 98.6 Degrees F, the Upper Limit of the Normal Body Temperature, and Other Legacies of Carl Reinhold August Wunderlich") reported body temperature, gender, and heart rate for a number of subjects. The body temperatures for 25 female subjects follow: \(97.8,97.2\), \(97.4,97.6,97.8,97.9,98.0,98.0,98.0,98.1,98.2,98.3,98.3\), \(98.4,98.4,98.4,98.5,98.6,98.6,98.7,98.8,98.8,98.9,98.9\), and 99.0.

  1. Test the hypothesis \(H_0: \mu=98.6\) versus \(H_1: \mu \neq 98.6\), using \(\alpha=0.05\). Find the \(P\)-value.
  2. Check the assumption that female body temperature is normally distributed.
  3. Explain how the question in part (a) could be answered by constructing a two-sided confidence interval on the mean female body temperature.
 
  1. 1) The parameter of interest is the true mean female body temperature, \(\mu\).

    2) \(H_0: \mu = 98.6\)

    3) \(H_1: \mu \neq 98.6\).

    4) \(t_0=\frac{\bar{x}-\mu}{s / \sqrt{n}}\)

    5) Reject \(\mathrm{H}_0\) if \(\left|\mathrm{t}_0\right| \geq \mathrm{t}_{\alpha / 2, \mathrm{n}-1} \quad\) where \(\alpha=0.05\) and \(\mathrm{t}_{\alpha / 2, \mathrm{n}-1}=2.064\) for \(\mathrm{n}=25\)

    6) \(\bar{x}=98.264, \mathrm{~s}=0.4821, \mathrm{n}=25\)

    \[ t_0=\frac{98.264-98.6}{0.4821 / \sqrt{25}}=-3.48 \]

    7) Because \(3.48>2.064\), reject the null hypothesis. Conclude that the true mean female body temperature differs from \(98.6^{\circ} \mathrm{F}\) at \(\alpha=0.05\).

    \[ P \text {-value }=2(0.001)=0.002 \]
  2. The data on the normal probability plot falls along a line. The normality assumption is reasonable.

  3. \(95 \%\) two sided confidence interval

    \[ \begin{aligned} \bar{x}-t_{0.025,24}\left(\frac{s}{\sqrt{n}}\right) & \leq \mu \leq \bar{x}+t_{0.025,24}\left(\frac{s}{\sqrt{n}}\right) \\ 98.264-2.064\left(\frac{0.4821}{\sqrt{25}}\right) & \leq \mu \leq 98.264+2.064\left(\frac{0.4821}{\sqrt{25}}\right) \\ 98.065 & \leq \mu \leq 98.463 \end{aligned} \]

    We conclude that the mean female body temperature differs from 98.6 at \(\alpha=0.05\) because the value is not included inside the confidence interval.

Øvelse 3

An article in the British Medical Journal ["Comparison of Treatment of Renal Calculi by Operative Surgery, Percutaneous Nephrolithotomy, and Extra-Corporeal Shock Wave Lithotripsy" (1986, Vol. 292, pp. 879-882)] repeated that percutaneous nephrolithotomy (PN) had a success rate in removing kidney stones of 289 of 350 patients. The traditional method was \(78 \%\) effective.

  1. Is there evidence that the success rate for PN is greater than the historical success rate? Find the \(P\)-value.
  2. Explain how the question in part (a) could be answered with a confidence interval.
 
  1. 1) The parameter of interest is the true success rate

    2) \(\mathrm{H}_0: p=0.78\)

    3) \(\mathrm{H}_1: p>0.78\)

    4) \(z_0=\frac{x-n p_0}{\sqrt{n p_0\left(1-p_0\right)}}\) or \(z_0=\frac{\hat{p}-p_0}{\sqrt{\frac{p_0\left(1-p_0\right)}{n}}}\); Either approach will yield the same conclusion

    5) Reject \(H_0\) if \(\mathrm{z}_0>\mathrm{Z}_\alpha\). Since the value for \(\alpha\) is not given. We assume \(\alpha=0.05\) and \(\mathrm{z}_\alpha=\mathrm{z}_{0.05}=1.65\)

    6)

    \(x=289\)

    \(n=350\)

    \(\hat{p}=\frac{289}{350} \cong 0.83\)

    \[ z_0=\frac{x-n p_0}{\sqrt{n p_0\left(1-p_0\right)}}=\frac{289-350(0.78)}{\sqrt{350(0.78)(0.22)}}=2.06 \]

    7) Because \(2.06>1.65\), reject the null hypothesis and conclude the true success rate is greater than 0.78 at \(\alpha=0.05\).

    \[ \text { P-value }=1-0.9803=0.0197 \]
  2. The \(95 \%\) lower confidence interval:

    \[ \begin{array}{r} \hat{p}-z_\alpha \sqrt{\frac{\hat{p}(1-\hat{p})}{n}} \leq p \\ .83-1.65 \sqrt{\frac{0.83(0.17)}{350}} \leq p \\ 0.7969 \leq p \end{array} \]

    Because the hypothesized value is not in the confidence interval \((0.78<0.7969)\), reject the null hypothesis.

Øvelse 4

An article in Fortune (September 21, 1992) claimed that nearly one-half of all engineers continue academic studies beyond the B.S. degree, ultimately receiving either an M.S. or a Ph.D. degree. Data from an article in Engineering Horizons (Spring 1990) indicated that 117 of 484 new engineering graduates were planning graduate study.

  1. Are the data from Engineering Horizons consistent with the claim reported by Fortune? Use \(\alpha=0.05\) in reaching your conclusions. Find the \(P\)-value for this test.
  2. Discuss how you could have answered the question in part (a) by constructing a two-sided confidence interval on \(p\).
 
  1. 1) The parameter of interest is the true proportion of engineering students planning graduate studies

    2) \(\mathrm{H}_0: \mathrm{p}=0.50\)

    3) \(\mathrm{H}_1: \mathrm{p} \neq 0.50\)

    4) \(z_0=\frac{x-n p_0}{\sqrt{n p_0\left(1-p_0\right)}}\) or \(z_0=\frac{\hat{p}-p_0}{\sqrt{\frac{p_0\left(1-p_0\right)}{n}}}\); Either approach will yield the same conclusion

    5) Reject \(\mathrm{H}_0\) if \(\mathrm{z}_0<-\mathrm{z}_{\alpha / 2}\) where \(\alpha=0.05\) and \(-\mathrm{z}_{\alpha / 2}=-\mathrm{z}_{0.025}=-1.96\) or \(\mathrm{z}_0>\mathrm{z}_{\alpha / 2}\) where \(\alpha=0.05\) and \(\mathrm{z}_{\alpha / 2}=\) \(\mathrm{z}_{0.025}=1.96\)

    6) \(\mathrm{x}=117 \mathrm{n}=484\)

    \[ \begin{aligned} & \hat{p}=\frac{117}{484}=0.2417 \\ & z_0=\frac{x-n p_0}{\sqrt{n p_0\left(1-p_0\right)}}=\frac{117-484(0.5)}{\sqrt{484(0.5)(0.5)}}=-11.36 \end{aligned} \]

    7) Because \(-11.36>-1.65\) reject the null hypothesis and conclude that the true proportion of engineering students planning graduate studies differs from 0.5 , at \(\alpha=0.05\).

    \[ \text { P-value }=2[1-\Phi(11.36)] \cong 0 \]
  2. \(\hat{p}=\frac{117}{484}=0.2417 \approx 0.242\)

    \[ \begin{aligned} \hat{p}-z_{\alpha / 2} \sqrt{\frac{\hat{p}(1-\hat{p})}{n}} & \leq p \leq \hat{p}+z_{\alpha / 2} \sqrt{\frac{\hat{p}(1-\hat{p})}{n}} \\ 0.242-1.96 \sqrt{\frac{0.242(0.758)}{484}} & \leq p \leq 0.242-1.96 \sqrt{\frac{0.242(0.758)}{484}} \\ 0.204 & \leq p \leq 0.280 \end{aligned} \]

    Because the \(95 \%\) confidence interval does not contain the value 0.5 we conclude that the true proportion of engineering students planning graduate studies differs from 0.5.

Øvelse 5 (Tidligere eksamensopgave)

Two different machines, \(A\) and \(B\), which are used to measure blood pressure, are tested on 12 different patients such that each patient has his/her blood pressure measured by both machines. The results for the systolic blood pressure are displayed in the table below:

Patient 1 2 3 4 5 6 7 8 9 10 11 12
Machine
A
119 130 141 123 149 156 134 108 123 138 119 156
Machine
B
112 126 145 112 138 156 130 112 112 119 112 152
  1. Determine the mean, standard deviation and interquartile range for both sets of data
  2. Is it possible to conclude with statistical significance that the two machines give different measurement? Design an appropriate test to answer this question.
  3. Explain what the P -value obtained in b) actually means.
 
  1. Machine A Machine B
    119 112
    130 126
    141 145
    123 112
    149 138
    156 156
    134 130
    108 112
    123 112
    138 119
    119 112
    156 152
    Mean 133 127,16667
    St. Dev. 15,462565 16,813595
    IQR 21 27,75
  2. Same patient measured on both machines → paired design. Test mean difference \(D = A - B\):

    • \(H_0\): \(\mathbb{E}[D] = 0\)
    • \(H_1\): \(\mathbb{E}[D] \neq 0\)
    import numpy as np
    from scipy.stats import ttest_rel
    
    machine_a = np.array([119, 130, 141, 123, 149, 156, 134, 108, 123, 138, 119, 156])
    machine_b = np.array([112, 126, 145, 112, 138, 156, 130, 112, 112, 119, 112, 152])
    
    t_stat, p_two = ttest_rel(machine_a, machine_b, alternative="two-sided")
    print(f"Paired t (H0: mean difference = 0): t = {t_stat:.4f}, p = {p_two:.4f}")
    

    Use a paired \(t\)-test (ttest_rel), not ttest_ind on the two columns as independent samples (Tutorial 8, §7). The output gives \(p \approx 0.0117\); reject \(H_0\) at \(\alpha = 0.05\) and conclude that the machines differ on average.

  3. The p-value is the probability, under \(H_0\) (no systematic difference between machines), of observing a paired \(t\)-statistic at least as extreme as the one from these data — not the probability that \(H_0\) is true. Here \(p \approx 0.0117\).

Øvelse 6 (Tidligere eksamensopgave)

An industrial safety program was recently instituted in the computer chip industry. The average weekly loss (averaged over 1 month) in labor-hours due to accidents in 10 similar plants both before and after the program are as follows:

Plant Before After
1 30.5 23
2 18.5 21
3 24.5 22
4 32 28.5
5 16 14.5
6 15 15.5
7 23.5 24.5
8 25.5 21
9 28 23.5
10 18 16.5
  1. Determine whether the safety program has had a significant effect on reducing labor-hours due to accidents in the 10 plants.
  2. Setup a \(95 \%\) confidence interval on the average difference and state how this interval could have been used to answer question a.
  3. Is there evidence to support the claim that the program has had an effect at the \(1 \%\) level of significance?
 
  1. Before = [30.5, 18.5, 24.5, 32, 16, 15, 23.5, 25.5, 28, 18]
    After = [23, 21, 22, 28.5, 14.5, 15.5, 24.5, 21, 23.5, 16.5]
    
    df = pd.DataFrame({'Before': Before,
                    'After': After})
    df['Difference'] = df['Before']- df['After']
    meandiff = np.mean(df['Difference'])
    

    We check for normality of the differences

    stats.probplot(df['Difference'], plot=plt)
    plt.ylabel('Difference in Labor-hours')
    plt.show()
    print('Skewness = ' + repr(round(stats.skew(df['Difference']),4)))
    print('Kurtosis = ' + repr(round(stats.kurtosis(df['Difference']),4)))
    fig, ax = plt.subplots()
    df['Difference'].plot.kde(ax=ax, legend=False, title='Distribution');
    

    Skewness = 0.1328

    Kurtosis = -0.7163

    Plotting

    n1 = len(df['Before'])
    SE1 = stats.sem(df['Before'])
    mean1 = np.mean(df['Before'])
    
    n2 = len(df['After'])
    SE2 = stats.sem(df['After'])
    mean2 = np.mean(df['After'])
    
    x1 = np.linspace(mean1-4*SE1, mean1+4*SE1, 1000)
    x2 = np.linspace(mean2-4*SE2, mean2+4*SE2, 1000)
    
    y1 = stats.t.pdf(x1, n1-1, mean1, SE1)
    y2 = stats.t.pdf(x2, n2-1, mean2, SE2)
    
    plt.plot(x1,y1, color='red')
    plt.plot(x2,y2, color='blue')
    
    plt.show()
    

    Hypothesis test (paired \(t\), aligned with Tutorial 8):

    from scipy.stats import ttest_rel
    
    t_stat, p_two = ttest_rel(df["Before"], df["After"], alternative="two-sided")
    alpha = 0.05
    print(f"t = {t_stat:.4f}, p (two-sided) = {p_two:.4f}")
    if p_two < alpha:
        print(f"Reject H0 since p = {p_two:.4f} < {alpha}")
    else:
        print(f"Fail to reject H0 since p = {p_two:.4f} >= {alpha}")
    

    Example output: \(t \approx 2.27\), \(p \approx 0.0497\) — reject \(H_0\) at \(\alpha = 0.05\) (evidence of a change in mean labor-hours).

  2. \(95\%\) CI for the mean paired difference: use the differences \(d_i = \text{Before}_i - \text{After}_i\), \(SE = s_d/\sqrt{n}\), and \(t_{0.025,\,n-1}\) (Tutorial 8, §7). If \(0\) lies outside the interval, that matches rejecting \(H_0\) in (1) at \(\alpha = 0.05\).

  3. At \(\alpha = 0.01\), the same two-sided \(p \approx 0.0497\) is greater than \(0.01\), so fail to reject \(H_0\): insufficient evidence of an effect at the \(1\%\) level.

Øvelse 7 (Tidligere eksamensopgave)

A recent study among 254 computer science graduates from Aarhus University was made in order to determine how successful the former students were in their current employment. 98 of these students had taken a course in linear algebra and of these 92 were classified as "successful" in their current employment. 136 of the students who had not taken a course in linear algebra were classified as "successful" in their current employment.

  1. Is the evidence to support the claim that computer science graduates who had taken a linear algebra course were more successful in their current employment than those who had not taken such a course?
  2. Explain the meaning of the p-value obtained in question (a), i.e. what does this probability refer to?
 
  1. Two proportions, \(H_0: p_1 = p_2\) vs \(H_1: p_1 > p_2\) — pooled \(z\) as in Tutorial 8, §9.

    import numpy as np
    from scipy.stats import norm
    
    alg = 98  # n with linear algebra
    algs = 92  # successful among those
    nonalgs = 136  # successful without LA
    nonalg = 254 - alg  # n without LA
    
    x1, n1 = algs, alg
    x2, n2 = nonalgs, nonalg
    p1h, p2h = x1 / n1, x2 / n2
    ph = (x1 + x2) / (n1 + n2)
    se = np.sqrt(ph * (1 - ph) * (1 / n1 + 1 / n2))
    z_obs = (p1h - p2h) / se
    p_one = norm.sf(z_obs)
    alpha = 0.05
    print(f"z = {z_obs:.4f}, p (one-sided p1 > p2) = {p_one:.4f}")
    if p_one < alpha:
        print(f"Reject H0 since p = {p_one:.4f} < {alpha}")
    else:
        print(f"Fail to reject H0 since p >= {alpha}")
    

    Example output: \(z \approx 1.71\), \(p \approx 0.0432\) — reject \(H_0\) at \(\alpha = 0.05\).

  2. The p-value is the probability, if \(H_0\) were true (\(p_1 = p_2\)), of observing a pooled \(z\)-statistic at least as large as \(1.71\) (direction \(p_1 > p_2\)). It is not \(P(H_0 \text{ true} \mid \text{data})\).

Øvelse 8 (Tidligere eksamensopgave)

Two producers of batteries measure the longevity of 30 batteries of the same type, which were randomly chosen from a larger batch of such batteries. The lifetime (in hundreds of hours) is displayed in Batteries.xlsx.

  1. Check the dataset for outliers and replace any outliers with the mean lifetime of the producer in question. Use this cleaned dataset in the following questions.
  2. Determine estimates for the quartiles, average lifetime, standard deviation and variance of each producer's battery
  3. Setup \(95 \%\) confidence intervals for each mean battery lifetime from the two producers, and accompany the intervals with plots that display the rejection region.
  4. Is it reasonable to conclude that the lifetime of the two producer's battery follow a normal distribution? Explain using plots and discussing skewness and kurtosis.
  5. Setup a \(95 \%\) confidence interval for the difference between the two producer's battery, and accompany the intervals with plots that display the rejection region.
  6. Is there significant evidence to support the claim that the mean lifetime of the batteries from the two producers differ from one another?
 
  1. df = pd.read_excel(
        'Batteries.xlsx'
    )
    df.head()
    
    Producer 1 Producer 2
    0 2.1162 1.1259
    1 2.5135 3.1725
    2 1.8137 2.4492
    3 0.8075 3.7766
    4 1.5554 4.4673
    q3, q1 = np.percentile(df['Producer 1'], [75,25])
    iqr = q3 - q1
    upper = q3+1.5*iqr
    lower = q1 - 1.5*iqr
    average = df.loc[(df['Producer 1'] < upper) & (df['Producer 1'] > lower)  , 'Producer 1'].mean()
    df['Producer 1'] = np.where((df['Producer 1'] > upper) | (df['Producer 1'] < lower), average, df['Producer 1'])
    
    q3, q1 = np.percentile(df['Producer 2'], [75,25])
    iqr = q3 - q1
    upper = q3+1.5*iqr
    lower = q1 - 1.5*iqr
    average = df.loc[(df['Producer 2'] < upper) & (df['Producer 2'] > lower)  , 'Producer 2'].mean()
    df['Producer 2'] = np.where((df['Producer 2'] > upper) | (df['Producer 2'] < lower), average, df['Producer 2'])
    
  2. df1 = df['Producer 1']
    df2 = df['Producer 2']
    
    print('Producer 1: ')
    print('q1 = ', round(df1.quantile(0.25), 4))
    print('q2 = ', round(df1.quantile(0.5), 4))
    print('q3 = ', round(df1.quantile(0.75), 4))
    print('q4 = ', round(df1.quantile(1), 4))
    print('average = ', round(df1.mean(), 4))
    print('std = ', round(df1.std(), 4))
    print('std = ', round(df1.var(), 4))
    print(' ')
    print('Producer 2: ')
    print('q1 = ', round(df2.quantile(0.25), 4))
    print('q2 = ', round(df2.quantile(0.5), 4))
    print('q3 = ', round(df2.quantile(0.75), 4))
    print('q4 = ', round(df2.quantile(1), 4))
    print('average = ', round(df2.mean(), 4))
    print('std = ', round(df2.std(), 4))
    print('std = ', round(df2.var(), 4))
    

    Producer 1:

    q1 = 1.1888

    q2 = 1.9196

    q3 = 2.4074

    q4 = 3.637

    average = 1.9029

    std = 0.9109

    std = 0.8298

    Producer 2:

    q1 = 2.0375

    q2 = 2.5158

    q3 = 3.0069

    q4 = 4.4673

    average = 2.4776

    std = 0.9124

    std = 0.8325

  3. Using t.interval

    from scipy import stats
    n = len(df1)
    mean = np.mean(df1)
    SE = stats.sem(df1)
    Level = 0.95
    
    CI = stats.t.interval(Level, n-1, loc=mean, scale=SE)
    
    print('An ' + repr(Level*100) + ' % upper confidence interval for the sample mean is ['
        + repr(round(CI[0],2)) + '; ' + repr(round(CI[1],2)) + ']')
    

    An 95.0 % upper confidence interval for the sample mean is [1.56; 2.24]

    import numpy as np
    import scipy.stats as stats
    import matplotlib.pyplot as plt
    
    # Using the formula
    data = df1
    
    # Calculate the mean and standard deviation of the data
    mean = np.mean(data)
    std_dev = np.std(data, ddof=1)  # ddof=1 gives an unbiased estimator of the population std dev
    
    # Calculate the standard error of the mean
    std_error = std_dev / np.sqrt(len(data))
    
    # Set the significance level and degrees of freedom for the t-distribution
    alpha = 0.05  # 95% confidence level
    dof = len(data) - 1
    
    # Calculate the critical t-value for the two-tailed t-test
    t_crit = stats.t.ppf(1 - alpha/2, dof)
    
    # Calculate the confidence interval for the mean
    lower = mean - t_crit * std_error
    upper = mean + t_crit * std_error
    
    # Print the confidence interval
    print("95% Confidence Interval mean Producer 1: [{:.2f}, {:.2f}]".format(lower, upper))
    
    # Plot the t-distribution with the rejection region shaded
    x = np.linspace(mean-4*std_error, mean+4*std_error, 1000)
    y = stats.t.pdf(x,dof, mean, std_error)
    plt.plot(x, y, 'k', linewidth=2)
    shade = np.linspace(lower, upper, 300)
    plt.fill_between(shade, stats.t.pdf(shade, dof, mean, std_error), alpha=0.5)
    plt.axvline(x=lower, linestyle='--', color='k')
    plt.axvline(x=upper, linestyle='--', color='k')
    plt.title("t-Distribution with 95% Confidence Interval \n for the mean of batteries from producer 1")
    plt.xlabel("t-value")
    plt.ylabel("Probability density")
    plt.show()
    
    # Using the formula
    data = df2
    
    # Calculate the mean and standard deviation of the data
    mean = np.mean(data)
    std_dev = np.std(data, ddof=1)  # ddof=1 gives an unbiased estimator of the population std dev
    
    # Calculate the standard error of the mean
    std_error = std_dev / np.sqrt(len(data))
    
    # Set the significance level and degrees of freedom for the t-distribution
    alpha = 0.05  # 95% confidence level
    dof = len(data) - 1
    
    # Calculate the critical t-value for the two-tailed t-test
    t_crit = stats.t.ppf(1 - alpha/2, dof)
    
    # Calculate the confidence interval for the mean
    lower = mean - t_crit * std_error
    upper = mean + t_crit * std_error
    
    # Print the confidence interval
    print("95% Confidence Interval mean Producer 2: [{:.2f}, {:.2f}]".format(lower, upper))
    
    # Plot the t-distribution with the rejection region shaded
    x = np.linspace(mean-4*std_error, mean+4*std_error, 1000)
    y = stats.t.pdf(x,dof, mean, std_error)
    plt.plot(x, y, 'k', linewidth=2)
    shade = np.linspace(lower, upper, 300)
    plt.fill_between(shade, stats.t.pdf(shade, dof, mean, std_error), alpha=0.5)
    plt.axvline(x=lower, linestyle='--', color='k')
    plt.axvline(x=upper, linestyle='--', color='k')
    plt.title("t-Distribution with 95% Confidence Interval \n for the mean of batteries from producer 2")
    plt.xlabel("t-value")
    plt.ylabel("Probability density")
    plt.show()
    

    95% Confidence Interval mean Producer 1: [1.56, 2.24]

    95% Confidence Interval mean Producer 2: [2.14, 2.82]

  4. stats.probplot(df1, plot=plt)
    plt.ylabel('Producer 1')
    plt.show()
    print('Skewness = ' + repr(round(stats.skew(df1),4)))
    print('Kurtosis = ' + repr(round(stats.kurtosis(df1),4)))
    fig, ax = plt.subplots()
    df1.plot.kde(ax=ax, legend=False, title='Distribution of mean of Producer 1');
    

    Skewness = 0.1134

    Kurtosis = -0.4326

    stats.probplot(df2, plot=plt)
    plt.ylabel('Producer 2')
    plt.show()
    print('Skewness = ' + repr(round(stats.skew(df2),4)))
    print('Kurtosis = ' + repr(round(stats.kurtosis(df2),4)))
    fig, ax = plt.subplots()
    df2.plot.kde(ax=ax, legend=False, title='Distribution of mean of Producer 2');
    

    Skewness = -0.1821

    Kurtosis = -0.19

  5. import numpy as np
    import scipy.stats as stats
    import matplotlib.pyplot as plt
    
    # Generate some sample data for two independent samples (replace this with your own data)
    data1 = df1
    data2 = df2
    
    # Calculate the mean and standard deviation of the data
    mean1 = np.mean(data1)
    mean2 = np.mean(data2)
    std_dev1 = np.std(data1, ddof=1)  # ddof=1 gives an unbiased estimator of the population std dev
    std_dev2 = np.std(data2, ddof=1)
    
    # Calculate the standard error of the difference in means
    std_error = np.sqrt((std_dev1 ** 2 / len(data1)) + (std_dev2 ** 2 / len(data2)))
    
    # Set the significance level and degrees of freedom for the t-distribution
    alpha = 0.05  # 95% confidence level
    df = len(data1) + len(data2) - 2
    
    # Calculate the critical t-value for the two-tailed t-test
    t_crit = stats.t.ppf(1 - alpha/2, df)
    
    # Calculate the confidence interval for the difference in means
    diff = mean1 - mean2
    lower = diff - t_crit * std_error
    upper = diff + t_crit * std_error
    
    # Print the confidence interval
    print("95% Confidence Interval for the Difference in Means: [{:.2f}, {:.2f}]".format(lower, upper))
    
    # Plot the t-distribution with the rejection region shaded
    x = np.linspace(-4, 4, 1000)
    y = stats.t.pdf(x, df)
    plt.plot(x, y, 'k', linewidth=2)
    shade1 = np.linspace(-t_crit, t_crit, 300)
    plt.fill_between(shade1, stats.t.pdf(shade1, df), alpha=0.5)
    plt.axvline(x=t_crit, linestyle='--', color='k')
    plt.axvline(x=-t_crit, linestyle='--', color='k')
    plt.title("t-Distribution with 95% Confidence Interval for the Difference in Means")
    plt.xlabel("t-value")
    plt.ylabel("Probability density")
    plt.show()
    

    95% Confidence Interval for the Difference in Means: [-1.05, -0.10]

  6. Pooled two-sample \(t\)-test for \(\mu_1 \neq \mu_2\) (Tutorial 8, §6). Code below matches the tutorial; run it after parts 1–2 so df1 and df2 exist. The plot is the same diagnostic figure as before.

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy import stats
    from scipy.stats import ttest_ind
    
    data1 = df1
    data2 = df2
    
    mean1 = np.mean(data1)
    mean2 = np.mean(data2)
    std_dev1 = np.std(data1, ddof=1)
    std_dev2 = np.std(data2, ddof=1)
    
    alpha = 0.05
    df_t = len(data1) + len(data2) - 2
    
    t_stat, p_two = ttest_ind(data1, data2, equal_var=True, alternative="two-sided")
    p_value = p_two
    print(f"Pooled t-test: t = {t_stat:.4f}, p (two-sided) = {p_two:.4f}")
    
    t_crit = stats.t.ppf(1 - alpha / 2, df_t)
    if p_value < alpha:
        print(f"Reject H0 since p = {p_value:.4f} < {alpha}")
    else:
        print(f"Fail to reject H0 since p = {p_value:.4f} >= {alpha}")
    
    x = np.linspace(-4, 4, 1000)
    y = stats.t.pdf(x, df_t)
    plt.plot(x, y, "k", linewidth=2)
    shade1 = np.linspace(-t_crit, t_crit, 300)
    shade2 = np.linspace(t_crit, 4, 300)
    plt.fill_between(shade1, stats.t.pdf(shade1, df_t), alpha=0.5)
    plt.fill_between(shade2, stats.t.pdf(shade2, df_t), alpha=0.5)
    plt.axvline(x=t_crit, linestyle="--", color="k")
    plt.axvline(x=-t_crit, linestyle="--", color="k")
    if p_value < alpha / 2:
        plt.annotate(
            "p = {:.4f}".format(p_value),
            xy=(t_stat, 0.1),
            xytext=(t_stat + 1, 0.3),
            arrowprops=dict(facecolor="green", shrink=0.05),
        )
    elif p_value > 1 - alpha / 2:
        plt.annotate(
            "p = {:.4f}".format(p_value),
            xy=(t_stat, 0.1),
            xytext=(t_stat - 1, 0.3),
            arrowprops=dict(facecolor="green", shrink=0.05),
        )
    else:
        plt.annotate(
            "p = {:.4f}".format(p_value),
            xy=(t_stat, 0.1),
            xytext=(t_stat, 0.3),
            arrowprops=dict(facecolor="green", shrink=0.05),
        )
    plt.title("t-Distribution with Hypothesis Test Results")
    plt.xlabel("t-value")
    plt.ylabel("Probability density")
    plt.show()
    

    Reject since 0.0177 < 0.05