首页 > 解决方案 > 在 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)

标签: numpytensorflowscipytensorentropy

解决方案


TensorFlow 张量不向下兼容 numpy 数组。您可以尝试将对 scipy 的调用包装在 tf.py_func 中以调用 scipy。


推荐阅读