Python Keras module 'keras.backend' has no attribute 'image_data_format'

问题:

当使用Keras运行示例程序mnist_cnn时,出现如下错误: 'keras.backend' has no attribute 'image_data_format'

程序路径https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py

使用的python conda环境是udacity自动驾驶课程的carnd-term1

 

故障程序段:

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

完整代码见 https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py

 

故障分析:

conda环境中的Keras版本比例子程序中的版本旧,因此没有'image_data_format'这个变量

 

解决方法:

以下两种方法,任选其一

1)如果不升级Keras版本

将 K.image_data_format() == 'channels_first' 替换为 K.image_dim_ordering() == 'th'

 

2)升级Keras版本到最新

 > activate carnd-term1 //激活你的conda环境,我的这个环境叫做carnd-term1

 (carnd-term1)> conda list //显示当前环境中安装的包

 (carnd-term1)> pip uninstall Keras //卸载旧版本的Keras, Keras是使用pip方式安装的,因此卸载和重装都要使用pip相关命令

 (carnd-term1)> pip install Keras //重新安装新版本的Keras

 (carnd-term1)> conda list //检查版本是否已经更新

 

posted on 2017-05-06 14:34  lion_zheng  阅读(12770)  评论(0编辑  收藏  举报

导航