Tensorflow 2.16.0+在PyCharm中找不到keras的报错解决

在PyCharm(2024.2版本)中,直接使用from tensorflow import keras会提示"Cannot find reference 'keras' in 'init .py' ",找不到keras,如下图所示。

查阅相关资料,可以发现在tf2.16之后,默认的keras后端升级为了3.0,且直接引用即可。

参考链接:PyCharm cannot parse any content under tensorflow.keras 2.16.2 #73110

以及:Introducing Keras 3.0

TF 2.15: Keras2.0

python 复制代码
import tensorflow as tf
from tensorflow import keras

TF 2.16: Keras 3.0

python 复制代码
import tensorflow as tf
import keras

reddit上也有人讨论:

Because in the old days Keras was entirely separate to Tensorflow. It had a backend for Theano and maybe some other stuff. Then Francois and the TF team at Google decided to bring Keras into TF as their main high level API, trying to address the fragmentation that had been created in TF land. Since TF usage is dwindling in research, and possibly showing signs of similar in industry, Keras is now multi-backend again, supporting TensorFlow, PyTorch, and JAX.

  1. Very old code will import keras directly, and be referring to Keras 1. This code will usually use > Theano or TensorFlow 1.x as well.
  2. More recent code will import tensorflow.keras and be referring to Keras 2. This is the majority of the code you'll find.
  3. Very recent code (i.e. this year I think) will import keras directly again, or maybe keras_core, and be referring to Keras 3, the latest version.

也就是说,在最新版(2.16.0+)的Tensorflow中,只需要直接引用import keras即可正常使用keras3.0。经测试,使用keras.modelskeras.layers均可正常使用,也会有代码补全。

相关推荐
qq_2575630715 小时前
PyCharm高效快捷键全攻略
pycharm·快捷键
知远同学1 天前
Pycharm顶部菜单栏固定显示
ide·python·pycharm
Everybody_up2 天前
pycharm中编译环境配置
ide·python·pycharm
雪落无尘处2 天前
Anaconda 虚拟环境配置全攻略+Pycharm使用虚拟环境开发:从安装到高效管理
后端·python·pycharm·conda·anaconda
Franklin2 天前
移植一个Pycharm的复杂项目:
ide·python·pycharm
祁思妙想2 天前
修改python后端项目名称:pycharm中fastapi框架的项目
ide·pycharm·fastapi
星源~2 天前
TensorFlow 开发环境搭建指南:Anaconda 与 Miniconda 抉择及环境搭建步骤
人工智能·python·tensorflow·嵌入式·mcu+ai
BBB努力学习程序设计3 天前
Python异步编程完全指南:从asyncio到高性能应用
python·pycharm
BBB努力学习程序设计3 天前
Python迭代器与生成器深度解析:懒加载的艺术
python·pycharm
程序员龙语3 天前
CSS 盒模型与文档流
人工智能·python·tensorflow