Skip to main content

Understanding Z-Test and P-Value with ML Use Cases

Learn about z-test and p-value in statistics with detailed examples and Python code. Understand how they apply to Machine Learning and Deep Learning for model evaluation.

What is a P-Value?

The p-value is a probability that measures the strength of the evidence against the null hypothesis. Specifically, it is the probability of observing a test statistic (like the z-score) at least as extreme as the one computed from your sample, assuming that the null hypothesis is true.

A smaller p-value indicates stronger evidence against the null hypothesis. Common thresholds to reject the null hypothesis are:

  • p < 0.05: statistically significant
  • p < 0.01: highly significant

Python Example of Z-Test

Let’s assume we want to test whether the mean of a sample differs from a known population mean:


import numpy as np
from scipy import stats

# Sample data
sample = [2.9, 3.0, 2.5, 3.2, 3.8, 3.5]
mu = 3.0       # Population mean
sigma = 0.5    # Population std deviation
n = len(sample)
x_bar = np.mean(sample)

# Calculate z-score
z = (x_bar - mu) / (sigma / np.sqrt(n))
p_value = 2 * (1 - stats.norm.cdf(abs(z)))

print("Z-score:", z)
print("P-value:", p_value)
  

Using Z-Test and P-Value in ML/DL

In Machine Learning (ML) and Deep Learning (DL), z-tests and p-values help validate experimental results, such as whether a new model significantly outperforms a baseline model. Without statistical testing, we might mistake random fluctuations in performance for real improvements.

  • Compare two models: Test if the performance difference between two models (e.g., accuracy) is statistically significant.
  • A/B testing: Evaluate changes in algorithms, UI components, or features based on user interactions.
  • Feature selection: Check whether the mean of a feature differs between classes significantly, which may indicate predictive power.

Example: Comparing Two Models

Let’s compare the accuracy of two models over multiple runs:


acc_model_a = [0.83, 0.85, 0.82, 0.84, 0.86]
acc_model_b = [0.79, 0.78, 0.80, 0.77, 0.81]

mean_a = np.mean(acc_model_a)
mean_b = np.mean(acc_model_b)
sd = np.std(acc_model_a + acc_model_b, ddof=1)
n = len(acc_model_a)

z = (mean_a - mean_b) / (sd * np.sqrt(2/n))
p = 2 * (1 - stats.norm.cdf(abs(z)))

print("Z-Score:", z)
print("P-Value:", p)
  

Conclusion

The z-test and p-value are essential statistical tools for validating model improvements, experimental hypotheses, and performance evaluations. Especially in ML/DL pipelines, applying these tests ensures that your decisions are backed by robust statistical evidence rather than randomness.

References

Comments

Popular

How to Fine-Tune LLaMA 3.2-1B-Instruct for Korean Instruction Tasks with LoRA and Hugging Face

LLaMA 3.2-1B-Instruct is a lightweight instruction-tuned language model released by Meta. It is designed to handle a wide range of instruction-based tasks with relatively low computational resources. Although the model was trained with multilingual capabilities, its performance on languages not included in its training set—such as Korean—is limited. This tutorial demonstrates how to fine-tune this open-source model on a Korean dataset using Hugging Face Transformers and PEFT (specifically LoRA), enabling it to better respond to Korean instructions. 1. Prerequisites Before running the example code below, ensure you have the following libraries installed: pip install torch transformers datasets peft accelerate mlflow huggingface_hub To use the LLaMA model or KoAlpaca datasets, you'll need a Hugging Face token. Additionally, you may need to handle potential CUDA Out-Of-Memory (OOM) errors. The following code takes care of both: from huggingface_hub import login login("y...

Using Gemini API in LangChain: Step-by-Step Tutorial

What is LangChain and Why Use It? LangChain  is an open-source framework that simplifies the use of  Large Language Models (LLMs)  like OpenAI, Gemini (Google), and others by adding structure, tools, and memory to help build real-world applications such as chatbots, assistants, agents, or AI-enhanced software. Why Use LangChain for LLM Projects? Chainable Components : Easily build pipelines combining prompts, LLMs, tools, and memory. Multi-Model Support : Work with Gemini, OpenAI, Anthropic, Hugging Face, etc. Built-in Templates : Manage prompts more effectively. Supports Multi-Turn Chat : Manage complex interactions with memory and roles. Tool and API Integration : Let the model interact with external APIs or functions. Let's Walk Through the Code: Gemini + LangChain I will break the code into  4 main parts , each showcasing different features of LangChain and Gemini API. Part 1: Basic Gemini API Call Using LangChain import os from dotenv import load_dotenv load_dot...

Building an MCP Agent with UV, Python & mcp-use

Model Context Protocol (MCP) is an open protocol designed to enable AI agents to interact with external tools and data in a standardized way. MCP is composed of three components: server , client , and host . MCP host The MCP host acts as the interface between the user and the agent   (such as Claude Desktop or IDE) and plays the role of connecting to external tools or data through MCP clients and servers. Previously, Anthropic’s Claude Desktop was introduced as a host, but it required a separate desktop app, license, and API key management, leading to dependency on the Claude ecosystem.   mcp-use is an open-source Python/Node package that connects LangChain LLMs (e.g., GPT-4, Claude, Groq) to MCP servers in just six lines of code, eliminating dependencies and supporting multi-server and multi-model setups. MCP Client The MCP client manages the MCP protocol within the host and is responsible for connecting to MCP servers that provide the necessary functions for the ...