You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Keras导入Sequential类时遇ModuleNotFoundError问题求助

解决Keras导入Sequential时出现ModuleNotFoundError: No module named 'keras.engine.base_layer_v1'的问题

问题场景

运行以下代码时触发错误:

from keras.models import Sequential
from keras.layers import Embedding, LSTM, Dense

model = Sequential()
model.add(Embedding(10000, 64, input_length=80))
model.add(LSTM(100))
model.add(Dense(2, activation='sigmoid'))
model.compile(loss='binary_crossentropy', metrics=['accuracy'], optimizer='adam')

错误信息

Cell In[80], line 1
----> 1 model=Sequential()
      2 model.add(Embedding(10000,64,input_length=80))
      3 model.add(LSTM(100))

File c:\Users\Isaac\anaconda3\envs\textattackenv\lib\site-packages\keras\engine\training.py:184, in __new__(cls, *args, **kwargs)

File c:\Users\Isaac\anaconda3\envs\textattackenv\lib\site-packages\keras\utils\version_utils.py:61, in __new__(cls, *args, **kwargs)

File c:\Users\Isaac\anaconda3\envs\textattackenv\lib\site-packages\keras\utils\generic_utils.py:1221, in __getattr__(self, item)

File c:\Users\Isaac\anaconda3\envs\textattackenv\lib\site-packages\keras\utils\generic_utils.py:1212, in _load(self)

File c:\Users\Isaac\anaconda3\envs\textattackenv\lib\importlib\__init__.py:127, in import_module(name, package)
    125             break
    126         level += 1
--> 127 return _bootstrap._gcd_import(name[level:], package, level)

File <frozen importlib._bootstrap>:1014, in _gcd_import(name, package, level)

File <frozen importlib._bootstrap>:991, in _find_and_load(name, import_)

File <frozen importlib._bootstrap>:973, in _find_and_load_unlocked(name, import_)

ModuleNotFoundError: No module named 'keras.engine.base_layer_v1'

解决方法

这个错误通常是Keras版本与TensorFlow版本不兼容,或环境残留旧版本Keras缓存文件导致的,可按以下步骤处理:

  • 完全卸载并清理残留
    先卸载现有相关包:

    pip uninstall -y keras tensorflow tensorflow-gpu
    

    手动进入conda环境的site-packages目录(如c:\Users\Isaac\anaconda3\envs\textattackenv\lib\site-packages),删除所有带keras、tensorflow的文件夹和文件。

  • 安装匹配版本的TensorFlow
    TensorFlow 2.x已整合Keras,直接安装稳定版本的TensorFlow即可避免版本冲突:

    pip install tensorflow==2.15.0  # 推荐选择稳定版,如2.15.0
    
  • 修改导入方式
    使用TensorFlow官方推荐的tensorflow.keras导入路径替换原代码:

    from tensorflow.keras.models import Sequential
    from tensorflow.keras.layers import Embedding, LSTM, Dense
    
    model = Sequential()
    model.add(Embedding(10000, 64, input_length=80))
    model.add(LSTM(100))
    model.add(Dense(2, activation='sigmoid'))
    model.compile(loss='binary_crossentropy', metrics=['accuracy'], optimizer='adam')
    
  • 清理Python缓存
    删除项目目录及环境中的__pycache__文件夹,避免旧缓存干扰。

内容的提问来源于stack exchange,提问作者Messalti Ishak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 04:15:37