已安装TensorFlow仍出现ModuleNotFoundError,该如何解决?
Hey there! Let's work through this issue together—there are two key things to address here: your Python environment mismatch, and a version mismatch between your test code and the TensorFlow version you installed.
What's Going On?
- Even though you've installed TensorFlow 2.2.0 via Anaconda, the Python interpreter running your code can't find the package. This almost always means you're using a different Python environment than the one where TensorFlow was installed.
- On top of that, your test code uses TensorFlow 1.x syntax (like
tf.Session()), but you have TensorFlow 2.x installed. Even if we fix the import error, you'd hit another error aboutSessionnot existing.
Step-by-Step Solutions
1. Make Sure You're Using the Right Python Environment
Since you installed TensorFlow in your Anaconda environment, you need to ensure your code runs in that same environment:
- Open Anaconda Prompt, activate your target environment (skip this if you used the base environment).
- Run
python --versionto confirm it shows Python 3.7.1. - Run
pip listand check thattensorflow 2.2.0appears in the list. - Run your code directly in this terminal, or use Anaconda's built-in tools like Spyder or Jupyter Notebook to avoid using your system's default Python.
If you're using an IDE like VS Code:
- Press
Ctrl+Shift+P, search forPython: Select Interpreter, and pick the interpreter atc:\users\my name\anaconda3\python.exe.
2. Update Your Test Code for TensorFlow 2.x
Your current code is written for TensorFlow 1.x. Here are two ways to fix this:
Option 1: Use TF1.x Compatibility Mode
If you want to keep using the Session syntax, enable compatibility with TF2.x:
import tensorflow.compat.v1 as tf tf.disable_v2_behavior() hello = tf.constant("hello TensorFlow!") sess = tf.Session() print(sess.run(hello))
Option 2: Use Native TF2.x Syntax (Recommended)
TensorFlow 2.x uses eager execution by default, so you don't need a Session at all:
import tensorflow as tf hello = tf.constant("hello TensorFlow!") print(hello.numpy().decode('utf-8'))
3. Reinstall TensorFlow If Environment Checks Pass
If you've confirmed you're in the right environment but still get the import error, the installation might be corrupted:
- Uninstall the current version:
pip uninstall tensorflow -y - Reinstall the exact version you need:
pip install tensorflow==2.2.0
Quick Environment Check
Just to confirm: your Windows 8.1, Python 3.7.1, and pip 20.1.1 all meet the requirements for TensorFlow 2.2.0, so environment compatibility isn't the root issue here.
内容的提问来源于stack exchange,提问作者Nazanin

