亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python神經(jīng)網(wǎng)絡(luò)使用Keras進(jìn)行模型的保存與讀取

 更新時(shí)間:2022年05月05日 08:27:50   作者:Bubbliiiing  
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡(luò)使用Keras進(jìn)行模型的保存與讀取,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

學(xué)習(xí)前言

開始做項(xiàng)目的話,有些時(shí)候會(huì)用到別人訓(xùn)練好的模型,這個(gè)時(shí)候要學(xué)會(huì)load噢。

Keras中保存與讀取的重要函數(shù)

1、model.save

model.save用于保存模型,在保存模型前,首先要利用pip install安裝h5py的模塊,這個(gè)模塊在Keras的模型保存與讀取中常常被使用,用于定義保存格式。

pip install h5py

完成安裝后,可以通過(guò)如下函數(shù)保存模型。

model.save("./model.hdf5")

其中,model是已經(jīng)訓(xùn)練完成的模型,save函數(shù)傳入的參數(shù)就是保存后的位置+名字。

2、load_model

load_model用于載入模型。

具體使用方式如下:

model = load_model("./model.hdf5")

其中,load_model函數(shù)傳入的參數(shù)就是已經(jīng)完成保存的模型的位置+名字。./表示保存在當(dāng)前目錄。

全部代碼

這是一個(gè)簡(jiǎn)單的手寫體識(shí)別例子,在之前也講解過(guò)如何構(gòu)建

python神經(jīng)網(wǎng)絡(luò)學(xué)習(xí)使用Keras進(jìn)行簡(jiǎn)單分類,在最后我添加上了模型的保存與讀取函數(shù)。

import numpy as np
from keras.models import Sequential,load_model,save_model
from keras.layers import Dense,Activation ## 全連接層
from keras.datasets import mnist
from keras.utils import np_utils
from keras.optimizers import RMSprop
# 獲取訓(xùn)練集
(X_train,Y_train),(X_test,Y_test) = mnist.load_data()
# 首先進(jìn)行標(biāo)準(zhǔn)化 
X_train = X_train.reshape(X_train.shape[0],-1)/255
X_test = X_test.reshape(X_test.shape[0],-1)/255
# 計(jì)算categorical_crossentropy需要對(duì)分類結(jié)果進(jìn)行categorical
# 即需要將標(biāo)簽轉(zhuǎn)化為形如(nb_samples, nb_classes)的二值序列
Y_train = np_utils.to_categorical(Y_train,num_classes= 10)
Y_test = np_utils.to_categorical(Y_test,num_classes= 10)
# 構(gòu)建模型
model = Sequential([
    Dense(32,input_dim = 784),
    Activation("relu"),
    Dense(10),
    Activation("softmax")
    ]
)
rmsprop = RMSprop(lr = 0.001,rho = 0.9,epsilon = 1e-08,decay = 0)
## compile
model.compile(loss = 'categorical_crossentropy',optimizer = rmsprop,metrics=['accuracy'])
print("\ntraining")
cost = model.fit(X_train,Y_train,nb_epoch = 2,batch_size = 100)
print("\nTest")
# 測(cè)試
cost,accuracy = model.evaluate(X_test,Y_test)
print("accuracy:",accuracy)
# 保存模型
model.save("./model.hdf5")
# 刪除現(xiàn)有模型
del model
print("model had been del")
# 再次載入模型
model = load_model("./model.hdf5")
# 預(yù)測(cè)
cost,accuracy = model.evaluate(X_test,Y_test)
print("accuracy:",accuracy)

實(shí)驗(yàn)結(jié)果為:

Epoch 1/2
60000/60000 [==============================] - 6s 104us/step - loss: 0.4217 - acc: 0.8888
Epoch 2/2
60000/60000 [==============================] - 6s 99us/step - loss: 0.2240 - acc: 0.9366
Test
10000/10000 [==============================] - 1s 149us/step
accuracy: 0.9419
model had been del
10000/10000 [==============================] - 1s 117us/step
accuracy: 0.9419

以上就是python神經(jīng)網(wǎng)絡(luò)使用Keras進(jìn)行模型的保存與讀取的詳細(xì)內(nèi)容,更多關(guān)于Keras模型保存讀取的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論