随机现象&随机变量
概率分布
import random
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def flip_coin(times):
# times表示抛硬币次数
data_array = np.empty(times)
weight_array = np.empty(times)
weight_array.fill(1 / times)
for i in range(0, times):
data_array[i] = random.randint(0, 1) # 假设0表示正面 1表示反面
data_frame = pd.DataFrame(data_array)
data_frame.plot(kind='hist', legend=False) # 获取正反面统计次数的直方图
data_frame.plot(kind='hist', legend=False, weights=weight_array).set_ylabel('Probability') # 获取正反面统计概率的直方图
plt.show()
if __name__ == '__main__':
flip_coin(10)
结果
离散分布模型
伯努利分布
$P(x=0)=1-λ$
$P(x=1)=λ$
或者写作:
$P(x)=λ^x(1-λ)^(1-x) $
其中x只能为0或1。
from scipy.stats import binom # 导入伯努利分布
import matplotlib.pyplot as plt
import numpy as np
def bernoulli():
# 次数
n = 10
# 概率
p = 0.3
# 导入特征系数
k = np.arange(0, 21)
# 伯努利分布的特征值导入
binomial = binom.pmf(k, n, p)
plt.plot(k, binomial, 'o-')
plt.title('Binomial: n = %i, p=%0.2f' % (n, p), fontsize=15)
plt.xlabel('Number of successes')
plt.ylabel('Probability of sucesses', fontsize=15)
plt.show()
if __name__ == '__main__':
bernoulli()
结果
- 分类分布
- 二项分布
- 泊松分布
连续分布模型
正态分布/高斯分布
$公式占位符$
μ表示均值,σ表示方差。
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
def demo1():
mu, sigma = 0, 1
sampleNo = 1000
np.random.seed(0)
s = np.random.normal(mu, sigma, sampleNo)
plt.hist(s, bins=100, density=True)
plt.show()
def demo2():
mu, sigma, num_bins = 0, 1, 50
x = mu + sigma * np.random.randn(1000000)
# 正态分布的数据
n, bins, patches = plt.hist(x, num_bins, density=True, facecolor='blue', alpha=0.5)
# 拟合曲线
y = norm.pdf(bins, mu, sigma)
plt.plot(bins, y, 'r--')
plt.xlabel('Expectation')
plt.ylabel('Probability')
plt.title('histogram of normal distribution: $\mu = 0$, $\sigma=1$')
plt.subplots_adjust(left=0.15)
plt.show()
if __name__ == '__main__':
demo2()
demo1结果
demo2结果
- 均匀分布
- 指数分布
- 拉普拉斯分布