Home Ciencia y Tecnología Consejos para escribir código limpio en TensorFlow 2

Consejos para escribir código limpio en TensorFlow 2

30
0

Descripción common del contenido

  • Descripción common
  • Configuración
  • Recomendaciones para TensorFlow Idiomatic 2
  • Refactorizar su código en módulos más pequeños
  • Ajuste la tasa de aprendizaje predeterminada para algunos tf.keras.optimizers
  • Use capas TF.Modules y Keras para administrar variables
  • Combinar tf.knowledge.datasets y tf.función
  • Use bucles de entrenamiento keras
  • Personalice la capacitación y escriba su propio bucle
  • Aproveche la función de TF con el flujo de management de Python
  • Métricas y pérdidas de estilo nuevo
  • Depuración
  • No guarde tf.tensors en sus objetos
  • Recursos y lecturas adicionales

Descripción common

Esta guía proporciona una lista de las mejores prácticas para escribir código utilizando TensorFlow 2 (TF2), está escrita para usuarios que recientemente se han cambiado de TensorFlow 1 (TF1). Consulte la sección de migración de la guía para obtener más información sobre la migración de su código TF1 a TF2.

Configuración

Importe TensorFlow y otras dependencias para los ejemplos de esta guía.

import tensorflow as tf
import tensorflow_datasets as tfds
2023-10-04 01:22:53.526066: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN manufacturing facility: Making an attempt to register manufacturing facility for plugin cuDNN when one has already been registered
2023-10-04 01:22:53.526110: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT manufacturing facility: Making an attempt to register manufacturing facility for plugin cuFFT when one has already been registered
2023-10-04 01:22:53.526158: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS manufacturing facility: Making an attempt to register manufacturing facility for plugin cuBLAS when one has already been registered

Recomendaciones para TensorFlow Idiomatic 2

Refactorizar su código en módulos más pequeños

Una buena práctica es refactorizar su código en funciones más pequeñas que se denominan según sea necesario. Para el mejor rendimiento, debe intentar decorar los bloques de cálculo más grandes que puede en un tf.operate (Tenga en cuenta que las funciones de pitón anidadas llamadas por un tf.operate no requiere sus propias decoraciones separadas, a menos que desee usar diferentes jit_compile Configuración para el tf.operate). Dependiendo de su caso de uso, estos podrían ser múltiples pasos de entrenamiento o incluso todo su circuito de entrenamiento. Para casos de uso de inferencia, podría ser un solo modelo de avance de modelo.

Ajuste la tasa de aprendizaje predeterminada para algunos tf.keras.optimizers

Algunos optimizadores de Keras tienen diferentes tasas de aprendizaje en TF2. Si ve un cambio en el comportamiento de convergencia para sus modelos, verifique las tasas de aprendizaje predeterminadas.

No hay cambios para optimizers.SGD, optimizers.Adamo optimizers.RMSprop.

Las siguientes tasas de aprendizaje predeterminadas han cambiado:

  • optimizers.Adagrad de 0.01 a 0.001
  • optimizers.Adadelta de 1.0 a 0.001
  • optimizers.Adamax de 0.002 a 0.001
  • optimizers.Nadam de 0.002 a 0.001

Usar tf.Modulecapas sy keras para administrar variables

tf.Modulearea tf.keras.layers.Layers Ofrezca lo conveniente variables y trainable_variables Propiedades, que recurre recursivamente todas las variables dependientes. Esto facilita la gestión de las variables localmente a donde se están utilizando.

Las capas/modelos de Keras heredan de tf.prepare.Checkpointable y están integrados con @tf.operatelo que hace posible directamente el punto de management o exportar modelos guardados de los objetos Keras. No necesariamente tienes que usar keras ‘ Mannequin.match API para aprovechar estas integraciones.

Lea la sección sobre el aprendizaje de transferencia y el ajuste fino en la Guía Keras para aprender a recopilar un subconjunto de variables relevantes usando Keras.

Combinar tf.knowledge.Datasetarea tf.operate

El paquete de conjuntos de datos TensorFlow (tfds) contiene utilidades para cargar conjuntos de datos predefinidos como tf.knowledge.Dataset objetos. Para este ejemplo, puede cargar el conjunto de datos MNIST usando tfds:

