无法将符号 Keras input/output 转换为 numpy 数组。在 Tensorflow 2.4 中使用 model.optimizer.get_gradients 时

Cannot convert a symbolic Keras input/output to a numpy array. when using model.optimizer.get_gradients in Tensorflow 2.4

我在 colab 中遵循了教程 A Primer on Deep Learning in Genomics - Public.ipynb,但是当我尝试在第 sal = compute_salient_bases(model, input_features[sequence_index]).

行执行步骤 4.Interpret 时得到了 TypeError: Cannot convert a symbolic Keras input/output to a numpy array...
import tensorflow.keras.backend as K

def compute_salient_bases(model, x):
  input_tensors = [model.input]
  gradients = model.optimizer.get_gradients(model.output[0][1], model.input)
  compute_gradients = K.function(inputs = input_tensors, outputs = gradients)
  
  x_value = np.expand_dims(x, axis=0)
  gradients = compute_gradients([x_value])[0][0]
  sal = np.clip(np.sum(np.multiply(gradients,x), axis=1),a_min=0, a_max=None)
  return sal

sequence_index = 1999  # You can change this to compute the gradient for a different example. But if so, change the coloring below as well.
sal = compute_salient_bases(model, input_features[sequence_index])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-b6400cc2276d> in <module>()
      1 sequence_index = 1999  # You can change this to compute the gradient for a different example. But if so, change the coloring below as well.
----> 2 sal = compute_salient_bases(model, input_features[sequence_index])
      3 
      4 plt.figure(figsize=[16,5])
      5 barlist = plt.bar(np.arange(len(sal)), sal)

14 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/keras_tensor.py in __array__(self)
    272   def __array__(self):
    273     raise TypeError(
--> 274         'Cannot convert a symbolic Keras input/output to a numpy array. '
    275         'This error may indicate that you\'re trying to pass a symbolic value '
    276         'to a NumPy call, which is not supported. Or, '

TypeError: Cannot convert a symbolic Keras input/output to a numpy array. This error may indicate that you're trying to pass a symbolic value to a NumPy call, which is not supported. Or, you may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model.

问题出在 model.optimizer.get_gradients(model.output[0][1], model.input)。根据 https://www.tensorflow.org/api_docs/python/tf/gradients

我认为这是正确的用法
get_gradients(
    loss, params
)

我对这个错误很困惑。或者是否有 compute_salient_bases 的替代方法?

降级 TensorFlow 版本,重新启动 运行time 并再次 运行 notebook。

!pip install tensorflow==1.13.2
import tensorflow as tf
print(tf.__version__)