簡體   English   中英

如何從keras API模型獲取tf.gradients?

[英]How to get tf.gradients from keras API model?

我想知道如何從使用tf.gradients API構建的模型中獲取tf.gradients

import Tensorflow as tf
from tensorflow import keras
from sklearn.datasets.samples_generator import make_blobs

# Create the model
inputs = keras.Input(shape=(2,))
x = keras.layers.Dense(12, activation='relu')(inputs)
x = keras.layers.Dense(8, activation='relu')(x)
predictions = keras.layers.Dense(3, activation='softmax')(x)
model = keras.models.Model(inputs=inputs, outputs=predictions)
model.compile(optimizer=tf.train.AdamOptimizer(0.001),
          loss='categorical_crossentropy',
          metrics=['accuracy'])

# Generate random data
X, y = make_blobs(n_samples=1000, centers=3, n_features=2)
labels = keras.utils.to_categorical(y, num_classes=3)

# Compute the gradients wrt inputs
y_true = tf.convert_to_tensor(labels)
y_pred = tf.convert_to_tensor(np.round(model.predict(X)))
sess = tf.Session()
sess.run(tf.global_variables_initializer())
grads = tf.gradients(model.loss_functions[0](y_true, y_pred), 
                      model.inputs[0])
sess.run(grads, input_dict={model.inputs[0]: X, model.outputs: y})

上面的第一次嘗試:我的畢業生為None 在下面的第二次嘗試中:

sess.run(grads, input_dict={model.inputs: X, model.outputs: y })

我收到以下錯誤:

TypeError: unhashable type: 'list'

我認為使用Keras時不應直接與Tensorflow創建新會話。 相反,最好使用Keras隱式創建的會話:

import keras.backend as K

sess = K.get_session()

但是,我認為在這種情況下,您根本不需要檢索會話。 您可以輕松使用后端函數(例如K.gradients()K.function()來實現您的目標。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM