The Wayback Machine - https://web.archive.org/web/20240118165659/https://www.geeksforgeeks.org/understanding-hypothesis-testing/
Open In App
Related Articles

Understanding Hypothesis Testing

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Hypothesis testing involves formulating assumptions about population parameters and rigorously evaluating these assumptions against empirical evidence. This article sheds light on the significance of hypothesis testing, its parameters, and the critical steps involved in the process.

What is Hypothesis Testing? 

Hypothesis testing is a statistical method that is used for making a statistical decision using experimental data. Hypothesis testing is basically an assumption that we make about a population parameter. It evaluates two mutually exclusive statements about a population to determine which statement is best supported by the sample data. 

Example: You say an average student in the class is 30 or a boy is taller than a girl. All of these is an assumption that we are assuming, and we need some statistical way to prove these. We need some mathematical conclusion whatever we are assuming is true.

Parameters of Hypothesis Testing

  • Null hypothesis(H0): In statistics, the null hypothesis is a general given statement or default position that there is no relationship between two measured cases or no relationship among groups. In other words, it is a basic assumption or made based on the problem knowledge. Example: A company production is = 50 units/per day etc.
  • Alternative hypothesis(H1): The alternative hypothesis is the hypothesis used in hypothesis testing that is contrary to the null hypothesis. Example: A company’s production is not equal to 50 units/per day etc.
  • Level of significance It refers to the degree of significance in which we accept or reject the null hypothesis. 100% accuracy is not possible for accepting a hypothesis, so we, therefore, select a level of significance that is usually 5%. This is normally denoted with \alpha         and generally, it is 0.05 or 5%, which means your output should be 95% confident to give a similar kind of result in each sample.
  • P-value The P value, or calculated probability, is the probability of finding the observed/extreme results when the null hypothesis(H0) of a study-given problem is true. If your P-value is less than the chosen significance level then you reject the null hypothesis i.e. accept that your sample claims to support the alternative hypothesis.
  • Critical values
  • Probability distributions
  • Statistical tests
  • Test statistics

Why do we use Hypothesis Testing?

Hypothesis testing is an important procedure in statistics. Hypothesis testing evaluates two mutually exclusive population statements to determine which statement is most supported by sample data. When we say that the findings are statistically significant, thanks to hypothesis testing. 

What are Type 1 and Type 2 errors in Hypothesis Testing?

In hypothesis testing, Type I and Type II errors are two possible errors that researchers can make when drawing conclusions about a population based on a sample of data. These errors are associated with the decisions made regarding the null hypothesis and the alternative hypothesis.

  • Type I error: When we reject the null hypothesis, although that hypothesis was true. Type I error is denoted by alpha(\alpha       ).
  • Type II errors: When we accept the null hypothesis, but it is false. Type II errors are denoted by beta(\beta       ).

Null Hypothesis is True

Null Hypothesis is False

Null Hypothesis is True (Accept)

Correct Decision

Type II Error (False Negative)

Alternative Hypothesis is True (Reject)

Type I Error (False Positive)

Correct Decision

What are the Steps in Hypothesis Testing?

Step 1: Define Null and Alternative Hypothesis

State the null hypothesis (H_o       ), representing no effect, and the alternative hypothesis (H_1       ​), suggesting an effect or difference.

We first identify the problem about which we want to make an assumption keeping in mind that our assumption should be contradictory to one another, assuming Normally distributed data.

Step 2 – Choose significance level

Select a significance level (\alpha       ), typically 0.05, to determine the threshold for rejecting the null hypothesis. It provides validity to our hypothesis test, ensuring that we have sufficient data to back up our claims. Usually, we determine our significance level beforehand of the test. The p-value is the criterion used to calculate our significance value.

Step 3 – Collect and Analyze data.

Gather relevant data through observation or experimentation. Analyze the data using appropriate statistical methods to obtain a test statistic.

Step 4-Calculate Test Statistic

The data for the tests are evaluated in this step we look for various scores in this step like z-score and mean values. The choice of the test statistic depends on the type of hypothesis test being conducted.

There are various hypothesis tests, each appropriate for various goal to calculate our test. This could be a Z-test, Chi-square, T-test, and so forth. let’s use T-test in this article to test our hypothesis.

T-statistic is a measure of the difference between the means of two groups relative to the variability within each group. It is calculated as the difference between the sample means divided by the standard error of the difference. It is also known as the t-value or t-score.

Step 5 – Comparing Test Static to Significance Level

In this stage, we decide where we should accept the null hypothesis or reject the null hypothesis.

  • When the test statistic surpasses the chosen significance level, we have grounds to reject the null hypothesis, suggesting substantial evidence in favor of our alternative hypothesis.
  • Conversely, if the test statistic doesn’t surpass the significance level, we refrain from rejecting the null hypothesis. This implies that we lack adequate statistical evidence to endorse the alternative hypothesis.

Step 6- Interpret the Results

At last, we can conclude our experiment.

How do you calculate hypothesis testing? 

To validate our hypothesis about a population parameter we use statistical functions. We use the z-score, p-value, and level of significance(alpha) to make evidence for our hypothesis for normally distributed data.

z = \frac{\bar{x} - \mu}{\frac{\sigma}{\sqrt{n}}}

  •  where, \bar{x}        is the sample mean,
  • μ represents the population mean, 
  • σ is the standard deviation
  • and n is the size of the sample.

And Chi-Square Test for Independence categorical Data (Non-normally distributed) using:

