如何在张量流中实现指标函数?

时间:2017-09-24 04:24:35

标签: python tensorflow

我想实现这样的函数:if x == k,f(x)= 1,否则f(x)= 0(k是参数)。所以我使用了tf.equal和tf.cast,我的代码是这样的:

import tensorflow as tf

a = range(12)
a = tf.Variable(a)
b = 6
b = tf.Variable(b)
a = tf.reshape(a, [3, 4])

sess = tf.Session()

init = tf.global_variables_initializer()
sess.run(init)
c = tf.equal(a, b)
d = tf.cast(c, tf.int32)
print sess.run(c)
print sess.run(d)

看起来很好,但问题是tf.gradients(d,a)和tf.gradients(d,b)都是None。我试过tf.gradients(c,a)并得到了TypedError。有没有合适的方法来实现这个功能?

2 个答案:

答案 0 :(得分:0)

我不确定此处是否定义了渐变。

如果a = b,则指标函数为f(a,b)= 1,否则为0。远离a = b,该函数是常数(零),因此具有零导数。在a = b的任何一点,函数是不连续的,所以它没有那里的导数。

更直观地说:衍生品并不存在于你有跳跃的地方。在你的功能。

答案 1 :(得分:0)

可以使用正态分布的PDF来近似指标功能。我也是TensorFlow的新手,请随时指出任何问题。

##I am using tensorflow2
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import tensorflow_probability as tfp 

a = tf.range(12)
a = tf.Variable(a)
b = 6
b = tf.Variable(b)
a = tf.reshape(a, [3, 4])

## Define the PDF of a normal distribution to approximate the indicator function
dist = tfp.distributions.Normal(0., 0.1)
scalar = dist.prob(0) # a normalization constant
#since the pdf at data zero is not one

## Implement the approximazed indicator function
a = tf.cast(a, dtype= tf.float32)
b = tf.cast(b, dtype= tf.float32)
c = dist.prob(a-b)/scalar
#d = tf.cast(c, tf.int32)

sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(c))

## calcualte the gradient
c_a = tf.gradients(c, a) 
print(sess.run(c_a))