本文介绍了将模型另存为 H5 或 SavedModel 时出现 TensorFlow Hub 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用这个 TF Hub 资产:https://tfhub.dev/google/imagenet/resnet_v1_50/feature_vector/3

I want to use this TF Hub asset:https://tfhub.dev/google/imagenet/resnet_v1_50/feature_vector/3

版本:

Version:  1.15.0-dev20190726
Eager mode:  False
Hub version:  0.5.0
GPU is available

代码

feature_extractor_url = "https://tfhub.dev/google/imagenet/resnet_v1_50/feature_vector/3"
feature_extractor_layer = hub.KerasLayer(module,
                                         input_shape=(HEIGHT, WIDTH, CHANNELS))

我明白了:

ValueError: Importing a SavedModel with tf.saved_model.load requires a 'tags=' argument if there is more than one MetaGraph. Got 'tags=None', but there are 2 MetaGraphs in the SavedModel with tag sets [[], ['train']]. Pass a 'tags=' argument to load this SavedModel.

我试过了:

module = hub.Module("https://tfhub.dev/google/imagenet/resnet_v1_50/feature_vector/3",
                    tags={"train"})
feature_extractor_layer = hub.KerasLayer(module,
                                         input_shape=(HEIGHT, WIDTH, CHANNELS))

但是当我尝试保存模型时,我得到:

But when I try to save the model I get:

tf.keras.experimental.export_saved_model(model, tf_model_path)
# model.save(h5_model_path) # Same error

NotImplementedError: Can only generate a valid config for `hub.KerasLayer(handle, ...)`that uses a string `handle`.
Got `type(handle)`: <class 'tensorflow_hub.module.Module'>

教程这里

推荐答案

已经有一段时间了,但是假设您已经迁移到 TF2,这可以使用最新的模型版本轻松完成,如下所示:

It's been a while, but assuming you have migrated to the TF2, this can easily be accomplished with the most recent model version as follows:

import tensorflow as tf
import tensorflow_hub as hub

num_classes=10 # For example
m = tf.keras.Sequential([
    hub.KerasLayer("https://tfhub.dev/google/imagenet/resnet_v1_50/feature_vector/5", trainable=True)
    tf.keras.layers.Dense(num_classes, activation='softmax')
])
m.build([None, 224, 224, 3])  # Batch input shape.

# train as needed

m.save("/some/output/path")

如果这对您不起作用,请更新此问题.我相信您的问题是由 hub.Modulehub.KerasLayer 混合引起的.您使用的模型版本是 TF1 Hub 格式,因此在 TF1 中,它只能与 hub.Module 一起使用,而不能与 hub.KerasLayer 混合使用.在 TF2 中,hub.KerasLayer 可以直接从它们的 URL 加载 TF1 Hub 格式的模型以组合在更大的模型中,但它们不能被微调.

Please update this question if that doesn't work for you. I believe your issue arose from mixing hub.Module with hub.KerasLayer. The model version you were using was in TF1 Hub format, so within TF1 it is meant to be used exclusively with hub.Module, and not mixed with hub.KerasLayer. Within TF2, hub.KerasLayer can load TF1 Hub format models directly from their URL for composition in larger models, but they cannot be fine-tuned.

请参阅此兼容性指南了解更多信息

这篇关于将模型另存为 H5 或 SavedModel 时出现 TensorFlow Hub 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 21:40