# 找到的一些归一化/标准化的操作,未测试
# 归一化
norm_image = cv2.normalize(img, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
# 标准化
img -= np.mean(img, keepdims=True)
img /= np.std(img, keepdims=True) + K.epsilon()
# OpenCV读取
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
# Pillow读取
img = pil_image.open(expand_path(p))
img = img.convert('L')
可用Keras中提供的ImageDataGenerator()
函数
列出了一些常用的参数,详见:https://keras.io/preprocessing/image/
datagen = ImageDataGenerator(
featurewise_center=False, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalization=False, # divide inputs by std of the dataset
samplewise_std_normalization=False, # divide each input by its std
zca_whitening=False, # apply ZCA whitening
rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180)
zoom_range = 0.1, # Randomly zoom image
width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)
height_shift_range=0.1, # randomly shift images vertically (fraction of total height)
horizontal_flip=True, # randomly flip images
vertical_flip=False) # randomly flip images
img1 = cv2.imread('46.bmp')
# img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) # 转换通道顺序
img2 = Image.open('46.bmp')
img2 = np.asarray(img2)
plt.subplot(121),plt.imshow(img1)
plt.subplot(122),plt.imshow(img2)
img = cv2.imread(TRAIN_DIR+'cat.0.jpg', cv2.IMREAD_GRAYSCALE)
plt.imshow(img, cmap='gray')
image = image.reshape(ROWS, COLS, 1)
搭建完网络后用model.summary()
查看网络结构,看是否正确
Keras模型可视化
安装相应模块
pip install pydot-ng
pip install graphviz
pip install pydot
安装了以上模块,但是还是报错误,发现GraphViz的可执行文件没有:
OSError: pydot failed to call GraphViz.Please install GraphViz (https://www.graphviz.org/) and ensure that its executables are in the $PATH.
apt install graphviz
,问题解决。打印模型图
from keras.utils import plot_model
plot_model(model, to_file='model.png')
注意设置通道顺序
from keras import backend
backend.set_image_dim_ordering('th') # th通道最前,tf通道最后
训练技巧——Callbacks
early_stopping、ModelCheckpoint、learning_rate_reduction
不能用keras 2.2.3 保存模型的时候有bug,升级到2.2.4解决
KeyError: 'Cannot set attribute. Group with name "keras_version" exists.'
第14章 使用保存点保存最好的模型 · 深度学习:Python教程
learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc',
patience=3,
verbose=1,
factor=0.5,
min_lr=0.00001)
early_stopping = EarlyStopping(monitor='val_loss', patience=6, min_delta=0.0002, verbose=1, mode='auto')
filepath="./weights/weights.best.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='auto')
model_his = model.fit_generator(datagen.flow(X_train,Y_train, batch_size=batch_size),
epochs = epochs, validation_data = (X_val,Y_val),
shuffle=True, verbose = 1,
steps_per_epoch=X_train.shape[0] // batch_size
, callbacks=[learning_rate_reduction,
early_stopping, checkpoint])
过拟合
Conv2D、Batch Normalization、activation、pooling、dropout层的效果和顺序
图像读取顺序
图像标签编码