TensorFlow与NumPy版本不匹配致初始化失败,无法调用TensorFlow
解决TensorFlow导入报错ImportError: initialization failed(NumPy版本不匹配)
已完成所有模块及依赖安装,但运行以下代码时无法正常访问TensorFlow:
import numpy as np import pandas as pd import sklearn import tensorflow as tf import matplotlib.pyplot as plt # 检查TensorFlow GPU访问权限 print(f"TensorFlow has access to the following devices:\n{tf.config.list_physical_devices()}") # 查看TensorFlow版本 print(f"TensorFlow version: {tf.__version__}")
报错信息
RuntimeError Traceback (most recent call last)RuntimeError: The above exception was the direct cause of the following exception:
File ~/miniforge3/envs/env_new/lib/python3.8/site-packages/tensorflow/python/client/pywrap_tf_session.py:19 17 # pylint: disable=invalid-import-order,g-bad-import-order, wildcard-import, unused-import 18 from tensorflow.python import pywrap_tensorflow ---> 19 from tensorflow.python.client._pywrap_tf_session import * 20 from tensorflow.python.client._pywrap_tf_session import _TF_SetTarget 21 from tensorflow.python.client._pywrap_tf_session import _TF_SetConfig ImportError: initialization failed
问题原因
经排查,该问题由TensorFlow库与NumPy库版本不匹配导致。
解决方案
- 查看当前已安装的TensorFlow和NumPy版本:
pip show tensorflow numpy - 根据TensorFlow版本安装对应兼容的NumPy版本,常见兼容组合示例:
- TensorFlow 2.10+:兼容NumPy 1.21.x ~ 1.24.x
- TensorFlow 2.9:兼容NumPy 1.20.x ~ 1.23.x
- 卸载现有NumPy并安装指定版本:
pip uninstall -y numpy pip install numpy==[替换为对应兼容版本号] - 重新运行原代码,验证TensorFlow是否能正常导入并输出设备信息与版本。
内容的提问来源于stack exchange,提问作者NANDA KIRAN K
相关产品推荐
相关产品推荐

