基于TensorFlow的Cats vs. Dogs

本文介绍了如何使用TensorFlow进行Cats vs. Dogs图像分类,包括数据读取、模型构建、训练及测试评估。通过Kaggle数据集,作者详细讲解了数据预处理、神经网络模型的设计和训练过程,并提供了相关代码链接。
摘要由CSDN通过智能技术生成

Cats vs. Dogs(猫狗大战)是Kaggle大数据竞赛某一年的一道赛题,利用给定的数据集,用算法实现猫和狗的识别。
  数据集可以从Kaggle官网上下载或者:网盘提取码:k7ik
电脑配置环境:win10+cuda9.0+cudnn v7+anaconda+tensorflow1.8(gpu)
IDE:pycham
  在这里插入图片描述

  • 新建data文件夹下包含test和train两个子文件夹,分别用于存放测试数据和训练数据,下载的数据直接解压到相应的文件夹下即可
  • logs文件夹用于存放我们训练时的模型结构以及训练参数
  • input_data.py负责实现读取数据,生成批次(batch)
  • model.py负责实现我们的神经网络模型
  • training.py负责实现模型的训练以及评估

1. 数据的读取——input_data.py

函数get_files(file_dir)的功能是获取给定路径file_dir下的所有的训练数据(包括图片和标签),以list的形式返回。
  由于训练数据前12500张是猫,后12500张是狗,如果直接按这个顺序训练,训练效果可能会受影响(我自己猜的),所以需要将顺序打乱,至于是读取数据的时候乱序还是训练的时候乱序可以自己选择(视频里说在这里乱序速度比较快)。因为图片和标签是一一对应的,所以要整合到一起乱序。
  这里先用np.hstack()方法将猫和狗图片和标签整合到一起,得到image_list和label_list,hstack((a,b))的功能是将a和b以水平的方式连接,比如原来cats和dogs是长度为12500的向量,执行了hstack(cats, dogs)后,image_list的长度为25000,同理label_list的长度也为25000。接着将一一对应的image_list和label_list再合并一次。temp的大小是2×25000,经过转置(变成25000×2),然后使用np.random.shuffle()方法进行乱序。
  最后从temp中分别取出乱序后的image_list和label_list列向量,作为函数的返回值。这里要注意,因为label_list里面的数据类型是字符串类型,所以加上label_list = [int(i) for i in label_list]这么一行将其转为int类型。

# coding=utf-8
import tensorflow as tf
import numpy as np
import os

train_dir = 'D:/PychamProjects/Cats_Dogs/data/train/'

def get_files(file_dir):
    '''
    Args:
        file_dir: file directory
    Returns:
        list of images and labels
    '''
    cats = []
    label_cats = []
    dogs = []
    label_dogs = []
    for file in os.listdir(file_dir):
        # name = file.split(sep='.')
        name = file.split('.')
        if name[0] == 'cat':
            cats.append(file_dir + file)
            label_cats.append(0)  #获取路径下所有猫的图片路径,存放到cats,同时贴上标签0
        else:
            dogs.append(file_dir + file)
            label_dogs.append(1)
    print('There are %d cats\nThere are %d dogs' % (len(cats), len(dogs)))
    #把cat dog合起来组成一个list
    image_list = np.hstack((cats, dogs))
    label_list = np.hstack((label_cats, label_dogs))
    #利用shuuffle打乱顺序
    temp = np.array([image_list, label_list])
    temp = temp.transpose()
    np.random.shuffle(temp)
    # 从打乱的temp中再取出list(img和lab
    image_list = list(temp[:, 0])
    label_list = list(temp[:, 1])
    label_list = [int(i) for i in label_list]

    return image_list, label_list


# 裁剪图片
#将上面生成的List传入get_batch() ,转换类型,产生一个输入队列queue,因为img和lab是分开的,
#所以使用tf.train.slice_input_producer(),然后用tf.read_file()从队列中读取图像
def get_batch(image, label, image_W, image_H, batch_size, capacity):
    '''
    Args:
        image: list type
        label: list type
        image_W: image width
        image_H: image height
        batch_size: batch size
        capacity: the maximum elements in queue
    Returns:
        image_batch: 4D tensor [batch_size, width, height, 3], dtype=tf.float32
        label_batch: 1D tensor [batch_size], dtype=tf.int32
    '''
    # 转换类型
    # 将python.list类型转换成tf能够识别的格式
    image = tf.cast(image, tf.string)
    label = tf.cast(label,<
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是使用猫狗大战数据集进行训练的Python代码,可以用来参考: ```python import tensorflow as tf from tensorflow.keras import layers, models import os import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.preprocessing.image import ImageDataGenerator # 下载猫狗大战数据集并解压 # 可以在以下网站下载并解压:https://www.kaggle.com/c/dogs-vs-cats/data # 将数据集解压到当前目录下的"data"文件夹中 # 数据集包含25,000张猫和狗的图片,分为训练集和测试集,每个类别各有12,500张图片 train_dir = './data/train' validation_dir = './data/validation' # 数据预处理 train_datagen = ImageDataGenerator(rescale=1./255) test_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow_from_directory( train_dir, target_size=(150, 150), 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') # 定义卷积神经网络模型 model = models.Sequential() model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3))) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(128, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(128, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Flatten()) model.add(layers.Dense(512, activation='relu')) model.add(layers.Dense(1, activation='sigmoid')) # 定义损失函数、优化器和评价指标 model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # 训练模型 history = model.fit( train_generator, steps_per_epoch=100, epochs=30, validation_data=validation_generator, validation_steps=50) # 可视化模型训练过程中的损失和准确率变化 acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.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.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.show() ``` 在执行该代码之前,需要先下载猫狗大战数据集,并将数据集解压到当前目录下的"data"文件夹中。 这段代码定义了一个卷积神经网络模型,使用ImageDataGenerator进行数据预处理,使用"binary_crossentropy"作为损失函数,使用"rmsprop"作为优化器,训练过程中记录了损失和准确率的变化,并可视化展示。 可以通过调整以下参数来优化模型的性能: 1. 网络的初始化方式:例如使用He或Xavier等初始化方法; 2. 卷积核个数:增加或减少卷积核的数量,以提高模型的灵敏度和泛化能力; 3. 卷积池化层数:增加或减少池化层的数量,以控制模型的复杂度和过拟合程度; 4. 损失函数:例如使用"mean_squared_error"等其他损失函数; 5. 优化方式:例如使用"Adam"等其他优化器; 6. 全连接神经元数:增加或减少全连接层的神经元数量,以控制模型的复杂度和过拟合程度。 通过上述方法可以不断优化模型,提高模型的性能和准确率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值