猫狗图像分类-划分数据集

📚博客主页:knighthood2001
公众号:认知up吧 (目前正在带领大家一起提升认知,感兴趣可以来围观一下)
🎃知识星球:【认知up吧|成长|副业】介绍
❤️如遇文章付费,可先看看我公众号中是否发布免费文章❤️
🙏笔者水平有限,欢迎各位大佬指点,相互学习进步!

首先,我们的数据如下,猫和狗的图片在里面,但是没有划分过训练集和测试集。
在这里插入图片描述

运行下面这个代码,就能把数据划分。

import os
from shutil import copy
import random

def mkdir(directory):
    if not os.path.exists(directory):
        os.makedirs(directory)


# TODO 获取data文件夹下所有文件夹名(即需要分类的类名)
file_path = 'data_cat_dog'
flower_class = [cla for cla in os.listdir(file_path)]

# 创建 训练集train 文件夹,并由类名在其目录下创建5个子目录
mkdir('data/train')
for cla in flower_class:
    mkdir('data/train/' + cla)

# 创建 测试集文件夹,并由类名在其目录下创建子目录
mkdir('data/test')
for cla in flower_class:
    mkdir('data/test/' + cla)

# 划分比例,训练集 : 测试集 = 9 : 1
split_rate = 0.1

# 遍历所有类别的全部图像并按比例分成训练集和验证集
for cla in flower_class:
    cla_path = file_path + '/' + cla + '/'  # 某一类别的子目录
    images = os.listdir(cla_path)  # iamges 列表存储了该目录下所有图像的名称
    num = len(images)
    eval_index = random.sample(images, k=int(num * split_rate))  # 从images列表中随机抽取 k 个图像名称
    for index, image in enumerate(images):
        # eval_index 中保存验证集val的图像名称
        if image in eval_index:
            image_path = cla_path + image
            new_path = 'data/test/' + cla
            copy(image_path, new_path)  # 将选中的图像复制到新路径

        # 其余的图像保存在训练集train中
        else:
            image_path = cla_path + image
            new_path = 'data/train/' + cla
            copy(image_path, new_path)
        print("\r[{}] processing [{}/{}]".format(cla, index + 1, num), end="")  # processing bar
    print()

print("processing done!")

划分好的数据集如下图

在这里插入图片描述
这样数据集就划分好了。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是使用Python编写的图像分类代码: 首先需要导入必要的包: ```python import numpy as np import matplotlib.pyplot as plt import os import cv2 from sklearn.model_selection import train_test_split from keras.utils import to_categorical from keras.models import Sequential, load_model from keras.layers import Conv2D, MaxPool2D, Dense, Flatten, Dropout ``` 接着,我们需要读入数据集: ```python DATADIR = "dataset" CATEGORIES = ["cats", "dogs"] IMG_SIZE = 50 training_data = [] def create_training_data(): for category in CATEGORIES: path = os.path.join(DATADIR, category) class_num = CATEGORIES.index(category) for img in os.listdir(path): try: img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) training_data.append([new_array, class_num]) except Exception as e: pass create_training_data() X = [] y = [] for features, label in training_data: X.append(features) y.append(label) X = np.array(X).reshape(-1, IMG_SIZE, IMG_SIZE, 1) X = X/255.0 y = to_categorical(y, num_classes=2) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) ``` 在这里,我们使用了OpenCV库来读取和处理图像,然后将它们添加到训练数据中。我们还使用了sklearn库中的train_test_split函数来将数据集划分为训练集和测试集。最后,我们将图像和标签转换成numpy数组,并将像素值缩放到0到1之间。 接下来,我们可以构建模型: ```python model = Sequential() model.add(Conv2D(32, (3,3), activation='relu', input_shape=X_train.shape[1:])) model.add(MaxPool2D(pool_size=(2,2))) model.add(Dropout(0.25)) model.add(Conv2D(64, (3,3), activation='relu')) model.add(MaxPool2D(pool_size=(2,2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(2, activation='softmax')) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) ``` 这个模型使用了卷积神经网络的结构,包含两个卷积层和一个全连接层。我们使用了ReLU激活函数和MaxPooling层来增加模型的非线性能力。Dropout层用于减少过拟合。 最后,我们可以训练模型并评估其性能: ```python history = model.fit(X_train, y_train, batch_size=32, epochs=20, validation_data=(X_test, y_test)) model.save('cat_dog_classifier.h5') test_loss, test_acc = model.evaluate(X_test, y_test) print('Test loss:', test_loss) print('Test accuracy:', test_acc) ``` 这里我们使用了keras库来训练模型。我们还保存了训练好的模型,并计算了模型在测试集上的准确率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

knighthood2001

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值