【发布时间】:2018-11-20 11:51:51
【问题描述】:
tensorflow中是否有logit函数,即sigmoid函数的反函数?我搜索了谷歌,但没有找到。
【问题讨论】:
-
删除了@joseph-budin
标签: tensorflow machine-learning neural-network inverse activation-function
tensorflow中是否有logit函数,即sigmoid函数的反函数?我搜索了谷歌,但没有找到。
【问题讨论】:
标签: tensorflow machine-learning neural-network inverse activation-function
不,函数tf.log_sigmoid 不是 sigmoid 的逆函数。
@benjaminplanche 的第一个答案非常正确。
import tensorflow as tf
logit = lambda x: -tf.math.log(1/x-1)
assert logit(tf.math.sigmoid(0.4))==0.4
这也在scipy.special.logit 中实现。
`
【讨论】:
tf.log_sigmoid() 不是logit 函数。这是逻辑函数的日志。
来自 TF 文档:
y = log(1 / (1 + exp(-x)))
据我所知,TF 没有 logit 函数,所以你必须自己制作,正如最初建议的第一个答案。
【讨论】:
编辑:正如@AGP 所指出的,Tensorflow 已经提供了一个实现:tf.log_sigmoid()。
鉴于 logit 函数的定义(与 sigmoidal 逻辑函数相反),自己实现它相当简单(参见 Wikipedia "Logit" article):
作为sigmoid(x) = 1 / (1 + exp(-x)),
logit(y) = sigmoid(x)^-1 = log(y / (1 - p)) = -log( 1 / p - 1)
实施:
import tensorflow as tf
def logit(x):
""" Computes the logit function, i.e. the logistic sigmoid inverse. """
return - tf.log(1. / x - 1.)
x = tf.random_uniform((5, ), minval=-10., maxval=10., dtype=tf.float64)
# sigmoid(x):
x_sig = tf.sigmoid(x)
# logit(sigmoid(x)) = x:
x_id = logit(x_sig)
# Verifying the equality:
comp = tf.abs(x - x_id)
with tf.Session() as sess:
a, a_id, co = sess.run([x, x_id, comp])
print(a)
# [ 0.99629643 1.4082849 6.6794731 7.64434123 6.99725702]
print(a_id)
# [ 0.99629643 1.4082849 6.6794731 7.64434123 6.99725702]
print(co)
# [ 2.22044605e-16 0.00000000e+00 7.28306304e-14 4.35207426e-14 7.81597009e-14]
注意:当sigmoid(x) 快速收敛到其渐近线极限时,等式适用于相当小的x 值(即x in [-n, n] 的较小值n):
import tensorflow as tf
def logit(x):
""" Computes the logit function, i.e. the logistic sigmoid inverse. """
return - tf.log(1. / x - 1.)
x = tf.constant([-1000, -100, -10, -1, 0, 1, 10, 100, 1000], dtype=tf.float64)
# sigmoid(x):
x_sig = tf.sigmoid(x)
# logit(sigmoid(x)) = x:
x_id = logit(x_sig)
with tf.Session() as sess:
a, a_id = sess.run([x, x_id])
print(a)
# [-1000. -100. -10. -1. 0. 1. 10. 100. 1000.]
print(a_id)
# [ -inf -100. -10. -1. 0. 1. 10. inf inf ]
【讨论】: