numpy - 如何在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
非常感谢任何输入:)
解决方案
看起来你有一系列关于这个问题的问题。我会在这里解决。
您根据您的代码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
它是根据统计概率值计算的。也许你需要重新考虑你的隐藏层结构。
推荐阅读
- reactjs - 当服务器位于“/path”下时,无法让 React Router 与 Webpack 和 historyApiFallback 一起使用
- amazon-web-services - 使用 Cognito 令牌访问 S3 时获取“AccessDenied”
- android - 是否可以将两个(正在积极开发的)Android 应用程序模块合并到同一个 Android Studio 项目中?
- javascript - 在透明视图上创建阴影 - 反应原生
- android - 如何在 Android Studio 中删除多余的演员表?
- javascript - 用户定义的异常在 JavaScript Promise 中不起作用
- ecmascript-6 - 为什么 promise.resolve 在异步函数中失去价值?
- python - 为什么 asyncio 不总是使用执行器?
- javascript - 从 settimeout 中调用的函数返回承诺
- reactjs - Redux-form 和 react-datepicker - 如何区分输入和实际值格式中的呈现值格式?