python使用TensorFlow库的时候运行报错
当我使用pycharm使用TensorFlow的时候,首先安装了TensorFlow相关的库,但是在运行的过程中,控制台给我抛出了下面这个错误。
D:\Python\项目\pythonProject\venv\Scripts\python.exe D:/Python/项目/pythonProject/ceshi.py
Traceback (most recent call last):
File "D:/Python/项目/pythonProject/ceshi.py", line 1, in <module>
from tensorflow import keras
File "D:\Python\项目\pythonProject\venv\lib\site-packages\tensorflow\__init__.py", line 41, in <module>
from tensorflow.python.tools import module_util as _module_util
File "D:\Python\项目\pythonProject\venv\lib\site-packages\tensorflow\python\__init__.py", line 40, in <module>
from tensorflow.python.eager import context
File "D:\Python\项目\pythonProject\venv\lib\site-packages\tensorflow\python\eager\context.py", line 32, in <module>
from tensorflow.core.framework import function_pb2
File "D:\Python\项目\pythonProject\venv\lib\site-packages\tensorflow\core\framework\function_pb2.py", line 16, in <module>
from tensorflow.core.framework import attr_value_pb2 as tensorflow_dot_core_dot_framework_dot_attr__value__pb2
File "D:\Python\项目\pythonProject\venv\lib\site-packages\tensorflow\core\framework\attr_value_pb2.py", line 16, in <module>
from tensorflow.core.framework import tensor_pb2 as tensorflow_dot_core_dot_framework_dot_tensor__pb2
File "D:\Python\项目\pythonProject\venv\lib\site-packages\tensorflow\core\framework\tensor_pb2.py", line 16, in <module>
from tensorflow.core.framework import resource_handle_pb2 as tensorflow_dot_core_dot_framework_dot_resource__handle__pb2
File "D:\Python\项目\pythonProject\venv\lib\site-packages\tensorflow\core\framework\resource_handle_pb2.py", line 16, in <module>
from tensorflow.core.framework import tensor_shape_pb2 as tensorflow_dot_core_dot_framework_dot_tensor__shape__pb2
File "D:\Python\项目\pythonProject\venv\lib\site-packages\tensorflow\core\framework\tensor_shape_pb2.py", line 36, in <module>
_descriptor.FieldDescriptor(
File "D:\Python\项目\pythonProject\venv\lib\site-packages\google\protobuf\descriptor.py", line 561, in __new__
_message.Message._CheckCalledFromGeneratedFile()
TypeError: Descriptors cannot not be created directly.
If this call came from a _pb2.py file, your generated code is out of date and must be regenerated with protoc >= 3.19.0.
If you cannot immediately regenerate your protos, some other possible workarounds are:
1. Downgrade the protobuf package to 3.20.x or lower.
2. Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python (but this will use pure-Python parsing and will be much slower).
More information: https://developers.google.com/protocol-buffers/docs/news/2022-05-06#python-updates
Process finished with exit code 1
通过发现,这个错误引发的原因是由于protobuf包的版本所导致的,其中protobuf它是TensorFlow的一个依赖项。
解决方案:
1.重新生成生成的代码:如果你有任何生成的代码文件(通常以_pb2.py结尾),可能这些文件已经过时了。尝试使用更新版本的protoc编译器(版本3.19.0或更高)重新生成这些文件。
2.降级protobuf包:如果重新生成代码不可行,你可以尝试将protobuf包降级到低版本。你可以使用Python的包管理器来完成降级操作。
具体包降级相关操作:在控制台输入 :
//这里我演示的版本是3.20版本
pip install protobuf==3.20