最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

keras訓(xùn)練淺層卷積網(wǎng)絡(luò)并保存和加載模型實(shí)例

 更新時(shí)間:2020年07月02日 11:21:55   作者:OliverkingLi  
這篇文章主要介紹了keras訓(xùn)練淺層卷積網(wǎng)絡(luò)并保存和加載模型實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

這里我們使用keras定義簡(jiǎn)單的神經(jīng)網(wǎng)絡(luò)全連接層訓(xùn)練MNIST數(shù)據(jù)集和cifar10數(shù)據(jù)集:

keras_mnist.py

from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from keras.models import Sequential
from keras.layers.core import Dense
from keras.optimizers import SGD
from sklearn import datasets
import matplotlib.pyplot as plt
import numpy as np
import argparse
# 命令行參數(shù)運(yùn)行
ap = argparse.ArgumentParser()
ap.add_argument("-o", "--output", required=True, help="path to the output loss/accuracy plot")
args =vars(ap.parse_args())
# 加載數(shù)據(jù)MNIST,然后歸一化到【0,1】,同時(shí)使用75%做訓(xùn)練,25%做測(cè)試
print("[INFO] loading MNIST (full) dataset")
dataset = datasets.fetch_mldata("MNIST Original", data_home="/home/king/test/python/train/pyimagesearch/nn/data/")
data = dataset.data.astype("float") / 255.0
(trainX, testX, trainY, testY) = train_test_split(data, dataset.target, test_size=0.25)
# 將label進(jìn)行one-hot編碼
lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.transform(testY)
# keras定義網(wǎng)絡(luò)結(jié)構(gòu)784--256--128--10
model = Sequential()
model.add(Dense(256, input_shape=(784,), activation="relu"))
model.add(Dense(128, activation="relu"))
model.add(Dense(10, activation="softmax"))
# 開始訓(xùn)練
print("[INFO] training network...")
# 0.01的學(xué)習(xí)率
sgd = SGD(0.01)
# 交叉驗(yàn)證
model.compile(loss="categorical_crossentropy", optimizer=sgd, metrics=['accuracy'])
H = model.fit(trainX, trainY, validation_data=(testX, testY), epochs=100, batch_size=128)
# 測(cè)試模型和評(píng)估
print("[INFO] evaluating network...")
predictions = model.predict(testX, batch_size=128)
print(classification_report(testY.argmax(axis=1), predictions.argmax(axis=1), 
	target_names=[str(x) for x in lb.classes_]))
# 保存可視化訓(xùn)練結(jié)果
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.savefig(args["output"])

使用relu做激活函數(shù):

使用sigmoid做激活函數(shù):

接著我們自己定義一些modules去實(shí)現(xiàn)一個(gè)簡(jiǎn)單的卷基層去訓(xùn)練cifar10數(shù)據(jù)集:

imagetoarraypreprocessor.py

'''
該函數(shù)主要是實(shí)現(xiàn)keras的一個(gè)細(xì)節(jié)轉(zhuǎn)換,因?yàn)橛?xùn)練的圖像時(shí)RGB三顏色通道,讀取進(jìn)來的數(shù)據(jù)是有depth的,keras為了兼容一些后臺(tái),默認(rèn)是按照(height, width, depth)讀取,但有時(shí)候就要改變成(depth, height, width)
'''
from keras.preprocessing.image import img_to_array
class ImageToArrayPreprocessor:
	def __init__(self, dataFormat=None):
		self.dataFormat = dataFormat
 
	def preprocess(self, image):
		return img_to_array(image, data_format=self.dataFormat)
 

shallownet.py

'''
定義一個(gè)簡(jiǎn)單的卷基層:
input->conv->Relu->FC
'''
from keras.models import Sequential
from keras.layers.convolutional import Conv2D
from keras.layers.core import Activation, Flatten, Dense
from keras import backend as K
 
class ShallowNet:
	@staticmethod
	def build(width, height, depth, classes):
		model = Sequential()
		inputShape = (height, width, depth)
 
		if K.image_data_format() == "channels_first":
			inputShape = (depth, height, width)
 
		model.add(Conv2D(32, (3, 3), padding="same", input_shape=inputShape))
		model.add(Activation("relu"))
 
		model.add(Flatten())
		model.add(Dense(classes))
		model.add(Activation("softmax"))
 
		return model

然后就是訓(xùn)練代碼:

keras_cifar10.py

from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import classification_report
from shallownet import ShallowNet
from keras.optimizers import SGD
from keras.datasets import cifar10
import matplotlib.pyplot as plt
import numpy as np
import argparse
 
