无法加载TensorFlow官方预训练ResNet pb文件报错求助
Hey there, let's work through this error you're encountering when trying to load the ResNet pretrained PB file. The issue stems from the protobuf parsing step, so here are the most common solutions to resolve it:
1. Verify the PB File is Not Corrupted
First things first—make sure your downloaded and extracted PB file is intact:
- Re-download the
resnet_v1_imagenet_savedmodel.tar.gzfile and re-extract it. Sometimes partial downloads can lead to corrupted PB files that fail parsing. - Check the file size of the extracted PB (usually named
saved_model.pb). A valid ResNet PB file should be several hundred megabytes; if it's only a few KB, it's definitely corrupted.
2. Fix Protobuf-TensorFlow Version Compatibility
The error coming from google/protobuf/message.py is a strong indicator of version mismatch between TensorFlow and protobuf. TensorFlow relies heavily on protobuf and has strict version requirements:
- First, check your TensorFlow version with:
pip show tensorflow - Look up the protobuf version compatible with your TensorFlow release (e.g., TensorFlow 1.15.x typically works with protobuf 3.8.x, while TensorFlow 2.x requires newer versions like 3.19.x+).
- Uninstall the current protobuf and install the correct version:
pip uninstall protobuf -y pip install protobuf==<your-compatible-version>
3. Adjust the Graph Import Code for Your TensorFlow Version
Your current code uses TensorFlow 1.x APIs, which might cause issues if you're running TensorFlow 2.x. Here's the adjusted code for both versions:
For TensorFlow 1.x
Ensure your code uses the correct 1.x modules (no accidental TF2 imports):
import tensorflow as tf with tf.Graph().as_default(): with tf.gfile.FastGFile(path, 'rb') as file: graph_def = tf.GraphDef() graph_def.ParseFromString(file.read()) tf.import_graph_def(graph_def, name='')
For TensorFlow 2.x
Use the compatibility modules and updated file I/O API (since tf.gfile.FastGFile is deprecated):
import tensorflow as tf # Disable eager execution to use graph mode tf.compat.v1.disable_eager_execution() with tf.compat.v1.Graph().as_default(): with tf.io.gfile.GFile(path, 'rb') as file: graph_def = tf.compat.v1.GraphDef() graph_def.ParseFromString(file.read()) tf.import_graph_def(graph_def, name='')
4. Double-Check the File Path
Make sure the path variable points directly to the extracted PB file (not the tar.gz archive). Use an absolute file path instead of a relative one to avoid path resolution issues—this eliminates any ambiguity about where the code is looking for the file.
内容的提问来源于stack exchange,提问作者LIN Chaojian

