无法将符号Keras输入/输出转换为numpy数组。在Tensorflow 2.4中使用model.optimizer.get_梯度时

2024-09-28 05:23:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我遵循了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


Tags: thetoinputoutputindexmodelarraykeras
1条回答
网友
1楼 · 发布于 2024-09-28 05:23:00

降级TensorFlow版本,重新启动运行时并再次运行笔记本

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

相关问题 更多 >

    热门问题