本次选取泰坦尼克号的数据,利用python进行抽样分布描述,主要是提供实现代码,具体的理论知识不会过多涉及。(注:是否服从T分布不是进行t检验~)
字段说明:
Age:年龄,指登船者的年龄。
Fare:价格,指船票价格。
Embark:登船的港口。
需要验证的是:
1、验证数据是否服从正态分布?
2、验证数据是否服从T分布?
3、验证数据是否服从卡方分布?
我们选取年龄作为栗子进行数据验证。
import pandas as pdimport numpy as nppath = 'D:\\数据\\data\\data.xlsx'data = pd.read_excel(path)# 按照港口分类,计算数据的统计量embark = data.groupby(['Embarked'])embark_basic = data.groupby(['Embarked']).agg(['count','min','max','median','mean','var','std'])age_basic = embark_basic['Age']fare_basic = embark_basic['Fare']age_basicfare_basic
1、 先验证价格年龄是否服从正态分布。
画出年龄的图像
import seaborn as snssns.set_palette("hls") #设置所有图的颜色,使用hls色彩空间sns.distplot(data['Age'],color="r",bins=10,kde=True)plt.title('Age')plt.xlim(-10,80)plt.grid(True)plt.show()
2、验证是否服从正态分布?
#分别用kstest、shapiro、normaltest来验证分布系数from scipy import statsks_test = stats.kstest(data['Age'], 'norm')shapiro_test = stats.shapiro(data['Age']normaltest_test = stats.normaltest(data['Age'],axis=0)print('ks_test:',ks_test)print('shapiro_test:',shapiro_test)print('normaltest_test:',normaltest_test)
由检验结果知,p <0.05,所以拒绝原假设,认为数据不服从正态分布
# 由于p <0.05, 拒绝原假设,认为数据不服从正态分布# 绘制拟合正态分布曲线age = data['Age']plt.figure()age.plot(kind = 'kde') #原始数据的正态分布M_S = stats.norm.fit(age) #正态分布拟合的平均值loc,标准差 scalenormalDistribution = 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'])
3、 验证是否服从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)
由检验结果知,p <0.05,所以拒绝原假设,认为数据不服从T分布
绘制拟合的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'])
3、验证数据是否服从卡方分布
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'])
