기본 콘텐츠로 건너뛰기

pandas_ta를 적용한 통계적 인덱스 지표

Estimation

Contents

  1. Point estimation
  2. Interval estimation
  3. Confidence Interval

Estimation

Estimation is divided into point estimation, which estimates a specific value of a parameter, and interval estimation, which estimates a certain interval in which the parameter is included.

Point estimation

A statistic used to estimate the parameters of a population from a sample is called an estimator, and an estimate that meets some assumptions and has no bias is used as an unbiased estimator. For example, to estimate the population mean, the sample mean is used as an unbiased estimate.

The sample mean of n samples X1, X2, …, Xn is calculated as in Equation 1 and is an estimator of the population mean.

$$\begin{align}\tag{1} \hat{\mu}&=\bar{X}\\ &=\frac{1}{n}(\bar{X_1}+\bar{X_2}+\cdots+\bar{X_n})\\ &=\frac{1}{n}\sum^n_{i=1}\bar{X_i } \end{align}$$

Also, in general, the population variance σ2 is an unknown value, so it is calculated as in Equation 2 using the standard deviation s of the sampling distribution as an estimator.

$$\begin{align} \tag{2}\hat{\sigma}&=s\\ &=\sqrt{\frac{1}{n-1}\sum^n_{i=1}(\bar{X_i}-\bar{X})}\\ n :&\text{sample size} \end{align}$$

Interval estimation

Parameters estimated by the statistic of a sample have uncertainty because they vary depending on the sample being sampled from the population. Therefore, rather than representing a parameter with a single value, such as a point estimate, it would be more reasonable to represent an interval that includes the parameter at a level that is probabilistically reliable. These intervals are called confidence intervals.

Confidence Interval

The sample mean ($\bar{x}$) can be a good estimator for the population mean ($\mu$), but uncertainty about perfect agreement exists. Therefore, based on the estimator, it is possible to indicate by setting the interval where the population mean is most likely to exist. For example, assuming a normal distribution, you can specify an interval in which the estimate can exist in either or both directions around the mean with the highest probability. Such an interval is called confidence interval.

If the sample mean is within the confidence interval for estimating the population mean, then the basis for using the sample mean as the population mean is prepared. However, if it is located outside that interval, it may be difficult to use it as a population mean. That is, the assumption of the distribution and the establishment of a confidence interval are used as criteria for accepting or rejecting the estimator.

As shown in Figure 1, the 95% probability interval in the standard normal distribution exists in the interval (μ-1.96σ, μ+1.96 σ). By applying this interval, standardized values as in Equation 3 can be returned to their original values by Equation 4.

$$\begin{equation} \tag{4} Z=\frac{X-\mu_x}{\sigma_x} \end{equation}$$
import numpy as np
import pandas as pd 
import matplotlib.pyplot as plt
from scipy import stats
plt.figure(figsize=(6,3))
x=np.linspace(-3, 3.01, 1000)
y=[stats.norm.pdf(i) for i in x]
plt.plot(x, y, label='N(0, 1)')
plt.axhline(0, color="black")
plt.axvline(0, linestyle="--", color="black", label="Mean", alpha=0.3)
plt.axvline(-1.96, linestyle="--", color="green", label="Lower")
plt.axvline(1.96, linestyle="--", color="red", label="Upper")
plt.fill_between(x, 0, y, where=(x <=-1.96) | (x>=1.95), facecolor="skyblue", alpha=0.5)
plt.text(0, -0.09,"x", size="13", weight="bold")
plt.ylabel("pdf", size="13", weight="bold")
plt.legend(loc="best")
plt.xticks([])
plt.text(-0, -0.05, 0, size="13", weight="bold")
plt.text(-2.4, -0.05, -1.96, size="13", weight="bold")
plt.text(1.6, -0.05, 1.96, size="13", weight="bold")
plt.text(-2.6, 0.02, r"$\mathbf{\frac{\alpha}{2}}$", size="14", weight="bold")
plt.text(-0.3, 0.1, r"1-$\mathbf{\alpha}$(0.9)", size="14", weight="bold")
plt.text(2.0, 0.02, r"$\mathbf{\frac{\alpha}{2}}$", size="14", weight="bold")
plt.show()
Figure 1. Confidence and rejection intervals in the standard normal distribution(α=0.05).
$$\begin{align}\tag{4} &P(-1.96 \le Z \le 1.96)=0.95\\ &\rightarrow P\left(-1.96 \le \frac{\overline{y}-\mu}{\frac{\sigma}{\sqrt{n}}} \le 1.96 \right)=0.95\\ &\rightarrow P\left(\overline{y}-1.96\frac{\sigma}{\sqrt{n}} \le Z \le \overline{y}+1.96\frac{\sigma}{\sqrt{n}}\right)=0.95 \end{align}$$

In the result of Equation 4, based on the average $\mu$, the value on the left is lower bound, and the value on the right is upper bound. The bounds of this confidence interval can be calculated using Equation 5.

$$\begin{align}\tag{5} &\text{CI}_\mu=\overline{y} \pm z_\frac{\alpha}{2}\frac{\alpha}{\sqrt{n}}\\ &n: \text{ssample size}\\ &z_\frac{\alpha}{2}:\text{Standard score corresponding to} \,P=100(1-\alpha)\% \end{align}$$

