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

Windows环境下Keras 2.13.1报错:找不到tensorflow.keras模块求解

解决ModuleNotFoundError: No module named 'tensorflow.keras'问题

核心原因与解决方案

1. 版本不匹配导致冲突

从TensorFlow 2.x开始,Keras已被整合到TensorFlow内部,单独安装的Keras版本必须与TensorFlow严格对应。你安装的TensorFlow 2.13.0对应官方Keras版本应为2.13.0,而当前安装的2.13.1版本不兼容,导致tensorflow.keras模块无法被识别。

执行以下命令修复版本:

pip uninstall keras -y
pip install keras==2.13.0

2. 确认Python环境一致性

可能存在运行代码的环境与安装依赖的环境不一致的情况(比如未激活虚拟环境、多Python版本共存)。

  • 激活对应的虚拟环境(如果使用)
  • 运行pip list查看当前环境的TensorFlow和Keras版本,确保两者均为2.13.0

代码额外问题修正

即使解决模块问题,你的测试代码仍会因二分类任务配置错误报错,修正后的代码如下:

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

data = load_breast_cancer()
label_names = data['target_names']
labels = data['target']
feature_names = data['feature_names']
features = data['data']
train, test, train_labels, test_labels = train_test_split(features,labels,test_size = 0.40, random_state = 42)

model = Sequential()
model.add(Dense(units=64, activation='relu', input_shape=(30,)))  # 显式指定输入维度,避免警告
model.add(Dense(units=1, activation='sigmoid'))  # 二分类任务使用sigmoid激活,输出单元设为1

model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy'])  # 二分类对应binary_crossentropy
model.fit(train, train_labels, epochs=5, batch_size=32)
loss_and_metrics = model.evaluate(test, test_labels, batch_size=128)
classes = model.predict(test, batch_size=128)

print(loss_and_metrics)
print(classes)

内容的提问来源于stack exchange,提问作者Roberto Scarciello

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 18:05:02