기본 콘텐츠로 건너뛰기

라벨이 qqplot인 게시물 표시

[matplotlib]quiver()함수

Graph code related to statistical tests

The following graphs are the codes for the figures included in Chapter 5 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") #fig511 st=pd.Timestamp(2024, 4,20) et=pd.Timestamp(2024, 5, 30) da1=yf.download('GOOGL', st, et)["Close"] da2=yf.download('MSFT', st, et)["Close"] da1=da1.iloc[:,0].pct_change()[1:]*100 da2=da2.iloc[:,0].pct_change()[1:]*100 da=pd.DataFrame([da1, da2], index=['data1', 'data2']).T da.index=range(len(da1)) mu1, sd1, n1=np.mean(da1), np.std(da1, ddof=1), len(da1) mu2, sd2, n2=np.mean(da2), np.std(da2, ddof=1), len(da2) s_p=np.sqrt(((n1-1)*sd1**2+(n2-1)*sd2**2)/(n1+n2-2)) se=s_p*np.sqrt((1/n1+1/n2)) df=n1+n2-2 mu=mu1-mu2 testStatic=((mu1-mu2)-0)/se x=np.linspace(-3, 3, 500) p=stats.t.pdf(x, df) l=stats.t...

통계 검정에 관련된 그래프

다음 그래프들은 전자책 파이썬과 함께하는 통계이야기 5 장에 수록된 그림들의 코드들입니다. 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 511 st=pd.Timestamp(2024, 4,20) et=pd.Timestamp(2024, 5, 30) da1=fdr.DataReader('091160', st, et)["Close"] da2=fdr.DataReader('005930', st, et)["Close"] da1=da1.pct_change()[1:]*100 da2=da2.pct_change()[1:]*100 da=pd.DataFrame([da1, da2], index=['data1', 'data2']).T da.index=range(len(da1)) mu1, sd1, n1=np.mean(da1), np.std(da1, ddof=1), len(da1) mu2, sd2, n2=np.mean(da2), np.std(da2, ddof=1), len(da2) s_p=np.sqrt(((n1-1)*sd1**2+(n2-1)*sd2**2)/(n1+n2-2)) se=s_p*np.sqrt((1/n1+1/n2)) se=s_p*np.sqrt((1/n1+1/n2)) df=n1+n2-2 mu=mu1-mu2 ci=stats.t.interval(0.95, df, mu, se) testStatic=((mu1-mu2)-0)/se x=np.linspace(-3, 3, 500) ...

[data analysis] Cook's Distance(D)

Cook's Distance(D i ) 관련된 내용 회귀모형에서 이상치(outlier) 파악 Hat 행렬 레버리지(Leverage) 스튜던트 잔차(rstudent) 잔차들 중의 이상치는 잔차의 크기가 이상적으로 크거나 작은 경우에 해당되며 이는 레버리지와 잔차 자신의 크기가 모두 관계됩니다. 이 둘의 영향을 모두 반영하는 기준이 Cook’s distance(D) 이며 식1과 같이 정의 됩니다. \begin{align}D_i& = \frac{(y_i-\hat{y_{(i)}})^2}{(p+1)\text{MSE}}\cdot \frac{h_{ii}}{(1-h_{ii})^2}\\ & y_{(i)}:\; x_i\text{를 제외한 자료로부터 구현된 모델을 적용한 추정치}\\ & p:\;\text{설명변수의 수} \end{align} (식 1) 식 1에서 Cook’s distance(D)는 잔차(첫번째항)와 레버리지(두번째항)에 의해 결정됩니다. 즉, 각 샘플의 설명변수(X)와 반응변수(y) 모두를 고려합니다. 그러므로 D i 값이 크다면 추정값들 사이의 차이가 크다는 것으로 모델에 가하는 영향이 크다는 것을 의미하며 결정수준보다 크다면 왜곡된 모형을 생성할 가능성이 증가할 것입니다. 이 지표의 결정수준으로 다음을 사용합니다. D i > 0.5: i번째 데이터 포인트가 영향을 미칠 수 있으므로 추가 조사 필요 D i > 1: i번째 데이터 포인트가 영향을 미칠 가능성이 높음 Cook's distance를 해석하는 다른 방법은 측정값을 F(k+1, n-k-1) 분포와 연관시키고 해당 백분위수 값을 찾는 것입니다. 이 백분위수가 약 10% 또는 20% 미만이면 케이스가 적합치에 거의 영향을 미치지 않는 것입니다. 반면에 50%에 가깝거나 그 이상이면 해당하는 샘플(들)이 큰 영향을 미칩니다. 요소들의 평균값을 기준으로 ...

[data analysis] Q-Q plot

Q-Q plot 관련된 내용 Q-Q plot shapiro-Wilk test Kolmogorov-Smirnov Test Anderson-Darling 검정 Jarque-Bera test Q-Q(사분위수) plot은 두 자료들을 분위수로 구분한 후 동일한 분위수 값들에 대해 작성한 도표로서 두 그룹의 분포를 비교하는 방법으로 역누적분포에 의해 설명됩니다. 역누적분포 (Inverse cumulative distribution) 는 누적분포의 역함수입니다. 예를 들어 표준정규분포의 누적분포와 역누적분포는 그림 1과 같이 나타낼 수 있습니다. 그림 1. 표준정규분포의 (a) pdf, cdf와 (b)역누적확률분포. x=np.linspace(-3, 3,1000) pdf=stats.norm.pdf(x) cdf=stats.norm.cdf(x) q=np.linspace(0, 1, 1000) ppf=stats.norm.ppf(q) plt.figure(figsize=(8, 5)) plt.subplots_adjust(wspace=0.3) plt.subplot(1,2,1) plt.plot(x, pdf, color="blue", label="PDF") plt.plot(x, cdf, color="red", label="CDF") plt.xlabel("x") plt.ylabel("probability") plt.legend(loc="best") plt.title("(a)", loc="left") plt.subplot(1,2,2) plt.plot(q, ppf, color="green", label="Inverse CDF") plt.xlabel("probaility(q)") plt.ylabel("I(q)") plt.leg...

Normality Test

Contents Q-Q plot shapiro-Wilk test Kolmogorov-Smirnov Test Normality Test The central limit theorem approaches normal distribution as the number of samples in the data increases. In particular, the distribution of sample means corresponds to the normal distribution. However, for raw data other than the mean, it is sometimes important to match the normal distribution. For example, in regression, the difference between the observed values and the predicted values by the regression model is called residuals, and is performed on the assumption that the residuals conform to the normal distribution. Whether it fits the assumption or not is the basis for determining the fit of the established model. The normality test uses the following methods: Quantile-Quantile plot: Determination by visual analysis Shaprio-Wilks test: primarily used for number of samples (n < 2000) Kolmogoroves-Smrinov test: used when n>2000 Q-Q plot The Q-Q (Quadrant) plot i...