简体   繁体   English

如何使用 tf.keras 加载模型?

[英]How to load a model with tf.keras?

import tensorflow as tf Tensorflow 2.0将 tensorflow 导入为 tf Tensorflow 2.0

i saw that i can load a model from tensorflow like this我看到我可以像这样从 tensorflow 加载模型

    image_model = tf.keras.applications.MobileNet(include_top=True, weights='imagenet', pooling='avg')

Now i want to be able to load models from local machine.现在我希望能够从本地机器加载模型。 My issue is that i can not find an pretrained model that works like this:我的问题是我找不到像这样工作的预训练模型:

    image_model = tf.keras.models.load_model('inception_v4.h5')  (i used h5  from here https://github.com/titu1994/Inception-v4/releases?fbclid=IwAR0pK_CZaB9RwA92nvawNOha6DjY5xI0vtkc9Ff5HTATcFT9x5vGYBUXt5Q  (first h5 model))

       future: <Task finished coro=<server_task.<locals>.server_work() done, 
    defined at ....\x.py:249> exception=ValueError('No model found in config file.')>
    Traceback (most recent call last):
      File "....\x.py", line 280, in server_work
        image_model, layers_indices = init(model_choice, layers_to_see)
      File "....\x.py", line 146, in init
        image_model = options[choice]() 
    #tf.keras.applications.MobileNetV2(include_top=True, weights='imagenet', 
    pooling='avg')
      File "....\x.py", line 119, in model_H5_model
        image_model = tf.keras.models.load_model('..../inception_v4.h5')
      File "...\Python\Python37\lib\site- 
   packages\tensorflow_core\python\keras\saving\save.py", line 146, in 
    load_model
        return hdf5_format.load_model_from_hdf5(filepath, custom_objects, compile)
      File "...\AppData\Local\Programs\Python\Python37\lib\site- 
   packages\tensorflow_core\python\keras\saving\hdf5_format.py", line 165, in load_model_from_hdf5
     raise ValueError('No model found in config file.')
    ValueError: No model found in config file.

I also tried with a model like this我也试过这样的模型

    image_model = tf.keras.models.load_model('model.pb') 
  File "....\x.py", line 280, in server_work
    image_model, layers_indices = init(model_choice, layers_to_see)
  File "....\x.py", line 146, in init
    image_model = options[choice]() 
   #tf.keras.applications.MobileNetV2(include_top=True, weights='imagenet', 
   pooling='avg')
     File "....\x.py", line 119, in model_H5_model
    image_model = tf.keras.models.load_model('.../model/inceptionv4.pb')
     File "...\AppData\Local\Programs\Python\Python37\lib\site- 
     packages\tensorflow_core\python\keras\saving\save.py", line 149, in 
     load_model
     loader_impl.parse_saved_model(filepath)
       File "...\AppData\Local\Programs\Python\Python37\lib\site- 
      packages\tensorflow_core\python\saved_model\loader_impl.py", line 83, in 
      parse_saved_model    
      constants.SAVED_MODEL_FILENAME_PB))
      OSError: SavedModel file does not exist at: 
       .../model/inceptionv4.pb/{saved_model.pbtxt|saved_model.pb}

What i also tried was smth like this:我也试过是这样的:

    image_model = tf.keras.applications.MobileNet(include_top=True, 
    weights='imagenet', pooling='avg')
    image_model.save('test') - >  when trying to save i receive this error

    File "\Python\Python37\lib\site- 
    packages\tensorflow_core\python\framework\func_graph.py", line 905, in 
    wrapper
    raise e.ag_error_metadata.to_exception(e)
    TypeError: in converted code:
       relative to ...\Programs\Python\Python37\lib\site-packages:

    tensorflow_core\python\eager\def_function.py:606 initialize_variables  *
        for v, init in initializer_map.items():
    tensorflow_core\python\autograph\impl\api.py:438 converted_call
        if not options.user_requested and 
    conversion.is_whitelisted_for_graph(f):
        m = tf_inspect.getmodule(o)
    tensorflow_core\python\util\tf_inspect.py:337 getmodule
        return _inspect.getmodule(object)
    pycallgraph\tracer.py:372 wrapper
        if rest not in cache:

    TypeError: unhashable type: 'ObjectIdentityDictionary'

    tf.keras.models.load_model('test_model')

I am wondering where i can find a h5 file or pb (pretrained model) that actually works with tf.keras.models.load_model()我想知道在哪里可以找到实际与 tf.keras.models.load_model() 一起使用的 h5 文件或 pb(预训练模型)

Based on the first comment :基于第一条评论:

future: <Task finished coro=<server_task.<locals>.server_work() done, defined at c:\Users\...\Desktop\PrivateStuff\...\...\xx.py:249> exception=TypeError("in converted code:\n    relative to C:\\Users\\...\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages:\n\n    tensorflow_core\\python\\eager\\def_function.py:606 initialize_variables  *\n        for v, init in initializer_map.items():\n    tensorflow_core\\python\\autograph\\impl\\api.py:438 converted_call\n        if not options.user_requested and conversion.is_whitelisted_for_graph(f):\n    tensorflow_core\\python\\autograph\\impl\\conversion.py:352 is_whitelisted_for_graph\n        m = tf_inspect.getmodule(o)\n    tensorflow_core\\python\\util\\tf_inspect.py:337 getmodule\n        return _inspect.getmodule(object)\n    pycallgraph\\tracer.py:372 wrapper\n        if rest not in cache:\n\n    TypeError: unhashable type: 'ObjectIdentityDictionary'\n")>
Traceback (most recent call last):
  File "c:\Users\...\Desktop\PrivateStuff\...\...\xx.py", line 280, in server_work
    image_model, layers_indices = init(model_choice, layers_to_see)
  File "c:\Users\...\Desktop\PrivateStuff\...\...\xx.py", line 146, in init
    image_model = options[choice]() #tf.keras.applications.MobileNetV2(include_top=True, weights='imagenet', pooling='avg')
  File "c:\Users\...\Desktop\PrivateStuff\...\...\xx.py", line 55, in model_VGG16
    image_model.save(r'c:\test')
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\engine\network.py", line 975, in save
    signatures, options)
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\saving\save.py", line 115, in save_model
    signatures, options)
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\saving\saved_model\save.py", line 74, in save
    save_lib.save(model, filepath, signatures, options)
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\saved_model\save.py", line 870, in save
    checkpoint_graph_view)
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\saved_model\signature_serialization.py", line 64, in find_function_to_export
    functions = saveable_view.list_functions(saveable_view.root)
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\saved_model\save.py", line 141, in list_functions
    self._serialization_cache)
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py", line 2422, in _list_functions_for_serialization
    .list_functions_for_serialization(serialization_cache))
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\saving\saved_model\base_serialization.py", line 91, in list_functions_for_serialization
    fns = self.functions_to_serialize(serialization_cache)
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\saving\saved_model\layer_serialization.py", line 79, in 
functions_to_serialize
    serialization_cache).functions_to_serialize)
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\saving\saved_model\layer_serialization.py", line 94, in 
_get_serialized_attributes
    serialization_cache)
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\saving\saved_model\model_serialization.py", line 47, in 
_get_serialized_attributes_internal
    default_signature = save_impl.default_save_signature(self.obj)
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\saving\saved_model\save_impl.py", line 206, in default_save_signature
    fn.get_concrete_function()
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\eager\def_function.py", line 777, in get_concrete_function    
    self._initialize_uninitialized_variables(initializer_map)
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\eager\def_function.py", line 616, in _initialize_uninitialized_variables
    return initialize_variables.get_concrete_function()()
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\eager\function.py", line 1891, in get_concrete_function       
    graph_function, args, kwargs = self._maybe_define_function(args, kwargs)
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\eager\function.py", line 2150, in _maybe_define_function      
    graph_function = self._create_graph_function(args, kwargs)
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\eager\function.py", line 2041, in _create_graph_function      
    capture_by_value=self._capture_by_value),
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\func_graph.py", line 915, in func_graph_from_py_func
    func_outputs = python_func(*func_args, **func_kwargs)
  File "C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\func_graph.py", line 905, in wrapper
    raise e.ag_error_metadata.to_exception(e)
TypeError: in converted code:
    relative to C:\Users\...\AppData\Local\Programs\Python\Python37\lib\site-packages:

    tensorflow_core\python\eager\def_function.py:606 initialize_variables  *
        for v, init in initializer_map.items():
    tensorflow_core\python\autograph\impl\api.py:438 converted_call
        if not options.user_requested and conversion.is_whitelisted_for_graph(f):
    tensorflow_core\python\autograph\impl\conversion.py:352 is_whitelisted_for_graph
        m = tf_inspect.getmodule(o)
    tensorflow_core\python\util\tf_inspect.py:337 getmodule
        return _inspect.getmodule(object)
    pycallgraph\tracer.py:372 wrapper
        if rest not in cache:

    TypeError: unhashable type: 'ObjectIdentityDictionary'

I copied your code to load MobileNet.我复制了您的代码以加载 MobileNet。 It works if your provide a full path to save the model.如果您提供保存模型的完整路径,它会起作用。 See code below.请参阅下面的代码。 Note when you load a model with weights='imagenet' the weights are set for the model trained on the imagenet data set.请注意,当您使用 weights='imagenet' 加载模型时,会为在 imagenet 数据集上训练的模型设置权重。 You don't need to load any weights.您不需要加载任何重量。 Now if you want to load weights for the model pre-trained on some other data set first instantiate the model as shown below.现在,如果您想为在其他一些数据集上预训练的模型加载权重,请首先实例化模型,如下所示。 Then load the specific weights using model.load_weights.然后使用 model.load_weights 加载特定的权重。

image_model = tf.keras.applications.MobileNet(include_top=True, 
    weights='imagenet', pooling='avg')
image_model.save(r'c:\test')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM