小言_互联网的博客

猫狗图像分类_1

313人阅读  评论(0)
  • 需要猫狗图像数据集的私戳我
# coding: utf-8
"""Kaggle发布的猫狗数据集
   4000张猫狗图片,2000张猫,2000张狗。将2000张图片用于训练,1000张用于验证,1000张用于测试
   下载数据集之后,创建一个新的数据集,包含三个子集:每个类别各1000各样本的训练集,500各样本的验证集,500各样本的测试机"""
import os, shutil


original_dataset_dir = '/python 深度学习/datasets/kaggle/train' # 原始数据集的路径
base_dir = '/python 深度学习/datasets/cats_and_dogs_small' # 保存较小数据集的目录
os.mkdir(base_dir) # 在指定路径下创建一个文件夹

# ------------------------------划分训练、验证、测试的数据集目录-------------------------------------------------------------------
train_dir = os.path.join(base_dir, 'train')
os.mkdir(train_dir)

validation_dir = os.path.join(base_dir, 'validation')
os.mkdir(validation_dir)

test_dir = os.path.join(base_dir, 'test')
os.mkdir(test_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)

# ----------------------划分猫狗的验证数据集目录---------------------------------------------------------------------------------------
validation_cats_dir = os.path.join(validation_dir, 'cats')
os.mkdir(validation_cats_dir)

validation_dogs_dir = os.path.join(validation_dir, 'dogs')
os.mkdir(validation_dogs_dir)

# ----------------------划分猫狗的测试数据集目录------------------------------------------------------------------------------------------
test_cats_dir = os.path.join(test_dir, 'cats')
os.mkdir(test_cats_dir)

test_dogs_dir = os.path.join(test_dir, 'dogs')
os.mkdir(test_dogs_dir)
# coding: utf-8
"""在创建好的文件里面填充数据,将数据复制到里面"""
# ----------------------------------将前1000张猫的图片复制到train_cats_dir中-------------------------------------------------------------
fnames = ['cat.{}.jpg'.format(i) for i in range(1000)]
for fname in fnames:
    scr = os.path.join(original_dataset_dir, fname)
    dst = os.path.join(train_cats_dir, fname)
    shutil.copyfile(scr, dst)
    
# ----------------------------------将接下来的500张猫的图片复制到validation_cats_dir中---------------------------------------------------------------
fnames = ['cat.{}.jpg'.format(i) for i in range(1000, 1500)]
for fname in fnames:
    scr = os.path.join(original_dataset_dir, fname)
    dst = os.path.join(validation_cats_dir, fname)
    shutil.copyfile(scr, dst)
    
# ---------------------------------将接下来的500张猫的图片复制到test_cats_dir--------------------------------------------------------
fnames = ['cat.{}.jpg'.format(i) for i in range(1500, 2000)]
for fname in fnames:
    scr = os.path.join(original_dataset_dir, fname)
    dst = os.path.join(test_cats_dir, fname)
    shutil.copyfile(scr, dst)
    
# ---------------------------------将1000张狗的图片复制到train_dogs_dir--------------------------------------------------------
fnames = ['dog.{}.jpg'.format(i) for i in range(1000)]
for fname in fnames:
    scr = os.path.join(original_dataset_dir, fname)
    dst = os.path.join(train_dogs_dir, fname)
    shutil.copyfile(scr, dst)
    
# ----------------------------------将接下来的500张狗的图片复制到validation_dogs_dir中---------------------------------------------------------------
fnames = ['dog.{}.jpg'.format(i) for i in range(1000, 1500)]
for fname in fnames:
    scr = os.path.join(original_dataset_dir, fname)
    dst = os.path.join(validation_dogs_dir, fname)
    shutil.copyfile(scr, dst)
    
# ---------------------------------将接下来的500张狗的图片复制到test_dogs_dir--------------------------------------------------------
fnames = ['dog.{}.jpg'.format(i) for i in range(1500, 2000)]
for fname in fnames:
    scr = os.path.join(original_dataset_dir, fname)
    dst = os.path.join(test_dogs_dir, fname)
    shutil.copyfile(scr, dst)
print(len(os.listdir(train_cats_dir)))
print(len(os.listdir(train_dogs_dir)))
print(len(os.listdir(validation_cats_dir)))
print(len(os.listdir(validation_dogs_dir)))
print(len(os.listdir(test_cats_dir)))
print(len(os.listdir(test_dogs_dir)))
# coding: utf-8
"""网络构建"""
from tensorflow.keras import layers
from tensorflow.keras import models

model = models.Sequential()

model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 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.Dense(512, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

model.summary()

# coding: utf-8
"""配置模型用于训练"""
from tensorflow.keras import optimizers


model.compile(optimizer=optimizers.RMSprop(lr=1e-4),
              loss='binary_crossentropy',
              metrics=['acc'])
# coding: utf-8
"""数据预处理
   数据输入神经网络前,应该将数据格式化为经过预处理的浮点张量,目前的数据格式jpeg
   (1)读取图像文件
   (2)将JPEG文件解码为RGB
   (3)像素转化为浮点张量
   (4)normalization化,标准化数据,缩放到【0, 1】之间(神经网络喜欢处理较小的输入值)
   keras自带图像转化工具,快速创建python生成器,将硬盘上的图像文件自动转化为预处理好的张量,批量"""
from tensorflow.keras.preprocessing.image import ImageDataGenerator


# 将所有图像乘以1/255
train_datagen = ImageDataGenerator(rescale=1./255) 
test_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(train_dir, # 目标目录
                                                    target_size=(150, 150), # 大小
                                                    batch_size=20, 
                                                    class_mode='binary') # 因为使用binary_crossentropy所以需要二进制标签

validation_generator = test_datagen.flow_from_directory(validation_dir,
                                                        target_size=(150, 150),
                                                        batch_size=20,
                                                        class_mode='binary')
# coding: utf-8
"""利用批量生成器拟合模型"""
history = model.fit_generator(train_generator,
                              steps_per_epoch=100,
                              epochs=30,
                              validation_data=validation_generator,
                              validation_steps=50)

# ------------------------保存模型是个好习惯-----------------------------------------
model.save('cats_and_dogs_small_1.h5')


# coding: utf-8
"""绘制训练过程的损失与精度曲线"""
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, 30 + 1)

plt.plot(epochs, acc, 'bo', label='Training accuracy')
plt.plot(epochs, val_acc, 'b', label='Validation accuracy')
plt.xlabel('epochs')
plt.ylabel('accuracy')
plt.title('Training and Validation accuracy')
plt.legend()
plt.show()

plt.plot(epochs, loss, 'ro', label='Training loss')
plt.plot(epochs, val_loss, 'r', label='Validation loss')
plt.xlabel('epochs')
plt.ylabel('loss')
plt.title('Training and Validation loss')
plt.legend()
plt.show()

# 由于选择的样本较少,故发生了过拟合


转载:https://blog.csdn.net/weixin_44478378/article/details/102575365
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场