Migrar el flujo de trabajo del modelo guardado

Ver en TensorFlow.org Ejecutar en Google Colab Ver fuente en GitHub Descargar libreta

Una vez que haya migrado su modelo de los gráficos y las sesiones de TensorFlow 1 a las API de TensorFlow 2, como tf.function , tf.Module y tf.keras.Model , puede migrar el código de guardado y carga del modelo. Este cuaderno proporciona ejemplos de cómo puede guardar y cargar en el formato de modelo guardado en TensorFlow 1 y TensorFlow 2. Aquí hay una descripción general rápida de los cambios relacionados con la API para la migración de TensorFlow 1 a TensorFlow 2:

TensorFlow 1 Migración a TensorFlow 2
Ahorro tf.compat.v1.saved_model.Builder
tf.compat.v1.saved_model.simple_save
tf.saved_model.save
Keras: tf.keras.models.save_model
Cargando tf.compat.v1.saved_model.load tf.saved_model.load
Keras: tf.keras.models.load_model
Firmas : un conjunto de entrada
y tensores de salida que
se puede utilizar para ejecutar el
Generado usando las *.signature_def
(por ejemplo tf.compat.v1.saved_model.predict_signature_def )
Escriba una función tf. y tf.function usando el argumento de signatures
en tf.saved_model.save .
Clasificación
y regresión
:
tipos especiales de firmas
Generado con
tf.compat.v1.saved_model.classification_signature_def ,
tf.compat.v1.saved_model.regression_signature_def ,
y ciertas exportaciones de Estimator.
Estos dos tipos de firmas se eliminaron de TensorFlow 2.
Si la biblioteca de servicio requiere estos nombres de método,
tf.compat.v1.saved_model.signature_def_utils.MethodNameUpdater .

Para obtener una explicación más detallada del mapeo, consulte la sección Cambios de TensorFlow 1 a TensorFlow 2 a continuación.

Configuración

Los siguientes ejemplos muestran cómo exportar y cargar el mismo modelo ficticio de TensorFlow (definido como add_two a continuación) a un formato de modelo guardado mediante las API de TensorFlow 1 y TensorFlow 2. Comience configurando las funciones de importación y utilidad:

import tensorflow as tf
import tensorflow.compat.v1 as tf1
import shutil

def remove_dir(path):
  try:
    shutil.rmtree(path)
  except:
    pass

def add_two(input):
  return input + 2

TensorFlow 1: guardar y exportar un modelo guardado

En TensorFlow 1, utiliza las tf.compat.v1.saved_model.Builder , tf.compat.v1.saved_model.simple_save y tf.estimator.Estimator.export_saved_model para compilar, guardar y exportar el gráfico y la sesión de TensorFlow:

1. Guarde el gráfico como un modelo guardado con SavedModelBuilder

remove_dir("saved-model-builder")

with tf.Graph().as_default() as g:
  with tf1.Session() as sess:
    input = tf1.placeholder(tf.float32, shape=[])
    output = add_two(input)
    print("add two output: ", sess.run(output, {input: 3.}))

    # Save with SavedModelBuilder
    builder = tf1.saved_model.Builder('saved-model-builder')
    sig_def = tf1.saved_model.predict_signature_def(
        inputs={'input': input},
        outputs={'output': output})
    builder.add_meta_graph_and_variables(
        sess, tags=["serve"], signature_def_map={
            tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY: sig_def
    })
    builder.save()
add two output:  5.0
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.7/site-packages/tensorflow/python/saved_model/signature_def_utils_impl.py:208: build_tensor_info (from tensorflow.python.saved_model.utils_impl) is deprecated and will be removed in a future version.
Instructions for updating:
This function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.utils.build_tensor_info or tf.compat.v1.saved_model.build_tensor_info.
INFO:tensorflow:No assets to save.
INFO:tensorflow:No assets to write.
INFO:tensorflow:SavedModel written to: saved-model-builder/saved_model.pb
!saved_model_cli run --dir simple-save --tag_set serve \
 --signature_def serving_default --input_exprs input=10