\chi^2 = \sum \frac{(O_{ij} - E_{ij})^2}{E_{ij}}

  • where, O_{ij}   is the observed frequency in cell {ij}
  • i,j are the rows and columns index respectively.
  • E_{ij}    is the expected frequency in cell {ij}   , calculated as :

\frac{{\text{{Row total}} \times \text{{Column total}}}}{{\text{{Total observations}}}}

Real life Hypothesis Testing example

Let’s examine about Does a New Drug Affect Blood Pressure?

Imagine a pharmaceutical company has developed a new drug that they believe can effectively lower blood pressure in patients with hypertension. Before bringing the drug to market, they need to conduct a study to assess its impact on blood pressure.

Step 1: Null Hypothesis: The new drug has no effect on blood pressure.

Alternate Hypothesis: The new drug has an effect on blood pressure.

Step 2: Significance level at 0.05, indicating rejection of the null hypothesis. If the evidence suggests less than a 5% chance of observing the results due to random variation.

Step 3: Researchers collect blood pressure measurements from a sample of patients before and after treatment with the new drug. Using statistical methods (e.g., paired T-test), analyze the data to obtain a test statistic and a p-value.

Step 4: The test statistic (e.g., T-statistic) is calculated based on the differences between blood pressure measurements before and after treatment and the p-value is obtained.

Step 5:

  • If the p-value is less than or equal to 0.05, the researchers reject the null hypothesis.
  • If the p-value is greater than 0.05, they fail to reject the null hypothesis.

If the null hypothesis is rejected, the researchers conclude that there is statistically significant evidence that the new drug has an effect on blood pressure.

If the null hypothesis is not rejected, there is insufficient evidence to claim a significant difference in blood pressure before and after treatment with the new drug.

Python Implementation of Hypothesis Testing

Let’s create hypothesis testing with python, where we are testing whether a new drug affects blood pressure. For this example, we will use a paired T-test. We’ll use the scipy.stats library for the T-test.

Scipy is a mathematical library in Python that is mostly used for mathematical equations and computations.

In this code, we will create a function hypothesis_test in which we will pass arguments like pop_mean (population parameter upon which we are checking our hypothesis), sample dataset, level of confidence (alpha value), and type of testing (whether it’s a one-tailed test or two-tailed test). 

Python3




import numpy as np
from scipy.stats import ttest_rel
 
def hypothesis_test(sample, pop_mean, alpha=0.05, two_tailed=True):
    t_statistic, p_value = ttest_rel(sample, pop_mean)
 
    if two_tailed: # Calculate the p-value based on the test type and multiply for two-tailed
        p_value *= 2
 
    if p_value < alpha:
        result = "reject"
    else:
        result = "fail to reject"
 
    return t_statistic, p_value, result


Evaluate Hypothesis Function on Sample Dataset 

To evaluate our hypothesis test function, we will create a sample dataset of 80 data points having 120 as the mean and 8 as the standard deviation.

Python3




pop_mean = 120
 
np.random.seed(42)
sample = np.random.normal(loc=115, scale=8, size=80)
pop_mean = np.full_like(sample, pop_mean)
 
t_statistic, p_value, result = hypothesis_test(sample, pop_mean)
 
print("T-statistic:", t_statistic)
print("P-value:", p_value)
print(f"Result: {result} null hypothesis at alpha=0.05.")


Output:

T-statistic: -6.99524540387644
P-value: 1.5261459681023182e-09
Result: reject null hypothesis at alpha=0.05.

In the above example, given the T-statistic of approximately -6.995 and an extremely small p-value, the results indicate a strong case to reject the null hypothesis at a significance level of 0.05. 

  • The results suggest that the new drug, treatment, or intervention has a significant effect on lowering blood pressure.
  • The negative T-statistic indicates that the mean blood pressure after treatment is significantly lower than the assumed population mean before treatment.

Conclusion

Hypothesis testing stands as a cornerstone in statistical analysis, enabling data scientists to navigate uncertainties and draw credible inferences from sample data. By systematically defining null and alternative hypotheses, choosing significance levels, and leveraging statistical tests, researchers can assess the validity of their assumptions. The article also elucidates the critical distinction between Type I and Type II errors, providing a comprehensive understanding of the nuanced decision-making process inherent in hypothesis testing. The real-life example of testing a new drug’s effect on blood pressure using a paired T-test showcases the practical application of these principles, underscoring the importance of statistical rigor in data-driven decision-making.

Frequently Asked Questions (FAQs)

1. What are the 3 types of hypothesis test?

There are three types of hypothesis tests: right-tailed, left-tailed, and two-tailed. Right-tailed tests assess if a parameter is greater, left-tailed if lesser. Two-tailed tests check for non-directional differences, greater or lesser.

2.What are the 4 components of hypothesis testing?

Null Hypothesis (H_o       ): No effect or difference exists.

Alternative Hypothesis (H_1       ): An effect or difference exists.

Significance Level (\alpha       ): Risk of rejecting null hypothesis when it’s true (Type I error).

Test Statistic: Numerical value representing observed evidence against null hypothesis.

3.What is hypothesis testing in ML?

Statistical method to evaluate the performance and validity of machine learning models. Tests specific hypotheses about model behavior, like whether features influence predictions or if a model generalizes well to unseen data.

4.What is the difference between Pytest and hypothesis in Python?

Pytest purposes general testing framework for Python code while Hypothesis is a Property-based testing framework for Python, focusing on generating test cases based on specified properties of the code.


Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.
Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 21 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials