如何在 python keras 中计算张量上浮点数的熵

how to calculate entropy on float numbers over a tensor in python keras

我一直在努力解决这个问题,但无法让它发挥作用。希望有人能帮我解决这个问题。

我想计算 tensor 每一行的 entropy因为我的数据是浮点数而不是整数我想我需要使用 bin_histogram.

例如我的数据样本是tensor =[[0.2, -0.1, 1],[2.09,-1.4,0.9]]

仅供参考 我的模型是 seq2seq 并用 keras 编写,后端为 tensorflow。

到目前为止,这是我的代码:我需要更正 rev_entropy

class entropy_measure(Layer):

    def __init__(self, beta,batch, **kwargs):
        self.beta = beta
        self.batch = batch
        self.uses_learning_phase = True
        self.supports_masking = True
        super(entropy_measure, self).__init__(**kwargs)

    def call(self, x):
        return K.in_train_phase(self.rev_entropy(x, self.beta,self.batch), x)

    def get_config(self):
        config = {'beta': self.beta}
        base_config = super(entropy_measure, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))

    def rev_entropy(self, x, beta,batch):

        for i in x:
            i = pd.Series(i)
            p_data = i.value_counts()  # counts occurrence of each value
            entropy = entropy(p_data)  # get entropy from counts
            rev = 1/(1+entropy)
            return rev

        new_f_w_t = x * (rev.reshape(rev.shape[0], 1))*beta

        return new_f_w_t

非常感谢任何意见:)

看起来你有一系列关于这个问题的问题。我这就解决。

你根据你的代码计算出entropy的形式scipy.stats.entropy

scipy.stats.entropy(pk, qk=None, base=None)

Calculate the entropy of a distribution for given probability values.

If only probabilities pk are given, the entropy is calculated as S = -sum(pk * log(pk), axis=0).

Tensorflow 不提供直接 API 来计算张量每一行的 entropy。我们要做的就是实现上面的公式。

import tensorflow as tf
import pandas as pd
from scipy.stats import entropy

a = [1.1,2.2,3.3,4.4,2.2,3.3]
res = entropy(pd.value_counts(a))

_, _, count = tf.unique_with_counts(tf.constant(a))
# [1 2 2 1]
prob = count / tf.reduce_sum(count)
# [0.16666667 0.33333333 0.33333333 0.16666667]
tf_res = -tf.reduce_sum(prob * tf.log(prob))

with tf.Session() as sess:
    print('scipy version: \n',res)
    print('tensorflow version: \n',sess.run(tf_res))

scipy version: 
 1.329661348854758
tensorflow version: 
 1.3296613488547582

然后我们需要根据上面的代码在你的自定义图层中定义一个函数并实现for looptf.map_fn

def rev_entropy(self, x, beta,batch):
    def row_entropy(row):
        _, _, count = tf.unique_with_counts(row)
        prob = count / tf.reduce_sum(count)
        return -tf.reduce_sum(prob * tf.log(prob))

    value_ranges = [-10.0, 100.0]
    nbins = 50
    new_f_w_t = tf.histogram_fixed_width_bins(x, value_ranges, nbins)
    rev = tf.map_fn(row_entropy, new_f_w_t,dtype=tf.float32)

    new_f_w_t = x * 1/(1+rev)*beta

    return new_f_w_t

注意隐藏层不会产生无法向后传播的梯度,因为entropy是根据统计概率值计算的。也许你需要重新考虑你的隐藏层结构。