python - 无法构建具有 int 输入的 Keras 层
问题描述
我有一个复杂的 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 并且除块之外的结果将起作用并给出错误。
我假设您的输入形状是 16x16。不使用self.build([(16,16)])
这个,而是基于真实张量调用模型
inputs = tf.keras.Input(shape=(16,))
self.call(inputs)
推荐阅读
- swift - iOS 13 中的后台任务不会多次运行
- php - 在长回显字符串php中添加div
- excel - 使用VBA在word中复制表格前面的文本行
- python - 为 python 3.4 安装包
- perl - 如何(如果可能)为特定的闭包设置断点?
- oracle - Oracle APEX 框架响应页面请求太慢
- c# - Marshal.PtrToStructure 在指向本机 C++ 堆的指针上是否正常?
- javascript - 来自 d3.js 中 2 个点的区域生成器,例如 polygonHull
- c# - 如何在不指定文件位置的情况下打开应用程序?
- c# - 如何从 download.php 下载图像?链接并将其存储在文件中