tensorflow image classification model, don't show ms/step
Assistant
User
heres my code
import matplotlib.pyplot as plt
import numpy as np
import PIL
import tensorflow as tf
import pathlib
import os
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
To remove the ms/step information from your output when running the .evaluate() or .fit() methods in TensorFlow, you should adjust the verbose level. In your code, you are already using verbose=2 in the .evaluate() call, which skips the ms/step display but provides output at the end of each epoch.
Based on the code snippet you provided, it seems you are looking to apply this during the method. To further clarify, the parameter controls the level of verbosity:
User
it still shows
Assistant
If you've set verbose=2 in both your .fit() and .evaluate() methods and you're still seeing ms/step or similar timing information which you'd like to suppress, it's possible this output might not be coming directly from these calls or there might be a misunderstanding. Typically, should not show the during training or evaluation. However, TensorFlow's behavior can be influenced by other factors or there might have been updates or specific configurations in TensorFlow that cause unexpected behavior.
In TensorFlow, the training process often involves iterating over batches of data and repeatedly updating the model's weights to minimize the loss function. When you train your model using TensorFlow or Keras, it typically outputs progress logs, including the time taken per step or batch (commonly displayed as "ms/step"). This information is quite useful for understanding the performance and efficiency of your model training. However, there can be scenarios where you might want to suppress or modify these verbose outputs, especially if you wish for a cleaner log or you are primarily concerned with metrics other than time per step.
To achieve a training loop that doesn't show the ms/step information, you can control the verbosity of the output logs. Here's how you can do it in TensorFlow 2.x with the Keras API:
1. Using the verbose Argument
The simplest way to control the verbosity of the training output is by adjusting the verbose argument in the fit method of your model.
verbose=0 will train the model in silent mode - no logs will be shown.
verbose=1 will show a progress bar and the ms/step.
verbose=2 will show one line per epoch and won't specifically show ms/step.
If you want to suppress just the ms/step while keeping other information, it's a bit trickier because verbose=1 does not provide a way to customize the log content to that extent, and verbose=2 might suppress more than desired. Here's a workaround:
2. Custom Callback
For finer control over what gets printed during training, you can create a custom callback. This way, you can define exactly what gets output to the console during training.
import tensorflow as tf
from tensorflow.keras.callbacks import Callback
class CustomCallback(Callback):
def on_epoch_end(self, epoch, logs=None):
logs = logs or {}
print(f"Epoch {epoch + 1}: ", end="")
for log_name, log_value in logs.items():
print(f"{log_name}={log_value:.4f} ", end="")
print() # for new line
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Assuming your model and data are defined
model.fit(x_train, y_train, epochs=10, verbose=0, callbacks=[CustomCallback()])
This script gives you a template for creating a custom callback that prints out the epoch, and any desired metrics, without including the ms/step. You can further customize the CustomCallback class to include or exclude whatever information you find helpful.
Modifying verbosity levels or implementing a custom callback provides a way to tailor TensorFlow's output to your needs, giving you cleaner logs and potentially improving the interpretability of your model's training progress.
num_classes = len(class_names)
model = Sequential([
# т.к. у нас версия TF 2.6 локально
layers.experimental.preprocessing.Rescaling(1./255, input_shape=(img_height, img_width, 3)),
verbose=2: One line per epoch, doesn't show ms/step
Since you are already using verbose=2 in your model.evaluate(train_ds, verbose=2), you've essentially chosen the setting that doesn't show ms/step during evaluation.
For training (using .fit()), if you wish to suppress the ms/step info, you would do similarly by setting verbose=2 in your .fit() call. However, remember that this will still display one line per epoch without the progress bar and ms/step. If you're using .fit() somewhere else and forgot to add this, here's how you could adjust it:
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=10,
verbose=2, # Does not show ms/step
)
If you're seeking to completely customize what's displayed during training beyond the capabilities provided by the verbose parameter, you would need to implement a custom callback, as shown in my previous response. This would give you full control over console outputs during training or evaluation, allowing you to include or exclude whatever information you desire, such as loss, accuracy, or other metrics, while excluding ms/step.
However, given your current implementation and the use of verbose=2 within model.evaluate(), you've already applied a straightforward solution to avoid displaying ms/step during this phase of model evaluation. No additional change is needed in that call to achieve your goal.
verbose=2
ms/step
Given your situation, another approach to suppress all logs and manually control what gets printed is to utilize a custom callback that silences all default logging and only prints what you explicitly want it to print. This method gives you full control over your script's output.
Here's a simplified custom callback you can use to replace standard verbose behavior:
import tensorflow as tf
class SilentLogger(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs=None):
# Customize this to print anything you need
print(f"Epoch {epoch+1}, Loss: {logs['loss']:.4f}, Accuracy: {logs['accuracy']:.4f}")
def on_test_end(self, logs=None): # This is for `evaluate`
print(f"Test Loss: {logs['loss']:.4f}, Test Accuracy: {logs['accuracy']:.4f}")
# Use the callback
model.fit(
train_ds,
epochs=10,
validation_data=val_ds,
verbose=0, # Disable standard logging
callbacks=[SilentLogger()]
)
# For evaluation, there's nothing printed by default when verbose=0
loss, acc = model.evaluate(val_ds, verbose=0)
print(f"Evaluation - Loss: {loss:.4f}, Accuracy: {acc:.4f}")
This custom callback, SilentLogger, is utilized by passing it to the callbacks parameter in your .fit() method, and the verbose=0 parameter is used to entirely mute the built-in logging. Then, on_epoch_end you can customize what metrics or messages to print. Similarly, for .evaluate(), setting verbose=0 ensures no automatic logging occurs, and you manually print out the results afterward.
This approach not only addresses the issue of suppressing unwanted ms/step outputs but also gives you the flexibility to tailor the logging exactly to your requirements.