基于TensorFlow后端Keras:如何用TensorBoard同图绘制多模型训练准确率?
Got it, let's tackle this problem step by step. You're trying to compare training accuracies of Inception, VGG, ResNet on your custom dataset using Keras with TensorFlow backend, and want to plot them on the same graph. First, let's fix the TensorBoard approach since that's what you initially tried, then cover alternative plotting methods too.
Why It Might Have Failed
Chances are you either saved all models' logs to the same directory (overwriting data) or didn't properly configure TensorBoard to recognize multiple model runs. TensorBoard can easily compare multiple models—you just need to structure your logs correctly.
Step-by-Step Implementation
1. Structure Your Log Directories
Create a parent logs folder, then a subfolder for each model (e.g., logs/vgg, logs/resnet, logs/inception). This keeps each model's training data separate and avoids conflicts.
2. Train Models with Unique Log Paths
Use Keras' TensorBoard callback, pointing each model to its own subdirectory. You can also add a unique prefix to your accuracy metric to make curves easier to distinguish in the UI.
Here's a practical code example:
from tensorflow.keras.applications import VGG16, ResNet50, InceptionV3 from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten from tensorflow.keras.callbacks import TensorBoard import tensorflow as tf # Assume your dataset is loaded into x_train, y_train, x_val, y_val INPUT_SHAPE = (224, 224, 3) # Adjust based on your dataset's image size NUM_CLASSES = 10 # Update to match your classification task def build_model(model_name): # Load pre-trained base model (excluding top classification layers) if model_name == "vgg": base_model = VGG16(weights="imagenet", include_top=False, input_shape=INPUT_SHAPE) elif model_name == "resnet": base_model = ResNet50(weights="imagenet", include_top=False, input_shape=INPUT_SHAPE) elif model_name == "inception": base_model = InceptionV3(weights="imagenet", include_top=False, input_shape=INPUT_SHAPE) else: raise ValueError(f"Unknown model type: {model_name}") # Assemble the full model with custom top layers model = Sequential([ base_model, Flatten(), Dense(256, activation="relu"), Dense(NUM_CLASSES, activation="softmax") ]) # Freeze base model weights (adjust if you plan to fine-tune later) base_model.trainable = False # Compile with a unique accuracy metric name for each model model.compile( optimizer="adam", loss="sparse_categorical_crossentropy", # Use 'categorical_crossentropy' if labels are one-hot encoded metrics=[tf.keras.metrics.SparseCategoricalAccuracy(name=f"{model_name}_accuracy")] ) return model # Train each model and save logs to their dedicated directories model_names = ["vgg", "resnet", "inception"] for name in model_names: print(f"Starting training for {name}...") model = build_model(name) log_dir = f"./logs/{name}" tb_callback = TensorBoard(log_dir=log_dir, histogram_freq=1) model.fit( x_train, y_train, validation_data=(x_val, y_val), epochs=20, batch_size=32, callbacks=[tb_callback] )
3. Launch TensorBoard with Multiple Log Sources
Open your terminal and run this command to tell TensorBoard to load all three model logs and label them clearly:
tensorboard --logdir=vgg:./logs/vgg,resnet:./logs/resnet,inception:./logs/inception
Verify the Results
Open the TensorBoard UI (usually at http://localhost:6006), navigate to the Scalars tab. You'll see all three models' training and validation accuracy curves plotted together. Use the legend to toggle individual curves on/off for closer inspection.
If you prefer a static plot you can save or embed in reports, use Matplotlib to plot the accuracy curves directly from the training history objects returned by model.fit().
Step-by-Step Code
import matplotlib.pyplot as plt # Store training history for each model history_dict = {} for name in model_names: model = build_model(name) print(f"Training {name}...") history = model.fit( x_train, y_train, validation_data=(x_val, y_val), epochs=20, batch_size=32, verbose=1 ) history_dict[name] = history # Plot all curves on a single graph plt.figure(figsize=(12, 8)) for name, history in history_dict.items(): # Plot training accuracy plt.plot(history.history[f"{name}_accuracy"], label=f"{name} - Training Accuracy") # Plot validation accuracy (optional but helpful for checking overfitting) plt.plot(history.history[f"val_{name}_accuracy"], label=f"{name} - Validation Accuracy") plt.title("Model Accuracy Comparison") plt.xlabel("Epoch") plt.ylabel("Accuracy") plt.legend(loc="lower right") plt.grid(True) plt.show()
Customization Tips
- Add
plt.savefig("accuracy_comparison.png")to save the plot as an image file. - Adjust line styles, colors, or markers to make curves more distinct (e.g.,
plt.plot(..., linestyle="--", marker="o")). - Critical note: Ensure all models are trained under identical conditions (same epochs, batch size, optimizer, learning rate, data preprocessing) for a fair and meaningful comparison.
内容的提问来源于stack exchange,提问作者Kavitha Devan

