首页 > 解决方案 > 回溯错误:ModuleNotFoundError:没有名为“tensorflow.keras”的模块

问题描述

如何使用 conda 安装 tensor-keras?我有以下错误消息。我在导入下面的模块时看到这个错误在这里我复制了我的代码片段我在我的代码中实际尝试的内容

from tensorflow.keras.callbacks import ModelCheckpoint
import tensorflow as tf

callback=tf.keras.callbacks.ModelCheckpoint(filepath='Regressor_model.h5',
                                                monitor='mean_absolute_error',
                                                verbose=0,
                                                save_best_only=True,
                                                save_weights_only=False,
                                                mode='auto')

通过使用以下命令,我在 Anaconda 提示符下成功安装了 tensorflow。

conda create -n tf tensorflow conda
activate tf conda
install keras

顺便说一句,我几次重新启动了 pycharm IDE。我仍然有同样的错误

conda create -n tf tensorflow conda activate tf conda install keras

Traceback (most recent call last):
  File "C:\Users\rethi1\Anaconda-python\lib\site-packages\IPython\core\interactiveshell.py", line 3418, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-353837d93f8d>", line 1, in <module>
    runfile('C:/Users/rethi1/PycharmProjects/pythonProject/stock_prediction_test/__init__.py', wdir='C:/Users/rethi1/PycharmProjects/pythonProject/stock_prediction_test')
  File "C:\Program Files\JetBrains\PyCharm 2020.2.3\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm 2020.2.3\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/rethi1/PycharmProjects/pythonProject/stock_prediction_test/__init__.py", line 273, in <module>
    from tensorflow.keras.callbacks import ModelCheckpoint
  File "C:\Program Files\JetBrains\PyCharm 2020.2.3\plugins\python\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
ModuleNotFoundError: No module named 'tensorflow.keras'

我尝试了一个导入和使用 tensorflow 模块的简单代码

import tensorflow as tf

# Initialize two constants
x1 = tf.constant([9,10,11,12])
x2 = tf.constant([5,6,7,8])

# Multiply
result = tf.multiply(x1, x2)

# Print the result
print(result)

错误看起来类似于上面的无法使用模块

x1 = tf.constant([9,10,11,12])
AttributeError: module 'tensorflow' has no attribute 'constant'

提前致谢!

标签: pythontensorflowkeraspycharmanaconda

解决方案


我想出了一个现在正在工作的灵魂。我将我的 py 版本降级为 python 3.6.8 建议遵循:tensorflow.org/install/pip#system-install这个问题的原因很明显。大多数用户可能会遇到同样的问题。使用完全超出范围的不兼容版本作为初学者,大多数人最终都会遇到兼容性问题。我强烈建议遵循原始文件


推荐阅读