For example, in Figure 1, the standard normal distribution, the tail of the curve is the region corresponding to the significance level. Conversely, the part excluding the significance level from the overall probability, that is, 1-α, is called confidence level or confidence coefficient.

For a significance level of 0.05, the left and right edges of the curve are 0.025 and 1-0.025. The value corresponding to this point is the standard score and is expressed as zα/2. This value can be checked using the scipy.stats.norm.ppf(q, loc=0, scale=1) method. This method returns a value corresponding to probability q (0.025 or 0.975). This result is equal to the lower or upper bound returned by the interval(1-α, loc=0, scale=1) method. (The method interval() assumes a two-sided test.(see Hypothesis Test)

round(stats.norm.ppf(0.975), 4), round(stats.norm.ppf(0.025),4)
(1.96, -1.96)
np.around(stats.norm.interval(0.95), 4)
array([-1.96,  1.96])

댓글

이 블로그의 인기 게시물

[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' 와 같...

유리함수 그래프와 점근선 그리기

내용 유리함수(Rational Function) 점근선(asymptote) 유리함수 그래프와 점근선 그리기 유리함수(Rational Function) 유리함수는 분수형태의 함수를 의미합니다. 예를들어 다음 함수는 분수형태의 유리함수입니다. $$f(x)=\frac{x^{2} - 1}{x^{2} + x - 6}$$ 분수의 경우 분모가 0인 경우 정의할 수 없습니다. 이와 마찬가지로 유리함수 f(x)의 정의역은 분모가 0이 아닌 부분이어야 합니다. 그러므로 위함수의 정의역은 분모가 0인 부분을 제외한 부분들로 구성됩니다. sympt=solve(denom(f), a); asympt [-3, 2] $$-\infty \lt x \lt -3, \quad -3 \lt x \lt 2, \quad 2 \lt x \lt \infty$$ 이 정의역을 고려해 그래프를 작성을 위한 사용자 정의함수는 다음과 같습니다. def validX(x, f, symbol): ① a=[] b=[] for i in x: try: b.append(float(f.subs(symbol, i))) a.append(i) except: pass return(a, b) #x는 임의로 지정한 정의역으로 불연속선점을 기준으로 구분된 몇개의 구간으로 전달할 수 있습니다. #그러므로 인수 x는 2차원이어야 합니다. def RationalPlot(x, f, sym, dp=100): fig, ax=plt.subplots(dpi=dp) # ② for k in x: #③ x4, y4=validX(k, f, sym) ax.plot(x4, y4) ax.spines['left'].set_position(('data', 0)) ax.spines['right...

turtle로 정오각형 그리기

정오각형 그리기  오각형을 그리는 것 역시 정사각형 , 정삼각형 을 그리는 것과 유사한 과정을 거칩니다. 단지 각 꼭지점의 각도만이 다르지요. 그러면 정오각형의 각 모서리의 각도는 어떻게 될까요? 이를 생각하기에 앞서 각 도형의 내각을 먼저 생각해보죠. 우리는 삼각형의 내각의 합을 알고 있습니다. 이를 이용하면 각 도형에서 삼각형이 몇개가 존재하는지를 알아보고 "삼각형의 갯수×180"로 그 도형의 내각의 합을 구할 수 있을 것입니다. 다음 그림을 볼까요? 위 그림의 사각형은 1개의 대각선으로 2개의 삼각형으로 구성됩니다. 오각형의 경우 2개의 대각선으로 3개의 삼각형으로 구성됩니다. 즉, 다음의 관계를 보이지요. 사각형의 내각 : 삼각형 2개 2×180=360 한각의 값  360/4=90 오각형의 내각 : 삼각형 3개 3×180=540 한각의 값  540/5=108 육각형의 내각 : 삼각형 4개 4×180=720 한각의 값  720/6=120 ... 위 그림에서 내각과 외각의 관계를 보면 위 그림의 검은색은 각 모서리의 내각이고 빨간색은 외각을 나타냅니다. 외각은 내각을 이루는 하나의 선을 연장했을 경우 상대되는 각도이라고 했습니다. 그러므로 오각형의 경우 내각 108도에 대한 외각은 72도입니다. 특이할 사항은 사각형이나 오각형이나 외각의 합은 360입니다. 즉, 모든 도형의 외각의 합은 360도입니다. (삼각형의 외각의 합을 구해보세요.) 그러므로 모든 정다각형에서 하나의 외각은 다음과 같이 계산될 수 있겠지요. 360/변수의 수=다각형에서 하나의 외각 위에서 회전을 할 경우 내각이 아닌 외각을 사용해야 함을 알았습니다. 그러므로 오각형을 그리는 계획은 다음과 같이 작성할 수 있겠죠. 1) 지정한 길이만큼 앞으로 이동합니다. 2) 오른쪽 또는 왼쪽으로 72도를 회전합니다. 3) 앞으로 동일한 길이만큼 이동합니다. 4) 오른쪽 또는 왼쪽으로 72도 만큼 이동합니다. 5)1번부터 4번 ...