기본 콘텐츠로 건너뛰기

벡터와 행렬에 관련된 그림들

Exponential distribution

Exponential Distribution

The exponential distribution is one of the most used continuous distributions and is widely used to model the passage of time between certain events.

The distribution of a continuous random variable X having a probability density function (PDF) as in Equation 1 is called an exponential distribution, and the parameter λ means the mean frequency.

$$\begin{align}\tag{1} &X \sim \text{Exponential}(\lambda)\\ &f(x)=\begin{cases} \lambda e^{-\lambda x}&\quad x>0\\ 0 & \quad \text{otherwise} \end{cases}\\ & \quad \lambda >0 \end{align}$$

The cumulative distribution function of the exponential distribution is calculated by the integral of the probability density function.

Use the sympy.integrate() function.

import numpy as np
import pandas as pd 
import matplotlib.pyplot as plt
from sympy import *
from scipy import stats
x, l=symbols("x lambda", positive=True)
f=l*exp(-l*x)
f
$\qquad \color{blue}{\displaystyle l e^{- \lambda x}}$
F=integrate(f, (x, 0, x))
simplify(F)
$\qquad \color{blue}{\displaystyle 1-e^{- \lambda x}}$

The mean and variance of the exponential distribution are defined as Equation 2 according to their respective definitions.

$$\begin{align}\tag{2} &\begin{aligned}E(x)&=\mu\\&=\int^\infty_0 xf(x)\, dx\\&=\int^\infty_0 x\lambda e^{-\lambda x}\, dx\\&=\left. \frac{1}{\lambda}(-e^{-\lambda x}-xe^{-\lambda x})\right|^\infty_0\\&=\frac{1}{\lambda} \end{aligned}\\ &\begin{aligned}E(x^2)&=\int^\infty_0 x^2f(x)\, dx\\&=\int^\infty_0 x^2\lambda e^{-\lambda x}\, dx\\&=\frac{2}{\lambda^2} \end{aligned}\\ &\begin{aligned}\text{Var(X)}&=E(x^2)-(E(x))^2\\&=\frac{2}{\lambda^2}-\frac{1}{\lambda^2}\\&=\frac{1}{\lambda^2} \end{aligned} \end{align}$$
E=integrate(x*f,(x, 0, oo))
E
$\qquad \color{blue}{\displaystyle \frac{1}{\lambda}}$
E2=integrate(x**2*f, (x, 0, oo))
E2
$\qquad \color{blue}{\displaystyle \frac{2}{\lambda^2}}$
var=E2-E**2
var
$\qquad \color{blue}{\displaystyle \frac{1}{\lambda^2}}$

Statistics of random variables conforming to the exponential distribution can be calculated using various methods of the expon class of the scipy.stats module.

  • If λ > 1, scale (indicator of spread of data) < 1
  • if λ < 1, scale > 1

As a result, λ can be said to be a parameter that controls the spread of the data.

Example 1)
  It is said that the time it takes to repair a machine follows an exponential distribution with the parameter λ=3. Mean and standard deviation?

It is calculated using the probability density function of the exponential distribution as follows.

$$f(x)=\lambda e^{-\lambda x}$$
E=integrate(x*f,(x, 0, oo))
E.subs(l, 3)
$\qquad \color{blue}{\displaystyle \frac{1}{3}}$
var=E2-E**2
var.subs(l, 3)
$\qquad \color{blue}{\displaystyle \frac{1}{9}}$

Check the mean and standard deviation calculated above with the stats.expon class.

np.around(stats.expon.stats(scale=1/3, moments="mv"), 4)
array([0.3333, 0.1111])

Use the moment() method of this class to calculate the mean and variance.

E=stats.expon.moment(1,scale=1/3)
round(E, 4)
0.3333
E2=stats.expon.moment(2, scale=1/3)
round(E2, 4)
0.2222
var=E2-E**2
round(var, 4)
0.1111

The following shows the distribution change according to λ.

plt.figure(figsize=(7, 4))
lamda=[0.5, 1, 2]
for i in lamda:
    p=[stats.expon.pdf(j, 0, 1/i) for j in np.arange(0, 2, 0.001)]
    plt.plot(np.arange(0, 2, 0.001), p, label="Expon("+str(i)+")")
plt.xlabel("X", fontsize="13", fontweight="bold")
plt.ylabel("PDF", fontsize="13", fontweight="bold")
plt.legend(loc="best")
plt.show()

The exponential distribution above is similar to the geometric distribution of discrete variables. The following is the geometric distribution when the probability in one run is p.

plt.figure(figsize=(7, 4))
p=[0.05, 0.1, 0.5]
for j in p:
    p=[stats.geom.pmf(i, j) for i in np.arange(10)]
    plt.plot(np.arange(10), p, label="geom("+str(j)+")")
plt.xlabel("X", fontsize="13", fontweight="bold")
plt.ylabel("PDF", fontsize="13", fontweight="bold")
plt.legend(loc="best")
plt.show()

