一、基本介绍
最近在家闲着没事做尝试着用keras做一个图像的多级分类。基本上来说我自己制作了个比较简单的数据集,其中包括两大类:交通工具、动物;然后往下细分的话,交通工具中我简单地设置了三类:SUV、飞机和摩托车,动物则设置了两类:猫和狗。
目标自己训练一个多输出模型,可以用于判断输入图片属于动物还是交通工具,然后同样也可以细分归类是阿猫阿狗还是摩托suv飞机。
交通工具 | 名称(大类-细类-样本编号) |
---|---|
SUV | vehicle_SUV_1 |
飞机 | vehicle_plane_1 |
摩托车 | vehicle_motor_1 |
动物 | 名称(大类-细类-样本编号) |
---|---|
猫 | animal_cat_1 |
狗 | animal_dog_1 |
二、数据及标签处理
自行编写了prepare函数用于将数据进行一定的预处理。首先将图片数据读入,然后使用per_image_standardization函数将图片进行规范化处理。至于标签的处理,则将其分为两类标签分别是labels1和labels2,分别对应交通工具这样的大类标签以及SUV这样的细类标签。
import matplotlib
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import Adam
from keras.preprocessing.image import img_to_array
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.model_selection import train_test_split
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import random
import pickle
import cv2
import os
Image_width=150
Image_height=150
Image_size=(Image_width,Image_height)
Image_channels=3
batch_size=15
#输入训练文件路径,返回数据array以及labels
def prepare(path):
fileList = os.listdir(path) # 训练数据文件夹
data=[]
labels1=[]
labels2=[]
for fileName in fileList:
image=cv2.imread(os.path.join(path,fileName))
if image is not None:
std_image=tf.image.per_image_standardization(image)#图片normalization
image2=cv2.resize(std_image.numpy(),Image_size)
image2=img_to_array(image2)
data.append(image2)
label1=str(fileName