【问题标题】:Restrict NN outputs' maximum to be positive in Tensorflow/Keras在 Tensorflow/Keras 中将 NN 输出的最大值限制为正
【发布时间】:2021-10-29 10:38:31
【问题描述】:

我有一个神经网络,可以输出多个输出num_out

我知道如果我希望所有输出都是正数,我可以在输出层上应用relu 激活函数(或其他)。

但是,我的目标是确保只有所有 num_out 输出中的最大值为正。我找不到强制执行的方法。

【问题讨论】:

  • 你能提供你的代码吗?

标签: python tensorflow keras neural-network


【解决方案1】:

解决问题的一种方法是使用tf.wheretf.reduce_max

import tensorflow as tf
x = tf.constant([
                 [-1, -2, -3], 
                 [-4, -5, -6]
                ])

max_val = tf.reduce_max(x, keepdims=True)
new_max_val = tf.where(tf.greater(max_val, 0), max_val, tf.math.negative(max_val))
result = tf.where(tf.equal(x, max_val), tf.ones(tf.shape(x), dtype=x.dtype) * new_max_val, x)
 
print('Max value: ', max_val)
print('New Max value: ', new_max_val)
print('Result: ', result)
Max value:  tf.Tensor([[-1]], shape=(1, 1), dtype=int32)
New Max value:  tf.Tensor([[1]], shape=(1, 1), dtype=int32)
Result:  tf.Tensor(
[[ 1 -2 -3]
 [-4 -5 -6]], shape=(2, 3), dtype=int32)

我首先在张量x 中找到最大值,然后如果它是负数则将其转换为正值,否则保持不变。之后,我用新值更新张量 x。如果你的张量中的最大值是正的,那么什么都不会改变:

x = tf.constant([
                 [-1, -2, -3], 
                 [ 4,  5,  6]
                ])
# -->
Max value:  tf.Tensor([[6]], shape=(1, 1), dtype=int32)
New Max value:  tf.Tensor([[6]], shape=(1, 1), dtype=int32)
Result:  tf.Tensor(
[[-1 -2 -3]
 [ 4  5  6]], shape=(2, 3), dtype=int32)

如果要确保除最大值之外的所有其他元素都是负数,请更改此行:

result = tf.where(tf.equal(x, max_val), tf.ones(tf.shape(x), dtype=x.dtype) * new_max_val, tf.abs(x)*-1)
Max value:  tf.Tensor([[6]], shape=(1, 1), dtype=int32)
New Max value:  tf.Tensor([[6]], shape=(1, 1), dtype=int32)
Result:  tf.Tensor(
[[-1 -2 -3]
 [-4 -5  6]], shape=(2, 3), dtype=int32)

【讨论】:

    猜你喜欢
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 2018-10-03
    相关资源
    最近更新 更多