一、數(shù)據(jù)的正態(tài)性檢驗(yàn)
數(shù)據(jù)源:http://jse.amstat.org/datasets/normtemp.dat.txt
驗(yàn)證體溫?cái)?shù)據(jù)是否符合正態(tài)分布。
- scipy.stats.kstest
實(shí)驗(yàn):
from scipy.stats import kstest
kstest(data['temperature'], 'norm', (data['temperature'].mean(), data['temperature'].std()))
返回值:
statistic = 0.065, pvalue = 0.645
value > 0.05, 認(rèn)為假設(shè)正確,體溫?cái)?shù)據(jù)滿足正態(tài)分布。
- 基礎(chǔ)信息統(tǒng)計(jì)分析
均值=98.25,眾數(shù)=98.0,中位數(shù)=98.3
偏態(tài)系數(shù)skew=-0.004
偏態(tài)系數(shù)約為0,基本符合正態(tài)分布。
- 數(shù)據(jù)分布形態(tài)

image
圖中藍(lán)色曲線為正態(tài)分布概率密度函數(shù)曲線,黃色柱狀圖為體溫?cái)?shù)據(jù)分布形態(tài)(體溫-概率)。
從圖中直觀感覺體溫?cái)?shù)據(jù)符合正態(tài)分布(數(shù)據(jù)量較少,部分區(qū)段有缺失)。
【代碼摘要】
import pandas as pd
import numpy as np
from scipy.stats import kstest
data = pd.read_csv('http://jse.amstat.org/datasets/normtemp.dat.txt', names = ['temperature', 'gender', 'heart_rate'], sep = '\s+')
# 1\. kstest
kstest(data['temperature'], 'norm', (data['temperature'].mean(), data['temperature'].std()))
# 2\. base analyze
data['temperature'].skew()
# 3\. plot
def norm_func(data):
mean = data.mean()
std = data.std()
pdf = np.exp(-((data - mean)**2)/(2*std**2)) / (std * np.sqrt(2*np.pi))
return pdf
data_normal = np.arange(data['temperature'].min(), data['temperature'].max()+ 0.01, 0.01)
p_normal = norm_func(data_normal)
plt.plot(data_normal, p_normal)
step = 0.01
bins_array = np.arange(data['temperature'].min(), data['temperature'].max() + step, step)
hist, bin_edges = np.histogram(data['temperature'], bins=bins_array)
hist = hist / sum(hist)
plt.bar(bins_array[:-1], hist, color = 'yellow', width = 0.1)
二、常見數(shù)據(jù)分布可視化
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from pylab import mpl
import numpy as np
from scipy import stats
mpl.rcParams['font.sans-serif'] = ['FangSong']
mpl.rcParams['axes.unicode_minus'] = False
# 伯努利分布
x = [0, 1]
p0 = 0.5
p = [p0, 1-p0]
plt.bar(x, p)
plt.xlabel('事件')
plt.ylabel('概率')
plt.title('伯努利分布概率分布')
# 二項(xiàng)分布
p = 0.5
n = 50
k = np.arange(0, n+1)
binomial = stats.binom.pmf(k, n, p)
plt.bar(k, binomial)
plt.xlabel('hit_times')
plt.ylabel('probability')
plt.title('二項(xiàng)分布概率分布')
# 泊松分布
lam = 5
x = np.random.poisson(lam = lam, size = 1000)
plt.hist(x, bins = 100)
# 均勻分布
def func_p_avg(x):
return 1 / (x.max() - x.min())
x = np.arange(1,10)
y = [func_p_avg(x)] * len(x)
plt.plot(x, y)
# 正態(tài)分布
mu = 0.0
sigma = 1.0
x = np.arange(-10, 10, 0.1)
y = stats.norm.pdf(x, mu, sigma)
plt.plot(x,y)
# beta分布
a = 0.5
b = 0.5
x = np.arange(0, 1, 0.01)
y = stats.beta.pdf(x, a, b)
plt.plot(x, y)