from keras import Sequential
from keras import layers
from keras import optimizers
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
model = Sequential()
model.add(layers.Conv2D(32,(3,3),activation="relu",input_shape=(150,150,3)))
model.add(layers.MaxPooling2D(2,2))
model.add(layers.Conv2D(64,(3,3),activation="relu"))
model.add(layers.MaxPooling2D(2,2))
model.add(layers.Conv2D(128,(3,3),activation="relu"))
model.add(layers.MaxPooling2D(2,2))
model.add(layers.Conv2D(128,(3,3),activation="relu"))
model.add(layers.MaxPooling2D(2,2))
model.add(layers.Flatten())
model.add(layers.Dropout(0.5))
model.add(layers.Dense(512,activation="relu"))
model.add(layers.Dense(1,activation="sigmoid"))
model.compile(
optimizer=optimizers.rmsprop(lr=1e-4),
loss = "binary_crossentropy",
metrics=["acc"]
)
#######################图像数据增强
train_datagen = ImageDataGenerator(
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,
)
#####图像归一化
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
"D:/cats_and_dogs_small/train",
target_size=(150,150),
batch_size=32,
class_mode="binary"
)
validation_generator = test_datagen.flow_from_directory(
"D:/cats_and_dogs_small/validation",
target_size=(150,150),
batch_size=32,
class_mode="binary"
)
history = model.fit_generator(
train_generator,
steps_per_epoch=100,
epochs=1,
validation_data=validation_generator,
validation_steps=50
)
# model.save("cat_and_dogs_small_2.h5")
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()