如何在tensorflow中的两个选定维度中执行tf.nn.softmax?

如何在tensorflow中的两个选定维度中执行tf.nn.softmax?,tensorflow,softmax,Tensorflow,Softmax,我想为形状为(批次大小=?,高度,宽度,通道)的张量的选定二维实现tf.nn.softmax() 但是tf.nn.softmax()似乎不可能同时接收2个轴。使用tf.softmax(张量,轴=[1,2])将在tensorflow中增加轴误差 如何在矢量化模式下优雅地实现这一点?thx:D你可以 array = np.random.rand(1, 2, 2, 1) s1 = tf.nn.softmax(array, axis=1) s2 = tf.nn.softmax(array, axis=2

我想为形状为
(批次大小=?,高度,宽度,通道)的张量的选定二维实现
tf.nn.softmax()

但是
tf.nn.softmax()
似乎不可能同时接收2个轴。使用
tf.softmax(张量,轴=[1,2])
将在tensorflow中增加轴误差

如何在矢量化模式下优雅地实现这一点?thx:D

你可以

array = np.random.rand(1, 2, 2, 1)
s1 = tf.nn.softmax(array, axis=1)
s2 = tf.nn.softmax(array, axis=2)
rs = tf.reduce_sum([s1, s2], 0)
这将返回与初始数组形状相同的张量

array = np.random.rand(1, 2, 2, 1)
s1 = tf.nn.softmax(array, axis=1)
s2 = tf.nn.softmax(array, axis=2)
rs = tf.reduce_sum([s1, s2], 0)

这将返回与初始数组形状相同的张量

而不是一次传递两个维度,我将首先相应地重塑输入,例如:

array = tf.constant([[1., 2.], [3., 4.]])

tf.nn.softmax(array, axis=0) # Calculate for axis 0
tf.nn.softmax(array, axis=1) # Calculate for axis 1

tf.nn.softmax(tf.reshape(array, [-1])) # Calculate for both axes

我不会一次传递两个维度,而是首先相应地重塑输入,例如:

array = tf.constant([[1., 2.], [3., 4.]])

tf.nn.softmax(array, axis=0) # Calculate for axis 0
tf.nn.softmax(array, axis=1) # Calculate for axis 1

tf.nn.softmax(tf.reshape(array, [-1])) # Calculate for both axes

可通过keras激活功能完成:

# logits has shape [BS, H, W, CH]
prob = tf.keras.activations.softmax(logits, axis=[1, 2])
# prob has shape [BS, H, W, CH]
check = tf.reduce_sum(prob, axis=[1, 2])
# check is tensor of ones with shape [BS, CH]

可通过keras激活功能完成:

# logits has shape [BS, H, W, CH]
prob = tf.keras.activations.softmax(logits, axis=[1, 2])
# prob has shape [BS, H, W, CH]
check = tf.reduce_sum(prob, axis=[1, 2])
# check is tensor of ones with shape [BS, CH]

是的,但它不能确保数组中所有元素的和为1,这是一个重要的考虑因素,因为softmax通常用于将输出解释为概率。是的,但它不能确保数组中所有元素的和为1,这是一个重要的考虑因素,因为softmax通常用于将输出解释为概率。