numpy - 在 TensorFlow Graph 中使用 scipy.stats.entropy
问题描述
我的目标是在下面的代码片段中计算两个概率密度函数之间的距离,称为 p_distb 和 q_distb。我尝试通过利用 Jensen-Shannon-divergence 来实现这一点,因为它是对称且有界的,必要的熵函数是从scipy.stats导入的。
当我尝试运行图表时,出现以下错误:
if len(qk) != len(pk): TypeError: len() of unsized object
显然, scipy.stats.entropy 无法处理tensorflow 张量,即使这些张量是向下兼容的并且应该像 numpy 数组一样工作。
有没有人有这个问题的解决方案?
非常感谢!!
from scipy.stats import entropy
import tensorflow as tf
import numpy as np
graph = tf.Graph()
with graph.as_default():
i_dim = 8
j_dim = 8
input_dim = 201
weights = tf.Variable(tf.random_normal(shape=[i_dim*j_dim, input_dim]))
input_vector = tf.Variable(tf.random_normal(shape=[input_dim,1]))
min_codebook_dist = []
for index in range(i_dim*j_dim):
p_distb = tf.div(weights[index,:],tf.reduce_sum(weights[index,:]))
p_distb = tf.reshape(p_distb, shape=[input_dim,])
q_distb = tf.div(input_vector,tf.reduce_sum(input_vector))
q_distb = tf.reshape(input_vector, shape=[input_dim,])
m_distb = tf.div(tf.add(p_distb,q_distb),2)
dist_pq = np.sqrt((entropy(p_distb[:], m_distb[:]) + entropy(q_distb[:], m_distb[:])) / 2)
min_codebook_dist.append(dist_pq)
sess = tf.InteractiveSession()
init_op = tf.initialize_all_variables()
sess.run(init_op)
解决方案
TensorFlow 张量不向下兼容 numpy 数组。您可以尝试将对 scipy 的调用包装在 tf.py_func 中以调用 scipy。
推荐阅读
- javascript - 我们如何在 React JS 中将多个 JSON 文件的值呈现为表格格式?
- javascript - 从 Twitter API V1.1 切换到 Twitter API V2 以将推文从个人资料发送到 Google 表格
- c# - C# 引用列表中的特定项目
- python - 并排直方图:更改轴
- selenium - 是否可以使用 appium 扫描二维码?
- reactjs - NextJS + SSR + IIS 部署
- sql - 如何删除或重命名数据库?
- design-patterns - 应该如何为两个以上的层次结构实现“桥”设计模式?
- angular - 在数组中取一个随机数,每次浏览器重新加载它都会改变
- laravel-8 - 注销并再次登录后出现 419 错误