【问题标题】:TypeError: 'Tensor' object cannot be interpreted as an integer when using tf.map_fn()TypeError:使用 tf.map_fn() 时,“张量”对象不能解释为整数
【发布时间】:2021-01-01 18:09:48
【问题描述】:

我正在尝试在 keras/tensorflow 中构建依赖于标签的卷积过滤器。因此,卷积滤波器取决于批次中的每个示例。

# function used for tf.map_fn
def single_conv(tupl):
    x, kernel = tupl
    return tf.nn.conv2d(x, kernel, strides=(1, 1, 1, 1), padding='SAME')

# first dimension is None (batch size)
input_img = tf.keras.layers.Input(shape=(28,28,1), dtype=tf.float32)
label = tf.keras.layers.Input(shape=(10,), dtype=tf.float32) 

# the network is learning a mapping for the label
label_encoded = tf.keras.layers.Dense(9, activation='relu')(label) 
# turn mapping into conv filter 
kernels = tf.keras.layers.Reshape((3,3,1,1))(label_encoded) 

# class dependent filter(s)
conditional_conv = tf.map_fn(single_conv, (tf.expand_dims(input_img, 1), kernels), fn_output_signature=tf.float32) 

当我运行这段代码 sn-p 时,我得到了最后一行的 TypeError: 'Tensor' object cannot be interpreted as an integer。由于最后一行使用tf.map_fn,我看到如果使用的函数(在本例中为single_conv)不可调用或函数的输出结构与fn_output_signature 不匹配,则tf.map_fn 会导致TypeError:https://www.tensorflow.org/api_docs/python/tf/map_fn#raises .

但是,我仍然不确定为什么会这样?我觉得这两个原因应该不是问题?

【问题讨论】:

  • 请参阅this 问题。另外,请添加完整的堆栈跟踪。
  • this 有帮助吗?

标签: python tensorflow mapping conv-neural-network tf.keras


【解决方案1】:

对我有用的是创建一个自定义层,并在那里执行 map_fn。

class custom_layer(tf.keras.layers.Layer):
    def __init__(self):
        super(custom_layer, self).__init__()

    def call(self, inputs):
        return tf.map_fn(single_conv, inputs, fn_output_signature=tf.float32)

在你的情况下,

conditional_conv = custom_layer()((tf.expand_dims(input_img, 1), kernels))

【讨论】:

    猜你喜欢
    • 2017-08-01
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2015-03-18
    • 2016-01-26
    • 2021-02-10
    相关资源
    最近更新 更多