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 二分类的实例_keras分类之二分类实例(Cat and dog)相关推荐

  1. python遥感影像分类代码_python,sklearn,svm,遥感数据分类,代码实例

    python,sklearn,svm,遥感数据分类,代码实例,数据,函数,精度,遥感,路径 python,sklearn,svm,遥感数据分类,代码实例 易采站长站,站长之家为您整理了python,s ...

  2. python 机器学习——K 近邻分类理论及鸢尾( Iris )数据集实例操作

    K 近邻分类理论及鸢尾( Iris )数据集实例操作 一.K 近邻分类理论 二.K 近邻分类实例操作 (1)导入数据 划分训练集测试集 (3)数据标准化 (4)用 K 近邻法建立模型 (5)性能评估 ...

  3. [Python人工智能] 二十三.基于机器学习和TFIDF的情感分类(含详细的NLP数据清洗)

    从本专栏开始,作者正式研究Python深度学习.神经网络及人工智能相关知识.前一篇文章分享了自定义情感词典(大连理工词典)实现情感分析和情绪分类的过程.这篇文章将详细讲解自然语言处理过程,基于机器学习 ...

  4. matlab 使用svm进行分类含实例代码(适用于二分类和多分类)

    matlab 使用svm进行分类(适用于二分类和多分类 1. 简单二分类 2. 多分类(不调用工具箱) 3.多分类(调用libsvm工具箱) 1. 简单二分类 clear,clc%% 二分类 %训练数 ...

  5. [Python从零到壹] 十四.机器学习之分类算法五万字总结全网首发(决策树、KNN、SVM、分类对比实验)

    欢迎大家来到"Python从零到壹",在这里我将分享约200篇Python系列文章,带大家一起去学习和玩耍,看看Python这个有趣的世界.所有文章都将结合案例.代码和作者的经验讲 ...

  6. 用 Python 对 Excel 表格内数据进行去重、分类,标记异常及分析

    Python与Excel表格综合实例四:对 Excel 表格内数据进行去重.分类,异常处理及分析 前言: 主要实现代码及思路: 1.主要思路: 2.读取数据函数: 3.数据去重函数: 4.数据分类函数 ...

  7. python 多分类算法_深入理解GBDT多分类算法

    我的个人微信公众号:Microstrong 微信公众号ID:MicrostrongAI 微信公众号介绍:Microstrong(小强)同学主要研究机器学习.深度学习.计算机视觉.智能对话系统相关内容, ...

  8. python十大标准_python对标准类型的分类

    python的标准类型可以按照三种方式分类. 一.按存储模型分类 按存储模型分可以分为原子(标量)类型和容器类型. 原子(标量)类型指对象(这里的对象不是对象数据类型,而是任何可能的值)的值只能含有一 ...

  9. 用二项逻辑斯蒂回归解决二分类问题

    逻辑斯蒂回归: 逻辑斯蒂回归是统计学习中的经典分类方法,属于对数线性模型.logistic回归的因变量可以是二分类的, 也可以是多分类的 基本原理 logistic 分布 折X是连续的随机变量,X服从 ...

最新文章

  1. 服务器上tomcat修改内存,修改Tomcat运行内存
  2. 重新理解 Monad
  3. jQuery简单的Ajax调用示例
  4. 系统功能图怎么画_[分享]照明系统图和照明平面图怎么看?系统讲解
  5. 网站架构之缓存应用(摘录)
  6. Java 解析URL
  7. 深度学习笔记(41) 候选区域
  8. 关于信道利用率的总结与一道习题的最终解释
  9. Gamvas Web 0.8.4 发布,JavaScript 游戏引擎
  10. 聪明贝塔(Smart Beta)
  11. 爱快服务器怎么重置系统,爱快软路由 备份设置以及恢复备份设置教程-路由器怎么恢复出厂设置...
  12. V Rising 服务器搭建
  13. 货车什么叫半挂?什么叫全挂?
  14. 【数值分析×机器学习】以SVD的分解形式进行深度神经网络的训练(逐渐熟练)
  15. 【区块链技术前沿】可下载内容与NFT
  16. 3.28 将文字转换为路径并进行艺术再加工 [原创Ps教程]
  17. crh寄存器_寄存器简写
  18. C++ 的静态成员变量为什么一定要在类外定义
  19. Opencv-python教程(6)——Thresholding OpenCV
  20. 北大信科夏令营博客收集

热门文章

  1. python的两种循环结构_python分支和循环结构
  2. 当年中国的“四大工学院”,现在都咋样了?
  3. 40+张最全Linux/C/C++思维导图,收藏!
  4. 可以编程的 “骰子” :带 LED、陀螺仪,WiFi!
  5. _Linux软件安装
  6. mysql正则替换字符串_mysql中替换字符串(正则) 模糊
  7. 常州彪马机器人_PUMA560型机器人
  8. 二元偏导数存在的条件_多元函数 可导、可微、连续、一阶偏导数连续 之间关系的总结...
  9. 华硕服务器显示模块,华硕远程管理模块 ASMB4-iKVM 华硕服务器主板专用 现货 IPMI...
  10. html中地图的绘制toolbars,三维GIS实验一:Surfer8地理信息制图.doc