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 is not supported when eager execution is enabled. Use tf.GradientTape instead.
所以我嘗試使用它
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' object has no attribute '_id'
這兩種方法在模型之外都可以正常作業。我的最終目標是在損失函式中使用雅可比和黑森矩陣,因此也可以使用其他方法
uj5u.com熱心網友回復:
不確定您到底想做什么,但可以嘗試使用以下自定義Keras層tf.gradients:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/426834.html
上一篇:正確的軸以使用點積來評估listwise學習排名模型的最終輸出
下一篇:使用image_dataset_from_directory時,是否可以將tensorflow資料集拆分為訓練、驗證和測驗資料集?
