使用d2l包:
import math
import numpy as np
from d2l import torch as d2l
import matplotlib.pyplot as plt
def normal(x, mu, sigma):
p = 1 / math.sqrt(2 * math.pi * sigma ** 2)
return p * np.exp(-0.5 / sigma ** 2 * (x - mu) ** 2)
# 创建一个 NumPy 数组 x,其中包含从 -7 到 7 的数值,步长为 0.01
x = np.arange(-7, 7, 0.01)
# 均值和标准差对
params = [(0, 1), (0, 2), (3, 1)]
# figsize设置图形的尺寸大小为宽度 4.5 英寸,高度 2.5 英寸
d2l.plot(x, [normal(x, mu, sigma) for mu, sigma in params], xlabel='x',
ylabel='p(x)', figsize=(4.5, 2.5),
legend=[f'mean {mu}, std {sigma}' for mu, sigma in params])
plt.show()
结果图:
不使用d2l包,