【问题标题】:Probability density function in SciPy behaves differently than expectedSciPy 中的概率密度函数的行为与预期不同
【发布时间】:2019-08-21 11:18:55
【问题描述】:

我正在尝试使用 Python 绘制正态分布曲线。首先我使用正态概率密度函数手动完成,然后我发现在 stats 模块下的 scipy 中有一个退出函数pdf。但是,我得到的结果却大不相同。

下面是我试过的例子:

import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats

mean = 5
std_dev = 2
num_dist = 50

# Draw random samples from a normal (Gaussion) distribution
normalDist_dataset = np.random.normal(mean, std_dev, num_dist)

# Sort these values.
normalDist_dataset = sorted(normalDist_dataset)

# Create the bins and histogram
plt.figure(figsize=(15,7))
count, bins, ignored = plt.hist(normalDist_dataset, num_dist, density=True)

new_mean = np.mean(normalDist_dataset)
new_std = np.std(normalDist_dataset)

normal_curve1 = stats.norm.pdf(normalDist_dataset, new_mean, new_std)
normal_curve2 = (1/(new_std *np.sqrt(2*np.pi))) * (np.exp(-(bins - new_mean)**2 / (2 * new_std**2)))

plt.plot(normalDist_dataset, normal_curve1, linewidth=4, linestyle='dashed')
plt.plot(bins, normal_curve2, linewidth=4, color='y')

结果显示我得到的两条曲线彼此非常不同。

我的猜测是它与 binspdf 的行为与通常的公式不同。我对这两个图都使用了相同的和新的均值和标准差。那么,如何更改我的代码以匹配 stats.norm.pdf 正在做的事情?

我还不知道哪条曲线是正确的。

【问题讨论】:

  • 尝试例如num_dist = 50000,并将plt.histbins参数从num_dist更改为bins=100

标签: python numpy scipy statistics normal-distribution


【解决方案1】:

函数plot 只是将点与线段连接起来。您的 bin 没有足够的点来显示平滑曲线。可能的解决方案:

....
normal_curve1 = stats.norm.pdf(normalDist_dataset, new_mean, new_std)
bins = normalDist_dataset # Add this line
normal_curve2 = (1/(new_std *np.sqrt(2*np.pi))) * (np.exp(-(bins - new_mean)**2 / (2 * new_std**2)))
....

【讨论】:

    猜你喜欢
    • 2015-07-31
    • 2022-11-26
    • 2015-06-18
    • 2023-03-04
    • 2012-11-21
    • 1970-01-01
    • 2018-01-28
    • 2020-08-07
    • 1970-01-01
    相关资源
    最近更新 更多