国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

tensorflow2.0保存和恢復模型3種方法

2020-02-15 21:26:34
字體:
來源:轉載
供稿:網友

方法1:只保存模型的權重和偏置

這種方法不會保存整個網絡的結構,只是保存模型的權重和偏置,所以在后期恢復模型之前,必須手動創建和之前模型一模一樣的模型,以保證權重和偏置的維度和保存之前的相同。

tf.keras.model類中的save_weights方法和load_weights方法,參數解釋我就直接搬運官網的內容了。

save_weights( filepath, overwrite=True, save_format=None)

Arguments:

filepath: String, path to the file to save the weights to. When saving in TensorFlow format, this is the prefix used for checkpoint files (multiple files are generated). Note that the '.h5' suffix causes weights to be saved in HDF5 format.

overwrite: Whether to silently overwrite any existing file at the target location, or provide the user with a manual prompt.

save_format: Either 'tf' or 'h5'. A filepath ending in '.h5' or '.keras' will default to HDF5 if save_format is None. Otherwise None defaults to 'tf'.

load_weights( filepath, by_name=False)

實例1:

import tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras import datasets, layers, optimizers # step1 加載訓練集和測試集合mnist = tf.keras.datasets.mnist(x_train, y_train),(x_test, y_test) = mnist.load_data()x_train, x_test = x_train / 255.0, x_test / 255.0  # step2 創建模型def create_model(): return tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(512, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax') ])model = create_model() # step3 編譯模型 主要是確定優化方法,損失函數等model.compile(optimizer='adam',  loss='sparse_categorical_crossentropy',  metrics=['accuracy']) # step4 模型訓練 訓練一個epochsmodel.fit(x=x_train,  y=y_train,  epochs=1,  ) # step5 模型測試loss, acc = model.evaluate(x_test, y_test)print("train model, accuracy:{:5.2f}%".format(100 * acc)) # step6 保存模型的權重和偏置model.save_weights('./save_weights/my_save_weights') # step7 刪除模型del model # step8 重新創建模型model = create_model()model.compile(optimizer='adam',  loss='sparse_categorical_crossentropy',  metrics=['accuracy']) # step9 恢復權重model.load_weights('./save_weights/my_save_weights') # step10 測試模型loss, acc = model.evaluate(x_test, y_test)print("Restored model, accuracy:{:5.2f}%".format(100 * acc))

train model, accuracy:96.55%

Restored model, accuracy:96.55%

可以看到在模型的權重和偏置恢復之后,在測試集合上同樣達到了訓練之前相同的準確率。

方法2:直接保存整個模型

這種方法會將網絡的結構,權重和優化器的狀態等參數全部保存下來,后期恢復的時候就沒必要創建新的網絡了。

tf.keras.model類中的save方法和load_model方法

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 札达县| 湖州市| 赤城县| 枣强县| 阜阳市| 玉屏| 上杭县| 五家渠市| 平湖市| 佳木斯市| 达孜县| 温泉县| 永丰县| 通城县| 小金县| 凤翔县| 那坡县| 宜君县| 清新县| 霍山县| 鸡泽县| 惠州市| 集安市| 象山县| 泰来县| 大港区| 抚顺市| 商丘市| 麟游县| 阿克陶县| 益阳市| 黎城县| 仙桃市| 郓城县| 扶沟县| 巴马| 永顺县| 中西区| 丰城市| 江达县| 东乡县|