1作业简介
1.1问题描述
在这个问题中,你将面临一个经典的机器学习分类挑战——猫狗大战。你的任务是建立一个分类模型,能够准确地区分图像中是猫还是狗。
1.2预期解决方案
你的目标是通过训练一个机器学习模型,使其在给定一张图像时能够准确地预测图像中是猫还是狗。模型应该能够推广到未见过的图像,并在测试数据上表现良好。我们期待您将其部署到模拟的生产环境中——这里推理时间和二分类准确度(F1分数)将作为评分的主要依据。
1.3数据集
链接:https://pan.baidu.com/s/1vyJUrX9iA0Z-L_Xxtx3e1g
提取码:1227
1.4图像显示
2数据预处理
本数据集经划分后分成了两部分,train训练集,test测试集
2.1数据集结构
train训练集和test测试集下都有有cats和dogs文件夹,训练时文件夹的名字将会作为标签,即在cats文件夹里的图片标签是猫,dogs文件夹里的图片标签是狗。一开始我并没有进行划分子文件夹,因为每张图片都有含有cat或者dog,就直接使用图片名作为标签,但是这样放到模型去训练的时候需要耗费大量的时间,训练时间远比分子文件夹要多。
cats子文件夹下的部分图片(dogs子文件夹类似)
2.2统计训练集和测试集的大小
def count_images_in_folder(folder_path):
cat_count = len([file for file in os.listdir(os.path.join(folder_path, 'cats')) if file.endswith('.jpg')])
dog_count = len([file for file in os.listdir(os.path.join(folder_path, 'dogs')) if file.endswith('.jpg')])
return cat_count, dog_count
train_folder_path = '../Cats vs Dogs/train' # 训练集文件路径
test_folder_path = '../Cats vs Dogs/test' # 测试集文件路径
train_cat_count, train_dog_count = count_images_in_folder(train_folder_path)
test_cat_count, test_dog_count = count_images_in_folder(test_folder_path)
print(f"Train set: Cats - {train_cat_count} images, Dogs - {train_dog_count} images")
print(f"Test set: Cats - {test_cat_count} images, Dogs - {test_dog_count} images")
运行结果
训练集共25000张图片,其中猫的图片有12500张,狗的图片有12500张
测试集共1000张图片,其中猫的图片有500张,狗的图片有500张
2.3查看测试集部分图片
from PIL import Image
import os
import random
import matplotlib.pyplot as plt
def show_random_images(folder_path, num_images=3):
cat_files = [file for file in os.listdir(os.path.join(folder_path, 'cats')) if file.endswith('.jpg')]
dog_files = [file for file in os.listdir(os.path.join(folder_path, 'dogs')) if file.endswith('.jpg')]
random_cat_files = random.sample(cat_files, num_images)
random_dog_files = random.sample(dog_files, num_images)
for cat_file, dog_file in zip(random_cat_files, ra