python編程判斷閏年,python實踐作業_實踐-python實現假設檢驗

 2023-09-30 阅读 31 评论 0

摘要:作業鏈接:https://mp.weixin.qq.com/s/Jj6b_F25TsbziYxedr-jHgpython編程判斷閏年。知識點:假設檢驗本周是統計學學習小組-第二期的第十一周,我們這周的學習內容是假設檢驗實踐,主要是使用python對我們上周學習的內容進行實踐~ 本周需要解決的幾個

作業鏈接:

https://mp.weixin.qq.com/s/Jj6b_F25TsbziYxedr-jHg

python編程判斷閏年。知識點:假設檢驗

本周是統計學學習小組-第二期的第十一周,我們這周的學習內容是假設檢驗實踐,主要是使用python對我們上周學習的內容進行實踐~ 本周需要解決的幾個小問題:

1、人體體溫的總體均值是否為98.6華氏度?

python作業編程。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("http://ww2.amstat.org/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("人體的溫度與心率具有相關性:極弱")

其它打印結果:

參考來源:

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/107107.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息