Traceback (most recent call last):
  File "/tmpfs/src/tf_docs_env/bin/saved_model_cli", line 8, in <module>
    sys.exit(main())
  File "/tmpfs/src/tf_docs_env/lib/python3.7/site-packages/tensorflow/python/tools/saved_model_cli.py", line 1211, in main
    args.func(args)
  File "/tmpfs/src/tf_docs_env/lib/python3.7/site-packages/tensorflow/python/tools/saved_model_cli.py", line 769, in run
    init_tpu=args.init_tpu, tf_debug=args.tf_debug)
  File "/tmpfs/src/tf_docs_env/lib/python3.7/site-packages/tensorflow/python/tools/saved_model_cli.py", line 417, in run_saved_model_with_feed_dict
    tag_set)
  File "/tmpfs/src/tf_docs_env/lib/python3.7/site-packages/tensorflow/python/tools/saved_model_utils.py", line 117, in get_meta_graph_def
    saved_model = read_saved_model(saved_model_dir)
  File "/tmpfs/src/tf_docs_env/lib/python3.7/site-packages/tensorflow/python/tools/saved_model_utils.py", line 55, in read_saved_model
    raise IOError("SavedModel file does not exist at: %s" % saved_model_dir)
OSError: SavedModel file does not exist at: simple-save

2. Cree un modelo guardado para servir

remove_dir("simple-save")

with tf.Graph().as_default() as g:
  with tf1.Session() as sess:
    input = tf1.placeholder(tf.float32, shape=[])
    output = add_two(input)
    print("add_two output: ", sess.run(output, {input: 3.}))

    tf1.saved_model.simple_save(
        sess, 'simple-save',
        inputs={'input': input},
        outputs={'output': output})
add_two output:  5.0
WARNING:tensorflow:From /tmp/ipykernel_26511/250978412.py:12: simple_save (from tensorflow.python.saved_model.simple_save) is deprecated and will be removed in a future version.
Instructions for updating:
This function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.simple_save.
INFO:tensorflow:Assets added to graph.
INFO:tensorflow:No assets to write.
INFO:tensorflow:SavedModel written to: simple-save/saved_model.pb
!saved_model_cli run --dir simple-save --tag_set serve \
 --signature_def serving_default --input_exprs input=10
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.7/site-packages/tensorflow/python/tools/saved_model_cli.py:453: load (from tensorflow.python.saved_model.loader_impl) is deprecated and will be removed in a future version.
Instructions for updating:
This function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.loader.load or tf.compat.v1.saved_model.load. There will be a new function for importing SavedModels in Tensorflow 2.0.
INFO:tensorflow:Saver not created because there are no variables in the graph to restore
INFO:tensorflow:The specified SavedModel has no variables; no checkpoints were restored.
Result for output key output:
12.0

3. Exporte el gráfico de inferencia del Estimador como un modelo guardado

En la definición del Estimator model_fn (definido a continuación), puede definir firmas en su modelo devolviendo export_outputs en tf.estimator.EstimatorSpec . Hay diferentes tipos de salidas:

Estos producirán tipos de firma de clasificación, regresión y predicción, respectivamente.

Cuando el estimador se exporta con tf.estimator.Estimator.export_saved_model , estas firmas se guardarán con el modelo.

def model_fn(features, labels, mode):
  output = add_two(features['input'])
  step = tf1.train.get_global_step()
  return tf.estimator.EstimatorSpec(
      mode,
      predictions=output,
      train_op=step.assign_add(1),
      loss=tf.constant(0.),
      export_outputs={
          tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY: \
          tf.estimator.export.PredictOutput({'output': output})})
est = tf.estimator.Estimator(model_fn, 'estimator-checkpoints')

# Train for one step to create a checkpoint.
def train_fn():
  return tf.data.Dataset.from_tensors({'input': 3.})
est.train(train_fn, steps=1)

# This utility function `build_raw_serving_input_receiver_fn` takes in raw
# tensor features and builds an "input serving receiver function", which
# creates placeholder inputs to the model.
serving_input_fn = tf.estimator.export.build_raw_serving_input_receiver_fn(
    {'input': tf.constant(3.)})  # Pass in a dummy input batch.
estimator_path = est.export_saved_model('exported-estimator', serving_input_fn)

# Estimator's export_saved_model creates a time stamped directory. Move this
# to a set path so it can be inspected with `saved_model_cli` in the cell below.
!rm -rf estimator-model
import shutil
shutil.move(estimator_path, 'estimator-model')
INFO:tensorflow:Using default config.
INFO:tensorflow:Using config: {'_model_dir': 'estimator-checkpoints', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true
graph_options {
  rewrite_options {
    meta_optimizer_iterations: ONE
  }
}
, '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_checkpoint_save_graph_def': True, '_service': None, '_cluster_spec': ClusterSpec({}), '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1}
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.7/site-packages/tensorflow/python/training/training_util.py:401: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.
Instructions for updating:
Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.
INFO:tensorflow:Calling model_fn.
INFO:tensorflow:Done calling model_fn.
INFO:tensorflow:Create CheckpointSaverHook.
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Running local_init_op.
INFO:tensorflow:Done running local_init_op.
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 0...
INFO:tensorflow:Saving checkpoints for 0 into estimator-checkpoints/model.ckpt.
INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 0...
INFO:tensorflow:loss = 0.0, step = 1
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 1...
INFO:tensorflow:Saving checkpoints for 1 into estimator-checkpoints/model.ckpt.
INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 1...
INFO:tensorflow:Loss for final step: 0.0.
INFO:tensorflow:Calling model_fn.
INFO:tensorflow:Done calling model_fn.
INFO:tensorflow:Signatures INCLUDED in export for Classify: None
INFO:tensorflow:Signatures INCLUDED in export for Regress: None
INFO:tensorflow:Signatures INCLUDED in export for Predict: ['serving_default']
INFO:tensorflow:Signatures INCLUDED in export for Train: None
INFO:tensorflow:Signatures INCLUDED in export for Eval: None
INFO:tensorflow:Restoring parameters from estimator-checkpoints/model.ckpt-1
INFO:tensorflow:Assets added to graph.
INFO:tensorflow:No assets to write.
INFO:tensorflow:SavedModel written to: exported-estimator/temp-1636162129/saved_model.pb
'estimator-model'
!saved_model_cli run --dir estimator-model --tag_set serve \
 --signature_def serving_default --input_exprs input=[10]
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.7/site-packages/tensorflow/python/tools/saved_model_cli.py:453: load (from tensorflow.python.saved_model.loader_impl) is deprecated and will be removed in a future version.
Instructions for updating:
This function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.loader.load or tf.compat.v1.saved_model.load. There will be a new function for importing SavedModels in Tensorflow 2.0.
INFO:tensorflow:Restoring parameters from estimator-model/variables/variables
Result for output key output:
[12.]

TensorFlow 2: guardar y exportar un modelo guardado

Guarde y exporte un modelo guardado definido con tf.Module

Para exportar su modelo en TensorFlow 2, debe definir un tf.Module o un tf.keras.Model para contener todas las variables y funciones de su modelo. Luego, puede llamar a tf.saved_model.save para crear un modelo guardado. Consulte Guardar un modelo personalizado en la guía de formato Uso del modelo guardado para obtener más información.

class MyModel(tf.Module):
  @tf.function
  def __call__(self, input):
    return add_two(input)

model = MyModel()

@tf.function
def serving_default(input):
  return {'output': model(input)}

signature_function = serving_default.get_concrete_function(
    tf.TensorSpec(shape=[], dtype=tf.float32))
tf.saved_model.save(
    model, 'tf2-save', signatures={
        tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature_function})
INFO:tensorflow:Assets written to: tf2-save/assets
2021-11-06 01:28:53.105391: W tensorflow/python/util/util.cc:368] Sets are not currently considered sequences, but this may change in the future, so consider avoiding using them.
!saved_model_cli run --dir tf2-save --tag_set serve \
 --signature_def serving_default --input_exprs input=10
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.7/site-packages/tensorflow/python/tools/saved_model_cli.py:453: load (from tensorflow.python.saved_model.loader_impl) is deprecated and will be removed in a future version.
Instructions for updating:
This function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.loader.load or tf.compat.v1.saved_model.load. There will be a new function for importing SavedModels in Tensorflow 2.0.
INFO:tensorflow:Restoring parameters from tf2-save/variables/variables
Result for output key output:
12.0

Guarde y exporte un modelo guardado definido con Keras

Las API de Keras para guardar y exportar Mode.save o tf.keras.models.save_model pueden exportar un modelo guardado desde un tf.keras.Model . Consulte Guardar y cargar modelos de Keras para obtener más detalles.

inp = tf.keras.Input(3)
out = add_two(inp)
model = tf.keras.Model(inputs=inp, outputs=out)

@tf.function(input_signature=[tf.TensorSpec(shape=[], dtype=tf.float32)])
def serving_default(input):
  return {'output': model(input)}

model.save('keras-model', save_format='tf', signatures={
        tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY: serving_default})
WARNING:tensorflow:Compiled the loaded model, but the compiled metrics have yet to be built. `model.compile_metrics` will be empty until you train or evaluate the model.
WARNING:tensorflow:Model was constructed with shape (None, 3) for input KerasTensor(type_spec=TensorSpec(shape=(None, 3), dtype=tf.float32, name='input_1'), name='input_1', description="created by layer 'input_1'"), but it was called on an input with incompatible shape ().
INFO:tensorflow:Assets written to: keras-model/assets
!saved_model_cli run --dir keras-model --tag_set serve \
 --signature_def serving_default --input_exprs input=10
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.7/site-packages/tensorflow/python/tools/saved_model_cli.py:453: load (from tensorflow.python.saved_model.loader_impl) is deprecated and will be removed in a future version.
Instructions for updating:
This function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.loader.load or tf.compat.v1.saved_model.load. There will be a new function for importing SavedModels in Tensorflow 2.0.
INFO:tensorflow:Restoring parameters from keras-model/variables/variables
Result for output key output:
12.0

Cargando un modelo guardado

Un modelo guardado guardado con cualquiera de las API anteriores se puede cargar con las API de TensorFlow 1 o TensorFlow.

Un modelo guardado de TensorFlow 1 generalmente se puede usar para inferencias cuando se carga en TensorFlow 2, pero el entrenamiento (generar gradientes) solo es posible si el modelo guardado contiene variables de recursos . Puede verificar el tipo de variable de las variables; si el tipo de variable contiene "_ref", entonces es una variable de referencia.

Un modelo guardado de TensorFlow 2 se puede cargar y ejecutar desde TensorFlow 1 siempre que el modelo guardado se guarde con firmas.

Las siguientes secciones contienen ejemplos de código que muestran cómo cargar los modelos guardados guardados en las secciones anteriores y llamar a la firma exportada.

TensorFlow 1: carga un modelo guardado con tf.saved_model.load

En TensorFlow 1, puede importar un modelo guardado directamente en el gráfico y la sesión actuales mediante tf.saved_model.load . Puede llamar a Session.run en los nombres de entrada y salida del tensor:

def load_tf1(path, input):
  print('Loading from', path)
  with tf.Graph().as_default() as g:
    with tf1.Session() as sess:
      meta_graph = tf1.saved_model.load(sess, ["serve"], path)
      sig_def = meta_graph.signature_def[tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY]
      input_name = sig_def.inputs['input'].name
      output_name = sig_def.outputs['output'].name
      print('  Output with input', input, ': ', 
            sess.run(output_name, feed_dict={input_name: input}))

