keras分类之二分类实例(Cat and dog)


Posted in Python onJuly 09, 2020

1. 数据准备

在文件夹下分别建立训练目录train,验证目录validation,测试目录test,每个目录下建立dogs和cats两个目录,在dogs和cats目录下分别放入拍摄的狗和猫的图片,图片的大小可以不一样。

2. 数据读取

# 存储数据集的目录
base_dir = 'E:/python learn/dog_and_cat/data/'
 
# 训练、验证数据集的目录
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'validation')
test_dir = os.path.join(base_dir, 'test')
 
# 猫训练图片所在目录
train_cats_dir = os.path.join(train_dir, 'cats')
 
# 狗训练图片所在目录
train_dogs_dir = os.path.join(train_dir, 'dogs')
 
# 猫验证图片所在目录
validation_cats_dir = os.path.join(validation_dir, 'cats')
 
# 狗验证数据集所在目录
validation_dogs_dir = os.path.join(validation_dir, 'dogs')
 
print('total training cat images:', len(os.listdir(train_cats_dir))) 
print('total training dog images:', len(os.listdir(train_dogs_dir))) 
print('total validation cat images:', len(os.listdir(validation_cats_dir))) 
print('total validation dog images:', len(os.listdir(validation_dogs_dir)))

3. 模型建立

# 搭建模型
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu',
         input_shape=(150, 150, 3)))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
 
print(model.summary())
 
model.compile(loss='binary_crossentropy',
       optimizer=RMSprop(lr=1e-4),
       metrics=['acc'])

4. 模型训练

train_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)
 
train_generator = train_datagen.flow_from_directory(
  train_dir, # target directory
  target_size=(150, 150), # resize图片
  batch_size=20,
  class_mode='binary'
)
 
validation_generator = test_datagen.flow_from_directory(
  validation_dir,
  target_size=(150, 150),
  batch_size=20,
  class_mode='binary'
)
 
for data_batch, labels_batch in train_generator:
  print('data batch shape:', data_batch.shape)
  print('labels batch shape:', labels_batch.shape)
  break
 
hist = model.fit_generator(
  train_generator,
  steps_per_epoch=100,
  epochs=10,
  validation_data=validation_generator,
  validation_steps=50
)
 
model.save('cats_and_dogs_small_1.h5')

5. 模型评估

acc = hist.history['acc']
val_acc = hist.history['val_acc']
loss = hist.history['loss']
val_loss = hist.history['val_loss']
 
epochs = range(len(acc))
 
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
 
plt.legend()
plt.figure()
 
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.legend()
plt.show()

6. 预测

imagename = 'E:/python learn/dog_and_cat/data/validation/dogs/dog.2026.jpg'
test_image = image.load_img(imagename, target_size = (150, 150))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis=0)
result = model.predict(test_image)
 
if result[0][0] == 1:
  prediction ='dog'
else:
  prediction ='cat'
  
print(prediction)

代码在spyder下运行正常,一般情况下,可以将文件分为两个部分,一部分为Train.py,包含深度学习模型建立、训练和模型的存储,另一部分Predict.py,包含模型的读取,评价和预测

补充知识:keras 猫狗大战自搭网络以及vgg16应用

导入模块

import os
import numpy as np
import tensorflow as tf
import random
import seaborn as sns
import matplotlib.pyplot as plt
import keras
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Activation, Flatten, Input,BatchNormalization
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.optimizers import RMSprop, Adam, SGD
from keras.preprocessing import image
from keras.preprocessing.image import ImageDataGenerator
from keras.applications.vgg16 import VGG16, preprocess_input
 
from sklearn.model_selection import train_test_split

加载数据集

def read_and_process_image(data_dir,width=64, height=64, channels=3, preprocess=False):
  train_images= [data_dir + i for i in os.listdir(data_dir)]
  
  random.shuffle(train_images)
  
  def read_image(file_path, preprocess):
    img = image.load_img(file_path, target_size=(height, width))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    # if preprocess:
      # x = preprocess_input(x)
    return x
  
  def prep_data(images, proprocess):
    count = len(images)
    data = np.ndarray((count, height, width, channels), dtype = np.float32)
    
    for i, image_file in enumerate(images):
      image = read_image(image_file, preprocess)
      data[i] = image
    
    return data
  
  def read_labels(file_path):
    labels = []
    for i in file_path:
      label = 1 if 'dog' in i else 0
      labels.append(label)
    
    return labels
  
  X = prep_data(train_images, preprocess)
  labels = read_labels(train_images)
  
  assert X.shape[0] == len(labels)
  print("Train shape: {}".format(X.shape))
  return X, labels

