Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 绕过不可微的tf.argmax_Python_Tensorflow - Fatal编程技术网

Python 绕过不可微的tf.argmax

Python 绕过不可微的tf.argmax,python,tensorflow,Python,Tensorflow,我已经为我的神经网络写了一个自定义的损失函数,但它不能计算任何梯度。我认为这是因为我需要最高值的索引,因此使用argmax来获取该索引 因为argmax是不可微的,所以我想避开这个问题,但我不知道这是怎么可能的 有人能帮忙吗?tf.argmax是不可微的,因为它返回一个整数索引。tf.reduce_max和tf.max是可微的如果你对近似值很冷静 import tensorflow as tf import numpy as np sess = tf.Session() x = tf.plac

我已经为我的神经网络写了一个自定义的损失函数,但它不能计算任何梯度。我认为这是因为我需要最高值的索引,因此使用argmax来获取该索引

因为argmax是不可微的,所以我想避开这个问题,但我不知道这是怎么可能的


有人能帮忙吗?

tf.argmax是不可微的,因为它返回一个整数索引。tf.reduce_max和tf.max是可微的

如果你对近似值很冷静

import tensorflow as tf
import numpy as np

sess = tf.Session()
x = tf.placeholder(dtype=tf.float32, shape=(None,))
beta = tf.placeholder(dtype=tf.float32)

# Pseudo-math for the below
# y = sum( i * exp(beta * x[i]) ) / sum( exp(beta * x[i]) )
y = tf.reduce_sum(tf.cumsum(tf.ones_like(x)) * tf.exp(beta * x) / tf.reduce_sum(tf.exp(beta * x))) - 1

print("I can compute the gradient", tf.gradients(y, x))

for run in range(10):
    data = np.random.randn(10)
    print(data.argmax(), sess.run(y, feed_dict={x:data/np.linalg.norm(data), beta:1e2}))
这是使用一种技巧,计算低温环境下的平均值,得到概率空间的近似最大值。在这种情况下,低温与
beta
非常大相关


事实上,随着
beta
接近无穷大,我的算法将收敛到最大值(假设最大值是唯一的)。不幸的是,在出现数字错误并得到
NaN
之前,beta不能变得太大,但如果您愿意,我可以研究一些技巧来解决这个问题

输出看起来像

0 2.24459
9 9.0
8 8.0
4 4.0
4 4.0
8 8.0
9 9.0
6 6.0
9 8.99995
1 1.0

因此,你可以看到,它在一些地方搞砸了,但往往得到正确的答案。根据您的算法,这可能很好。

如果您输入的值范围为正值,您不需要最大值的精确索引,但它是一个热形式就足够了,您可以使用
符号
函数如下:

import tensorflow as tf
import numpy as np

sess = tf.Session()
x = tf.placeholder(dtype=tf.float32, shape=(None,))

y = tf.sign(tf.reduce_max(x,axis=-1,keepdims=True)-x)
y = (y-1)*(-1)

print("I can compute the gradient", tf.gradients(y, x))

for run in range(10):
    data = np.random.random(10)
    print(data.argmax(), sess.run(y, feed_dict={x:data}))

正如艾丹所说,这只是一个测试版的极限。我们可以使用
tf.nn.softmax
绕过数字问题:

def softargmax(x, beta=1e10):
  x = tf.convert_to_tensor(x)
  x_range = tf.range(x.shape.as_list()[-1], dtype=x.dtype)
  return tf.reduce_sum(tf.nn.softmax(x*beta) * x_range, axis=-1)

还有tf.minimum和tf.maximum可微吗?这应该是一个注释。好主意。谢谢分享。
tf.sign
可微吗?根据,它似乎不是这样。“但是如果你愿意,我可以研究一些解决方法。”请告诉我一些避免数字溢出的方法,以及我可以从中了解更多有关该方法的资源。我真的需要它。