深度学习——数据集处理

深度学习的三大要素:数据、算法、算力。
数据在深度学习中有着着重要的地位,数据集的好坏决定了模型的训练结果,由于可见数据预处理的重要性。
本文简单介绍一下如何初步处理数据,给数据分类,打标签。

例:
现在有几万张照片,每张照片的文件名中包含了年龄、性别等信息,假如我们现在需要训练一个识别年龄的模型;
首先需要进行图片预处理,第一步就是把照片按不同年龄段筛选出来,然后打上年龄标签进行分类,再进行转tf格式(之前文章介绍过怎么转格式),最后得到数据集拿去训练。

# -*- coding: UTF-8 -*- 
import re
import os
import shutil
from PIL import Image


#打开txt文本
f1=open('F:/TF2/new/txt/1/data-clear-new.txt','r')
txt_path="F:/TF2/new/data-pic/txt/"
f15=open(txt_path+'20.txt','w+')
f20=open(txt_path+'21-25.txt','w+')
f25=open(txt_path+'26-30.txt','w+')
f30=open(txt_path+'31-35.txt','w+')
f35=open(txt_path+'36-40.txt','w+')
f40=open(txt_path+'41-45.txt','w+')
f45=open(txt_path+'45.txt','w+')

#获取年龄和文件名
for line in f1.readlines():
    file_split=line.split() #以空格为分割符,把关键词分割出来

    old_name=file_split[0]   #原文件名
    old_back=os.path.splitext(old_name)[0]  #分离文件名与后缀
    # print(old_back)

    age=int(file_split[1])   #年龄
    # print(age)

    sub=file_split[2]   #性别
    # print(sub)

    folder=file_split[3]   #原文件夹名称
    # print(folder)
    root_path="F:/TF2/new/tf2-data-clear/"
    save_path = "F:/TF2/new/data-pic/"
    if age <= 20:
        print(line)
        f15.write(line)
        shutil.move(root_path + old_name, save_path + "20/" + old_name)

    if age >= 21 and age <= 25:
        f20.write(line)
        shutil.move(root_path + old_name, save_path + "21-25/" + old_name)

    if age >= 26 and age <= 30:
        f25.write(line)
        shutil.move(root_path + old_name, save_path + "26-30/" + old_name)

    if age >= 31 and age <= 35:
        f30.write(line)
        shutil.move(root_path + old_name, save_path + "31-35/" + old_name)

    if age >= 36 and age <= 40:
        f35.write(line)
        shutil.move(root_path + old_name, save_path + "36-40/" + old_name)

    if age >= 41 and age <= 45:
        f40.write(line)
        shutil.move(root_path + old_name, save_path + "41-45/" + old_name)

    if age > 45:
        f45.write(line)
        shutil.move(root_path + old_name, save_path + "45/" + old_name)

f1.close()
f20.close()
f25.close()
f30.close()
f35.close()
f40.close()
f45.close()

以上结果得到6个不同年龄段的数据集,并且每一张照片都有一条txt记录了文件名和年龄,作为标签。

猜你喜欢

转载自blog.csdn.net/gm_Ergou/article/details/92842366