我试图充分理解TensorFlow中交叉熵的计算。在下面的代码中,numpy I生成双精度随机双数据x
,将其转换为logits
进行二进制分类(即每个数据点只有一个logit ),在sig
中通过sigmoid映射它,计算交叉熵ce
,然后计算平均交叉熵mce
。下面是TensorFlow中的类似计算。我的问题是:
为什么我的平均交叉熵mce
tf.losses.sigmoid_cross_entropy
**?** (在numpy中用双精度计算)与TensorFlow 之间存在差异?
我不知道,在哪里我忘了为TensorFlow指定双精度计算。此外,如果我使用tf.nn.reduce_mean
,看看mcetf2
的计算,在计算出的每个数据点的交叉熵上,我得到了我的numpy结果。这种差异从何而来?谢谢!
import numpy as np
import tensorflow as tf
#%%
# Number of data pionts nx and dimension dx
nx = 10
dx = 4
# Input data
x = np.random.rand(nx,dx)
#%% Numpy
# Transform to logits for binary classification with sigmoid
matrix = np.random.rand(dx,1)
logits = np.matmul(x,matrix)
print('Logits dimensions: %s' % str(logits.shape))
# Sigmoid
def sigmoid(x):
return 1. / (1. + np.exp(-x))
sig = sigmoid(logits)
print('Sigmoid dimensions: %s' % str(sig.shape))
# Discrete probabilities
p = np.random.randint(2,size=nx)[:,np.newaxis]
print('Probability dimensions: %s'% str(p.shape))
# Cross entropy for each data point
ce = p*np.log(1/sig)+(1-p)*np.log(1/(1-sig))
# Mean cross entropy
mce = np.mean(ce)
print('MCE with np: %.16f' % mce)
#%% Tensorflow
xp = tf.placeholder(dtype=tf.float64,shape=[None,dx])
pp = tf.placeholder(dtype=tf.float64,shape=[None,1])
model = xp
c1 = tf.constant(matrix,dtype=tf.float64)
model = tf.matmul(xp,c1)
sigtf = tf.nn.sigmoid(model)
cetf = tf.nn.sigmoid_cross_entropy_with_logits(labels=pp,logits=model)
mcetf = tf.losses.sigmoid_cross_entropy(pp,model)
mcetf2 = tf.reduce_mean(cetf)
sess = tf.Session()
feed = {xp:x,pp:p}
print('Error in logits: %.16f' % np.max(np.abs(sess.run(model,feed)-logits)))
print('Error in sigmoid: %.16f' % np.max(np.abs(sess.run(sigtf,feed)-sig)))
print('Error in CE: %.16f' % np.max(np.abs(sess.run(cetf,feed)-ce)))
print('Error in MCE: %.16f' % np.abs(sess.run(mcetf,feed)-mce))
print('Error in MCE2: %.16f' % np.abs(sess.run(mcetf2,feed)-mce))
sess.close()
标志尺寸:(10,1) 乙状结肠尺寸:(10,1) 概率维数:(10,1) np: 0.7413128316195762 日志中的错误: 0.0000000000000000 乙状结肠错误: 0.0000000000000000 CE: 0.0000000000000009中的错误 MCE中的错误: 0.0000000297816550 MCE2中错误: 0.0000000000000001
发布于 2019-01-14 05:26:32
(32位)float
的使用似乎是在Tensorflow中sigmoid_cross_entropy
使用的compute_weighted_loss()
函数中硬编码的。
作为次要的一点,计算ce
的numpy代码不是非常稳定的- but,在这里不会影响任何东西。我会把它实现为:
ce = p * -np.log(sig) + (1-p) * -np.log1p(-sig)
https://stackoverflow.com/questions/54180194
复制相似问题