如何使用Keras保存和调用CNN模型【程序+笔记2】

本文介绍如何在Keras中保存和加载训练好的卷积神经网络(CNN)模型,以避免重复训练,节省时间。通过示例代码详细阐述了模型的保存和预训练模型的加载过程。
摘要由CSDN通过智能技术生成

每一次测试自己的模型准确率的时候都要重新训练一次,这样耗费大量的时间,所以这一次我们讲讲如何保存自己之前训练的模型,在测试阶段调用模型。

本次实验会使用我们上一次建立的模型,如果没有看过上一节,链接如下

点击打开链接

一.保存训练的模型

程序步骤如下:

from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from pyimagesearch.preprocessing import ImageToArrayPreprocessor
from pyimagesearch.preprocessing import SimplePreprocessor
from pyimagesearch.datasets import SimpleDatasetLoader
from pyimagesearch.nn.conv import ShallowNet
from keras.optimizers import SGD
from imutils import paths
import matplotlib.pyplot as plt
import numpy as np
import argparse

ap=argparse.ArgumentParser()
ap.add_argument('-d','--dataset',required=True,help='path to the input dataset')
ap.add_argument('-m','--model',required=True,help='path to the output dataset')  ##多了一个保存模型的地方
args=vars(ap.parse_args())

print('[INFO] loading images...')
imagePaths=list(paths.list_images(args['dataset']))

sp=SimplePreprocessor.SimplePreprocessor(32,32)
iap=ImageToArrayPreprocessor.ImageToArrayPreprocessor()
sdl=SimpleDatasetLoader.SimpleDatasetLoader(preprocessors=[sp,iap])
(data,labels)=sdl.load(imagePaths,verbose=500)
data=data.astype('float')/255.0

(train_x,test_x,train_y,test_y)=train_test_split(data,labels,test_size=0.25,random_state=42)
train_y=LabelBinarizer().fit_transform(train_y)
test_y=LabelBinarizer().fit_transform(test_y)
#print(train_x.shape)
#print(train_y)
print('[INFO] compiling models...')
opt=SGD(lr=0.005)
model=ShallowNet.ShallowNet.build(width=32,height=32,depth=3,classes=1)
model.compile(loss='binary_crossentropy',optimizer=opt,metrics=['accuracy'])


print('[INFO] training network...')

H=model.fit(train_x,train_y,validation_data=(test_x,test_y),batch_size=32,epochs=100,verbose=1)

print('[INFO] serializing network...')   ##这一次的重点
model.save(args['model'])

print('[INFO] evaliatiing model...')
predictions=model.predict(test_x,batch_size=32)
print(classification_report(test_y.argmax(axis=1),predictions.argmax(axis=1),target_names=['cat','dog']))


plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0, 100), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, 100), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, 100), H.history["acc"], label="train_acc")
plt.plot(np.arange(0, 100), H.history["val_acc"], label="val_acc")
plt.title("Training Loss and Accuracy")
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend()
plt.show()

我们在命令行中输入这样的语句,就可以将训练权值存在你建立的hdf5文件中啦:

 python shallownet_train.py --dataset ../datasets/animals \
--model shallownet_weights.hdf5

二. 加载一个预训练的模型

建立一个新的程序文件,输入这样的程序,导入需要的包:

# import the necessary packages
from pyimagesearch.preprocessing import ImageToArrayPreprocessor
from pyimagesearch.preprocessing import SimplePreprocessor
from pyimagesearch.datasets import SimpleDatasetLoader
from keras.models import load_model
from imutils import paths
import numpy as np
import argparse
import cv2
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True,
help="path to input dataset")
ap.add_argument("-m", "--model", required=True,
help="path to pre-trained model")
args = vars(ap.parse_args())
# grab the list of images in the dataset then randomly sample
# indexes into the image paths list
print("[INFO] sampling images...")
imagePaths = np.array(list(paths.list_images(args["dataset"])))
idxs = np.random.randint(0, len(imagePaths), size=(10,))   #随机选10张文件夹里面的图片处理
imagePaths = imagePaths[idxs]
# initialize the image preprocessors
sp = SimplePreprocessor(32, 32)
iap = ImageToArrayPreprocessor()

# load the dataset from disk then scale the raw pixel intensities
# to the range [0, 1]
sdl = SimpleDatasetLoader(preprocessors=[sp, iap])
(data, labels) = sdl.load(imagePaths)
data = data.astype("float") / 255.0

下面这一步最为重要,加载我们之前保存的模型。

print("[INFO] loading pre-trained network...")
model = load_model(args["model"])

再进行预测:

print("[INFO] predicting...")
preds = model.predict(data, batch_size=32).argmax(axis=1)
在我们所测试的图片上进行
  # make predictions on the images
classLabels = ["cat", "dog", "panda"]   #你分类的类名
for (i, imagePath) in enumerate(imagePaths):
# load the example image, draw the prediction, and display it
# to our screen
image = cv2.imread(imagePath)
cv2.putText(image, "Label: {}".format(classLabels[preds[i]]),
(10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
cv2.imshow("Image", image)
cv2.waitKey(0)

好啦,你就可以看见图片上有标注出现啦。这个就是保存和调用自己模型的方法。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值