Hướng dẫn python exponential distribution



Hàm exp(x) trong Python trả về ex.

Nội dung chính

  • How to Generate an Exponential Distribution
  • How to Calculate Probabilities Using an Exponential Distribution
  • How to Plot an Exponential Distribution
  • Additional Resources
  • How do you generate a random number from exponential distribution in Python?
  • How do you generate a random number from an exponential distribution?
  • What is scale in Numpy random exponential?
  • How do you fit an exponential distribution in Python?

Nội dung chính

  • How to Generate an Exponential Distribution
  • How to Calculate Probabilities Using an Exponential Distribution
  • How to Plot an Exponential Distribution
  • Additional Resources

Cú pháp

Cú pháp của exp() trong Python:

Ghi chú: Hàm này không có thể truy cập trực tiếp, vì thế chúng ta cần import math module và sau đó chúng ta cần gọi hàm này bởi sử dụng đối tượng math.

Các tham số:

  • x: Đây là một biểu thức số.


Ví dụ sau minh họa cách sử dụng của hàm exp() trong Python.

import math
print ("math.exp(-45) : ", math.exp(-45))
print ("math.exp(10.15) : ", math.exp(10.15))
print ("math.exp(100) : ", math.exp(100))
print ("math.exp(math.pi) : ", math.exp(math.pi))

Chạy chương trình Python trên sẽ cho kết quả:

math.exp(-45) :  2.8625185805493937e-20
math.exp(10.15) :  25591.102206689702
math.exp(100) :  2.6881171418161356e+43
math.exp(math.pi) :  23.140692632779267



The exponential distribution is a probability distribution that is used to model the time we must wait until a certain event occurs.

If a random variable X follows an exponential distribution, then the cumulative distribution function of X can be written as:

F(x; λ) = 1 – e-λx

where:

  • λ: the rate parameter (calculated as λ = 1/μ)
  • e: A constant roughly equal to 2.718

This tutorial explains how to use the exponential distribution in Python.

How to Generate an Exponential Distribution

You can use the expon.rvs(scale, size) function from the SciPy library in Python to generate random values from an exponential distribution with a specific rate parameter and sample size:

from scipy.stats import expon

#generate random values from exponential distribution with rate=40 and sample size=10
expon.rvs(scale=40, size=10)

array([116.5368323 ,  67.23514699,  12.00399043,  40.74580584,
        34.60922432,   2.68266663,  22.70459831,  97.66661811,
         6.64272914,  46.15547298])

Note: You can find the complete documentation for the SciPy library here.

How to Calculate Probabilities Using an Exponential Distribution

Suppose the mean number of minutes between eruptions for a certain geyser is 40 minutes. What is the probability that we’ll have to wait less than 50 minutes for an eruption?

To solve this, we need to first calculate the rate parameter:

  • λ = 1/μ
  • λ = 1/40
  • λ = .025

We can plug in λ = .025 and x = 50 to the formula for the CDF:

  • P(X ≤ x) = 1 – e-λx
  • P(X ≤ 50) = 1 – e-.025(50)
  • P(X ≤ 50) = 0.7135

The probability that we’ll have to wait less than 50 minutes for the next eruption is 0.7135.

We can use the expon.cdf() function from SciPy to solve this problem in Python:

from scipy.stats import expon

#calculate probability that x is less than 50 when mean rate is 40
expon.cdf(x=50, scale=40)

0.7134952031398099

The probability that we’ll have to wait less than 50 minutes for the next eruption is 0.7135.

This matches the value that we calculated by hand.

How to Plot an Exponential Distribution

You can use the following syntax to plot an exponential distribution with a given rate parameter:

from scipy.stats import expon
import matplotlib.pyplot as plt

#generate exponential distribution with sample size 10000
x = expon.rvs(scale=40, size=10000)

#create plot of exponential distribution
plt.hist(x, density=True, edgecolor='black')

Hướng dẫn python exponential distribution

Additional Resources

The following tutorials explain how to use other common distributions in Python:

How to Use the Poisson Distribution in Python
How to Use the t Distribution in Python
How to Use the Uniform Distribution in Python

random.exponential(scale=1.0, size=None)#

Draw samples from an exponential distribution.

Nội dung chính

  • How do you generate a random number from exponential distribution in Python?
  • How do you generate a random number from an exponential distribution?
  • What is scale in Numpy random exponential?
  • How do you fit an exponential distribution in Python?

Its probability density function is

\[f(x; \frac{1}{\beta}) = \frac{1}{\beta} \exp(-\frac{x}{\beta}),\]

for x > 0 and 0 elsewhere. \(\beta\) is the scale parameter, which is the inverse of the rate parameter \(\lambda = 1/\beta\). The rate parameter is an alternative, widely used parameterization of the exponential distribution [3].

The exponential distribution is a continuous analogue of the geometric distribution. It describes many common situations, such as the size of raindrops measured over many rainstorms [1], or the time between page requests to Wikipedia [2].

