在 Python 中绘制概率密度函数

问题描述

我想根据数据框中某个列的值绘制两个概率密度函数 (pdf)。第一个是对应于 target label = 0 行的所有值,第二个是 target label = 1

我的尝试如下,但正如您所看到的,曲线看起来不像 pdf(最大值为 0,并且它们不限于 0-1 和 5-6 范围内的 X 轴。我想我可以得到通过玩 bw 因子来接近一些东西,但我正在寻找一个单线,它只是计算出正确的参数并绘制一个 pdf(包括找出正确的 X 轴开始/结束使用)。有没有内置的执行此操作的函数。如果没有,请提供有关如何构建此类内容的一些指示。

#matplotloib inline
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.neighbors import KernelDensity

values = np.random.rand(10)
values_shift5 = np.random.rand(10) + 5
df = pd.DataFrame({'values' : values,'label' : np.zeros(10)})
df = pd.concat([df,pd.DataFrame({'values' : values_shift5,'label' : np.ones(10)})])

kde_label_0 = KernelDensity(kernel='gaussian',bandwidth=0.5).fit(df[df.label == 0]['values'].values.reshape(-1,1))
kde_label_1 = KernelDensity(kernel='gaussian',bandwidth=0.5).fit(df[df.label == 1]['values'].values.reshape(-1,1))
X_plot = np.linspace(0,10,50).reshape(-1,1)
log_density_0 = kde_label_0.score_samples(X_plot)
log_density_1 = kde_label_1.score_samples(X_plot)
plt.plot(X_plot,log_density_0,label='Label 0')
plt.plot(X_plot,log_density_1,label='Label 1')
plt.legend()
plt.show()

Plot of what I get

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)