猫狗大战
- 自制模型
数据导入
将图像复制到训练,验证和测试目录
import os import shutil TRAIN_DIR = 'D:\\Jupyter\\dogs-vs-cats\\' BASE_DIR = 'E:\\BaiduNetdiskDownload\\kaggle\\train\\' #举一个train文件夹的例子 train_dir = os.path.join(TRAIN_DIR, 'train') #os.mkdir(train_dir) train_cats_dir = os.path.join(train_dir, 'cats') #os.mkdir(train_cats_dir) train_dogs_dir = os.path.join(train_dir, 'dogs') #os.mkdir(train_dogs_dir) #举一个复制图片里猫猫的例子 fnames = ['cat.{}.jpg'.format(i) for i in range(1000)] for fname in fnames: src = os.path.join(BASE_DIR, fname) dst = os.path.join(train_cats_dir, fname) shutil.copyfile(src, dst) fnames = ['cat.{}.jpg'.format(i) for i in range(1000,1500)] for fname in fnames: src = os.path.join(BASE_DIR, fname) dst = os.path.join(validation_cats_dir, fname) shutil.copyfile(src, dst) fnames = ['cat.{}.jpg'.format(i) for i in range(1500,2000)] for fname in fnames: src = os.path.join(BASE_DIR, fname) dst = os.path.join(test_cats_dir, fname) shutil.copyfile(src, dst)![目录结构](https://upload-images.jianshu.io/upload_images/2145769-86964833bc33a46a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/245)
### 构建模型
#定义一个包含dropout层的新卷积网络 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.Flatten()) model.add(layers.Dropout(0.5)) 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'])
数据预处理
使用数据增强
datagen = ImageDataGenerator( 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'#用于填充创建像素的方法,这些新像素可能来自旋转或宽度/高度平移 ) #增强预览 from keras .preprocessing import image fnames = [os.path.join(train_cats_dir, fname) for fname in os.listdir(train_cats_dir)] img_path = fnames[50]#选一张图片进行增强 img = image.load_img(img_path, target_size=(150, 150))#读取图像并且调整大小 x = image.img_to_array(img)#将其形状变成形状为(150,150,3)的Numpy数组 x = x.reshape((1,) + x.shape)#将其形状改变成为(1,150,150,3) i = 0 for batch in datagen.flow(x, batch_size=1): plt.figure() imgplot = plt.imshow(image.array_to_img(batch[0])) i += 1 if i % 4 ==0: break plt.show()
使用ImageDataGenerator从目录中读取图像
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( train_dir, target_size=(150, 150), batch_size=32, class_mode='binary',#因为使用了binary_crossentropy损失,所以需要用二进制标签 ) validation_generator = test_datagen.flow_from_directory( validation_dir, target_size=(150, 150), batch_size=32, class_mode='binary' )
利用批量生成器拟合模型
history = model.fit_generator( train_generator, steps_per_epoch=100, epochs=100, validation_data=validation_generator, validation_steps=50 )
绘制训练过程中的损失曲线和精度曲线
import matplotlib.pyplot as plt 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='Training acc') plt.plot(epochs, val_acc, 'b', label='Validaton acc') plt.title('Training and Validation accuracy') plt.legend() plt.figure() plt.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and Validation loss') plt.legend() plt.show()
保存模型
model.save(‘cats_and_dogs_small_2.h5’)