读取数据集

# 读取图片
WIDTH = 150
HEIGHT = 150
CHANNELS = 3
X, y = read_and_process_image('D:\\Python_Project\\train\\',width=WIDTH, height=HEIGHT, channels=CHANNELS)

查看数据集信息

# 统计y
sns.countplot(y)
 
# 显示图片
def show_cats_and_dogs(X, idx):
  plt.figure(figsize=(10,5), frameon=True)
  img = X[idx,:,:,::-1]
  img = img/255
  plt.imshow(img)
  plt.show()
 
 
for idx in range(0,3):
  show_cats_and_dogs(X, idx)
 
train_X = X[0:17500,:,:,:]
train_y = y[0:17500]
test_X = X[17500:25000,:,:,:]
test_y = y[17500:25000]
train_X.shape
test_X.shape

自定义神经网络层数

input_layer = Input((WIDTH, HEIGHT, CHANNELS))
# 第一层
z = input_layer
z = Conv2D(64, (3,3))(z)
z = BatchNormalization()(z)
z = Activation('relu')(z)
z = MaxPooling2D(pool_size = (2,2))(z)
 
z = Conv2D(64, (3,3))(z)
z = BatchNormalization()(z)
z = Activation('relu')(z)
z = MaxPooling2D(pool_size = (2,2))(z)
 
z = Conv2D(128, (3,3))(z)
z = BatchNormalization()(z)
z = Activation('relu')(z)
z = MaxPooling2D(pool_size = (2,2))(z)
 
z = Conv2D(128, (3,3))(z)
z = BatchNormalization()(z)
z = Activation('relu')(z)
z = MaxPooling2D(pool_size = (2,2))(z)
 
z = Flatten()(z)
z = Dense(64)(z)
z = BatchNormalization()(z)
z = Activation('relu')(z)
z = Dropout(0.5)(z)
z = Dense(1)(z)
z = Activation('sigmoid')(z)
 
model = Model(input_layer, z)
 
model.compile(
  optimizer = keras.optimizers.RMSprop(),
  loss = keras.losses.binary_crossentropy,
  metrics = [keras.metrics.binary_accuracy]
)
 
model.summary()

训练模型

history = model.fit(train_X,train_y, validation_data=(test_X, test_y),epochs=10,batch_size=128,verbose=True)
score = model.evaluate(test_X, test_y, verbose=0)
print("Large CNN Error: %.2f%%" %(100-score[1]*100))

复用vgg16模型

def vgg16_model(input_shape= (HEIGHT,WIDTH,CHANNELS)):
  vgg16 = VGG16(include_top=False, weights='imagenet',input_shape=input_shape)
  
  for layer in vgg16.layers:
    layer.trainable = False
  last = vgg16.output
  # 后面加入自己的模型
  x = Flatten()(last)
  x = Dense(256, activation='relu')(x)
  x = Dropout(0.5)(x)
  x = Dense(256, activation='relu')(x)
  x = Dropout(0.5)(x)
  x = Dense(1, activation='sigmoid')(x)
  
  model = Model(inputs=vgg16.input, outputs=x)
  
  return model

编译模型

model_vgg16 = vgg16_model()
model_vgg16.summary()
model_vgg16.compile(loss='binary_crossentropy',optimizer = Adam(0.0001), metrics = ['accuracy'])

训练模型

# 训练模型
history = model_vgg16.fit(train_X,train_y, validation_data=(test_X, test_y),epochs=5,batch_size=128,verbose=True)
score = model_vgg16.evaluate(test_X, test_y, verbose=0)
print("Large CNN Error: %.2f%%" %(100-score[1]*100))