datasets, data = tfds.load(identify='mnist', with_info=True, as_supervised=True)
mnist_train, mnist_test = datasets['train'], datasets['test']
2023-10-04 01:22:57.406511: W tensorflow/core/common_runtime/gpu/gpu_device.cc:2211] Can not dlopen some GPU libraries. Please ensure that the lacking libraries talked about above are put in correctly if you want to make use of GPU. Observe the information at  for how you can obtain and setup the required libraries on your platform.
Skipping registering GPU units...

Luego put together los datos para la capacitación:

  • Re-escala cada imagen.
  • Baraja el orden de los ejemplos.
  • Recopile lotes de imágenes y etiquetas.
BUFFER_SIZE = 10 # Use a a lot bigger worth for actual code
BATCH_SIZE = 64
NUM_EPOCHS = 5


def scale(picture, label):
  picture = tf.solid(picture, tf.float32)
  picture /= 255

  return picture, label

Para mantener el ejemplo corto, recorte el conjunto de datos para que solo devuelva 5 lotes:

train_data = mnist_train.map(scale).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
test_data = mnist_test.map(scale).batch(BATCH_SIZE)

STEPS_PER_EPOCH = 5

train_data = train_data.take(STEPS_PER_EPOCH)
test_data = test_data.take(STEPS_PER_EPOCH)
image_batch, label_batch = subsequent(iter(train_data))
2023-10-04 01:22:58.048011: W tensorflow/core/kernels/knowledge/cache_dataset_ops.cc:854] The calling iterator didn't totally learn the dataset being cached. With a view to keep away from sudden truncation of the dataset, the partially cached contents of the dataset  can be discarded. This will occur if in case you have an enter pipeline just like `dataset.cache().take(okay).repeat()`. You need to use `dataset.take(okay).cache().repeat()` as an alternative.

Use la iteración de Python common para iterar sobre los datos de entrenamiento que se ajustan a la memoria. De lo contrario, tf.knowledge.Dataset es la mejor manera de transmitir datos de capacitación del disco. Los conjuntos de datos son iterables (no iteradores), y funcionan al igual que otros Python Iterables en una ejecución ansiosa. Puede utilizar completamente las funciones de transmisión/transmisión del conjunto de datos del conjunto de datos envolviendo su código en tf.operateque reemplaza la iteración de Python con las operaciones de gráficos equivalentes utilizando autógrafos.

@tf.operate
def prepare(mannequin, dataset, optimizer):
  for x, y in dataset:
    with tf.GradientTape() as tape:
      # coaching=True is simply wanted if there are layers with totally different
      # habits throughout coaching versus inference (e.g. Dropout).
      prediction = mannequin(x, coaching=True)
      loss = loss_fn(prediction, y)
    gradients = tape.gradient(loss, mannequin.trainable_variables)
    optimizer.apply_gradients(zip(gradients, mannequin.trainable_variables))

Si usas los keras Mannequin.match API, no tendrá que preocuparse por la iteración del conjunto de datos.

mannequin.compile(optimizer=optimizer, loss=loss_fn)
mannequin.match(dataset)

Use bucles de entrenamiento keras

Si no necesita un management de bajo nivel de su proceso de capacitación, utilizando el Keras ‘incorporado match, considery predict se recomienda métodos. Estos métodos proporcionan una interfaz uniforme para capacitar al modelo independientemente de la implementación (secuencial, funcional o subcalse).

Las ventajas de estos métodos incluyen:

  • Aceptan matrices numpy, generadores de pitón y, tf.knowledge.Datasets.
  • Aplican regularización y pérdidas de activación automáticamente.
  • Apoyan tf.distribute donde el código de entrenamiento sigue siendo el mismo independientemente de la configuración de {hardware}.
  • Apoyan a los llamados arbitrarios como pérdidas y métricas.
  • Admiten devoluciones de llamada como tf.keras.callbacks.TensorBoardy devoluciones de llamada personalizadas.
  • Son corrientes, utilizando automáticamente gráficos TensorFlow.

Aquí hay un ejemplo de entrenamiento de un modelo que usa un Dataset. Para obtener detalles sobre cómo funciona esto, consulte los tutoriales.

mannequin = tf.keras.Sequential([
    tf.keras.layers.Conv2D(32, 3, activation='relu',
                           kernel_regularizer=tf.keras.regularizers.l2(0.02),
                           input_shape=(28, 28, 1)),
    tf.keras.layers.MaxPooling2D(),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dropout(0.1),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.BatchNormalization(),
    tf.keras.layers.Dense(10)
])

# Mannequin is the complete mannequin w/o customized layers
mannequin.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

mannequin.match(train_data, epochs=NUM_EPOCHS)
loss, acc = mannequin.consider(test_data)

print("Loss {}, Accuracy {}".format(loss, acc))
Epoch 1/5
5/5 [==============================] - 2s 44ms/step - loss: 1.6644 - accuracy: 0.4906
Epoch 2/5
2023-10-04 01:22:59.569439: W tensorflow/core/kernels/knowledge/cache_dataset_ops.cc:854] The calling iterator didn't totally learn the dataset being cached. With a view to keep away from sudden truncation of the dataset, the partially cached contents of the dataset  can be discarded. This will occur if in case you have an enter pipeline just like `dataset.cache().take(okay).repeat()`. You need to use `dataset.take(okay).cache().repeat()` as an alternative.
5/5 [==============================] - 0s 9ms/step - loss: 0.5173 - accuracy: 0.9062
Epoch 3/5
2023-10-04 01:23:00.062308: W tensorflow/core/kernels/knowledge/cache_dataset_ops.cc:854] The calling iterator didn't totally learn the dataset being cached. With a view to keep away from sudden truncation of the dataset, the partially cached contents of the dataset  can be discarded. This will occur if in case you have an enter pipeline just like `dataset.cache().take(okay).repeat()`. You need to use `dataset.take(okay).cache().repeat()` as an alternative.
5/5 [==============================] - 0s 9ms/step - loss: 0.3418 - accuracy: 0.9469
Epoch 4/5
2023-10-04 01:23:00.384057: W tensorflow/core/kernels/knowledge/cache_dataset_ops.cc:854] The calling iterator didn't totally learn the dataset being cached. With a view to keep away from sudden truncation of the dataset, the partially cached contents of the dataset  can be discarded. This will occur if in case you have an enter pipeline just like `dataset.cache().take(okay).repeat()`. You need to use `dataset.take(okay).cache().repeat()` as an alternative.
5/5 [==============================] - 0s 8ms/step - loss: 0.2707 - accuracy: 0.9781
Epoch 5/5
2023-10-04 01:23:00.766486: W tensorflow/core/kernels/knowledge/cache_dataset_ops.cc:854] The calling iterator didn't totally learn the dataset being cached. With a view to keep away from sudden truncation of the dataset, the partially cached contents of the dataset  can be discarded. This will occur if in case you have an enter pipeline just like `dataset.cache().take(okay).repeat()`. You need to use `dataset.take(okay).cache().repeat()` as an alternative.
5/5 [==============================] - 0s 8ms/step - loss: 0.2195 - accuracy: 0.9812
2023-10-04 01:23:01.120149: W tensorflow/core/kernels/knowledge/cache_dataset_ops.cc:854] The calling iterator didn't totally learn the dataset being cached. With a view to keep away from sudden truncation of the dataset, the partially cached contents of the dataset  can be discarded. This will occur if in case you have an enter pipeline just like `dataset.cache().take(okay).repeat()`. You need to use `dataset.take(okay).cache().repeat()` as an alternative.
5/5 [==============================] - 0s 4ms/step - loss: 1.6036 - accuracy: 0.6250
Loss 1.6036441326141357, Accuracy 0.625
2023-10-04 01:23:01.572685: W tensorflow/core/kernels/knowledge/cache_dataset_ops.cc:854] The calling iterator didn't totally learn the dataset being cached. With a view to keep away from sudden truncation of the dataset, the partially cached contents of the dataset  can be discarded. This will occur if in case you have an enter pipeline just like `dataset.cache().take(okay).repeat()`. You need to use `dataset.take(okay).cache().repeat()` as an alternative.

Personalice la capacitación y escriba su propio bucle

Si los modelos Keras funcionan para usted, pero necesita más flexibilidad y management del paso de entrenamiento o los bucles de capacitación externos, puede implementar sus propios pasos de capacitación o incluso bucles de capacitación completos. Consulte la Guía Keras sobre la personalización match para aprender más.

También puede implementar muchas cosas como un tf.keras.callbacks.Callback.

Este método tiene muchas de las ventajas mencionadas anteriormente, pero le brinda el management del paso del tren e incluso del bucle exterior.

Hay tres pasos para un bucle de entrenamiento estándar:

  1. Iterar sobre un generador de pitón o tf.knowledge.Dataset Para obtener lotes de ejemplos.
  2. Usar tf.GradientTape para recolectar gradientes.
  3. Use uno de los tf.keras.optimizers Para aplicar actualizaciones de peso a las variables del modelo.

Recordar:

  • Incluya siempre un coaching argumento en el name Método de capas y modelos subclaseados.
  • Asegúrese de llamar al modelo con el coaching argumento establecido correctamente.
  • Dependiendo del uso, las variables del modelo pueden no existir hasta que el modelo se ejecute en un lote de datos.
  • Debe manejar manualmente cosas como pérdidas de regularización para el modelo.

No es necesario ejecutar inicializadores variables o agregar dependencias de management handbook. tf.operate Maneja las dependencias de management automático y la inicialización variable de la creación para usted.

mannequin = tf.keras.Sequential([
    tf.keras.layers.Conv2D(32, 3, activation='relu',
                           kernel_regularizer=tf.keras.regularizers.l2(0.02),
                           input_shape=(28, 28, 1)),
    tf.keras.layers.MaxPooling2D(),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dropout(0.1),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.BatchNormalization(),
    tf.keras.layers.Dense(10)
])

optimizer = tf.keras.optimizers.Adam(0.001)
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)

@tf.operate
def train_step(inputs, labels):
  with tf.GradientTape() as tape:
    predictions = mannequin(inputs, coaching=True)
    regularization_loss=tf.math.add_n(mannequin.losses)
    pred_loss=loss_fn(labels, predictions)
    total_loss=pred_loss + regularization_loss

  gradients = tape.gradient(total_loss, mannequin.trainable_variables)
  optimizer.apply_gradients(zip(gradients, mannequin.trainable_variables))

for epoch in vary(NUM_EPOCHS):
  for inputs, labels in train_data:
    train_step(inputs, labels)
  print("Completed epoch", epoch)
2023-10-04 01:23:02.652222: W tensorflow/core/kernels/knowledge/cache_dataset_ops.cc:854] The calling iterator didn't totally learn the dataset being cached. With a view to keep away from sudden truncation of the dataset, the partially cached contents of the dataset  can be discarded. This will occur if in case you have an enter pipeline just like `dataset.cache().take(okay).repeat()`. You need to use `dataset.take(okay).cache().repeat()` as an alternative.
Completed epoch 0
2023-10-04 01:23:02.957452: W tensorflow/core/kernels/knowledge/cache_dataset_ops.cc:854] The calling iterator didn't totally learn the dataset being cached. With a view to keep away from sudden truncation of the dataset, the partially cached contents of the dataset  can be discarded. This will occur if in case you have an enter pipeline just like `dataset.cache().take(okay).repeat()`. You need to use `dataset.take(okay).cache().repeat()` as an alternative.
Completed epoch 1
2023-10-04 01:23:03.632425: W tensorflow/core/kernels/knowledge/cache_dataset_ops.cc:854] The calling iterator didn't totally learn the dataset being cached. With a view to keep away from sudden truncation of the dataset, the partially cached contents of the dataset  can be discarded. This will occur if in case you have an enter pipeline just like `dataset.cache().take(okay).repeat()`. You need to use `dataset.take(okay).cache().repeat()` as an alternative.
Completed epoch 2
2023-10-04 01:23:03.877866: W tensorflow/core/kernels/knowledge/cache_dataset_ops.cc:854] The calling iterator didn't totally learn the dataset being cached. With a view to keep away from sudden truncation of the dataset, the partially cached contents of the dataset  can be discarded. This will occur if in case you have an enter pipeline just like `dataset.cache().take(okay).repeat()`. You need to use `dataset.take(okay).cache().repeat()` as an alternative.
Completed epoch 3
Completed epoch 4
2023-10-04 01:23:04.197488: W tensorflow/core/kernels/knowledge/cache_dataset_ops.cc:854] The calling iterator didn't totally learn the dataset being cached. With a view to keep away from sudden truncation of the dataset, the partially cached contents of the dataset  can be discarded. This will occur if in case you have an enter pipeline just like `dataset.cache().take(okay).repeat()`. You need to use `dataset.take(okay).cache().repeat()` as an alternative.

Aprovechar tf.operate con flujo de management de pitón

tf.operate proporciona una forma de convertir el flujo de management dependiente de datos en equivalentes de modo gráfico como tf.cond y tf.while_loop.

Un lugar común donde aparece el flujo de management dependiente de datos es en los modelos de secuencia. tf.keras.layers.RNN envuelve una célula RNN, lo que le permite desenrollar de manera estadí o dinámica la recurrencia. Como ejemplo, puede reimplegar el desenrollado dinámico de la siguiente manera.

class DynamicRNN(tf.keras.Mannequin):

  def __init__(self, rnn_cell):
    tremendous(DynamicRNN, self).__init__(self)
    self.cell = rnn_cell

  @tf.operate(input_signature=[tf.TensorSpec(dtype=tf.float32, shape=[None, None, 3])])
  def name(self, input_data):

    # [batch, time, features] -> [time, batch, features]
    input_data = tf.transpose(input_data, [1, 0, 2])
    timesteps =  tf.form(input_data)[0]
    batch_size = tf.form(input_data)[1]
    outputs = tf.TensorArray(tf.float32, timesteps)
    state = self.cell.get_initial_state(batch_size = batch_size, dtype=tf.float32)
    for i in tf.vary(timesteps):
      output, state = self.cell(input_data[i], state)
      outputs = outputs.write(i, output)
    return tf.transpose(outputs.stack(), [1, 0, 2]), state
lstm_cell = tf.keras.layers.LSTMCell(items = 13)

my_rnn = DynamicRNN(lstm_cell)
outputs, state = my_rnn(tf.random.regular(form=[10,20,3]))
print(outputs.form)
(10, 20, 13)

Leer el tf.operate Guía para obtener más información.

Métricas y pérdidas de estilo nuevo

Las métricas y las pérdidas son objetos que funcionan con entusiasmo y en tf.operates.

Un objeto de pérdida es llamable y espera (y_true, y_pred) como argumentos:

cce = tf.keras.losses.CategoricalCrossentropy(from_logits=True)
cce([[1, 0]], [[-1.0,3.0]]).numpy()
4.01815

Utilice métricas para recopilar y mostrar datos

Puedes usar tf.metrics para agregar datos y tf.abstract Para registrar resúmenes y redirigirlo a un escritor utilizando un administrador de contexto. Los resúmenes se emiten directamente al escritor, lo que significa que debe proporcionar el step valor en el sitio de llamadas.

summary_writer = tf.abstract.create_file_writer('/tmp/summaries')
with summary_writer.as_default():
  tf.abstract.scalar('loss', 0.1, step=42)

Usar tf.metrics Para agregar datos antes de registrarlos como resúmenes. Las métricas son con estado muy condicionadas; acumulan valores y devuelven un resultado acumulativo cuando llame al consequence método (como Imply.consequence). Borrar valores acumulados con Mannequin.reset_states.

def prepare(mannequin, optimizer, dataset, log_freq=10):
  avg_loss = tf.keras.metrics.Imply(identify='loss', dtype=tf.float32)
  for photographs, labels in dataset:
    loss = train_step(mannequin, optimizer, photographs, labels)
    avg_loss.update_state(loss)
    if tf.equal(optimizer.iterations % log_freq, 0):
      tf.abstract.scalar('loss', avg_loss.consequence(), step=optimizer.iterations)
      avg_loss.reset_states()

def check(mannequin, test_x, test_y, step_num):
  # coaching=False is simply wanted if there are layers with totally different
  # habits throughout coaching versus inference (e.g. Dropout).
  loss = loss_fn(mannequin(test_x, coaching=False), test_y)
  tf.abstract.scalar('loss', loss, step=step_num)

train_summary_writer = tf.abstract.create_file_writer('/tmp/summaries/prepare')
test_summary_writer = tf.abstract.create_file_writer('/tmp/summaries/check')

with train_summary_writer.as_default():
  prepare(mannequin, optimizer, dataset)

with test_summary_writer.as_default():
  check(mannequin, test_x, test_y, optimizer.iterations)

Visualice los resúmenes generados señalando Tensorboard al directorio de registro de resumen:

tensorboard --logdir /tmp/summaries

Usar el tf.abstract API para escribir datos de resumen para la visualización en TensorBoard. Para más información, lea el tf.abstract guía.

# Create the metrics
loss_metric = tf.keras.metrics.Imply(identify='train_loss')
accuracy_metric = tf.keras.metrics.SparseCategoricalAccuracy(identify='train_accuracy')

@tf.operate
def train_step(inputs, labels):
  with tf.GradientTape() as tape:
    predictions = mannequin(inputs, coaching=True)
    regularization_loss=tf.math.add_n(mannequin.losses)
    pred_loss=loss_fn(labels, predictions)
    total_loss=pred_loss + regularization_loss

  gradients = tape.gradient(total_loss, mannequin.trainable_variables)
  optimizer.apply_gradients(zip(gradients, mannequin.trainable_variables))
  # Replace the metrics
  loss_metric.update_state(total_loss)
  accuracy_metric.update_state(labels, predictions)


for epoch in vary(NUM_EPOCHS):
  # Reset the metrics
  loss_metric.reset_states()
  accuracy_metric.reset_states()

  for inputs, labels in train_data:
    train_step(inputs, labels)
  # Get the metric outcomes
  mean_loss=loss_metric.consequence()
  mean_accuracy = accuracy_metric.consequence()

  print('Epoch: ', epoch)
  print('  loss:     {:.3f}'.format(mean_loss))
  print('  accuracy: {:.3f}'.format(mean_accuracy))
2023-10-04 01:23:05.220607: W tensorflow/core/kernels/knowledge/cache_dataset_ops.cc:854] The calling iterator didn't totally learn the dataset being cached. With a view to keep away from sudden truncation of the dataset, the partially cached contents of the dataset  can be discarded. This will occur if in case you have an enter pipeline just like `dataset.cache().take(okay).repeat()`. You need to use `dataset.take(okay).cache().repeat()` as an alternative.
Epoch:  0
  loss:     0.176
  accuracy: 0.994
2023-10-04 01:23:05.554495: W tensorflow/core/kernels/knowledge/cache_dataset_ops.cc:854] The calling iterator didn't totally learn the dataset being cached. With a view to keep away from sudden truncation of the dataset, the partially cached contents of the dataset  can be discarded. This will occur if in case you have an enter pipeline just like `dataset.cache().take(okay).repeat()`. You need to use `dataset.take(okay).cache().repeat()` as an alternative.
Epoch:  1
  loss:     0.153
  accuracy: 0.991
2023-10-04 01:23:06.043597: W tensorflow/core/kernels/knowledge/cache_dataset_ops.cc:854] The calling iterator didn't totally learn the dataset being cached. With a view to keep away from sudden truncation of the dataset, the partially cached contents of the dataset  can be discarded. This will occur if in case you have an enter pipeline just like `dataset.cache().take(okay).repeat()`. You need to use `dataset.take(okay).cache().repeat()` as an alternative.
Epoch:  2
  loss:     0.134
  accuracy: 0.994
2023-10-04 01:23:06.297768: W tensorflow/core/kernels/knowledge/cache_dataset_ops.cc:854] The calling iterator didn't totally learn the dataset being cached. With a view to keep away from sudden truncation of the dataset, the partially cached contents of the dataset  can be discarded. This will occur if in case you have an enter pipeline just like `dataset.cache().take(okay).repeat()`. You need to use `dataset.take(okay).cache().repeat()` as an alternative.
Epoch:  3
  loss:     0.108
  accuracy: 1.000
Epoch:  4
  loss:     0.095
  accuracy: 1.000
2023-10-04 01:23:06.678292: W tensorflow/core/kernels/knowledge/cache_dataset_ops.cc:854] The calling iterator didn't totally learn the dataset being cached. With a view to keep away from sudden truncation of the dataset, the partially cached contents of the dataset  can be discarded. This will occur if in case you have an enter pipeline just like `dataset.cache().take(okay).repeat()`. You need to use `dataset.take(okay).cache().repeat()` as an alternative.

Nombres métricos de Keras

Los modelos Keras son consistentes para manejar los nombres métricos. Cuando pasa una cadena en la lista de métricas, que exacto la cadena se usa como la métrica identify. Estos nombres son visibles en el objeto de historia devuelto por mannequin.matchy en los registros pasados a keras.callbacks. está configurado en la cadena que pasó en la lista de métricas.

