抽样分布实践(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'])
发布了42 篇原创文章 · 获赞 6 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/zkyxgs518/article/details/103646557