A geometric distribution is a distribution that shows the probability that success occurs for the first time by repeating Bernoulli trials with probability p. If this distribution is similar to the exponential distribution, which is the distribution of continuous variables, it can be considered that there is a correlation between the parameter p of the geometric distribution and λ, the parameter of the exponential distribution. In the case of the continuous distribution λ, it is a parameter related to the decay rate of the probability, and the smaller it is, the smaller the change in the probability. Similarly, the smaller the p of the geometric distribution, the smaller the change in probability. Therefore, the exponential distribution can be interpreted as a case in which the probability of first success in any trial is very small. For example, the probability distribution for the data that customers visit a store in a very short time interval can be thought of as an exponential distribution.

As such, the interpretation of the exponential distribution can be understood as the characteristics of the geometric distribution. Important of these characteristics is that they are not constrained by any previous conditions. If a coin toss is repeated and heads (success) have not been observed so far, the probability from that point on is not limited by the previous results. These attributes are called memoryless. That is, a continuous variable X following an exponential distribution with a parameter of λ > 0 is a memoryless random variable, which is proved by the following equations.

$$\begin{align} &P(X>x+a | X>a)=P(X>x)\\ &\begin{aligned}F(x)&=\int^x_0 \lambda e^{-\lambda t}\,dt\\&=1-e^{-\lambda x}\end{aligned}\\ &\begin{aligned}P(X>x+a | X>a)&=\frac{P(X>x+a) \cap P(X>a)}{P(X>a)}\\&=\frac{P(X>x+a)}{P(X>a)}\\&=\frac{1-F(x+a)}{1-F(a)}\\&=\frac{e^{-\lambda (x+a)}}{e^{-\lambda a}}\\&=e^{-\lambda x}\\&=1-F(x)\\&=P(X>x)\end{aligned} \end{align}$$

Example 2)
 An employee at a company makes an average of 6 calls every 10 minutes. In this case, it is assumed that the number of minutes between the call and the next call is called the random variable t, and that this variable follows an exponential distribution.
Determine the following:

1) The average frequency of calls per minute is λ, which is 0.6 calls per minute. Therefore, the probability density function of this distribution is

$$f(x)=0.6 \exp(-0.6 t), \quad t \gt 0$$

2) What is the probability that the next call will be within 5 minutes after the call?

t=symbols('t', positive=True)
f=0.6*exp(-0.6*t)
Flt5=f.integrate((t, 0, 5))
N(Flt5,4)
0.9502

3) Probability that the next call will be more than 2 minutes after a call?

Fgt2=1-f.integrate((t, 0, 2))
N(Fgt2,4)
0.3012
round(stats.expon.sf(2, scale=1/0.6), 4)
0.3012

Example 3)
 The daily fluctuations of the high and low prices of the Philadelphia Semiconductor Index(SOXX) over the following period are applied to an exponential distribution.

import FinanceDataReader as fdr
st=pd.Timestamp(2020,1, 1)
et=pd.Timestamp(2021, 12, 14)
da=fdr.DataReader("SOXX", st, et)
change=(da['High']-da['Low'])/da['Low']*100
change
Date
2020-01-02    1.300395
2020-01-03    1.095792
2020-01-06    0.982771
2020-01-07    1.584830
2020-01-08    1.106440
                ...   
2021-12-08    1.253281
2021-12-09    2.854305
2021-12-10    2.663311
2021-12-13    3.369283
2021-12-14    1.853975
Length: 493, dtype: float64

According to the expression 2, the reciprocal of the mean of change is the parameter λ.

plt.figure(figsize=(7,4))
rng=np.sort(change)
lam=1/rng.mean()
p=[stats.expon.pdf(i, loc=lam, scale=1/lam ) for i in rng]
f=plt.hist(rng, bins=10,density=True, alpha=0.4, label='daily change')
plt.plot(rng, p, linewidth=2, label='Expon('+str(round(lam,3))+')')
plt.xlabel('Change(%)', fontsize='13', fontweight='bold')
plt.ylabel('PDF(Density)', fontsize='13', fontweight='bold')
plt.legend(loc='best')
plt.show()

According to the above result, the probability that the rate of change between the low and high prices is 3% or more is as follows.

cf=stats.expon.sf(3, lam, 1/lam)
round(cf, 4)
0.3357

댓글

이 블로그의 인기 게시물

[Linear Algebra] 유사변환(Similarity transformation)

