简介:
本文主要介绍Python中,使用TensorFlow时,执行from keras.layers.normalization import BatchNormalization报错ImportError: cannot import name ‘BatchNormalization’ from ‘keras.layers.normalization’ 解决方法 。
报错信息:
Traceback (most recent call last):
File "C:\Data\breast-cancer-classification\train_model.py", line 10, in <module>
from cancernet.cancernet import CancerNet
File "C:\Data\breast-cancer-classification\cancernet\cancernet.py", line 2, in <module>
from keras.layers.normalization import BatchNormalization
ImportError: cannot import name 'BatchNormalization' from 'keras.layers.normalization' (C:\Users\Catalin\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\layers\normalization\__init__.py)
版本信息:
Keras version: 2.6.0
Tensorflow: 2.6.0
Python version: 3.9.7
安装使用的命令如下:
pip install numpy opencv-python pillow tensorflow keras imutils scikit-learn matplotlib
问题原因:
使用的是之前老的tf.keras导入。Layers现在可以直接从tensorflow.keras.layers导入。如下:
from tensorflow.keras.layers import BatchNormalization
示例代码:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import (
BatchNormalization, SeparableConv2D, MaxPooling2D, Activation, Flatten, Dropout, Dense
)
from tensorflow.keras import backend as K
class CancerNet:
@staticmethod
def build(width, height, depth, classes):
model = Sequential()
shape = (height, width, depth)
channelDim = -1
if K.image_data_format() == "channels_first":
shape = (depth, height, width)
channelDim = 1
model.add(SeparableConv2D(32, (3, 3), padding="same", input_shape=shape))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=channelDim))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(SeparableConv2D(64, (3, 3), padding="same"))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=channelDim))
model.add(SeparableConv2D(64, (3, 3), padding="same"))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=channelDim))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(SeparableConv2D(128, (3, 3), padding="same"))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=channelDim))
model.add(SeparableConv2D(128, (3, 3), padding="same"))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=channelDim))
model.add(SeparableConv2D(128, (3, 3), padding="same"))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=channelDim))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256))
model.add(Activation("relu"))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(classes))
model.add(Activation("softmax"))
return model
model = CancerNet()
了解更多分析及数据抓取可查看:
http://cloud.yisurvey.com:9081/html/529942a8-212c-4c85-9c92-9c56beb4a299.html?ly=csdn
特别说明:本文旨在技术交流,请勿将涉及的技术用于非法用途,否则一切后果自负。如果您觉得我们侵犯了您的合法权益,请联系我们予以处理。