기본 콘텐츠로 건너뛰기

통계관련 함수와 메서드 사전

A B C d E F G H I K L M N O P Q R S T U V W Z A statsmodels.ap.stats.anova_lm(x) statsmodels.formula.api.ols 에 의해 생성되는 모형 즉, 클래스 인스턴스(x)를 인수로 받아 anova를 실행합니다. np.argsort(x, axis=-1, kind=None) 객체 x를 정렬할 경우 각 값에 대응하는 인덱스를 반환합니다. Axis는 기준 축을 지정하기 위한 매개변수로서 정렬의 방향을 조정할 수 있음(-1은 기본값으로 마지막 축) pandas.Series.autocorr(lag=1) lag에 전달한 지연수에 따른 값들 사이의 자기상관을 계산 B scipy.stats.bernoulli(x, p) 베르누이분포에 관련된 통계량을 계산하기 위한 클래스를 생성합니다. x: 랜덤변수 p: 단일 시행에서의 확률 scipy.stats.binom(x, n, p) 이항분포에 관련된 통계량을 계산하기 위한 클래스를 생성합니다. x: 랜덤변수 n: 총 시행횟수 p: 단일 시행에서의 확률 C scipy.stats.chi2.pdf(x, df, loc=0, scale=1) 카이제곱분포의 확률밀도함수를 계산 $$f(x, k) =\frac{1}{2^{\frac{k}{2}−1}Γ(\frac{k}{2})}x^{k−1}\exp\left(−\frac{x^2}{2}\right)$$ x: 확률변수 df: 자유도 pd.concat(objs, axis=0, join=’outer’, …) 두 개이상의 객체를 결합한 새로운 객체를 반환. objs: Series, DataFrame 객체. Axis=0은 행단위 즉, 열 방향으로 결합, Axis=1은 열단위 즉, 행 방향으

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

댓글

이 블로그의 인기 게시물

matplotlib의 그래프 종류

1. 산포도(scatter plot) plt.scatter(x, y) >>> import matplotlib.pyplot as plt >>> import numpy as np >>> data=np.random.rand(1024, 2) >>> data[:3, :] >>> plt.scatter(data[:,0], data[:,1]) >>> plt.show() 2. 막대그래프(bar chart) plt.bar(x, hight, width, align='center') 매개변수중 width에 인수를 전달하여 막대의 두께를 조절할 수 있다. 또한 align의 인수는 'center'와 'edge' 이다. 기본값은 'center'이다. 이 값은 x축의 레이블이 막대의 중간에 위치(center) 또는 왼쪽 가장자리에 위치(edge)시킨다. 코드에서 np.random.randint 는 특정한 범위내에서 지정한 갯수의 랜덤수를 생성 np.unique(배열, retrun_counts=False, axis=None) : 객체 내의 중복되지 않은 수들을 반환한다. return_counts=True이면 각 수에 대한 빈도수를 반환한다. axis를 통해 행(1), 열(0)을 선택한다. >>> x=np.random.randint(1, 6, size=100) >>> uni,count=np.unique(x, return_counts=True) >>> uni array([1, 2, 3, 4, 5]) >>> count array([25, 17, 23, 16, 19], dtype=int64) >>> plt.bar(uni, count) >>> plt.show() 위의 막대그래프의 막대의

유사변환과 대각화

내용 유사변환 유사행렬의 특성 대각화(Diagonalization) 유사변환(Similarity transformation) 유사변환 n×n 차원의 정방 행렬 A, B 그리고 가역 행렬 P 사이에 식 1의 관계가 성립하면 행렬 A와 B는 유사하다고 하며 이 변환을 유사 변환 (similarity transformation)이라고 합니다. $$\begin{equation}\tag{1} A = PBP^{-1} \Leftrightarrow P^{-1}AP = B \end{equation}$$ 식 1의 유사 변환은 다음과 같이 고유값을 적용하여 특성 방정식 형태로 정리할 수 있습니다. $$\begin{align} B - \lambda I &= P^{-1}AP – \lambda P^{-1}P\\ &= P^{-1}(AP – \lambda P)\\ &= P^{-1}(A - \lambda I)P \end{align}$$ 위 식의 행렬식은 다음과 같이 정리됩니다. $$\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)\\ &= \t

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$$ 실수