python - 在 keras 模型中对输入进行微分以用于损失

标签 python tensorflow keras tensorflow2.0

keras 中是否有任何层可以计算输入的导数?例如,如果输入x,第一层是f(x),那么下一层的输出应该是f'(x) 。关于这个主题有多个问题,但所有问题都涉及模型外导数的计算。本质上,我想创建一个神经网络,其损失函数涉及输入的雅可比矩阵和粗麻布矩阵。

我尝试过以下方法

import keras.backend as K

def create_model():

    x = keras.Input(shape = (10,))
    layer = Dense(1, activation = "sigmoid")
    output = layer(x)

    jac = K.gradients(output, x)
    
    model = keras.Model(inputs=x, outputs=jac)
    
    return model

model = create_model()
X = np.random.uniform(size = (3, 10))

这会给出错误启用急切执行时不支持 tf.gradients。请改用 tf.GradientTape。

所以我尝试使用它

def create_model2():
    with tf.GradientTape() as tape:
        x = keras.Input(shape = (10,))
        layer = Dense(1, activation = "sigmoid")
        output = layer(x)

    jac = tape.gradient(output, x)
    
    model = keras.Model(inputs=x, outputs=jac)
    
    return model

model = create_model2()
X = np.random.uniform(size = (3, 10))

但这告诉我“KerasTensor”对象没有属性“_id”

这两种方法在模型之外都可以正常工作。我的最终目标是在损失函数中使用 Jacobian 和 Hessian,因此其他方法也将受到赞赏

最佳答案

不确定您到底想做什么,但也许可以尝试使用 tf.gradients 自定义 Keras 层:

import tensorflow as tf
tf.random.set_seed(111)

class GradientLayer(tf.keras.layers.Layer):
  def __init__(self):
    super(GradientLayer, self).__init__()
    self.dense = tf.keras.layers.Dense(1, activation = "sigmoid")
  
  @tf.function
  def call(self, inputs):
    outputs = self.dense(inputs)
    return tf.gradients(outputs, inputs)


def create_model2():
    gradient_layer = GradientLayer()
    inputs = tf.keras.layers.Input(shape = (10,))
    outputs = gradient_layer(inputs)    
    model = tf.keras.Model(inputs=inputs, outputs=outputs)
    
    return model

model = create_model2()
X = tf.random.uniform((3, 10))
print(model(X))
tf.Tensor(
[[-0.07935508 -0.12471244 -0.0702782  -0.06729251  0.14465885 -0.0818079
  -0.08996294  0.07622238  0.11422144 -0.08126545]
 [-0.08666676 -0.13620329 -0.07675356 -0.07349276  0.15798753 -0.08934557
  -0.09825202  0.08324542  0.12474566 -0.08875315]
 [-0.08661086 -0.13611545 -0.07670406 -0.07344536  0.15788564 -0.08928795
  -0.09818865  0.08319173  0.12466521 -0.08869591]], shape=(3, 10), dtype=float32)

关于python - 在 keras 模型中对输入进行微分以用于损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71130161/

相关文章:

python - 在 Keras 中使用迁移学习训练 CNN - 图像输入不起作用,但矢量输入起作用

tensorflow - 如何使用 tf.matmul 执行高效的稀疏矩阵乘法?

python - 如何在 Keras 中使用 fit_generator() 平衡数据集?

python - 训练后如何扩展进入神经网络的新数据

neural-network - 为什么在 Keras 中 CNN 的训练速度比完全连接的 MLP 慢?

python - 使用 Python Elasticserarch-py 包时出错

python - 如何在 python 中的二进制矩阵中跟踪 1 的所有唯一路径?

python - GIS:Python 中的 line_locate_point()

python - 为什么 TensorFlow 返回 [[nan nan]] 而不是 CSV 文件中的概率?

python - 将 '[a, b, c]' 形式的字符串转换为 python 中的列表,而不经过列表理解