使用TensorFlow官方MNIST网络时出现No module named 'official'错误求助
Hey there, let's get this sorted out. That ModuleNotFoundError usually means Python can't locate the official module directory, even if you tried setting PYTHONPATH. Here are the most reliable fixes tailored for your Windows setup:
1. Double-check your PYTHONPATH setup
First, make sure you're pointing to the root of the TensorFlow Models repo, not the official/mnist subdirectory. Your repo root is C:\Users\ry\Desktop\NNTesting\models in this case.
Temporary fix (for current cmd session):
Open your command prompt, navigate to any directory, and run:set PYTHONPATH=C:\Users\ry\Desktop\NNTesting\models;%PYTHONPATH%Then go back to the
official/mnistfolder and run the test again:cd C:\Users\ry\Desktop\NNTesting\models\official\mnist python mnist_test.pyNote: This only lasts until you close the cmd window.
Permanent fix (persists across sessions):
- Right-click "This PC" → "Properties" → "Advanced system settings" → "Environment Variables".
- Under "User variables", click "New".
- Set Variable name to
PYTHONPATH, Variable value toC:\Users\ry\Desktop\NNTesting\models. - Click "OK" to save, then restart your command prompt for changes to take effect.
2. Add the path directly in your test script
If setting PYTHONPATH still doesn't work, you can manually add the repo root to Python's path at the top of mnist_test.py:
import sys sys.path.append("C:\\Users\\ry\\Desktop\\NNTesting\\models") # Then the rest of the imports from official.mnist import mnist
This bypasses any environment variable issues and ensures Python can find the official module.
3. Check for virtual environment conflicts
If you're using a virtual environment (like venv or conda), make sure:
- You've activated the virtual environment before setting
PYTHONPATHor running the test. - The
PYTHONPATHis set within the activated environment session, or you've added the repo path to the virtual environment'ssite-packagesdirectory via a.pthfile:- Navigate to your venv's
Lib\site-packagesfolder (e.g.,C:\Users\ry\Desktop\NNTesting\venv\Lib\site-packages). - Create a new file named
tensorflow-models.pth. - Inside the file, write the full path to your models repo root:
C:\Users\ry\Desktop\NNTesting\models. - Save the file, then restart your Python session.
- Navigate to your venv's
4. Verify directory structure
Double-check that your models repo has the correct structure. You should see:
models/ ├── official/ │ ├── mnist/ │ │ ├── mnist.py │ │ └── mnist_test.py │ └── ... (other official modules) └── ... (other repo files)
If the official folder is missing or misplaced, re-clone the TensorFlow Models repo to get the correct structure.
内容的提问来源于stack exchange,提问作者Ryan Brady