유사변환(Similarity transformation) n×n 차원의 정방 행렬 A, B 그리고 가역 행렬 P 사이에 식 1의 관계가 성립하면 행렬 A와 B는 유사행렬(similarity matrix)이 되며 행렬 A를 가역행렬 P와 B로 분해하는 것을 유사 변환(similarity transformation) 이라고 합니다. $$\tag{1} A = PBP^{-1} \Leftrightarrow P^{-1}AP = B $$ 식 2는 식 1의 양변에 B의 고유값을 고려한 것입니다. \begin{align}\tag{식 2} B - \lambda I &= P^{-1}AP – \lambda P^{-1}P\\ &= P^{-1}(AP – \lambda P)\\ &= P^{-1}(A - \lambda I)P \end{align} 식 2의 행렬식은 식 3과 같이 정리됩니다. \begin{align} &\begin{aligned}\textsf{det}(B - \lambda I ) & = \textsf{det}(P^{-1}(AP – \lambda P))\\ &= \textsf{det}(P^{-1}) \textsf{det}((A – \lambda I)) \textsf{det}(P)\\ &= \textsf{det}(P^{-1}) \textsf{det}(P) \textsf{det}((A – \lambda I))\\ &= \textsf{det}(A – \lambda I)\end{aligned}\\ &\begin{aligned}\because \; \textsf{det}(P^{-1}) \textsf{det}(P) &= \textsf{det}(P^{-1}P)\\ &= \textsf{det}(I)\end{aligned}\end{align} 유사행렬의 특성 유사행렬인 두 정방행렬 A와 B는 'A ~ B' 와 같...

[sympy] Sympy객체의 표현을 위한 함수들

Sympy객체의 표현을 위한 함수들 General simplify(x): 식 x(sympy 객체)를 간단히 정리 합니다. import numpy as np from sympy import * x=symbols("x") a=sin(x)**2+cos(x)**2 a $\sin^{2}{\left(x \right)} + \cos^{2}{\left(x \right)}$ simplify(a) 1 simplify(b) $\frac{x^{3} + x^{2} - x - 1}{x^{2} + 2 x + 1}$ simplify(b) x - 1 c=gamma(x)/gamma(x-2) c $\frac{\Gamma\left(x\right)}{\Gamma\left(x - 2\right)}$ simplify(c) $\displaystyle \left(x - 2\right) \left(x - 1\right)$ 위의 예들 중 객체 c의 감마함수(gamma(x))는 확률분포 등 여러 부분에서 사용되는 표현식으로 다음과 같이 정의 됩니다. 감마함수는 음이 아닌 정수를 제외한 모든 수에서 정의됩니다. 식 1과 같이 자연수에서 감마함수는 factorial(!), 부동소수(양의 실수)인 경우 적분을 적용하여 계산합니다. $$\tag{식 1}\Gamma(n) =\begin{cases}(n-1)!& n:\text{자연수}\\\int^\infty_0x^{n-1}e^{-x}\,dx& n:\text{부동소수}\end{cases}$$ x=symbols('x') gamma(x).subs(x,4) $\displaystyle 6$ factorial 계산은 math.factorial() 함수를 사용할 수 있습니다. import math math.factorial(3) 6 a=gamma(x).subs(x,4.5) a.evalf(3) 11.6 simpilfy() 함수의 알고리즘은 식에서 공통사항을 찾아 정리하...

sympy.solvers로 방정식해 구하기

sympy.solvers로 방정식해 구하기 대수 방정식을 해를 계산하기 위해 다음 함수를 사용합니다. sympy.solvers.solve(f, *symbols, **flags) f=0, 즉 동차방정식에 대해 지정한 변수의 해를 계산 f : 식 또는 함수 symbols: 식의 해를 계산하기 위한 변수, 변수가 하나인 경우는 생략가능(자동으로 인식) flags: 계산 또는 결과의 방식을 지정하기 위한 인수들 dict=True: {x:3, y:1}같이 사전형식, 기본값 = False set=True :{(x,3),(y,1)}같이 집합형식, 기본값 = False ratioal=True : 실수를 유리수로 반환, 기본값 = False positive=True: 해들 중에 양수만을 반환, 기본값 = False 예 $x^2=1$의 해를 결정합니다. solve() 함수에 적용하기 위해서는 다음과 같이 식의 한쪽이 0이 되는 형태인 동차식으로 구성되어야 합니다. $$x^2-1=0$$ import numpy as np from sympy import * x = symbols('x') solve(x**2-1, x) [-1, 1] 위 식은 계산 과정은 다음과 같습니다. $$\begin{aligned}x^2-1=0 \rightarrow (x+1)(x-1)=0 \\ x=1 \; \text{or}\; -1\end{aligned}$$ 예 $x^4=1$의 해를 결정합니다. solve() 함수의 인수 set=True를 지정하였으므로 결과는 집합(set)형으로 반환됩니다. eq=x**4-1 solve(eq, set=True) ([x], {(-1,), (-I,), (1,), (I,)}) 위의 경우 I는 복소수입니다.즉 위 결과의 과정은 다음과 같습니다. $$x^4-1=(x^2+1)(x+1)(x-1)=0 \rightarrow x=\pm \sqrt{-1}, \; \pm 1=\pm i,\; \pm1$$ 실수...