load_tf1('saved-model-builder', 5.)
load_tf1('simple-save', 5.)
load_tf1('estimator-model', [5.])  # Estimator's input must be batched.
load_tf1('tf2-save', 5.)
load_tf1('keras-model', 5.)
Loading from saved-model-builder
WARNING:tensorflow:From /tmp/ipykernel_26511/1548963983.py:5: load (from tensorflow.python.saved_model.loader_impl) is deprecated and will be removed in a future version.
Instructions for updating:
This function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.loader.load or tf.compat.v1.saved_model.load. There will be a new function for importing SavedModels in Tensorflow 2.0.
INFO:tensorflow:Saver not created because there are no variables in the graph to restore
INFO:tensorflow:The specified SavedModel has no variables; no checkpoints were restored.
  Output with input 5.0 :  7.0
Loading from simple-save
INFO:tensorflow:Saver not created because there are no variables in the graph to restore
INFO:tensorflow:The specified SavedModel has no variables; no checkpoints were restored.
  Output with input 5.0 :  7.0
Loading from estimator-model
INFO:tensorflow:Restoring parameters from estimator-model/variables/variables
  Output with input [5.0] :  [7.]
Loading from tf2-save
INFO:tensorflow:Restoring parameters from tf2-save/variables/variables
  Output with input 5.0 :  7.0
Loading from keras-model
INFO:tensorflow:Restoring parameters from keras-model/variables/variables
  Output with input 5.0 :  7.0

TensorFlow 2: Cargue un modelo guardado con tf.saved_model

En TensorFlow 2, los objetos se cargan en un objeto de Python que almacena las variables y funciones. Esto es compatible con los modelos guardados de TensorFlow 1.

Consulte los documentos de la API tf.saved_model.load y la sección Carga y uso de un modelo personalizado de la guía de formato Uso del modelo guardado para obtener más información.

def load_tf2(path, input):
  print('Loading from', path)
  loaded = tf.saved_model.load(path)
  out = loaded.signatures[tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY](
      tf.constant(input))['output']
  print('  Output with input', input, ': ', out)

load_tf2('saved-model-builder', 5.)
load_tf2('simple-save', 5.)
load_tf2('estimator-model', [5.])  # Estimator's input must be batched.
load_tf2('tf2-save', 5.)
load_tf2('keras-model', 5.)
Loading from saved-model-builder
INFO:tensorflow:Saver not created because there are no variables in the graph to restore
  Output with input 5.0 :  tf.Tensor(7.0, shape=(), dtype=float32)
Loading from simple-save
INFO:tensorflow:Saver not created because there are no variables in the graph to restore
  Output with input 5.0 :  tf.Tensor(7.0, shape=(), dtype=float32)
Loading from estimator-model
  Output with input [5.0] :  tf.Tensor([7.], shape=(1,), dtype=float32)
Loading from tf2-save
  Output with input 5.0 :  tf.Tensor(7.0, shape=(), dtype=float32)
Loading from keras-model
  Output with input 5.0 :  tf.Tensor(7.0, shape=(), dtype=float32)

Los modelos guardados con la API de TensorFlow 2 también pueden acceder a tf.function y variables que están adjuntas al modelo (en lugar de las exportadas como firmas). Por ejemplo:

loaded = tf.saved_model.load('tf2-save')
print('restored __call__:', loaded.__call__)
print('output with input 5.', loaded(5))
restored __call__: <tensorflow.python.saved_model.function_deserialization.RestoredFunction object at 0x7f30cc940990>
output with input 5. tf.Tensor(7.0, shape=(), dtype=float32)

TensorFlow 2: carga un modelo guardado con Keras

La API de carga de Keras, tf.keras.models.load_model , le permite volver a cargar un modelo guardado en un objeto de modelo de Keras. Tenga en cuenta que esto solo le permite cargar modelos guardados guardados con Keras ( Model.save o tf.keras.models.save_model ).

Los modelos guardados con tf.saved_model.save deben cargarse con tf.saved_model.load . Puede cargar un modelo de Keras guardado con Model.save usando tf.saved_model.load pero solo obtendrá el gráfico de TensorFlow. Consulte los documentos de la API tf.keras.models.load_model y la guía Guardar y cargar modelos de Keras para obtener más información.

