기본 콘텐츠로 건너뛰기

라벨이 nbinom인 게시물 표시

[matplotlib]quiver()함수

Statistics related graph code

The following graphs are the codes for the figures included in Chapter 4 of the e-book Statistics with Python . import numpy as np import pandas as pd from scipy import stats from sklearn.preprocessing import StandardScaler import yfinance as yf import matplotlib.pyplot as plt import seaborn as sns sns.set_style("darkgrid") # fig 421 st=pd.Timestamp(2022,12, 1) et=pd.Timestamp(2023, 4, 1) da=yf.download("^DJI", st, et) pop=(da['Close']-da['Open'])/da['Open']*100 pop.columns=['change'] pop.index=pd.DatetimeIndex(pop.index.date) xBar=np.array([]) for i in range(20): x=pop.sample(5, replace=False, random_state=i) xBar=np.append(xBar, x.mean()) xBar2=np.array([]) for i in range(100): x=pop.sample(5, replace=False, random_state=i) xBar2=np.append(xBar2, x.mean()) plt.figure(figsize=(7, 3)) plt.subplot(1,2,1) plt.hist(xBar, 10, rwidth=0.8, color="blue", label="n=20") plt.axvline(-0.18, 0, 0.9, color=...

통계관련 그래프

다음 그래프들은 전자책 파이썬과 함께하는 통계이야기 4 장에 수록된 그림들의 코드들입니다. import numpy as np import pandas as pd from scipy import stats from sklearn.preprocessing import StandardScaler import FinanceDataReader as fdr import yfinance as yf import matplotlib.pyplot as plt import seaborn as sns sns.set_style("darkgrid") #fig 421 st=pd.Timestamp(2022,12, 1) et=pd.Timestamp(2023, 4, 1) da=fdr.DataReader("KS11", st, et) pop=(da['Close']-da['Open'])/da['Open']*100 np.random.seed(1) xBar=np.array([]) for i in range(20): x=pop.sample(5, random_state=i) xBar=np.append(xBar, x.mean()) xBar2=np.array([]) for i in range(100): x=pop.sample(5, random_state=i) xBar2=np.append(xBar2, x.mean()) fig, ax=plt.subplots(1, 2, figsize=(8, 3)) ax[0].hist(xBar, 10, rwidth=0.8, color="blue", label="n=20") ax[0].axvline(xBar.mean(), 0, 0.9, color="red", label=f"m={round(xBar.mean(), 2)}") ax[0].set_xlabel("x", weight=...

확률, 통계 관련 그래프

다음 그래프들은 전자책 파이썬과 함께하는 통계이야기 3 장에 수록된 그림들의 코드들입니다. import numpy as np import pandas as pd from scipy import stats import matplotlib.pyplot as plt import seaborn as sns sns.set_style("darkgrid") #fig 311 uni, p=[0, 1, 2],[0.25, 0.5, 0.25] fig, ax=plt.subplots(figsize=(4,3)) ax.bar(uni, p, color="g", alpha=0.3) ax.set_xlabel("# of head(H)") ax.set_ylabel("PMF") ax.set_yticks(p) ax.set_xticks(uni) plt.show() #fig 312 import itertools ca=list(itertools.product(range(1, 7), repeat=2)) S=[sum(i) for i in ca] uni, fre=np.unique(S, return_counts=True) fresum=sum(fre) p=[i/fresum for i in fre] fig, ax=plt.subplots(figsize=(4,3)) ax.bar(uni, p, color="g", alpha=0.3) ax.set_xlabel("Sum of number") ax.set_ylabel("PMF") ax.set_yticks(np.array(p).round(3)) ax.set_xticks(uni) plt.show() #fig 313 ca=list(itertools.product([0, 1], repeat=2)) S=[sum(i) for i in ca] uni, fre=np.unique(S, return_counts=True) re=pd.DataFrame([...

[data analysis] 음이항분포(Negative Binomial Distribution)

음이항분포(Negative Binomial Distribution) 음이항 분포는 베르누이 시행을 반복하면서 r번째 성공까지의 확률의 변화를 나타내는 분포이며 파스칼 분포 (Pascal distribution) 라고도 합니다. 예를 들어 동전의 앞면이 r회가 될 때까지 동전던지는 시행을 계속하는 경우로서 동전던지는 총 횟수가 확률변수 x가 됩니다. 이 확률변수는 동전 던지기 1회 당 앞면이 나오는 확률(p)가 앞면의 수(r)에 의존합니다. 이를 일반화하면 식 1과 같이 음이항분포의 확률변수는 성공횟수(r)와 베르누이 확률(p)을 매개변수로하는 확률분포로 나타낼 수 있습니다. X ~ NB(r, p) (식 1) 음이항 분포에서 최종 시행은 성공으로 시행이 종료되므로 식 2와 같이 마지막 시행을 제외한 경우에서 r - 1 횟수를 선택하는 이항확률로 간주할 수 있습니다(r은 성공횟수). \begin{align} f(x) &= P(X = x)\\&=\binom{x-1}{r-1}p^r(1-p)^{x-r}\\ x&=r, r+1, \cdots \end{align} (식 2) 식 2에서 성공횟수 r = 1인 경우는 기하분포가 됩니다. 예 1) 동전 던지기에서 4번 앞면이 발생하고 그 총 횟수가 10회가 되는 사건 A의 확률을 계산합니다. 사건 A의 확률은 식 3.1.32와 같이 나타낼 수 있습니다. A = {X = 10}, 10번 시행에 4번 앞면 (식 3.1.32) B = {X = 9}, 9번 시행에 3번 앞면 C = {X = 1}, 마지막 1번 시행이 앞면   P(A) = P(B ∩ C) 위 과정에서 P(C) = p(단일 시행에서 성공확률)가 되며 P(B)는 이항분포가 되므로 식 3과 같이 나타낼 수 있습니다. $$P(B) = \binom{9}{3}p^3(1-p)^6$$ (식 3) 결국 A의 확률질량함수는 식 3에서 나타낸 함수에 최후의 성공확률을 고려한 것으로 식 4와 같이 계산됩니다. \be...