如何使用frozen.pb文件进行测试?附测试数据集详情
Alright, let's walk through exactly how to use your frozen.pb model to test against your x_test and y_test data. I’ll focus on TensorFlow since frozen.pb files are standard for TensorFlow frozen graphs, and cover both TF1.x and TF2.x-compatible approaches.
Step 1: Load the Frozen .pb Graph
Frozen graphs are serialized protobuf files, so we first need to load them into a TensorFlow graph. If you’re using TensorFlow 2.x, we’ll use the compatibility module to handle the older graph format:
import tensorflow as tf from tensorflow.compat.v1 import Graph, Session # Load the frozen graph file graph = Graph() with graph.as_default(): graph_def = tf.compat.v1.GraphDef() with open("frozen.pb", "rb") as f: graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_def, name="") # Import graph with empty prefix # Initialize a session to run inference sess = Session(graph=graph)
Step 2: Identify Input & Output Tensor Names
This is critical—you need to know the exact names of the model’s input and output tensors to feed data and retrieve predictions. If you don’t have this info handy, print all tensor names in the graph to find them:
# Print all operation names to locate input/output tensors for op in graph.get_operations(): print(op.name)
Look for names like input_layer:0 (common for input) or dense_final/Softmax:0 (standard for classification outputs with softmax). Note these names—we’ll use them in the next step. Let’s assume your input tensor is input_x:0 and output is predictions:0 (adjust these to match your actual tensor names).
Step 3: Prepare Your x_test Data
Ensure your x_test data matches the format used during training:
- Apply the same preprocessing (e.g., normalization, scaling) that you used for training data.
- Confirm the shape aligns: your x_test is (1061, 88), so the model’s input tensor should accept a shape like
[None, 88](which is standard for batch inference).
Step 4: Run Inference on x_test
Feed your test data into the model to generate predictions:
# Fetch input and output tensors from the graph input_tensor = graph.get_tensor_by_name("input_x:0") output_tensor = graph.get_tensor_by_name("predictions:0") # Run prediction on the full test set predictions = sess.run(output_tensor, feed_dict={input_tensor: x_test})
The predictions variable will be a (1061, 6) array, where each row is the model’s probability distribution over your 6 classes (matching your one-hot encoded y_test labels).
Step 5: Evaluate Model Performance
Compare the predictions to your ground-truth y_test labels to measure performance. First, convert both one-hot labels and predictions to class indices, then calculate metrics:
import numpy as np from sklearn.metrics import accuracy_score, classification_report, confusion_matrix # Convert one-hot y_test to class indices y_test_classes = np.argmax(y_test, axis=1) # Convert predictions to class indices (select the highest-probability class) pred_classes = np.argmax(predictions, axis=1) # Calculate and print key metrics print(f"Test Accuracy: {accuracy_score(y_test_classes, pred_classes):.4f}") print("\nClassification Report:") print(classification_report(y_test_classes, pred_classes)) print("\nConfusion Matrix:") print(confusion_matrix(y_test_classes, pred_classes))
Optional: TF2.x Pure Mode Workflow
If you prefer to avoid compatibility mode, convert the frozen graph to a TF2-compatible SavedModel first:
import tensorflow as tf # Convert frozen.pb to SavedModel converter = tf.compat.v1.lite.TFLiteConverter.from_frozen_graph( graph_def_file="frozen.pb", input_arrays=["input_x"], # Replace with your input tensor name output_arrays=["predictions"] # Replace with your output tensor name ) # Save the converted model tflite_model = converter.convert() with open("converted_model.tflite", "wb") as f: f.write(tflite_model) # Load and use the converted model in TF2 interpreter = tf.lite.Interpreter(model_path="converted_model.tflite") interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() # Run inference interpreter.set_tensor(input_details[0]["index"], x_test.astype(np.float32)) interpreter.invoke() predictions = interpreter.get_tensor(output_details[0]["index"])
内容的提问来源于stack exchange,提问作者Bibhu Pala

