Pytorch深度学习---(1)计算正态分布

使用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包,用plt的plot函数画图

import math
import numpy as np
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)]
# 绘制曲线
plt.figure(figsize=(4.5, 2.5))  # 设置图形尺寸
for mu, sigma in params:
    y = normal(x, mu, sigma)
    plt.plot(x, y, label=f'mean {mu}, std {sigma}')

# 添加标签和标题
plt.xlabel('x')
plt.ylabel('p(x)')
plt.title('Normal Distribution')
# 添加网格
plt.grid(True)
# 添加图例,plt.legend() 函数用于在 matplotlib 绘图中添加图例,用于标识不同数据系列或不同曲线的含义。
plt.legend()
plt.show()

结果图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值