noHup - cnn
type: channel
link: http://www.nohup.cc/tag/cnn/
items: TensorFlow 2.0使用CNN进行图片分类

TensorFlow 2.0使用CNN进行图片分类
type: item
date: 2020-04-01T10:39:00+00:00
description: Overview1.加载数据2.处理数据3.构建模型4.编译并训练模型 Overview 本篇我们来记录一下怎么使用TensorFlow2.0当中的Keras模块来进行CNN图片分类。 1.加载数据 我们用经典的猫狗分类数据集来做这次图片分类。 import os import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D from tensorflow.keras.preprocessing.image import ImageDataGenerator # 下载数据 _URL = 'https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip' path_to_zip = tf.keras.utils.get_file('cats_and_dogs.zip', origin=_URL, extract=True) PATH = os.path.join(os.path.dirname(path_to_zip), 'cats_and_dogs_filtered') 统计下载到本地的数据： train_dir = os.path.join(PATH, 'train') validation_dir = os.path.join(PATH, 'validation') 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') # 验证集狗图 num_cats_train = len(os.listdir(train_cats_dir)) num_dogs_train = len(os.listdir(train_dogs_dir)) num_cats_val = len(os.listdir(validation_cats_dir)) num_dogs_val = len(os.listdir(validation_dogs_dir)) total_train = num_cats_train + num_dogs_train total_val = num_cats_val + num_dogs_val 2.处理数据 如果直接拿训练集去训练，会遇到过拟合问题，所以我们需要对训练集进行数据增强。图片的数据增强是很简单的，有水平或垂直翻转，旋转，缩放等等方式。 batch_size = 128 epochs = 15 IMG_HEIGHT = 150 IMG_WIDTH = 150 train_image_generator = ImageDataGenerator( rescale=1./255, rotation_range=45, width_shift_range=.15, height_shift_range=.15, horizontal_flip=True, zoom_range=0.5 ) # train_image_generator = ImageDataGenerator(rescale=1./255) validation_image_generator = ImageDataGenerator(rescale=1./255) 读取图片： train_data_gen = train_image_generator.flow_from_directory(batch_size=batch_size, directory=train_dir, shuffle=True, target_size=(IMG_HEIGHT, IMG_WIDTH), class_mode='binary') val_data_gen = validation_image_generator.flow_from_directory(batch_size=batch_size, directory=…