以上这篇keras分类之二分类实例(Cat and dog)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
跟老齐学Python之使用Python操作数据库(1)
Nov 25 Python
Python编程实现正则删除命令功能
Aug 30 Python
pandas 使用apply同时处理两列数据的方法
Apr 20 Python
python 实现将字典dict、列表list中的中文正常显示方法
Jul 06 Python
对sklearn的使用之数据集的拆分与训练详解(python3.6)
Dec 14 Python
基于Python的PIL库学习详解
May 10 Python
python 梯度法求解函数极值的实例
Jul 10 Python
Python&&GDAL实现NDVI的计算方式
Jan 09 Python
Django Admin设置应用程序及模型顺序方法详解
Apr 01 Python
Flask中sqlalchemy模块的实例用法
Aug 02 Python
使用jupyter notebook运行python和R的步骤
Aug 13 Python
python多线程和多进程关系详解
Dec 14 Python
python中tkinter窗口位置\坐标\大小等实现示例
Jul 09 #Python
Python2.x与3​​.x版本有哪些区别
Jul 09 #Python
浅谈keras中Dropout在预测过程中是否仍要起作用
Jul 09 #Python
在keras中对单一输入图像进行预测并返回预测结果操作
Jul 09 #Python
python求解汉诺塔游戏
Jul 09 #Python
Django中Aggregation聚合的基本使用方法
Jul 09 #Python
Python  word实现读取及导出代码解析
Jul 09 #Python
You might like
php中的静态变量的基本用法
2014/03/20 PHP
PHP工程师VIM配置分享
2015/12/15 PHP
Netbeans 8.2将支持PHP7 更精彩
2016/06/13 PHP
PHP数据库操作二:memcache用法分析
2017/08/16 PHP
利用php + Laravel如何实现部署自动化详解
2017/10/11 PHP
Javascript remove 自定义数组删除方法
2009/10/20 Javascript
js截取小数点后几位的写法
2013/11/14 Javascript
100个不能错过的实用JS自定义函数
2014/03/05 Javascript
JavaScript高级教程5.6之基本包装类型(详细)
2015/11/23 Javascript
JavaScript实现窗口抖动效果
2016/10/19 Javascript
浅谈JS读取DOM对象(标签)的自定义属性
2016/11/21 Javascript
HTML5canvas 绘制一个圆环形的进度表示实例
2016/12/16 Javascript
关于vue-router路径计算问题
2017/05/10 Javascript
Vue自定义事件(详解)
2017/08/19 Javascript
vue router动态路由下让每个子路由都是独立组件的解决方案
2018/04/24 Javascript
在微信小程序中使用mqtt服务的方法
2019/12/13 Javascript
ant-design-vue 快速避坑指南(推荐)
2020/01/21 Javascript
微信公众号中的JSSDK接入及invalid signature等常见错误问题分析(全面解析)
2020/04/11 Javascript
Vue跨域请求问题解决方案过程解析
2020/08/07 Javascript
WebStorm无法正确识别Vue3组合式API的解决方案
2021/02/18 Vue.js
Linux下用Python脚本监控目录变化代码分享
2015/05/21 Python
Python实现的简单计算器功能详解
2018/08/25 Python
从运行效率与开发效率比较Python和C++
2018/12/14 Python
在Python中通过getattr获取对象引用的方法
2019/01/21 Python
Python3.8对可迭代解包的改进及用法详解
2019/10/15 Python
python通过实例讲解反射机制
2019/10/17 Python
利用Python计算KS的实例详解
2020/03/03 Python
Foot Locker澳洲官网:美国运动服和鞋类零售商
2019/10/11 全球购物
兰蔻俄罗斯官方网站:Lancome俄罗斯
2019/12/09 全球购物
伊莱克斯阿根廷网上商店:Tienda Electrolux
2021/03/08 全球购物
PHP面试题大全
2015/10/16 面试题
秋季运动会活动方案
2014/02/05 职场文书
2014年寒假社会实践活动心得体会
2014/04/07 职场文书
2014年纳税评估工作总结
2014/12/23 职场文书
刑事附带民事起诉状
2015/05/19 职场文书
参加招聘会后的感想
2015/08/10 职场文书