一、导入 import
import numpy as np
import matplotlib.pyplot as plt
二、均匀分布与高斯分布函数
- 均匀分布:
def uniform():
return np.random.rand() #生成[0, 1)的数据
- 高斯分布:
def gaussian(mean, sigma):
return sigma*np.random.randn() + mean #randn生成均值为0,标准差为1的标准正态分布,sigma用于扩大数据,mean用来控制正态分布的对称轴
三、可视化
def plot(val_list):
min_val = min(val_list)
max_val = max(val_list)
val = max(abs(min_val), abs(max_val))
max_val = val
min_val = 0 if abs(min_val) < 1e-5 else -val if min_val < 0 else min_val
plt.hist(val_list, density=True, bins=100, range=[min_val, max_val]) #绘制直方图
plt.ylim([0., 2.05])
plt.gca().set(title='PDF', xlabel='Values')
四、试验
vals = [uniform() for _ in range(100000)]
plot(vals)
vals = [gaussian(0, 1) for _ in range(100000)]
plot(vals)
vals = [gaussian(-1, 1) for _ in range(100000)]
plot(vals)
vals = [gaussian(5, 3) for _ in range(100000)]
plot(vals)
vals = [gaussian(5, 0.2) for _ in range(100000)]
plot(vals)
sad = ':('
happy = ':)'
sad if uniform() < 0.3 else happy
‘😦’ 哈哈