假设我正在构建一个具有部分已知维度的模型:
# Multilayer Perceptron
from keras.layers import Input
from keras.layers import Dense
import tensorflow as tf
inputs = Input(shape=(10,))
hidden1 = Dense(10, activation='relu')(inputs)
hidden2 = tf.math.add(hidden1, 5)
hidden3 = tf.math.add(hidden2, 5)
hidden4 = my_custom_op(hidden2, hidden3)
output = Dense(10, activation='linear')(hidden4)my_custom_op是一个大型的、复杂的张量函数,它在不同的地方使用断言来确保关于形状和等级的假设得到满足。为了重现这个问题,我只想说:
def my_custom_op(hidden_x, hidden_y):
tf.assert_equal(tf.shape(hidden_x), tf.shape(hidden_y))
return hidden当我运行这个程序时,我会得到以下错误:
"tf.debugging.assert_equal_1/assert_equal_1/Assert/Assert“:
TypeError:无法为名称构建TypeSpec
我不明白这条错误信息在告诉我什么。如果我运行tf.assert_equal(2, 2),我不会得到异常,所以我假设这与维度尚不清楚这一事实有关。
但是,当尺寸已知时,难道不是断言它们运行的意义吗?如果不是,这是否意味着我不能在my_custom_op中使用断言,因为在构造图时,它们会导致这些错误?
以下是完整的错误消息:
TypeError: Could not build a TypeSpec for name: "tf.debugging.assert_equal_1/assert_equal_1/Assert/Assert"
op: "Assert"
input: "tf.debugging.assert_equal_1/assert_equal_1/All"
input: "tf.debugging.assert_equal_1/assert_equal_1/Assert/Assert/data_0"
input: "tf.debugging.assert_equal_1/assert_equal_1/Assert/Assert/data_1"
input: "Shape"
input: "tf.debugging.assert_equal_1/assert_equal_1/Assert/Assert/data_3"
input: "Shape_1"
attr {
key: "T"
value {
list {
type: DT_STRING
type: DT_STRING
type: DT_INT32
type: DT_STRING
type: DT_INT32
}
}
}
attr {
key: "summarize"
value {
i: 3
}
}
of unsupported type <class 'tensorflow.python.framework.ops.Operation'>.发布于 2022-07-26 06:18:40
问题是您不能将Keras符号张量提供给某些Tensorflow API。只需将函数my_custom_op包装在Lambda或自定义层中,它就会工作:
import tensorflow as tf
def my_custom_op(x):
hidden_x, hidden_y = x
tf.assert_equal(tf.shape(hidden_x), tf.shape(hidden_y))
return hidden_x
inputs = tf.keras.layers.Input(shape=(10,))
hidden1 = tf.keras.layers.Dense(10, activation='relu')(inputs)
hidden2 = tf.math.add(hidden1, 5)
hidden3 = tf.math.add(hidden2, 5)
hidden4 = tf.keras.layers.Lambda(my_custom_op)([hidden2, hidden3])
output = tf.keras.layers.Dense(10, activation='linear')(hidden4)https://stackoverflow.com/questions/73115505
复制相似问题