AttributeError: module 'tensorflow' has no attribute 'keras'相关问题解决方案

1、如题,在jupyter中提示如下报错信息:

AttributeError: module 'tensorflow' has no attribute 'keras'相关问题解决方案_第1张图片

经过查阅资料,个人认为应该是没有安装keras所致(忘记之前有没有安装过)。

2、 安装keras:

首先,电脑上得安装好anaconda并完成相关环境的配置。

–conda install theano
–conda install keras
出现如下信息,提示安装网站有问题,也懒得去解决这些问题。
AttributeError: module 'tensorflow' has no attribute 'keras'相关问题解决方案_第2张图片

直接 pip install keras==(版本)

若版本不一致:虽然也可以提示安装成功:

AttributeError: module 'tensorflow' has no attribute 'keras'相关问题解决方案_第3张图片AttributeError: module 'tensorflow' has no attribute 'keras'相关问题解决方案_第4张图片
但在jupyter中,调用keras模块相关功能时会提示:
AttributeError: module 'tensorflow' has no attribute 'keras'相关问题解决方案_第5张图片

此处一定要安装和TensorFlow版本一致的keras,否则会提示ModuleNotFoundError: No module named ‘tensorflow.python.eager’。检查TensorFlow版本可以在Python命令行下或jupyter中通过import tensorflow as tf和tf.__version__命令来查看版本。此为版本说明(https://docs.floydhub.com/guides/environments/)。

该篇博客也可供参考tensorflow和keras对应版本问题

所以一定要选择和TensorFlow版本一致的keras。若安装版本不一致,也可直接使用pip install -U tensorflow,升级TensorFlow到最新版本即可。

在这里插入图片描述

安装成功如下图:

AttributeError: module 'tensorflow' has no attribute 'keras'相关问题解决方案_第6张图片

3、检查keras是否安装成功:在终端进入Python环境,输入命令:import keras之后,若出现Using TensorFlow backend.则表示keras安装成功,如下图:

AttributeError: module 'tensorflow' has no attribute 'keras'相关问题解决方案_第7张图片

也有可能出现警告,如FutureWarning: Conversion of the second argument of issubdtype from ‘float’to ‘np.floating’ is deprecated. In future, it will be treated as’np.float64==np.dtype(float).type’. from ._conv import register_converters as _register_converters(此处忘记截图)。上网查阅发现为包内出错,是h5py包出现问题,

解决办法:对h5py进行更新升级,在命令窗口执行pip install h5py==2.8.0rc1命令即可。

4、安装keras之后,jupyter执行model = tf.keras.models.Sequential()语句仍有问题,提示AttributeError: module ‘tensorflow’ has no attribute ‘keras’。

解决办法:将model=tf.keras.models.Sequential()替换成model=tf.contrib.keras.models.Sequential(),成功执行。问题解决,原因如下:keras文件路径问题。

AttributeError: module 'tensorflow' has no attribute 'keras'相关问题解决方案_第8张图片

参考博客:https://blog.csdn.net/qq_34333481/article/details/84023848

https://blog.csdn.net/aioy123456/article/details/99306439


总结和收获:本来keras已经安装成功,但在jupyter中仍会报错,提示没有keras模块,便一直以为keras没有安装成功,反反复复查阅资料和卸载安装keras。几经思考之后认为是不是安装两个版本的Python的问题,于是花了大量时间在两个版本的Python的安装与运行上面,心态一度崩溃。还好经过这次学习,对anaconda的一些配置文件有了简单的了解,便于进一步的学习。

你可能感兴趣的:(TensorFlow)