【问题标题】:Inputs to eager execution function cannot be Keras symbolic tensors, but found急切执行函数的输入不能是 Keras 符号张量,但可以找到
【发布时间】:2020-07-30 00:42:07
【问题描述】:

我正在尝试通过输入(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)

模型是一个简单的 Keras 二元分类模型,Keras 2.15 和 Tensorflow 2。得到以下异常:

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 默认具有 Eager Execution。知道如何纠正这个问题吗?

【问题讨论】:

  • 你不应该打电话给model.predict(sample_x_tensor)而不是model(sample_x_tensor)?
  • 有趣,我这样做的原因是 GradientTape 只接受一个张量参数。因此,我将我的 numpy 数组转换为张量,然后按照此处将其作为参数提供给模型:keras.io/models/model 在这里您可以将张量作为参数提供给模型。由于我正在“观察”这个张量的行为,这难道不是正确的做法吗?
  • 你提供的链接是用来创建keras模型的,但是创建模型的时候只能调用predict函数
  • 在做你的建议时,我得到:“ValueError:如果你的数据是符号张量的形式,你应该指定steps参数(而不是batch_size参数,因为符号张量预计会产生批量输入数据)。”它应该开箱即用 - 我可以在张量上调用 predict 吗?
  • 我不确定这个错误,抱歉,如果你调用 predict 函数并给它一批输入,keras 模型应该可以工作。

标签: python tensorflow keras


【解决方案1】:

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

用于复制的代码:

%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. 检查您的模型,看看它是否在处理正确的数据类型
  2. 检查您的输入数据形状类型,确保它与使用的图层兼容。 (尽可能使用Tensor Datatype)

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-25
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多