Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

NumPy - Binomial Distribution



What is a Binomial Distribution?

The Binomial Distribution is a discrete probability distribution that describes the number of successes in a fixed number of independent trials, each with the same probability of success.

It is defined by two parameters: the number of trials (n) and the probability of success (p) in each trial. The probability mass function (PMF) of the binomial distribution gives the probability of getting exactly k successes in n trials. The formula for the PMF is −

P(X = k) = C(n, k) * pk * (1 - p)(n - k)

Where C(n, k) is the binomial coefficient, which can be calculated as −

C(n, k) = n! / (k! * (n - k)!)

Binomial Distributions in NumPy

NumPy provides the numpy.random.binomial() function to generate samples from a binomial distribution. This function allows you to specify the number of trials, the probability of success, and the size of the generated samples.

Example

In this example, we generate 10 random samples from a binomial distribution with 10 trials and a success probability of 0.5 −

import numpy as np

# Generate 10 random samples from a binomial distribution with 10 trials and a success probability of 0.5
samples = np.random.binomial(n=10, p=0.5, size=10)
print("Random samples from binomial distribution:", samples)

Following is the output obtained −

Random samples from binomial distribution: [5 7 5 7 1 3 5 8 7 5]

Visualizing Binomial Distributions

Visualizing binomial distributions helps to understand their properties better. We can use libraries such as Matplotlib to create histograms that display the distribution of generated samples.

Example

In the following example, we are first generating 1000 random samples from a binomial distribution with 10 trials and a success probability of 0.5. We then visualize this distribution by creating a histogram −

import numpy as np
import matplotlib.pyplot as plt

# Generate 1000 random samples from a binomial distribution with 10 trials and a success probability of 0.5
samples = np.random.binomial(n=10, p=0.5, size=1000)

# Create a histogram to visualize the distribution
plt.hist(samples, bins=np.arange(12) - 0.5, edgecolor='black', density=True)
plt.title('Binomial Distribution')
plt.xlabel('Number of successes')
plt.ylabel('Frequency')
plt.xticks(range(11))
plt.show()

The histogram shows the frequency of the number of successes in the binomial trials. The bars represent the probability of each possible outcome, which forms the characteristic shape of a binomial distribution −

Binomial Distribution

Applications of Binomial Distributions

Binomial distributions are used in various fields, including statistics, medicine, quality control, and social sciences. Here are a few practical applications −

  • Quality Control: Used to model the number of defective items in a batch of products.
  • Medicine: Used to model the number of patients who recover from a treatment out of a sample of patients.
  • Survey Analysis: Used to model the number of people who respond positively to a survey question.

Generating Cumulative Binomial Distributions

Sometimes, we are interested in the cumulative distribution function (CDF) of a binomial distribution, which gives the probability of getting up to and including k successes in n trials.

NumPy does not have a built-in function for the CDF of a binomial distribution, but we can calculate it using a loop and the scipy.stats.binom.cdf() function from the SciPy library.

Example

In this example, we are generating cumulative binomial distribution using NumPy library −

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import binom

# Define the number of trials and success probability
n = 10
p = 0.5

# Generate the cumulative distribution function (CDF) values
x = np.arange(0, n+1)
cdf = binom.cdf(x, n, p)

# Plot the CDF
plt.plot(x, cdf, marker='o', linestyle='-', color='b')
plt.title('Cumulative Binomial Distribution')
plt.xlabel('Number of successes')
plt.ylabel('Cumulative probability')
plt.grid(True)
plt.show()

The plot shows the cumulative probability of getting up to and including each number of successes in the binomial trials. The CDF is a step function that increases to 1 as the number of successes increases −

Cumulative Probability

Properties of Binomial Distributions

Binomial distributions have several key properties, they are −

  • Discrete Nature: The binomial distribution is discrete, meaning it only takes on integer values.
  • Mean: The mean of a binomial distribution is given by n * p.
  • Variance: The variance of a binomial distribution is given by n * p * (1 - p).
  • Symmetry: When p = 0.5, the binomial distribution is symmetric.

Binomial Distribution for Hypothesis Testing

Binomial distributions are often used in hypothesis testing, particularly in tests for proportions.

One common test is the binomial test, which is used to determine if the proportion of successes in a sample is significantly different from a specified proportion. Here is an example using the scipy.stats.binom_test() function.

Example

In this example, we perform a binomial test to determine if the proportion of successes (8 out of 10) is significantly different from 0.5. The p-value indicates the probability of obtaining a result at least as extreme as the observed result, assuming the null hypothesis is true −

from scipy.stats import binom_test

# Number of successes
successes = 8

# Number of trials
trials = 10

# Hypothesized probability of success
p = 0.5

# Perform the binomial test
p_value = binom_test(successes, trials, p)
print("P-value from binomial test:", p_value)

The output obtained is as shown below −

/home/cg/root/673c4ae169586/main.py:13: DeprecationWarning: 'binom_test' is deprecated in favour of 'binomtest' from version 1.7.0 and will be removed in Scipy 1.12.0.
  p_value = binom_test(successes, trials, p)
P-value from binomial test: 0.109375

Seeding for Reproducibility

To ensure reproducibility, you can set a specific seed before generating binomial distributions. This ensures that the same sequence of random numbers is generated each time you run the code.

Example

By setting the seed, you ensure that the random generation produces the same result every time the code is executed, as shown in the example below −

import numpy as np

# Set the seed for reproducibility
np.random.seed(42)

# Generate 10 random samples from a binomial distribution with 10 trials and a success probability of 0.5
samples = np.random.binomial(n=10, p=0.5, size=10)
print("Random samples with seed 42:", samples)

The result produced is as follows −

Random samples with seed 42: [4 8 6 5 3 3 3 7 5 6]
Advertisements