import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import uniform
%matplotlib inline
# 生成样本
fig, ax = plt.subplots(1,1)
r = uniform.rvs(loc=0, scale=1, size=1000)
ax.hist(r, density=True, histtype='stepfilled', alpha=0.5)
# 均匀分布 pdf
x = np.linspace(uniform.pdf(0.01), uniform.pdf(0.99), 100)
ax.plot(x, uniform.pdf(x), 'r-', lw=5, alpha=0.8, label='uniform pdf')
x = np.array([1,2,3,4,5,6,7,8,9])
y = np.array([9,8,7,6,5,4,3,2,1])
Mean = np.mean(x)
Var = np.var(x) # 默认总体方差
Var_unbias = np.var(x, ddof=1) # 样本方差(无偏方差)
Cov = np.cov(x, y)
Mean, Var, Var_unbias, Cov
'''
(5.0,
6.666666666666667,
7.5,
array([[ 7.5, -7.5],
[-7.5, 7.5]]))
'''
def plot_distribution(X, axes=None):
""" 给定随机变量,回绘制 PDF,PMF,CDF """
if axes is None:
fig, axes = plt.subplots(1, 2, figsize=(10,3))
x_min, x_max = X.interval(0.99)
x = np.linspace(x_min, x_max, 1000)
if hasattr(X.dist, 'pdf'): # 判断有没有 pdf,即是不是连续分布
axes[0].plot(x, X.pdf(x), label="PDF")
axes[0].fill_between(x, X.pdf(x), alpha=0.5) # alpha 是透明度, alpha=0 表示 100% 透明, alpha=100 表示完全不透明
else: # 离散分布
x_int = np.unique(x.astype(int))
axes[0].bar(x_int, X.pmf(x_int), label="PMF") # pmf 和 pdf 是类似的
axes[1].plot(x, X.cdf(x), label="CDF")
for ax in axes:
ax.legend()
return axes
from scipy.stats import bernoulli
fig, axes = plt.subplots(1, 2, figsize=(10,3)) # 画布
p = 0.3
X = bernoulli(p) # 伯努利分布
plot_distribution(X, axes=axes)
# 产生成功的概率
possibility = 0.3
def trials(n_samples):
samples = np.random.binomial(n_samples, possibility) # 成功的次数
proba_zero = (n_samples - samples) / n_samples
proba_one = samples / n_samples
return [proba_zero, proba_one]
fig, axes = plt.subplots(1, 2, figsize=(10,3))
# 一次试验,伯努利分布
n_samples = 1
axes[0].bar([0,1], trials(n_samples), label="Bernoulli")
# n 次试验,二项分布
n_samples = 1000
axes[1].bar([0,1], trials(n_samples), label="Binomial")
for ax in axes:
ax.legend()
def k_possibilities(k):
""" 随机产生一组 10 维概率向量 """
res = np.random.rand(k)
_sum = sum(res)
for i,x in enumerate(res):
res[i] = x / _sum
return res
fig, axes = plt.subplots(1, 2, figsize=(10,3))
# 一次试验,范畴分布
k, n_samples = 10, 1
samples = np.random.multinomial(n_samples, k_possibilities(k)) # 各维度“成功”的次数
axes[0].bar(range(len(samples)), samples/n_samples, label="Multinoulli")
# n 次试验,多项分布
n_samples = 1000
samples = np.random.multinomial(n_samples, k_possibilities(k))
axes[1].bar(range(len(samples)), samples/n_samples, label="Multinomial")
for ax in axes:
ax.legend()
from scipy.stats import norm
fig, axes = plt.subplots(1, 2, figsize=(10,3)) # 画布
mu, sigma = 0, 1
X = norm(mu, sigma) # 标准正态分布
plot_distribution(X, axes=axes)
from scipy.stats import multivariate_normal
import matplotlib.pyplot as plt
x, y = np.mgrid[-1:1:.01, -1:1:.01]
pos = np.dstack((x, y))
fig = plt.figure(figsize=(4,4))
axes = fig.add_subplot(111)
mu = [0.5, -0.2] # 均值
sigma = [[2.0, 0.3], [0.3, 0.5]] # 协方差矩阵
X = multivariate_normal(mu, sigma)
axes.contourf(x, y, X.pdf(pos))
from scipy.stats import expon
fig, axes = plt.subplots(1, 2, figsize=(10,3))
# 定义 scale = 1 / lambda
X = expon(scale=1)
plot_distribution(X, axes=axes)
from scipy.stats import laplace
fig, axes = plt.subplots(1, 2, figsize=(10,3))
mu, gamma = 0, 1
X = laplace(loc=mu, scale=gamma)
plot_distribution(X, axes=axes)