繁体   English   中英

急切执行 function 的输入不能是 Keras 符号张量,但可以找到

[英]Inputs to eager execution function cannot be Keras symbolic tensors, but found

我正在尝试获取我的 model wrt 输入的雅可比(sample_x 是 numpy 中的二进制向量)。

print("Initiating gradient checker")
    sample_x_tensor = sample_x.toarray()
    sample_x_tensor = tf.convert_to_tensor(sample_x.toarray())
    sample_x_tensor = tf.cast(sample_x_tensor, tf.float32)

    with tf.GradientTape() as tape:
        tape.watch(sample_x_tensor)
        y_pred = model(sample_x_tensor)
        print(y_pred[0])

    jacobian = tape.jacobian(y_pred, sample_x_tensor)

Model is a straightforward Keras binary classification model, Keras 2.15 and Tensorflow 2. Getting the following exception:

tensorflow.python.eager.core._SymbolicException: Inputs to eager execution function cannot be Keras symbolic tensors, but found [<tf.Tensor 'Reshape:0' 
shape=(1,) dtype=float32>]

据我了解,TF2 默认具有急切执行。 知道如何纠正这个问题吗?

使用您提供的代码片段并添加基本的 Keras 二进制分类Model。

用于复制的代码:

%tensorflow_version 2.x  # Using Google Colab

import tensorflow as tf  # Tensorflow 2.2.0-rc3
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential

model = Sequential()
model.add(Dense(32, input_shape = (2,)))
model.add(Dense(1, activation = 'sigmoid'))

print("Initiating gradient checker")
sample_x_tensor = tf.random.normal((100,2))
# sample_x_tensor = sample_x.toarray()
# sample_x_tensor = tf.convert_to_tensor(sample_x.toarray())
sample_x_tensor = tf.cast(sample_x_tensor, tf.float32)

with tf.GradientTape() as tape:
    tape.watch(sample_x_tensor)
    y_pred = model(sample_x_tensor)
    print(y_pred[0])

jacobian = tape.jacobian(y_pred, sample_x_tensor)

这将返回:

Initiating gradient checker
tf.Tensor([0.38266268], shape=(1,), dtype=float32)

它执行成功,但我会为您建议一些事情:

  1. 检查您的 Model,看看它是否处理了正确的数据类型
  2. 检查您的输入数据形状类型,确保它与使用的图层兼容。 (尽可能使用Tensor Datatype)

希望这对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM