假设检验实例(python)

         用ctrl+F键搜索normtemp下载txt文件

         包括130条记录,我们主要利用体温和性别来进行实验

import pandas as pd
import pylab
import math
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from scipy.stats import norm
import scipy.stats
import warnings
warnings.filterwarnings("ignore")


df = pd.read_csv('normtemp.txt',sep='   ',names = ['Temperature','Gender','Heart Rate'])
df.describe()

                    

 体温的分布是正态的吗?

observed_temperatures = df['Temperature'].sort_values()#将参数导入
#按从小到大的顺序进行
bin_val = np.arange(start= observed_temperatures.min(), stop= observed_temperatures.max(), step = .05)
mu, std = np.mean(observed_temperatures), np.std(observed_temperatures)#均值和方差


p = norm.pdf(observed_temperatures, mu, std)#画出pdf


plt.hist(observed_temperatures,bins = bin_val, density=True, stacked=True)#直方图
plt.plot(observed_temperatures, p, color = 'red')
plt.xticks(np.arange(95.75,101.25,0.25),rotation=90)
plt.xlabel('Human Body Temperature Distributions')
plt.xlabel('human body temperature')
plt.show()


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

                       

Average (Mu): 98.24923076923076 / Standard Deviation: 0.7303577789050376

 从图中可以看出该分布符合正态分布的样子。

再次进行检验:

x = observed_temperatures

#Shapiro-Wilk Test: https://en.wikipedia.org/wiki/Shapiro%E2%80%93Wilk_test
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('p:',p)


#Another method to determining normality is through Quantile-Quantile Plots.
scipy.stats.probplot(observed_temperatures, dist="norm", plot=pylab)
pylab.show()

 算出p值为0.2587479863488212

Shapiro-Wilk Stat: 0.9865769743919373  Shapiro-Wilk p-Value: 0.2331680953502655
p: 0.2587479863488212

                              

 画出ECDF:

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, 'with standard deviation of +/-', std)

#Random sampling of the data based off of the mean of the data.
normalized_sample = np.random.normal(mu, std, size=10000)
x_temperature, y_temperature = ecdf(df['Temperature'])
normalized_x, normalized_y = ecdf(normalized_sample)

# Plot the ECDFs
fig = plt.figure(figsize=(8, 5))
plt.plot(normalized_x, normalized_y)
plt.plot(x_temperature, y_temperature, marker='.', linestyle='none')
plt.ylabel('ECDF')
plt.xlabel('Temperature')
plt.legend(('Normal Distribution', 'Sample data'))

               

Mean temperature:  98.24923076923076 with standard deviation of +/- 0.730357778905038

可以看出上下波动的值很低。

有学者提出98.6是人类的平均体温,我们该这样认为吗?

在这里我们选择t检验,因为我们只能计算样本的标准差。

from scipy import stats

CW_mu = 98.6
stats.ttest_1samp(df['Temperature'], CW_mu, axis=0)
Ttest_1sampResult(statistic=-5.4548232923640771, pvalue=2.4106320415610081e-07)

T-Stat -5.454 p-value近乎0了. 我们该拒绝这样的假设

 男性和女性的体温有明显差异吗?

两独立样本t检验 H0: 没有明显差异 H1: 有明显差异

female_temp = df.Temperature[df.Gender == 2]
male_temp = df.Temperature[df.Gender == 1]
mean_female_temp = np.mean(female_temp)
mean_male_temp = np.mean(male_temp)
print('Average female body temperature = ' + str(mean_female_temp))
print('Average male body temperature = ' + str(mean_male_temp))

# Compute independent t-test 
stats.ttest_ind(female_temp, male_temp, axis=0)
Average female body temperature = 98.39384615384616
Average male body temperature = 98.1046153846154
Ttest_indResult(statistic=2.2854345381654984, pvalue=0.02393188312240236)

由于P值=0.024 < 0.05,我们需要拒绝原假设,我们有%95的自信认为是有差异的!

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
正太分布检验是用来检验一个样本是否服从正态分布的统计方法,一般用于连续型的数据。Python中可以使用scipy库中的stats模块来进行正太分布检验。下面以一个实例来说明如何用Python进行正太分布检验。 假设我们有一个数据集,包含100个身高数据。我们想要检验这个数据集是否服从正态分布。首先,我们需要导入必要的库: ```python import numpy as np from scipy import stats ``` 然后,我们生成一个样本数据集: ```python # 生成100个正态分布的随机数 np.random.seed(0) samples = np.random.normal(loc=170, scale=5, size=100) ``` 假设我们希望检验的显著水平为0.05,可以使用scipy库中的正态分布检验函数进行检验: ```python # 进行正太分布检验 p_value = stats.normaltest(samples)[1] ``` 检验结果的p值可以用来判断样本是否服从正态分布。通常情况下,如果p值小于显著水平(如0.05),则可以拒绝原假设,即认为样本不服从正态分布。如果p值大于显著水平,则不拒绝原假设,即认为样本服从正态分布。 ```python # 判断样本是否服从正态分布 if p_value < 0.05: print("样本不服从正态分布") else: print("样本服从正态分布") ``` 这就是用Python进行正太分布检验的一个实例。通过导入必要的库,生成样本数据,使用scipy库中的正态分布检验函数进行检验,可以判断样本是否服从正态分布。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长沙有肥鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值