失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python实践作业_实践-python实现假设检验

python实践作业_实践-python实现假设检验

时间:2022-07-16 06:34:14

相关推荐

python实践作业_实践-python实现假设检验

作业链接:

https://mp./s/Jj6b_F25TsbziYxedr-jHg

知识点:假设检验

本周是统计学学习小组-第二期的第十一周,我们这周的学习内容是假设检验实践,主要是使用python对我们上周学习的内容进行实践~ 本周需要解决的几个小问题:

1、人体体温的总体均值是否为98.6华氏度?

2、人体的温度是否服从正态分布?

3、人体体温中存在的异常数据是哪些?

4、男女体温是否存在明显差异?

5、体温与心率间的相关性(强?弱?中等?)

引申出来的点:你要怎么向运营或者产品的同事展示数据结果?

具体过程及实现参照如下:

导入所需的包

import pandasas pd

import pylab

import math

import numpyas np

import matplotlib.pyplotas plt

#%matplotlib inline

from scipy.statsimport norm

import scipy.stats

import warnings

warnings.filterwarnings("ignore")

#df = pd.read_csv("/publications/jse/datasets/normtemp.dat.txt", sep=" ",names=['Temperature', 'Gender', 'Heart Rate'])

df = pd.read_csv('D:/Users/Downloads/test.csv', sep=",", names=['Temperature', 'Gender', 'Heart Rate'])

df.head()

df.describe()

# 1.验证98.6为平均温度

from scipyimport stats

CW_mu =98.6

stats.ttest_1samp(df['Temperature'], CW_mu, axis=0)

# T-Stat -5.454 p-value 近乎0,拒绝原假设

#Ttest_1sampResult(statistic=-5.454823292364077, pvalue=2.410632041561008e-07)

# 2.人体的温度是否服从正态分布?

#采用shapiro_wiki进行判断,由返回的p_value进行判断,若p_value>0.05,则可认为该数据集近似于正态分布

#1.计算均值和标注差 前提检验正态分布 图示如下

observed_temperatures = df['Temperature'].sort_values()

bin_val = np.arange(start=observed_temperatures.min(), stop=observed_temperatures.max(), step=50)

mu, std = np.mean(observed_temperatures), np.std(observed_temperatures)

p = norm.pdf(observed_temperatures, mu, std)

plt.hist(observed_temperatures, bins=bin_val, normed=True, stacked=True)

plt.plot(observed_temperatures, p, color='r')

plt.xticks(np.arange(95.75, 101.25, 0.25), rotation=90)

plt.xlabel('Human Body Temperature Distributions')

plt.ylabel('human body temperature')

plt.show()

print("Average (Mu):" +str(mu) +"/ Standard Deviation:" +str(std))

#Average(Mu): 98.24923076923076 / StandardDeviation: 0.7303577789050376

# 2.1.确定指标进行正态检验

x = observed_temperatures

shapiro_test, shapiro_p = scipy.stats.shapiro(x)

print("Shapiro-Wilk Stat:", shapiro_test, "Shapiro-Wilk p-Value:", shapiro_p)

k2, p = scipy.stats.normaltest(observed_temperatures)

print("k2:", k2, "p:", p)

# 以上两种方法,p值大于0.05,认为正态分布

# Another method to determining normality is through Quantile-Quantile Plots

# 3.2 QQ图检查正态分布

scipy.stats.probplot(observed_temperatures, dist='norm', plot=pylab)

pylab.show()

#Shapiro - WilkStat: 0.9865769743919373 Shapiro - Wilkp - Value: 0.2331680953502655

#k2: 2.703801433319236 p: 0.2587479863488212

# 另一种检测正态分布的方法

def ecdf(data):

# Compute ECDF

n =len(data)

x = np.sort(data)

y = np.arange(1, n +1) / n

return x, y

# Compute empirical mean and standard deviation

# Number of samples

n =len(df['Temperature'])

# Sample mean

mu = np.mean(df['Temperature'])

# Sample standard deviation

std = np.std(df['Temperature'])

print("Mean Temperature:", mu, "Standard deviation:", std)

# 基于当前的均值和标准差,随机生成一个正态分布

normalized_sample = np.random.normal(mu, std, size=10000)

normalized_x, normalized_y = ecdf(normalized_sample)

x_temperature, y_temperature = ecdf(df['Temperature'])

# Plot the ECDFs

fig = plt.figure(figsize=(8, 6))

plt.plot(normalized_x, normalized_y)

plt.plot(x_temperature, y_temperature, marker='.', linestyle='none')

plt.xlabel('ECDF')

plt.ylabel("Temperature")

plt.legend(("Normal Distribution", "Sample data"))

pylab.show()

#Mean Temperature: 98.24923076923076 Standard deviation: 0.730357778905038

#3.人体体温中存在的异常数据是哪些?

percentile = np.percentile(df["Temperature"], [0, 25, 50, 75, 100])# 利用箱型图的四分位距来对数据进行异常的判断

IQR = percentile[3] - percentile[1]

up_limit = percentile[3] + IQR *1.5 # 上限设定为上四分位+1.5倍IQR(四分位距)距离

down_limit = percentile[1] - IQR *1.5

abnormal = df[(df["Temperature"] > up_limit) | (df["Temperature"] < down_limit)]

print("依据箱型图测试异常数据为\n", abnormal)

#4. 检验男女体温是否明显区别

# 两独立样本t检验

# H0:两样本没有明显差异,H1:有明显差异

female_temperature = df.Temperature[df.Gender ==2]

male_temperature = df.Temperature[df.Gender ==1]

mean_female_temperature = female_temperature.mean()

mean_male_temperature = male_temperature.mean()

print("男体温均值:", mean_male_temperature, "女体温均值:", mean_female_temperature)

# 两独立样本t检验

t_stats, t_p_value = stats.ttest_ind(female_temperature, male_temperature, axis=0)

print (t_p_value)

if t_p_value<=0.05:

print("异性之间在正常温度下存在明显差异")

else:

print("异性之间在正常温度不存在明显差异")

# 由于p值0.024 < 0.05 ,拒绝原假设,我们有95%的自信度认为是有差异的

#男体温均值:98.1046153846154 女体温均值: 98.39384615384616

#Ttest_indResult(statistic=2.2854345381654984, pvalue=0.02393188312240236)

#5.体温与心率间的相关性(强?弱?中等?)

sorted_df = df[(df["Temperature"] <= up_limit) & (df["Temperature"] >= down_limit)]# 剔除上回所显示的异常数据

pearson = sorted_df.corr()# 获取各个数据之间的相关性表

temp_and_rate = pearson["Temperature"]["Heart Rate"]# 取人体温度与心率的系数结果

if 0.8 < temp_and_rate <=1.0:# python中不存在switch-case语句

print("人体的温度与心率具有相关性:极强")

elif 0.6 < temp_and_rate <=0.8:

print("人体的温度与心率具有相关性:强")

elif 0.4 < temp_and_rate <=0.6:

print("人体的温度与心率具有相关性:中等")

elif 0.2 < temp_and_rate <=0.4:

print("人体的温度与心率具有相关性:弱")

elif 0 <= temp_and_rate <=0.2:

print("人体的温度与心率具有相关性:极弱")

其它打印结果:

参考来源:

如果觉得《python实践作业_实践-python实现假设检验》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。