mannequin.compile(
    optimizer = tf.keras.optimizers.Adam(0.001),
    loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics = ['acc', 'accuracy', tf.keras.metrics.SparseCategoricalAccuracy(name="my_accuracy")])
historical past = mannequin.match(train_data)
5/5 [==============================] - 1s 9ms/step - loss: 0.1077 - acc: 0.9937 - accuracy: 0.9937 - my_accuracy: 0.9937
2023-10-04 01:23:07.849601: W tensorflow/core/kernels/knowledge/cache_dataset_ops.cc:854] The calling iterator didn't totally learn the dataset being cached. With a view to keep away from sudden truncation of the dataset, the partially cached contents of the dataset  can be discarded. This will occur if in case you have an enter pipeline just like `dataset.cache().take(okay).repeat()`. You need to use `dataset.take(okay).cache().repeat()` as an alternative.
historical past.historical past.keys()
dict_keys(['loss', 'acc', 'accuracy', 'my_accuracy'])

Depuración

Use la ejecución ansiosa para ejecutar su código paso a paso para inspeccionar formas, tipos de datos y valores. Ciertas API, como tf.operate, tf.kerasand many others. están diseñados para usar la ejecución de gráficos, para el rendimiento y la portabilidad. Al depurar, usar tf.config.run_functions_eagerly(True) para usar una ejecución ansiosa dentro de este código.

Por ejemplo:

@tf.operate
def f(x):
  if x > 0:
    import pdb
    pdb.set_trace()
    x = x + 1
  return x

tf.config.run_functions_eagerly(True)
f(tf.fixed(1))
>>> f()
-> x = x + 1
(Pdb) l
  6     @tf.operate
  7     def f(x):
  8       if x > 0:
  9         import pdb
 10         pdb.set_trace()
 11  ->     x = x + 1
 12       return x
 13
 14     tf.config.run_functions_eagerly(True)
 15     f(tf.fixed(1))
[EOF]

Esto también funciona dentro de los modelos Keras y otras API que admiten una ejecución ansiosa:

class CustomModel(tf.keras.fashions.Mannequin):

  @tf.operate
  def name(self, input_data):
    if tf.reduce_mean(input_data) > 0:
      return input_data
    else:
      import pdb
      pdb.set_trace()
      return input_data // 2


tf.config.run_functions_eagerly(True)
mannequin = CustomModel()
mannequin(tf.fixed([-2, -4]))
>>> name()
-> return input_data // 2
(Pdb) l
 10         if tf.reduce_mean(input_data) > 0:
 11           return input_data
 12         else:
 13           import pdb
 14           pdb.set_trace()
 15  ->       return input_data // 2
 16
 17
 18     tf.config.run_functions_eagerly(True)
 19     mannequin = CustomModel()
 20     mannequin(tf.fixed([-2, -4]))

Notas:

  • tf.keras.Mannequin métodos como match, considery predict ejecutar como gráficos con tf.operate debajo del capó.
  • Al usar tf.keras.Mannequin.compilecolocar run_eagerly = True para deshabilitar el Mannequin lógica de estar envuelto en un tf.operate.
  • Usar tf.knowledge.experimental.enable_debug_mode para habilitar el modo de depuración para tf.knowledge. Lea los documentos de la API para más detalles.

No guarde tf.Tensors en tus objetos

Estos objetos tensores podrían crearse en un tf.operate o en el contexto ansioso, y estos tensores se comportan de manera diferente. Siempre usa tf.TensorS solo para valores intermedios.

Para rastrear el estado, use tf.VariableS como siempre se pueden usar de ambos contextos. Leer el tf.Variable Guía para obtener más información.

Recursos y lecturas adicionales

  • Lea las guías y tutoriales TF2 para obtener más información sobre cómo usar TF2.
  • Si previamente usó TF1.X, se recomienda que migre su código a TF2. Lea las guías de migración para aprender más.

Publicado originalmente en el Flujo tensor Sitio net, este artículo aparece aquí en un nuevo titular y tiene licencia bajo CC por 4.0. Muestras de código compartidas bajo la licencia Apache 2.0.

fuente

LEAVE A REPLY

Please enter your comment!
Please enter your name here