0
点赞
收藏
分享

微信扫一扫

解决 Keras 2.7.0以及更新版本后遇到的几处常见错误

f12b11374cba 2022-02-07 阅读 86

在这里插入图片描述

解决 Keras 2.7.0以及更新版本后遇到的几处常见错误

文章目录

1. 关于ValueError: : The data_format argument must be one of “channels_first”, “channels_last”. Received: channel_first

ValueError: The `data_format` argument must be one of "channels_first", "channels_last". Received: channel_first

  上述bug来自于下面代码中,原因其实很简单,因为将channels 写成了 channel,但是在此着重介绍一下data_format参数,data_format:是 一个字符串参数,其中末端通道(Channels Last)表示图像数据以三维阵列表示,而最后一个通道代表颜色通道;首端通道(Channels First)表示图像数据以三维阵列表示,其中第一通道代表颜色通道,例如彩色通道。 [channels],[rows],[cols]。此外,网络中,通常以 channels_last为默认值 , channels_last 对应着 (batch_size, height, width, channels) ,而 channels_first 对应的输入为 (batch_size, channels, height, width). 而其默认为源文件是 在~/.keras/keras.json.中的image_data_format 的值 ,若未更改这个地方,它就会是默认channels_last。

model.add(MaxPool2D(
    pool_size = 2,       #卷积核大下
    strides = 2,         #步长
    padding = 'same',    #降维操作
    data_format = 'channel_first',
))  

深度学习中图片格式Channels-First和 Channels-Last问题简介
keras Conv2D参数详解

2.ImportError: cannot import name ‘get_config’

ImportError: cannot import name 'get_config'

  此处import错误是由keras更新而导致的问题,通常在keras前边添加tensorflow.便可解决,其import的bug出自以下代码:

from keras.datasets import mnist        #从Keras的datasets库导入mnist数据集
from keras.models import Sequential
from keras.layers import Dense, Activation, Convolution2D, MaxPool2D,Flatten
from keras.optimizers import Adam

修改为

from tensorflow.keras.datasets import mnist        #从Keras的datasets库导入mnist数据集
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, Convolution2D, MaxPool2D,Flatten
from tensorflow.keras.optimizers import Adam

3. ImportError: cannot import name ‘np_utils’

ImportError: cannot import name 'np_utils'

  此处import的bug原因同样是源于keras的升级,下面源码是需要利用np_utils中的.to_categorical将标签转换为One-Hot编码:

from tensorflow.keras.utils import np_utils
y_train = np_utils.to_categorical(y_train, num_classes = 10)
y_test = np_utils.to_categorical(y_test, num_classes = 10)

  在此做如下修改,依然可以实现to_categorical的功能:将from tensorflow.keras.utils import np_utils 替换为from tensorflow.python.keras.utils.np_utils import to_categorical,之后代码做相应微调:

from tensorflow.python.keras.utils.np_utils import to_categorical
y_train = to_categorical(y_train, num_classes = 10)
y_test = to_categorical(y_test, num_classes = 10)

  解决ImportError: cannot import name ‘np_utils‘ from ‘tensorflow.keras.utils‘ 的问题

  最后附上其代码成功运行后结果:

10000/10000 [==============================] - 3s 296us/sample - loss: 0.0853 - acc: 0.9752

test loss:  0.08534580951035023

test accuracy:  0.9752

Process finished with exit code 0
举报

相关推荐

0 条评论