【问题标题】:Does tf.math.reduce_max allows gradient flow like torch.max?tf.math.reduce_max 是否允许像 torch.max 这样的梯度流?
【发布时间】:2020-10-24 04:50:44
【问题描述】:

我正在尝试在 Tensorflow 中构建多标签二元分类模型。该模型在两层之间有一个tf.math.reduce_max 运算符(它不是 Max Pooling,它用于不同的目的)。

并且班级数量是3。

我正在使用二元交叉熵损失并使用 Adam 优化器。

即使经过数小时的训练,当我检查预测时,所有预测都在 0.49 到 0.51 的范围内。

该模型似乎没有学习任何东西并且正在进行随机预测,这让我认为使用tf.math.reduce_max 函数可能会导致问题。

但是,我在网上看到 torch.max 函数允许通过它反向传播梯度。

当我在 Tensorboard 中检查图表时,我看到图表在 tf.math.reduce_max 运算符处显示为未连接。 那么,这个算子是否允许梯度通过它反向传播?

编辑: 添加代码

input_tensor = Input(shape=(256, 256, 3))
base_model_toc = VGG16(input_tensor=input_tensor,weights='imagenet',pooling=None, include_top=False)

x = base_model.output

x = GlobalAveragePooling2D()(x)

x = tf.math.reduce_max(x,axis=0,keepdims=True)

x = Dense(1024,activation='relu')(x)

output_1 = Dense(3, activation='sigmoid')(x)

model_a = Model(inputs=base_model_toc.input, outputs=output_1)

for layer in base_model.layers:
    layer.trainable = True

tf.math.reduce_max 与 axis = 0 一起完成,因为这是此模型中需要完成的操作

我使用的优化器是 Adam,初始学习率为 0.00001

【问题讨论】:

  • 为什么你认为是re​​duce_max?你能展示一些你尝试过的代码吗?
  • @FrederikBode 在帖子中添加了代码
  • 你确定吗?在tf.math.reduce_max(x,axis=0,keepdims=True) 之后的x.shape 是什么?
  • 我也觉得应该包裹在tf.keras.layers.Lambda层
  • @FrederikBode tf.math.reduce_max 之后的形状是 (1,512)。我将尝试使用 Lambda 层

标签: tensorflow deep-learning pytorch


【解决方案1】:

是的,tf.math.reduce_max 确实允许渐变流动。很容易检查(这是 TensorFlow 2.x 但在 1.x 中是相同的结果):

import tensorflow as tf

with tf.GradientTape() as tape:
    x = tf.linspace(0., 2. * 3.1416, 10)
    tape.watch(x)
    # A sequence of operations involving reduce_max
    y = tf.math.square(tf.math.reduce_max(tf.math.sin(x)))
# Check gradients
g = tape.gradient(y, x)
print(g.numpy())
# [ 0.         0.         0.3420142 -0.        -0.        -0.
#  -0.         0.         0.         0.       ]

如您所见,y 相对于x 有一个有效的渐变。只有一个值不是零,因为它是导致最大值的值,所以它是x 中唯一影响y 值的值。这是操作的正确梯度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    相关资源
    最近更新 更多