Note

New code should use the exponential method of a default_rng() instance instead; please see the Quick Start.

Parametersscalefloat or array_like of floats

The scale parameter, \(\beta = 1/\lambda\). Must be non-negative.

sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if scale is a scalar. Otherwise, np.array(scale).size samples are drawn.

Returnsoutndarray or scalar

Drawn samples from the parameterized exponential distribution.

References

1

Peyton Z. Peebles Jr., “Probability, Random Variables and Random Signal Principles”, 4th ed, 2001, p. 57.

2

Wikipedia, “Poisson process”, https://en.wikipedia.org/wiki/Poisson_process

3

Wikipedia, “Exponential distribution”, https://en.wikipedia.org/wiki/Exponential_distribution

I think you are actually asking about a regression problem, which is what Praveen was suggesting.

You have a bog standard exponential decay that arrives at the y-axis at about y=0.27. Its equation is therefore y = 0.27*exp(-0.27*x). I can model gaussian error around the values of this function and plot the result using the following code.

import matplotlib.pyplot as plt
from math import exp
from scipy.stats import norm


x = range(0, 16)
Y = [0.27*exp(-0.27*_) for _ in x]
error = norm.rvs(0, scale=0.05, size=9)
simulated_data = [max(0, y+e) for (y,e) in zip(Y[:9],error)]

plt.plot(x, Y, 'b-')
plt.plot(x[:9], simulated_data, 'r.')
plt.show()

print (x[:9])
print (simulated_data)

Here's the plot. Notice that I save the output values for subsequent use.

Now I can calculate the nonlinear regression of the exponential decay values, contaminated with noise, on the independent variable, which is what curve_fit does.

from math import exp
from scipy.optimize import curve_fit
import numpy as np

def model(x, p):
    return p*np.exp(-p*x)

x = list(range(9))
Y = [0.22219001972988275, 0.15537454187341937, 0.15864069451825827, 0.056411162886672819, 0.037398831058143338, 0.10278251869912845, 0.03984605649260467, 0.0035360087611421981, 0.075855255999424692]

popt, pcov = curve_fit(model, x, Y)
print (popt[0])
print (pcov)

The bonus is that, not only does curve_fit calculate an estimate for the parameter — 0.207962159793 — it also offers an estimate for this estimate's variance — 0.00086071 — as an element of pcov. This would appear to be a fairly small value, given the small sample size.

Here's how to calculate the residuals. Notice that each residual is the difference between the data value and the value estimated from x using the parameter estimate.

residuals = [y-model(_, popt[0]) for (y, _) in zip(Y, x)]
print (residuals)

If you wanted to further 'test that my function is indeed going through the data points' then I would suggest looking for patterns in the residuals. But discussions like this might be beyond what's welcomed on stackoverflow: Q-Q and P-P plots, plots of residuals vs y or x, and so on.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    With the help of numpy.random.exponential() method, we can get the random samples from exponential distribution and returns the numpy array of random samples by using this method.

    exponential distribution

    Syntax : numpy.random.exponential(scale=1.0, size=None)

    Return : Return the random samples of numpy array.

    Example #1 :

    In this example we can see that by using numpy.random.exponential() method, we are able to get the random samples of exponential distribution and return the samples of numpy array.

    Python3

    import numpy as np

    import matplotlib.pyplot as plt

    gfg = np.random.exponential(3.45, 10000)

    count, bins, ignored = plt.hist(gfg, 14, density = True)

    plt.show()

    Output :

    Example #2 :

    Python3

    import numpy as np

    import matplotlib.pyplot as plt

    gfg = np.random.exponential(101.123, 10000)

    gfg1 = np.random.exponential(gfg, 10000)

    count, bins, ignored = plt.hist(gfg1, 14, density = True)

    plt.show()

    Output :


    How do you generate a random number from exponential distribution in Python?

    exponential() in Python. With the help of numpy. random. exponential() method, we can get the random samples from exponential distribution and returns the numpy array of random samples by using this method.

    How do you generate a random number from an exponential distribution?

    So, one strategy we might use to generate a 1000 numbers following an exponential distribution with a mean of 5 is:.

    Generate a Y ∼ U ( 0 , 1 ) random number. ... .

    Then, use the inverse of Y = F ( x ) to get a random number X = F − 1 ( y ) whose distribution function is . ... .

    Repeat steps 1 and 2 one thousand times..

    What is scale in Numpy random exponential?

    numpy.random.exponential(scale=1.0, size=None) Exponential distribution. Its probability density function is. for x > 0 and 0 elsewhere. is the scale parameter, which is the inverse of the rate parameter.

    How do you fit an exponential distribution in Python?

    The solution is to fit using an exponential function where `b` is constrained to 0 (or whatever value you know it to be). ```python def monoExpZeroB(x, m, t): return m * np. exp(-t * x) # perform the fit using the function where B is 0 p0 = (2000, . 1) # start with values near those we expect paramsB, cv = scipy.