ap = argparse.ArgumentParser()
ap.add_argument("-o", "--output", required=True, help="path to the output loss/accuracy plot")
args = vars(ap.parse_args())
 
print("[INFO] loading CIFAR-10 dataset")
((trainX, trainY), (testX, testY)) = cifar10.load_data()
trainX = trainX.astype("float") / 255.0
testX = testX.astype("float") / 255.0
 
lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.transform(testY)
# 標(biāo)簽0-9代表的類別string
labelNames = ['airplane', 'automobile', 'bird', 'cat', 
	'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
 
print("[INFO] compiling model...")
opt = SGD(lr=0.0001)
model = ShallowNet.build(width=32, height=32, depth=3, classes=10)
model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"])
 
print("[INFO] training network...")
H = model.fit(trainX, trainY, validation_data=(testX, testY), batch_size=32, epochs=1000, verbose=1)
 
print("[INFO] evaluating network...")
predictions = model.predict(testX, batch_size=32)
print(classification_report(testY.argmax(axis=1), predictions.argmax(axis=1), 
	target_names=labelNames))
 
# 保存可視化訓(xùn)練結(jié)果
plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0, 1000), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, 1000), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, 1000), H.history["acc"], label="train_acc")
plt.plot(np.arange(0, 1000), H.history["val_acc"], label="val_acc")
plt.title("Training Loss and Accuracy")
plt.xlabel("# Epoch")
plt.ylabel("Loss/Accuracy")
plt.legend()
plt.savefig(args["output"])
 

代碼中可以對(duì)訓(xùn)練的learning rate進(jìn)行微調(diào),大概可以接近60%的準(zhǔn)確率。

然后修改下代碼可以保存訓(xùn)練模型:

from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import classification_report
from shallownet import ShallowNet
from keras.optimizers import SGD
from keras.datasets import cifar10
import matplotlib.pyplot as plt
import numpy as np
import argparse
 
ap = argparse.ArgumentParser()
ap.add_argument("-o", "--output", required=True, help="path to the output loss/accuracy plot")
ap.add_argument("-m", "--model", required=True, help="path to save train model")
args = vars(ap.parse_args())
 
print("[INFO] loading CIFAR-10 dataset")
((trainX, trainY), (testX, testY)) = cifar10.load_data()
trainX = trainX.astype("float") / 255.0
testX = testX.astype("float") / 255.0
 
lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.transform(testY)
# 標(biāo)簽0-9代表的類別string
labelNames = ['airplane', 'automobile', 'bird', 'cat', 
	'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
 
print("[INFO] compiling model...")
opt = SGD(lr=0.005)
model = ShallowNet.build(width=32, height=32, depth=3, classes=10)
model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"])
 
print("[INFO] training network...")
H = model.fit(trainX, trainY, validation_data=(testX, testY), batch_size=32, epochs=50, verbose=1)
 
model.save(args["model"])
 
print("[INFO] evaluating network...")
predictions = model.predict(testX, batch_size=32)
print(classification_report(testY.argmax(axis=1), predictions.argmax(axis=1), 
	target_names=labelNames))
 
# 保存可視化訓(xùn)練結(jié)果
plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0, 5), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, 5), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, 5), H.history["acc"], label="train_acc")
plt.plot(np.arange(0, 5), H.history["val_acc"], label="val_acc")
plt.title("Training Loss and Accuracy")
plt.xlabel("# Epoch")
plt.ylabel("Loss/Accuracy")
plt.legend()
plt.savefig(args["output"])
 

命令行運(yùn)行:

我們使用另一個(gè)程序來加載上一次訓(xùn)練保存的模型,然后進(jìn)行測(cè)試:

test.py

from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import classification_report
from shallownet import ShallowNet
from keras.optimizers import SGD
from keras.datasets import cifar10
from keras.models import load_model
import matplotlib.pyplot as plt
import numpy as np
import argparse
 
ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model", required=True, help="path to save train model")
args = vars(ap.parse_args())
 
# 標(biāo)簽0-9代表的類別string
labelNames = ['airplane', 'automobile', 'bird', 'cat', 
	'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
 
print("[INFO] loading CIFAR-10 dataset")
((trainX, trainY), (testX, testY)) = cifar10.load_data()
 
idxs = np.random.randint(0, len(testX), size=(10,))
testX = testX[idxs]
testY = testY[idxs]
 
trainX = trainX.astype("float") / 255.0
testX = testX.astype("float") / 255.0
 
lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.transform(testY)
 
print("[INFO] loading pre-trained network...")
model = load_model(args["model"])
 
print("[INFO] evaluating network...")
predictions = model.predict(testX, batch_size=32).argmax(axis=1)
print("predictions\n", predictions)
for i in range(len(testY)):
	print("label:{}".format(labelNames[predictions[i]]))
 
trueLabel = []
for i in range(len(testY)):
	for j in range(len(testY[i])):
		if testY[i][j] != 0:
			trueLabel.append(j)
print(trueLabel)
 
print("ground truth testY:")
for i in range(len(trueLabel)):
	print("label:{}".format(labelNames[trueLabel[i]]))
 
print("TestY\n", testY)

以上這篇keras訓(xùn)練淺層卷積網(wǎng)絡(luò)并保存和加載模型實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • OpenMV與JSON編碼問題解析

    OpenMV與JSON編碼問題解析

    這篇文章主要介紹了OpenMV與JSON編碼,JSON是一種簡(jiǎn)潔高效的交換數(shù)據(jù)的格式,本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2022-06-06
  • Python實(shí)現(xiàn)圖像隨機(jī)添加椒鹽噪聲和高斯噪聲

    Python實(shí)現(xiàn)圖像隨機(jī)添加椒鹽噪聲和高斯噪聲

    圖像噪聲是指存在于圖像數(shù)據(jù)中的不必要的或多余的干擾信息。在噪聲的概念中,通常采用信噪比(Signal-Noise?Rate,?SNR)衡量圖像噪聲。本文將利用Python實(shí)現(xiàn)對(duì)圖像隨機(jī)添加椒鹽噪聲和高斯噪聲,感興趣的可以了解一下
    2022-09-09
  • python 使用元類type創(chuàng)建類

    python 使用元類type創(chuàng)建類

    這篇文章主要介紹了Python 使用元類type創(chuàng)建類,結(jié)合實(shí)例形式詳細(xì)分析了Python元類的概念、功能及元類type創(chuàng)建類對(duì)象的常見應(yīng)用技巧,需要的朋友可以參考一下文章的具體內(nèi)容。希望對(duì)你有所幫助
    2021-10-10
  • Django Admin設(shè)置應(yīng)用程序及模型順序方法詳解

    Django Admin設(shè)置應(yīng)用程序及模型順序方法詳解

    這篇文章主要介紹了Django Admin設(shè)置應(yīng)用程序及模型順序方法詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-04-04
  • Python爬取微信讀書實(shí)現(xiàn)讀書免費(fèi)自由

    Python爬取微信讀書實(shí)現(xiàn)讀書免費(fèi)自由

    主要跟大家介紹一下,我是如何用Python爬取小說,再導(dǎo)入微信讀書的。成功實(shí)現(xiàn)在微信讀書中各種“白票”付費(fèi)小說,有需要的朋友可以借鑒參考下
    2021-09-09
  • Python處理excel與txt文件詳解

    Python處理excel與txt文件詳解

    大家好,本篇文章主要講的是Python處理excel與txt文件詳解,感興趣的同學(xué)趕快來看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽
    2021-12-12
  • Python操作MySQL數(shù)據(jù)庫(kù)的方法

    Python操作MySQL數(shù)據(jù)庫(kù)的方法

    pymsql是Python中操作MySQL的模塊,其使用方法和MySQLdb幾乎相同。接下來通過本文給大家介紹Python操作MySQL數(shù)據(jù)庫(kù)的方法,感興趣的朋友一起看看吧
    2018-06-06
  • numpy的sum函數(shù)的axis和keepdim參數(shù)詳解

    numpy的sum函數(shù)的axis和keepdim參數(shù)詳解

    這篇文章主要介紹了numpy的sum函數(shù)的axis和keepdim參數(shù)詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03
  • django中websocket的具體使用

    django中websocket的具體使用

    本文主要介紹了django中websocket的具體使用,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-01-01
  • python繪制動(dòng)態(tài)曲線教程

    python繪制動(dòng)態(tài)曲線教程

    今天小編就為大家分享一篇python繪制動(dòng)態(tài)曲線教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02

最新評(píng)論

沂南县| 朝阳市| 繁昌县| 濮阳县| 呈贡县| 安仁县| 宁都县| 仁化县| 涡阳县| 荣昌县| 常山县| 宝坻区| 霸州市| 临沭县| 凤阳县| 肇州县| 麟游县| 武威市| 义乌市| 光山县| 托里县| 衡南县| 苍梧县| 德格县| 留坝县| 竹山县| 禄劝| 北票市| 元氏县| 湘潭县| 诏安县| 大新县| 岳池县| 八宿县| 托克托县| 雷州市| 红河县| 宽城| 关岭| 清苑县| 醴陵市|