import keras
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.utils import plot_model
import os
import time
"""
(1). 如何保存模型
保存模型,训练好之后就可以保存了
save_dir = os.path.join(os.getcwd(), 'saved_models') # 存放文件夹地址
model_name = 'keras_cifar10_trained_model.h5' # 模型名称,用.h5保存
if not os.path.isdir(save_dir): # 文件夹地址是否存在
os.makedirs(save_dir) # 如果不存在,则创建地址
model_path = os.path.join(save_dir, model_name) # 模型的存放地址
# 利用model.save(地址)保存
model.save(model_path)
(2). 流程
# 1. 超参数
# 2.加载数据
# 3.搭建模型
# 4.编译模型
# 5.训练数据
# 6.保存模型
# 7.预测模型
(3). 生成器使用
datagen = ImageDataGenerator()
train_generator = datagen.flow()
model.fit_generator()
"""
start = time.time()
batch_size = 128
num_classes = 10
epochs = 5
data_augmentation = True
num_predictions = 20
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
y_train = keras.utils.to_categorical(y=y_train, num_classes=num_classes)
y_test = keras.utils.to_categorical(y=y_test, num_classes=num_classes)
model = Sequential()
model.add(Conv2D(filters=32, kernel_size=(3, 3),
padding='same', activation='relu',
input_shape=x_train.shape[1:]))
model.add(Conv2D(filters=32, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(rate=0.25))
model.add(Conv2D(filters=64, kernel_size=(3, 3), padding='same', activation='relu'))
model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))
model.add(Dropout(rate=0.25))
model.add(Flatten())
model.add(Dense(units=512, activation='relu'))
model.add(Dropout(rate=0.5))
model.add(Dense(units=num_classes, activation='softmax'))
opt = keras.optimizers.rmsprop(lr=0.0001, decay=1e-6)
model.compile(loss='categorical_crossentropy',
optimizer=opt,
metrics=['accuracy'])
if not data_augmentation:
print('不使用数据增强')
model.fit(x=x_train, y=y_train,
batch_size=batch_size,
epochs=epochs,
validation_data=(x_test, y_test),
shuffle=True)
else:
print("使用图像数据增强")
datagen = ImageDataGenerator(
featurewise_center=False,
samplewise_center=False,
featurewise_std_normalization=False,
samplewise_std_normalization=False,
zca_whitening=False,
rotation_range=0,
width_shift_range=0.1,
height_shift_range=0.1,
horizontal_flip=True,
vertical_flip=False,
)
datagen.fit(x_train)
train_generator = datagen.flow(x=x_train, y=y_train, batch_size=batch_size)
model.fit_generator(generator=train_generator,
epochs=epochs, validation_data=(x_test, y_test), workers=4)
save_dir = os.path.join(os.getcwd(), 'saved_models')
model_name = 'keras_cifar10_trained_model.h5'
if not os.path.isdir(save_dir):
os.makedirs(save_dir)
model_path = os.path.join(save_dir, model_name)
model.save(model_path)
plot_model(model=model, to_file='models/cifar10_cnn.png')
scores = model.evaluate(x=x_test, y=y_test, verbose=1)
print('Test loss:', scores[0])
print('Test accuracy:', scores[1])
end = time.time()
print("训练完成时间:", end-start, "s")