首页 > 解决方案 > 如何在python keras中计算张量上浮点数的熵

问题描述

我一直在为此苦苦挣扎,无法让它发挥作用。希望有人可以帮助我。

我想entropy计算tensor. 因为我的数据是浮点数而不是整数,所以我认为我需要使用 bin_histogram。

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

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

到目前为止,这是我的代码:我需要更正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

非常感谢任何输入:)

标签: numpytensorflowkerasscipyentropy

解决方案


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

您根据您的代码entropy以下列形式计算:scipy.stats.entropy

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

计算给定概率值的分布熵。

如果仅给出概率 pk,则熵计算为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 loop定义一个函数并实现。tf.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它是根据统计概率值计算的。也许你需要重新考虑你的隐藏层结构。


推荐阅读