from keras import Sequential
from keras import layers
from keras import optimizers
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
import keras
height = 224
width = 224
channels = 3
num_classes = 10
resNet50_fineTuneModel = Sequential()
resNet50_fineTuneModel.add(keras.applications.ResNet50(
include_top=False,
pooling="avg",
weights='imagenet'
))
resNet50_fineTuneModel.add(keras.layers.Dense(num_classes,activation="softmax"))
#######设置该resNet层不可训练
resNet50_fineTuneModel.layers[0].trainable = False
resNet50_fineTuneModel.compile(
optimizer="sgd",
loss="categorical_crossentropy",
metrics=["acc"]
)
#######################图像数据增强
train_datagen = ImageDataGenerator(
##########模型微调,已经归一化了
preprocessing_function=keras.applications.resnet50.preprocess_input,
# rescale=1. / 255, #####已经归一化,所以注释
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode="nearest"
)
valid_datagen = ImageDataGenerator(
##########模型微调
preprocessing_function=keras.applications.resnet50.preprocess_input,
)
batch_size = 32
train_generator = train_datagen.flow_from_directory(
"D:/monkey10_species/training/training",
target_size=(height, width),
batch_size=batch_size,
seed=10,
shuffle=True,
class_mode="categorical"
)
train_nums = train_generator.samples
validation_generator = valid_datagen.flow_from_directory(
"D:/monkey10_species/validation/validation",
target_size=(height, width),
batch_size=batch_size,
seed=10,
shuffle=False,
class_mode="categorical"
)
validation_nums = validation_generator.samples
epoches = 100
history = resNet50_fineTuneModel.fit_generator(
train_generator,
steps_per_epoch=train_nums // batch_size,
epochs=epoches,
validation_data=validation_generator,
validation_steps=validation_nums // batch_size
)
print(history.history.keys())
acc = history.history["acc"]
val_acc = history.history["val_acc"]
loss = history.history["loss"]
val_loss = history.history["val_loss"]
Epoches = range(1, len(acc) + 1)
plt.plot(Epoches, acc, "bo", label="Traing acc")
plt.plot(Epoches, val_acc, "b", label="Validation acc")
plt.title("Training and validation accuracy")
plt.legend()
plt.show()
plt.plot(Epoches, loss, "bo", label="Traing loss")
plt.plot(Epoches, val_loss, "b", label="Validation loss")
plt.title("Training and validation loss")
plt.legend()
plt.show()
设置最后5层可训练
resNet50 = keras.applications.ResNet50(include_top = False,pooling="avg",weights="imagenet")
for layer in resNet50.layers[0:-5]:
layer.trainable = False
resNet50_new = keras.models.Sequential()
resNet50_new.add(reesNet50)
resNet50_new.add(keras.layers.Dense(num_classes,activation="softmax")