pyimagesearch :主要包含建立 Keras 的模型代码文件--smallervggnet.py
examples:7张测试图片
3. 基于 Keras 建立的网络结构
本文采用的是一个简化版本的 VGGNet,VGGNet 是 2014 年由 Simonyan 和 Zisserman 提出的,论文--Very Deep Convolutional Networks for Large Scale Image Recognition。
这里先来展示下 SmallerVGGNet 的实现代码,首先是加载需要的 Keras 的模块和方法:
# import the necessary packages
from keras.models import Sequential
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.layers.core import Activation
from keras.layers.core import Flatten
from keras.layers.core import Dropout
from keras.layers.core import Dense
from keras import backend as K
classSmallerVGGNet:
@staticmethod
def build(width, height, depth, classes, finalAct="softmax"):
# initialize the model along with the input shape to be
# "channels last" and the channels dimension itself
model =Sequential()
inputShape =(height, width, depth)
chanDim =-1
# if we are using "channels first", update the input shape
# and channels dimension
if K.image_data_format()=="channels_first":
inputShape =(depth, height, width)
chanDim =1
首先,同样是导入必须的模块,主要是 keras ,其次还有绘图相关的 matplotlib、cv2,处理数据和标签的 sklearn 、pickle 等。
# set the matplotlib backend so figures can be saved in the background
import matplotlib
matplotlib.use("Agg")
# import the necessary packages
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
from pyimagesearch.smallervggnet import SmallerVGGNet
import matplotlib.pyplot as plt
from imutils import paths
import numpy as np
import argparse
import random
import pickle
import cv2
import os
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-d","--dataset", required=True,
help="path to input dataset (i.e., directory of images)")
ap.add_argument("-m","--model", required=True,
help="path to output model")
ap.add_argument("-l","--labelbin", required=True,
help="path to output label binarizer")
ap.add_argument("-p","--plot", type=str,default="plot.png",
help="path to output accuracy/loss plot")
args =vars(ap.parse_args())
# initialize the number of epochs to train for, initial learning rate,
# batch size, and image dimensions
EPOCHS =75
INIT_LR =1e-3
BS =32
IMAGE_DIMS =(96,96,3)
然后就开始数据处理部分的代码,首先是加载数据的代码:
# grab the image paths and randomly shuffle them
print("[INFO] loading images...")
imagePaths =sorted(list(paths.list_images(args["dataset"])))
random.seed(42)
random.shuffle(imagePaths)
# initialize the data and labels
data =[]
labels =[]
# loop over the input images
for imagePath in imagePaths:
# load the image, pre-process it, and store it in the data list
image = cv2.imread(imagePath)
image = cv2.resize(image,(IMAGE_DIMS[1], IMAGE_DIMS[0]))
image =img_to_array(image)
data.append(image)
# extract setofclasslabelsfrom the image path and update the
# labels list
l = label = imagePath.split(os.path.sep)[-2].split("_")
labels.append(l)
这部分代码,首先是将所有数据集的路径都保存到 imagePaths 中,接着进行 shuffle 随机打乱操作,然后循环读取图片,对图片做尺寸调整操作,并处理标签,得到 data 和 labels 两个列表,其中处理标签部分的实现结果如下所示:
$ python
>>>import os
>>> labels =[]>>> imagePath ="dataset/red_dress/long_dress_from_macys_red.png">>> l = label = imagePath.split(os.path.sep)[-2].split("_")>>> l
['red','dress']>>> labels.append(l)>>>>>> imagePath ="dataset/blue_jeans/stylish_blue_jeans_from_your_favorite_store.png">>> l = label = imagePath.split(os.path.sep)[-2].split("_")>>> labels.append(l)>>>>>> imagePath ="dataset/red_shirt/red_shirt_from_target.png">>> l = label = imagePath.split(os.path.sep)[-2].split("_")>>> labels.append(l)>>>>>> labels
[['red','dress'],['blue','jeans'],['red','shirt']]
# scale the raw pixel intensities to the range [0,1]
data = np.array(data, dtype="float")/255.0
labels = np.array(labels)print("[INFO] data matrix: {} images ({:.2f}MB)".format(len(imagePaths), data.nbytes /(1024*1000.0)))
# binarize the labels using scikit-learn's special multi-label
# binarizer implementation
print("[INFO] class labels:")
mlb =MultiLabelBinarizer()
labels = mlb.fit_transform(labels)
# loop over each of the possible classlabels and show them
for(i, label)inenumerate(mlb.classes_):print("{}. {}".format(i +1, label))
数据处理最后一步,划分训练集和测试集,以及采用 keras 的数据增强方法 ImageDataGenerator :
# partition the data into training and testing splits using 80%of
# the data for training and the remaining 20%fortesting(trainX, testX, trainY, testY)=train_test_split(data,
labels, test_size=0.2, random_state=42)
# construct the image generator for data augmentation
aug =ImageDataGenerator(rotation_range=25, width_shift_range=0.1,
height_shift_range=0.1, shear_range=0.2, zoom_range=0.2,
horizontal_flip=True, fill_mode="nearest")
# initialize the model using a sigmoid activation as the final layer
# in the network so we can perform multi-label classification
print("[INFO] compiling model...")
model = SmallerVGGNet.build(
width=IMAGE_DIMS[1], height=IMAGE_DIMS[0],
depth=IMAGE_DIMS[2], classes=len(mlb.classes_),
finalAct="sigmoid")
# initialize the optimizer
opt =Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
# compile the model using binary cross-entropy rather than
# categorical cross-entropy --this may seem counterintuitive for
# multi-label classification, but keep in mind that the goal here
# is to treat each output label as an independent Bernoulli
# distribution
model.compile(loss="binary_crossentropy", optimizer=opt,
metrics=["accuracy"])
# train the network
print("[INFO] training network...")
H = model.fit_generator(
aug.flow(trainX, trainY, batch_size=BS),
validation_data=(testX, testY),
steps_per_epoch=len(trainX)// BS,
epochs=EPOCHS, verbose=1)
这里采用的是 Adam 优化方法,损失函数是 binary cross-entropy 而非图像分类常用的 categorical cross-entropy,原因主要是多标签分类的目标是将每个输出的标签作为一个独立的伯努利分布,并且希望单独惩罚每一个输出节点。
最后就是保存模型,绘制曲线图的代码了:
# save the model to disk
print("[INFO] serializing network...")
model.save(args["model"])
# save the multi-label binarizer to disk
print("[INFO] serializing label binarizer...")
f =open(args["labelbin"],"wb")
f.write(pickle.dumps(mlb))
f.close()
# plot the training loss and accuracy
plt.style.use("ggplot")
plt.figure()
N = EPOCHS
plt.plot(np.arange(0, N), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, N), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, N), H.history["acc"], label="train_acc")
plt.plot(np.arange(0, N), H.history["val_acc"], label="val_acc")
plt.title("Training Loss and Accuracy")
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend(loc="upper left")
plt.savefig(args["plot"])
# import the necessary packages
from keras.preprocessing.image import img_to_array
from keras.models import load_model
import numpy as np
import argparse
import imutils
import pickle
import cv2
import os
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-m","--model", required=True,
help="path to trained model model")
ap.add_argument("-l","--labelbin", required=True,
help="path to label binarizer")
ap.add_argument("-i","--image", required=True,
help="path to input image")
args =vars(ap.parse_args())
# load the image
image = cv2.imread(args["image"])
output = imutils.resize(image, width=400)
# pre-process the image for classification
image = cv2.resize(image,(96,96))
image = image.astype("float")/255.0
image =img_to_array(image)
image = np.expand_dims(image, axis=0)
# load the trained convolutional neural network and the multi-label
# binarizer
print("[INFO] loading network...")
model =load_model(args["model"])
mlb = pickle.loads(open(args["labelbin"],"rb").read())
# classify the input image then find the indexes of the two class
# labels with the *largest* probability
print("[INFO] classifying image...")
proba = model.predict(image)[0]
idxs = np.argsort(proba)[::-1][:2]
# loop over the indexes of the high confidence classlabelsfor(i, j)inenumerate(idxs):
# build the label and draw the label on the image
label ="{}: {:.2f}%".format(mlb.classes_[j], proba[j]*100)
cv2.putText(output, label,(10,(i *30)+25),
cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,255,0),2)
# show the probabilities for each of the individual labels
for(label, p)inzip(mlb.classes_, proba):print("{}: {:.2f}%".format(label, p *100))
# show the output image
cv2.imshow("Output", output)
cv2.waitKey(0)