python - 在使用特定 P(x) 作为参考分布的 python 计算 KL 散度时,如何定义输入值 p 和 q?
问题描述
我想实现 KL 散度,我想使用 P(x) 作为参考分布,我想用它来比较我的模型的分布。如何从参考分布 P(x) 中获取直方图?
def P(x):
return ((32/(math.pi)**2)*(x)**2*np.exp(-(4/math.pi)*(x)**2))
x = np.array([0,0,0,0,0,3,3,2,2,2,1,1,1,1,])
fig = plt.figure()
ax = fig.add_subplot(111)
n,bins,patches = ax.hist(x,bins=10,density=True)
为了计算 KL 散度,我定义了函数
def KL(p,q):
KL_list =[]
for i in range(p):
val= p*np.log(q /p)
KL_list.append(val)
KL_list=-1*np.sum(np.array(KL_list))
return KL_list
现在为了调用函数 KL(p,q) 我必须定义 p 和 q 那么在我的情况下 p 和 q 的值是多少?
解决方案
正如我在这里已经回答的那样,以下是我的互信息计算解决方案(基本上是 KL):
def mutual_information(x, y, sigma=1):
bins = (256, 256)
# histogram
hist_xy = np.histogram2d(x, y, bins=bins)[0]
# smooth it out for better results
ndimage.gaussian_filter(hist_xy, sigma=sigma, mode='constant', output=hist_xy)
# compute marginals
hist_xy = hist_xy + EPS # prevent division with 0
hist_xy = hist_xy / np.sum(hist_xy)
hist_x = np.sum(hist_xy, axis=0)
hist_y = np.sum(hist_xy, axis=1)
# compute mi
mi = (np.sum(hist_xy * np.log(hist_xy)) - np.sum(hist_x * np.log(hist_x)) - np.sum(hist_y * np.log(hist_y)))
return mi
推荐阅读
- javascript - 如何在文本框中添加计算进度条?
- android - React Native:运行android应用程序时出错
- android - 我想知道如何正确使用连接Expandable List View的适配器和同时连接gridView的适配器
- node.js - 如何使用 Azure AD 保护 node.js Web api 并使用 React.js 前端使用它
- java - Android 视频播放器 mkv 视频支持
- php - PHP - 在 1 次操作中将文本连接到 2 个变量
- reactjs - React js构建更改css文件中的路径
- laravel - 存储为 id 时搜索列名
- events - 通过生产者创建 bean 后触发 CDI 事件
- python - 用于以 3D 张量时间序列作为输入的二进制分类的 Keras 神经网络模型