我有一个复杂的 keras 模型,其中一层是自定义预训练层,需要“int32”作为输入。该模型作为继承自 Model 的类实现,其实现如下:
class MyModel(tf.keras.models.Model):
def __init__(self, size, input_shape):
super(MyModel, self).__init__()
self.layer = My_Layer()
self.build(input_shape)
def call(self, inputs):
return self.layer(inputs)
但当它达到self.build
方法,它会抛出下一个错误:
ValueError: You cannot build your model by calling `build` if your layers do not support float type inputs. Instead, in order to instantiate and build your model, `call` your model on real tensor data (of the correct dtype).
我该如何修复它?
使用 model.build 构建模型时会引发异常。
model.build 函数根据给定的输入形状构建模型。
引发错误的原因是,当我们尝试构建模型时,它首先根据以下代码中的输入形状类型调用带有 x 参数的模型
if (isinstance(input_shape, list) and
all(d is None or isinstance(d, int) for d in input_shape)):
input_shape = tuple(input_shape)
if isinstance(input_shape, list):
x = [base_layer_utils.generate_placeholders_from_shape(shape)
for shape in input_shape]
elif isinstance(input_shape, dict):
x = {
k: base_layer_utils.generate_placeholders_from_shape(shape)
for k, shape in input_shape.items()
}
else:
x = base_layer_utils.generate_placeholders_from_shape(input_shape)
x 是 TensorFlow 占位符。因此,当尝试使用 x 作为输入调用模型时,它将弹出 TypeError,并且除 for 块之外的结果将起作用并给出错误。
我假设你的输入形状是 16x16。而不是使用self.build([(16,16)])
这个,调用基于实张量的模型
inputs = tf.keras.Input(shape=(16,))
self.call(inputs)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)