抽樣分佈實踐(python版)

任務描述:

    1、驗證數據是否服從正太分佈
    2、驗證數據是否服從T分佈
    3、驗證數據是否服從卡方分佈

背景知識:

    1、什麼是假設檢驗

         假設檢驗(hypothesis testing),又稱統計假設檢驗,是用來判斷樣本與樣本、樣本與總體的差異是由抽樣誤差引起還是本質差別造成的統計推斷方法。顯著性檢驗是假設檢驗中最常用的一種方法,也是一種最基本的統計推斷形式,其基本原理是先對總體的特徵做出某種假設,然後通過抽樣研究的統計推理,對此假設應該被拒絕還是接受做出推斷。常用的假設檢驗方法有Z檢驗、t檢驗、卡方檢驗、F檢驗等 [1] 

    2、什麼是P值

        P值(P value)就是當原假設爲真時所得到的樣本觀察結果或更極端結果出現的概率。如果P值很小,說明原假設情況的發生的概率很小,而如果出現了,根據小概率原理,我們就有理由拒絕原假設,P值越小,我們拒絕原假設的理由越充分。總之,P值越小,表明結果越顯著。但是檢驗的結果究竟是“顯著的”、“中度顯著的”還是“高度顯著的”需要我們自己根據P值的大小和實際問題來解決

通俗版的假設檢驗和什麼是P值可參考知乎馬同學的回答

涉及方法庫:

stats.kstest

stats.shapiro

stats.normaltest

stats.t.rvs

stats.chi2.rvs

具體的代碼實現(jupyter notbook )

# 導入需要的庫,讀入數據
import pandas as pd
import numpy as np

file = pd.read_excel(r'E:\Chrome\data.xlsx')
file.head()
file.describe()
"""
樣例數據展示
字段說明:
Age:年齡,指登船者的年齡。
Fare:價格,指船票價格。
Embark:登船的港口。
"""
##data overview
print ("Rows     : " ,file.shape[0])
print ("Columns  : " ,file.shape[1])
print ("\nFeatures : \n" ,file.columns.tolist())
print ("\nMissing values :  ", file.isnull().sum().values.sum())
print ("\nUnique values :  \n",file.nunique())
embark = file.groupby(["Embarked"])
embark_basic = file.groupby(['Embarked']).agg(['count','min','max','median','mean','var','std'])
age_basic = embark_basic["Age"]
fare_basic = embark_basic["Fare"]
# 1、可視化年齡分佈
import seaborn as sns 
import matplotlib.pyplot as plt
sns.set_palette("hls") #設置所有圖的顏色,使用hls色彩空間
sns.distplot(file['Age'],color="b",bins=10,kde=True)
plt.title('Age')
plt.xlim(-10,80)
plt.grid(True)
plt.show()
# 2、驗證是否服從正態分佈?
#分別用kstest、shapiro、normaltest來驗證分佈係數
from scipy import stats
ks_test = stats.kstest(file['Age'], 'norm')
shapiro_test = stats.shapiro(file['Age'])
normaltest_test = stats.normaltest(file['Age'],axis=0)

print('ks_test:',ks_test)
print('shapiro_test:',shapiro_test)
print('normaltest_test:',normaltest_test)
data =  file # 沒有什麼作用,爲了方便複製大佬代碼
# 由於p <0.05, 拒絕原假設,認爲數據不服從正態分佈

# 繪製擬合正態分佈曲線
age = data['Age']

plt.figure()
age.plot(kind = 'kde')   #原始數據的正態分佈

M_S = stats.norm.fit(age)  #正態分佈擬合的平均值loc,標準差 scale
normalDistribution = stats.norm(M_S[0], M_S[1])  # 繪製擬合的正態分佈圖
x = np.linspace(normalDistribution.ppf(0.01), normalDistribution.ppf(0.99), 100)
plt.plot(x, normalDistribution.pdf(x), c='orange')
plt.xlabel('Age about Titanic')
plt.title('Age on NormalDistribution', size=20)
plt.legend(['age', 'NormDistribution'])
# 2、驗證是否服從T分佈
np.random.seed(1)  
ks = stats.t.fit(age)
df = ks[0]
loc = ks[1]
scale = ks[2]
ks2 = stats.t.rvs(df=df, loc=loc, scale=scale, size=len(age))
stats.ks_2samp(age, ks2)
 # 繪製擬合的T分佈圖
plt.figure()
age.plot(kind = 'kde')
TDistribution = stats.t(ks[0], ks[1],ks[2]) 
x = np.linspace(TDistribution.ppf(0.01), TDistribution.ppf(0.99), 100)
plt.plot(x, TDistribution.pdf(x), c='orange')
plt.xlabel('age about Titanic')
plt.title('age on TDistribution', size=20)
plt.legend(['age', 'TDistribution'])

 

#驗證是否符合卡方分佈
np.random.seed(1)
chi_S = stats.chi2.fit(age)
df_chi = chi_S[0]
loc_chi = chi_S[1]
scale_chi = chi_S[2]
chi2 = stats.chi2.rvs(df=df_chi, loc=loc_chi, scale=scale_chi, size=len(age))
stats.ks_2samp(age, chi2)
# 對數據進行卡方擬合
plt.figure()
age.plot(kind = 'kde')
chiDistribution = stats.chi2(chi_S[0], chi_S[1],chi_S[2])  # 繪製擬合的正態分佈圖
x = np.linspace(chiDistribution.ppf(0.01), chiDistribution.ppf(0.99), 100)
plt.plot(x, chiDistribution.pdf(x), c='orange')
plt.xlabel('age about Titanic')
plt.title('age on chi-square_Distribution', size=20)
plt.legend(['age', 'chi-square_Distribution'])

 

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章