今天温习了一下keras实现猫狗两种图像分类的功能,具体的代码我贴在下面了:
训练和loss acc监测:
from keras import layers
from keras import models
from keras import optimizers
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
model = models.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.Dense(512, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer=optimizers.RMSprop(lr=1e-4), metrics=['acc'])
# data preprocessing
base_path = '/Users/**/猫狗图像分类/dogs-vs-cats/'
test_path = '/Users/**/猫狗图像分类/test_t/'
train_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
base_path,
target_size=(150,150),
batch_size=64,
class_mode='binary'
)
validation_generator = test_datagen.flow_from_directory(
test_path,
target_size=(150,150),
batch_size=20,
class_mode='binary'
)
history = model.fit_generator(
train_generator,
steps_per_epoch=190,
epochs=10,
validation_data=validation_generator,
validation_steps=7 # 从验证生成器中抽取多少个批次用于评估
)
model.save('catdog.h5')
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(acc) + 1)
plt.plot(epochs, acc, 'bo', label='Traing acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('train and val acc')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label='Traing loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('train and val loss')
plt.legend()
plt.show()
测试过程中loss和acc的图像效果如下:
loss-acc.png
train-val acc.png
关于flow_from_directory函数的参数需要说明一下:
directory:子文件夹所在的目录
classes:类别,子文件夹的数量,如['cat', 'dog']
class_mode:可以是'categorical'
batch_size
target_size:输出的图像尺寸如,(150,150)
下面是测试代码:
import os
import numpy as np
from keras.preprocessing import image
from keras.models import load_model
base_path = r'/Users/**/猫狗图像分类/dogs-vs-cats/dog'
model = load_model('catdog.h5')
num = 100
files_name = [name for name in os.listdir(base_path) if os.path.splitext(name)[1]=='.jpg']
sum = 0
for i in range(num):
# print()
f = str(i+1)+'.jpg'
f = files_name[i]
# print(f)
file_path = os.path.join(base_path, f)
img = image.load_img(file_path, target_size=(150, 150))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
y = model.predict_classes(x)
print(i, ' ', f, ' ', y)
if y[0][0]:
sum += 1
print('sum', sum)
点个小心心在走吧💗
网友评论