loaded_model = tf.keras.models.load_model('keras-model')
loaded_model.predict_on_batch(tf.constant([1, 3, 4]))
WARNING:tensorflow:No training configuration found in save file, so the model was *not* compiled. Compile it manually.
WARNING:tensorflow:Model was constructed with shape (None, 3) for input KerasTensor(type_spec=TensorSpec(shape=(None, 3), dtype=tf.float32, name='input_1'), name='input_1', description="created by layer 'input_1'"), but it was called on an input with incompatible shape (3,).
array([3., 5., 6.], dtype=float32)

GraphDef y MetaGraphDef

No existe una forma sencilla de cargar un GraphDef o MetaGraphDef sin procesar en TF2. Sin embargo, puede convertir el código TF1 que importa el gráfico en una función concrete_function de TF2 mediante v1.wrap_function .

Primero, guarde un MetaGraphDef:

# Save a simple multiplication computation:
with tf.Graph().as_default() as g:
  x = tf1.placeholder(tf.float32, shape=[], name='x')
  v = tf.Variable(3.0, name='v')
  y = tf.multiply(x, v, name='y')
  with tf1.Session() as sess:
    sess.run(v.initializer)
    print(sess.run(y, feed_dict={x: 5}))
    s = tf1.train.Saver()
    s.export_meta_graph('multiply.pb', as_text=True)
    s.save(sess, 'multiply_values.ckpt')
15.0

Con las API de TF1, puede usar tf1.train.import_meta_graph para importar el gráfico y restaurar los valores:

with tf.Graph().as_default() as g:
  meta = tf1.train.import_meta_graph('multiply.pb')
  x = g.get_tensor_by_name('x:0')
  y = g.get_tensor_by_name('y:0')
  with tf1.Session() as sess:
    meta.restore(sess, 'multiply_values.ckpt')
    print(sess.run(y, feed_dict={x: 5}))
INFO:tensorflow:Restoring parameters from multiply_values.ckpt
15.0

No hay API de TF2 para cargar el gráfico, pero aún puede importarlo a una función concreta que se puede ejecutar en modo ansioso:

def import_multiply():
  # Any graph-building code is allowed here.
  tf1.train.import_meta_graph('multiply.pb')

# Creates a tf.function with all the imported elements in the function graph.
wrapped_import = tf1.wrap_function(import_multiply, [])
import_graph = wrapped_import.graph
x = import_graph.get_tensor_by_name('x:0')
y = import_graph.get_tensor_by_name('y:0')

# Restore the variable values.
tf1.train.Saver(wrapped_import.variables).restore(
    sess=None, save_path='multiply_values.ckpt')

# Create a concrete function by pruning the wrap_function (similar to sess.run).
multiply_fn = wrapped_import.prune(feeds=x, fetches=y)

# Run this function
multiply_fn(tf.constant(5.))  # inputs to concrete functions must be Tensors.
WARNING:tensorflow:Saver is deprecated, please switch to tf.train.Checkpoint or tf.keras.Model.save_weights for training checkpoints. When executing eagerly variables do not necessarily have unique names, and so the variable.name-based lookups Saver performs are error-prone.
INFO:tensorflow:Restoring parameters from multiply_values.ckpt
<tf.Tensor: shape=(), dtype=float32, numpy=15.0>

Cambios de TensorFlow 1 a TensorFlow 2

Esta sección enumera los términos clave para guardar y cargar de TensorFlow 1, sus equivalentes de TensorFlow 2 y lo que ha cambiado.

Modelo guardado

SavedModel es un formato que almacena un programa TensorFlow completo con parámetros y cálculos. Contiene firmas utilizadas por las plataformas de servicio para ejecutar el modelo.

El formato de archivo en sí no ha cambiado significativamente, por lo que los modelos guardados se pueden cargar y servir con las API de TensorFlow 1 o TensorFlow 2.

Diferencias entre TensorFlow 1 y TensorFlow 2

