我是靠谱客的博主 精明楼房,这篇文章主要介绍数据分析-神经网络-CNN-猫狗识别案例数据集,现在分享给大家,希望可以做个参考。

数据集

来源网络,经典的猫狗数据集。

引入必要的模块

复制代码
1
2
3
4
5
6
7
import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt %matplotlib inline import numpy as np import glob import os

获取猫狗图片的路径

复制代码
1
train_image_path = glob.glob('d:/datasets/dc/train/*.jpg')

文件名中提取标签(猫为1)

复制代码
1
train_image_label = [int(p.split('\')[1][0:3] == 'cat') for p in train_image_path]

 定义函数,读取指定图片文件的数据(数据处理的是RGB格式的图片,不是图片的路径字符串。)。输入路径和标签,返回路径对应文件的文件内容,并解压。jpg是压缩格式的图片,要还原到非压缩的格式。

复制代码
1
2
3
4
5
6
7
8
def load_preprosess_image(path, label): image = tf.io.read_file(path) #读入文件内容 image = tf.image.decode_jpeg(image, channels=3) #jpg彩色图片(压缩)解码 image = tf.image.resize(image, [256, 256]) #大小一致 image = tf.cast(image, tf.float32) image = image/255 label = tf.reshape(label, [1]) return image, label

 读入图片数据

复制代码
1
2
3
train_image_ds = tf.data.Dataset.from_tensor_slices((train_image_path, train_image_label)) AUTOTUNE = tf.data.experimental.AUTOTUNE train_image_ds = train_image_ds.map(load_preprosess_image, num_parallel_calls=AUTOTUNE)

 构建数据集

复制代码
1
2
3
4
5
BATCH_SIZE = 32 train_count = len(train_image_path) train_image_ds = train_image_ds.shuffle(train_count).batch(BATCH_SIZE) train_image_ds = train_image_ds.prefetch(AUTOTUNE)

 处理测试图片集

复制代码
1
2
3
4
5
6
test_image_path = glob.glob('d:/datasets/dc/test/*.jpg') test_image_label = [int(p.split('\')[1] == 'cat') for p in test_image_path] test_image_ds = tf.data.Dataset.from_tensor_slices((test_image_path, test_image_label)) test_image_ds = test_image_ds.map(load_preprosess_image, num_parallel_calls=AUTOTUNE) test_image_ds = test_image_ds.batch(BATCH_SIZE) test_image_ds = test_image_ds.prefetch(AUTOTUNE)

 构建模型

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
model = keras.Sequential([ tf.keras.layers.Conv2D(64, (3, 3), input_shape=(256, 256, 3), activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.Conv2D(256, (3, 3), activation='relu'), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Conv2D(512, (3, 3), activation='relu'), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Conv2D(1024, (3, 3), activation='relu'), tf.keras.layers.GlobalAveragePooling2D(), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dense(1) ])

  编译模型

复制代码
1
model.compile(optimizer="adam",loss="binary_crossentropy",metrics="acc")

 训练

复制代码
1
2
3
4
his=model.fit(train_image_ds,epochs=30, steps_per_epoch=32, validation_data=test_image_ds )

待完善

最后

以上就是精明楼房最近收集整理的关于数据分析-神经网络-CNN-猫狗识别案例数据集的全部内容,更多相关数据分析-神经网络-CNN-猫狗识别案例数据集内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(97)

评论列表共有 0 条评论

立即
投稿
返回
顶部