首页 > 解决方案 > 使用 TF Lite Model Maker 创建的模型出现 TF.js 导入错误

问题描述

我使用https://www.tensorflow.org/lite/tutorials/model_maker_image_classification上的教程创建了一个模型,并将其导出为 TF.js 格式:

import os

import matplotlib.pyplot as plt
import tensorflow as tf
from tflite_model_maker import image_classifier, model_spec
from tflite_model_maker.config import ExportFormat, QuantizationConfig
from tflite_model_maker.image_classifier import DataLoader

image_path = tf.keras.utils.get_file(
      'flower_photos.tgz',
      'https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz',
      extract=True)
image_path = os.path.join(os.path.dirname(image_path), 'flower_photos')
data = DataLoader.from_folder(image_path)
train_data, test_data = data.split(0.9)
model = image_classifier.create(train_data)
loss, accuracy = model.evaluate(test_data)

# Export model to TF.js format
model.export(export_dir='.', export_format=ExportFormat.TFJS)

在使用 TF.js 加载此模型时,出现tf.loadLayersModel以下错误:

Uncaught (in promise) Error: Unknown layer: HubKerasLayerV1V2. 
This may be due to one of the following reasons:
1. The layer is defined in Python, in which case it needs to be
ported to TensorFlow.js or your JavaScript code.
2. The custom layer is defined in JavaScript, but is not registered
properly with tf.serialization.registerClass()

我猜错误是由于原因(1),但我怎样才能将HubKerasLayerV1V2层移植到 TF.js?

标签: tensorflowtensorflow-litetensorflow.js

解决方案


我相信这是模型转换器在层模型内部存在部分图形问题的问题。

您可以通过将模型序列化为正常SaveModel格式并导出 HDF5 来解决此问题。获得.h5输出后,使用 TensorFlow.js 转换器 ( tensorflowjs_converter ) 创建一个纯图形模型。然后尝试加载 with tf.loadGraphModel


推荐阅读