SciPy中的概率密度函数表现与预期不同

问题描述 投票:0回答:1

我试图用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')

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

enter image description here

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

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

python numpy scipy statistics normal-distribution
1个回答
2
投票

函数plot只是将点与线段连接起来。您的垃圾箱没有足够的点来显示平滑的曲线。可能的方法:

....
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)))
....
© www.soinside.com 2019 - 2024. All rights reserved.