import os
import glob
import numpy as np
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
%matplotlib inline
数据处理
提取数据内容及标签
提取所有数据的路径
train_image_path = glob.glob('./数据集/猫狗数据集2000/train/*/*.jpg')
test_image_path = glob.glob('./数据集/猫狗数据集2000/test/*/*.jpg')
train_image_path[:5]
>>>['./数据集/猫狗数据集2000/train/cat/cat.952.jpg',
'./数据集/猫狗数据集2000/train/cat/cat.946.jpg',
'./数据集/猫狗数据集2000/train/cat/cat.6.jpg',
'./数据集/猫狗数据集2000/train/cat/cat.749.jpg',
'./数据集/猫狗数据集2000/train/cat/cat.991.jpg']
使用.split()
方法提取路径
p = './数据集/猫狗数据集2000/train/cat/cat.952.jpg'
p.split('/')
>>>['.', '数据集', '猫狗数据集2000', 'train', 'cat', 'cat.952.jpg']
猫
由1
表示
狗
由0
表示
train_image_label = [int(p.split('/')[4] == 'cat') for p in train_image_path]
test_image_label = [int(p.split('/')[4] == 'cat') for p in test_image_path]
解码图片,并提取类别(图片增强,本节重点)
使用tf.image.random_*()
方法进行图片增强
图片增强(使数据集图片数据随机剪裁,亮度等,使模型将注意力主要放在内容上,而不会因为其他因素影响预测结果)
具体使用详细说明:参考🔗
def load_preprosess_image(path, label):
image = tf.io.read_file(path) # 读取路径下的文件
image = tf.image.decode_jpeg(image, channels=3) # 图片解码
image = tf.image.resize(image, [256, 256]) # 统一所有图片的大小
# 图片增强(使数据集图片数据随机剪裁,亮度等,使模型将注意力主要放在内容上,而不会因为其他因素影响预测结果)
# 更多:https://blog.csdn.net/sinat_29957455/article/details/80629098
image = tf.image.random_crop(image, [256, 256, 3]) # 随机地将张量裁剪为给定的大小
image = tf.image.random_flip_left_right(image) # 按水平(从左向右)随机翻转图像
image = tf.image.random_flip_up_down(image) # 按水平(从上向下)随机翻转图像
image = tf.image.random_brightness(image, 0.5) # 通过随机因子调整图像的亮度
image = tf.image.random_contrast(image, 0, 1) # 通过随机因子调整图像的对比度
image = tf.cast(image, tf.float32) # 转换数据类型
image = image/255 # 归一化
# 转换label的形状(由1维转到2维):[1, 2, 3] ==> [[1], [2], [3]]
label = tf.reshape(label, [1])
return image, label
构建数据集
train_image_ds = tf.data.Dataset.from_tensor_slices((train_image_path, train_image_label))
test_image_ds = tf.data.Dataset.from_tensor_slices((test_image_path, test_image_label))
AUTOTUNE = tf.data.experimental.AUTOTUNE # 根据电脑,自动进行并行计算
# 复习 dataset.map(fun)函数: 对dataset中的所有数据进行fun运算
train_image_ds = train_image_ds.map(load_preprosess_image, num_parallel_calls=AUTOTUNE)
test_image_ds = test_image_ds.map(load_preprosess_image, num_parallel_calls=AUTOTUNE)
train_image_ds
>>><ParallelMapDataset shapes: ((256, 256, 3), (1,)), types: (tf.float32, tf.int32)>
随机检查一个数据和其类别
for img, label in train_image_ds.take(1):
plt.imshow(img)
plt.show()
print('Label:', label)
>>>Label: tf.Tensor([1], shape=(1,), dtype=int32)
进行分批和乱序
参考:深度学习 - 关于batch,repeat,shuffle的讲解
BATCH_SIZE