深度挖掘AI的图像分类能力!


今天第一节介绍如何搭建一个自己的神经网络,让他分辨猫狗,并且知道他是如何分类的!更有原创视频介绍!猫狗分类,正式开始!看完,加油~

今天开更,干货满满!一开始我们就从实践项目开始,第一个重量级练手项目就是猫狗大战,我们计划分为三个部分来讲解,逐步提高我们的分类精度,在这个项目中,你将get:1、Keras基本方法;2、基本网络设计;3、迁移学习思想;4、Dropout作用及效果;5、数据增强作用及效果;6、集成方法的强大魅力!

2014年,Kaggle举办了一项竞赛,以确定图像中包含猫还是狗。本项目将使用Keras创建CNN,来测试精度,继而使用迁移学习,进而应用图像增强。在第1部分,我们将从一个基本的神经网络开始,该神经网络在预测图像包含猫还是狗时的准确率为84%。然后,我们将添加Dropout,并进行数据增强,以达到92.8%的分类精度。在第2部分中,我们将看到如何微调在ImageNet上进行预训练的网络,并利用迁移学习来达到98.6%的准确度(获胜作品得分98.9%)。在第3部分中,更换使用PyTorch而不是Keras来构建集成模型,这些模型集成起来提供的预测能力比任何单个模型都更高,并且达到99.1%的准确性。

猫狗大战第一节:使用Keras手搭CNN加Dropout并数据增强可以达到92.8%的分类精度具体查看视频:https://pan.baidu.com/s/1Qu8iYqLUugv9qMgkXt0ypQ提取码:1q20





数据集下载:在Kaggle网站搜索cat vs dog即可。




本章完整代码!代码讲解请看视频(文章首部):

from keras import layers, models, optimizers
import os
import tensorflow as tf
from keras.preprocessing import image
import matplotlib.pyplot as plt
from keras.preprocessing.image import ImageDataGenerator

os.environ["CUDA_VISIBLE_DEVICES"] = "0"
gpu_options = tf.GPUOptions(allow_growth=True)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))


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')

fnames = [os.path.join('./train_total/cat/', fname) for fname in os.listdir('./train_total/cat/')]
img_path = fnames[4]  # Choose one image to augment
img = image.load_img(img_path, target_size=(224, 224)) # load image and resize it
x = image.img_to_array(img) # Convert to a Numpy array with shape (224, 224, 3)
x = x.reshape((1,) + x.shape)

i = 0
for batch in datagen.flow(x, batch_size=1):
    plt.figure(i)
    imgplot = plt.imshow(image.array_to_img(batch[0]))
    i += 1
    if i % 3 == 0:
        break
plt.show()

model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)))
model.add(layers.MaxPool2D(2, 2))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPool2D(2, 2))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPool2D(2, 2))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPool2D(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'])


train_datagen = ImageDataGenerator(rescale=1./255)
# keras 数据增强
# 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_total/',
    target_size=(224, 224),  # resize all images to 224 x 224
    batch_size=80,
    class_mode='binary')  # because we use binary_crossentropy loss we need binary labels

validation_generator = test_datagen.flow_from_directory(
    r'E:\python_file\Pytorch_Advanced\val_total',
    target_size=(224, 224),
    batch_size=80,
    class_mode='binary')

history = model.fit_generator(
    train_generator,
    steps_per_epoch=320,  # 50 batches in the generator, so it takes 320 batches to get to 16000 images
    epochs=30,
    validation_data=validation_generator,
    validation_steps=90)

test_generator = test_datagen.flow_from_directory(
    r'E:\python_file\Pytorch_Advanced\val_total',
    target_size=(224, 224),
    batch_size=50,
    class_mode='binary')

test_loss, test_acc = model.evaluate_generator(test_generator, steps=90)
print('test acc:', test_acc)
model.save('models/cat_dog.h5')






 

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')