Los casos de uso de servicio e inferencia no se han actualizado en TensorFlow 2, además de los cambios de la API: la mejora se introdujo en la capacidad de reutilizar y componer modelos cargados desde SavedModel.

En TensorFlow 2, el programa está representado por objetos como tf.Variable , tf.Module o modelos Keras de nivel superior ( tf.keras.Model ) y capas ( tf.keras.layers ). Ya no hay variables globales que tengan valores almacenados en una sesión, y el gráfico ahora existe en diferentes tf.function s. En consecuencia, durante la exportación de un modelo, SavedModel guarda cada componente y los gráficos de funciones por separado.

Cuando escribe un programa de TensorFlow con las API de Python de TensorFlow, debe crear un objeto para administrar las variables, las funciones y otros recursos. Por lo general, esto se logra mediante el uso de las API de Keras, pero también puede compilar el objeto creando o subclasificando tf.Module .

Los modelos Keras ( tf.keras.Model ) y tf.Module automáticamente las variables y funciones asociadas a ellos. SavedModel guarda estas conexiones entre módulos, variables y funciones, para que puedan restaurarse al cargar.

firmas

Las firmas son los puntos finales de un modelo guardado: le dicen al usuario cómo ejecutar el modelo y qué entradas se necesitan.

En TensorFlow 1, las firmas se crean enumerando los tensores de entrada y salida. En TensorFlow 2, las firmas se generan pasando funciones concretas . (Lea más sobre las funciones de TensorFlow en la Introducción a los gráficos y la guía tf.function ). En resumen, una función concreta se genera a partir de una tf.function :

# Option 1: Specify an input signature.
@tf.function(input_signature=[...])
def fn(...):
  ...
  return outputs

tf.saved_model.save(model, path, signatures={
    'name': fn
})
# Option 2: Call `get_concrete_function`
@tf.function
def fn(...):
  ...
  return outputs

tf.saved_model.save(model, path, signatures={
    'name': fn.get_concrete_function(...)
})

Session.run

En TensorFlow 1, puede llamar a Session.run con el gráfico importado siempre que conozca los nombres de los tensores. Esto le permite recuperar los valores de las variables restauradas o ejecutar partes del modelo que no se exportaron en las firmas.

En TensorFlow 2, puede acceder directamente a una variable, como una matriz de pesos ( kernel ):

model = tf.Module()
model.dense_layer = tf.keras.layers.Dense(...)
tf.saved_model.save('my_saved_model')
loaded = tf.saved_model.load('my_saved_model')
loaded.dense_layer.kernel

o llame a tf.function s adjuntas al objeto modelo: por ejemplo, loaded.__call__ .

A diferencia de TF1, no hay forma de extraer partes de una función y acceder a valores intermedios. Debe exportar toda la funcionalidad necesaria en el objeto guardado.

Notas de migración de TensorFlow Serving

SavedModel se creó originalmente para trabajar con TensorFlow Serving . Esta plataforma ofrece diferentes tipos de solicitudes de predicción: clasificar, retroceder y predecir.

La API de TensorFlow 1 te permite crear este tipo de firmas con las utilidades:

La clasificación ( classification_signature_def ) y la regresión ( regression_signature_def ) restringen las entradas y salidas, por lo que las entradas deben ser un tf.Example y las salidas deben ser classes , scores o prediction . Mientras tanto, la firma de predicción ( predict_signature_def ) no tiene restricciones.

Los modelos guardados exportados con la API de TensorFlow 2 son compatibles con TensorFlow Serving, pero solo contendrán firmas de predicción. Se han eliminado las firmas de clasificación y regresión.

Si requiere el uso de las firmas de clasificación y regresión, puede modificar el modelo guardado exportado usando tf.compat.v1.saved_model.signature_def_utils.MethodNameUpdater .

Próximos pasos

Para obtener más información sobre los modelos guardados en TensorFlow 2, consulte las siguientes guías:

Si está utilizando TensorFlow Hub, estas guías pueden resultarle útiles: