概述
数据集
来源网络,经典的猫狗数据集。
引入必要的模块
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import glob
import os
获取猫狗图片的路径
train_image_path = glob.glob('d:/datasets/dc/train/*.jpg')
文件名中提取标签(猫为1)
train_image_label = [int(p.split('\')[1][0:3] == 'cat') for p in train_image_path]
定义函数,读取指定图片文件的数据(数据处理的是RGB格式的图片,不是图片的路径字符串。)。输入路径和标签,返回路径对应文件的文件内容,并解压。jpg是压缩格式的图片,要还原到非压缩的格式。
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
读入图片数据
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)
构建数据集
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)
处理测试图片集
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)
构建模型
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)
])
编译模型
model.compile(optimizer="adam",loss="binary_crossentropy",metrics="acc")
训练
his=model.fit(train_image_ds,epochs=30,
steps_per_epoch=32,
validation_data=test_image_ds
)
待完善
最后
以上就是精明楼房为你收集整理的数据分析-神经网络-CNN-猫狗识别案例数据集的全部内容,希望文章能够帮你解决数据分析-神经网络-CNN-猫狗识别案例数据集所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复