我使用Keras(版本2.2.4)训练了以下模型:
# imports ...
model = Sequential()
model.add(Conv2D(filters=64, kernel_size=5, data_format="channels_last", activation="relu"))
model.add(BatchNormalization())
model.add(MaxPooling2D(data_format="channels_last"))
model.add(Conv2D(filters=32, kernel_size=3, data_format="channels_last", activation="relu"))
model.add(BatchNormalization())
model.add(MaxPooling2D(data_format="channels_last"))
model.add(Flatten(data_format="channels_last"))
model.add(Dense(units=256, activation="relu"))
model.add(Dense(units=128, activation="relu"))
model.add(Dense(units=32, activation="relu"))
model.add(Dense(units=8, activation="softmax"))
# training ...
model.save("model.h5")
输入是形状为(28, 28, 1)
的28 x 28灰度图像。
我使用tensorflowjs_converter
转换了模型,现在我想使用TensorFlow.js(版本1.1.0)将其加载到我的网站中:
tf.loadLayersModel('./model/model.json')
这会产生以下错误:
The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.
at new e (errors.ts:48)
at e.add (models.ts:440)
at e.fromConfig (models.ts:1020)
at vp (generic_utils.ts:277)
at nd (serialization.ts:31)
at models.ts:299
at common.ts:14
at Object.next (common.ts:14)
at o (common.ts:14)
如何在不重新训练模型的情况下解决此错误?
答案 0 :(得分:0)
尝试将神经网络调整为以下格式:
input_img = Input(batch_shape=(None, 28,28,1))
layer1=Conv2D(filters=64, kernel_size=5, data_format="channels_last", activation="relu")(input_img)
layer2=BatchNormalization()(layer1)
.
.
.
final_layer=Dense(units=8, activation="softmax")(previous_layer)
...等等。最后:
model = Model(inputs = input_img, outputs = final_layer)
答案 1 :(得分:0)
您必须在keras模型的Conv2D层中指定输入形状。
# imports ...
model = Sequential()
model.add(Conv2D(input_shape=(28, 28, 1), filters=64, kernel_size=5, data_format="channels_last", activation="relu"))
model.add(BatchNormalization())
model.add(MaxPooling2D(data_format="channels_last"))
model.add(Conv2D(filters=32, kernel_size=3, data_format="channels_last", activation="relu"))
model.add(BatchNormalization())
model.add(MaxPooling2D(data_format="channels_last"))
model.add(Flatten(data_format="channels_last"))
model.add(Dense(units=256, activation="relu"))
model.add(Dense(units=128, activation="relu"))
model.add(Dense(units=32, activation="relu"))
model.add(Dense(units=8, activation="softmax"))
# training ...
model.save("model.h5")
答案 2 :(得分:0)
最好的方法是更改您的keras模型并重新训练。
无论如何,如果您不能重新训练网络,则可以手动编辑model.json
文件。
您需要在model.json
文件中找到输入层并添加
"config": {
...
"batch_input_shape": [
null,
28,
28,
1
]
...
}