首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >"TypeError:无法为名称构建一个TypeSpec .“在未知维数上使用tf.assert时

"TypeError:无法为名称构建一个TypeSpec .“在未知维数上使用tf.assert时
EN

Stack Overflow用户
提问于 2022-07-25 21:24:25
回答 1查看 85关注 0票数 2

假设我正在构建一个具有部分已知维度的模型:

代码语言:javascript
复制
# 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是一个大型的、复杂的张量函数,它在不同的地方使用断言来确保关于形状和等级的假设得到满足。为了重现这个问题,我只想说:

代码语言:javascript
复制
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中使用断言,因为在构造图时,它们会导致这些错误?

以下是完整的错误消息:

代码语言:javascript
复制
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'>.
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-26 06:18:40

问题是您不能将Keras符号张量提供给某些Tensorflow API。只需将函数my_custom_op包装在Lambda或自定义层中,它就会工作:

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73115505

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档