<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # 保存并加載您的 Keras 深度學習模型 > 原文: [https://machinelearningmastery.com/save-load-keras-deep-learning-models/](https://machinelearningmastery.com/save-load-keras-deep-learning-models/) Keras 是一個簡單而強大的 Python 庫,用于深度學習。 鑒于深度學習模型可能需要數小時,數天甚至數周才能進行訓練,因此了解如何從磁盤保存和加載它們非常重要。 在這篇文章中,您將了解如何將 Keras 模型保存到文件中并再次加載它們以進行預測。 讓我們開始吧。 * **2017 年 3 月更新**:添加了先安裝 h5py 的說明。在每個示例中的最終打印語句中添加了缺少括號。 * **2017 年 3 月更新**:更新了 Keras 2.0.2,TensorFlow 1.0.1 和 Theano 0.9.0 的示例。 * **更新 March / 2018** :添加了備用鏈接以下載數據集,因為原始圖像已被刪除。 ![Save and Load Your Keras Deep Learning Models](https://img.kancloud.cn/06/9a/069a2173dcb8f838bc757c6cdd763280_640x428.png) 保存并加載您的 Keras 深度學習模型 照片由 [art_inthecity](https://www.flickr.com/photos/art_inthecity/6346545268/) 保留,保留一些權利。 ## 教程概述 Keras 將保存模型架構和保存模型權重的問題分開。 模型權重保存為 [HDF5 格式](http://www.h5py.org/)。這是一種網格格式,非常適合存儲多維數字數組。 可以使用兩種不同的格式描述和保存模型結構:JSON 和 YAML。 在這篇文章中,我們將看兩個保存模型并將其加載到文件的示例: * 將模型保存為 JSON。 * 將模型保存到 YAML。 每個示例還將演示如何將模型權重保存并加載到 HDF5 格式的文件中。 這些例子將使用在 Pima Indians 糖尿病二元分類數據集開始時訓練的相同簡單網絡。這是一個包含所有數字數據的小型數據集,易于使用。您可以[下載此數據集](http://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data)并將其放在您的工作目錄中,文件名為“ _pima-indians-diabetes.csv_ ”(更新:[從這里下載](https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv))。 確認您安裝了最新版本的 Keras(截至 2017 年 3 月的 v1.2.2)。 注意:您可能需要先安裝 _h5py_ : ```py sudo pip install h5py ``` ## 將您的神經網絡模型保存為 JSON JSON 是一種用于分層描述數據的簡單文件格式。 Keras 提供了使用帶有 _to_json()_ 函數的 JSON 格式描述任何模型的功能。這可以保存到文件中,然后通過 _model_from_json()_ 函數加載,該函數將根據 JSON 規范創建新模型。 使用 _save_weights()_ 函數直接從模型保存權重,然后使用對稱 _load_weights()_ 函數加載。 以下示例訓練和評估 Pima Indians 數據集上的簡單模型。然后將模型轉換為 JSON 格式并寫入本地目錄中的 model.json。網絡權重寫入本地目錄中的 _model.h5_ 。 從保存的文件加載模型和重量數據,并創建新模型。在加載模型使用之前編譯它是很重要的。這樣使用該模型進行的預測可以使用 Keras 后端的適當有效計算。 以相同的方式評估模型,打印相同的評估分數。 ```py # MLP for Pima Indians Dataset Serialize to JSON and HDF5 from keras.models import Sequential from keras.layers import Dense from keras.models import model_from_json import numpy import os # fix random seed for reproducibility numpy.random.seed(7) # load pima indians dataset dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",") # split into input (X) and output (Y) variables X = dataset[:,0:8] Y = dataset[:,8] # create model model = Sequential() model.add(Dense(12, input_dim=8, kernel_initializer='uniform', activation='relu')) model.add(Dense(8, kernel_initializer='uniform', activation='relu')) model.add(Dense(1, kernel_initializer='uniform', activation='sigmoid')) # Compile model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # Fit the model model.fit(X, Y, epochs=150, batch_size=10, verbose=0) # evaluate the model scores = model.evaluate(X, Y, verbose=0) print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100)) # serialize model to JSON model_json = model.to_json() with open("model.json", "w") as json_file: json_file.write(model_json) # serialize weights to HDF5 model.save_weights("model.h5") print("Saved model to disk") # later... # load json and create model json_file = open('model.json', 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) # load weights into new model loaded_model.load_weights("model.h5") print("Loaded model from disk") # evaluate loaded model on test data loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) score = loaded_model.evaluate(X, Y, verbose=0) print("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100)) ``` 運行此示例提供下面的輸出。 ```py acc: 78.78% Saved model to disk Loaded model from disk acc: 78.78% ``` 該模型的 JSON 格式如下所示: ```py { "keras_version":"2.0.2", "backend":"theano", "config":[ { "config":{ "dtype":"float32", "bias_regularizer":null, "activation":"relu", "bias_constraint":null, "use_bias":true, "bias_initializer":{ "config":{ }, "class_name":"Zeros" }, "kernel_regularizer":null, "activity_regularizer":null, "kernel_constraint":null, "trainable":true, "name":"dense_1", "kernel_initializer":{ "config":{ "maxval":0.05, "minval":-0.05, "seed":null }, "class_name":"RandomUniform" }, "batch_input_shape":[ null, 8 ], "units":12 }, "class_name":"Dense" }, { "config":{ "kernel_regularizer":null, "bias_regularizer":null, "activation":"relu", "bias_constraint":null, "use_bias":true, "bias_initializer":{ "config":{ }, "class_name":"Zeros" }, "activity_regularizer":null, "kernel_constraint":null, "trainable":true, "name":"dense_2", "kernel_initializer":{ "config":{ "maxval":0.05, "minval":-0.05, "seed":null }, "class_name":"RandomUniform" }, "units":8 }, "class_name":"Dense" }, { "config":{ "kernel_regularizer":null, "bias_regularizer":null, "activation":"sigmoid", "bias_constraint":null, "use_bias":true, "bias_initializer":{ "config":{ }, "class_name":"Zeros" }, "activity_regularizer":null, "kernel_constraint":null, "trainable":true, "name":"dense_3", "kernel_initializer":{ "config":{ "maxval":0.05, "minval":-0.05, "seed":null }, "class_name":"RandomUniform" }, "units":1 }, "class_name":"Dense" } ], "class_name":"Sequential" } ``` ## 將您的神經網絡模型保存到 YAML 此示例與上述 JSON 示例大致相同,只是 [YAML](https://en.wikipedia.org/wiki/YAML) 格式用于模型規范。 使用 YAML 描述模型,保存到文件 model.yaml,然后通過 _model_from_yaml()_ 函數加載到新模型中。權重的處理方式與上面 HDF5 格式相同,如 model.h5。 ```py # MLP for Pima Indians Dataset serialize to YAML and HDF5 from keras.models import Sequential from keras.layers import Dense from keras.models import model_from_yaml import numpy import os # fix random seed for reproducibility seed = 7 numpy.random.seed(seed) # load pima indians dataset dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",") # split into input (X) and output (Y) variables X = dataset[:,0:8] Y = dataset[:,8] # create model model = Sequential() model.add(Dense(12, input_dim=8, kernel_initializer='uniform', activation='relu')) model.add(Dense(8, kernel_initializer='uniform', activation='relu')) model.add(Dense(1, kernel_initializer='uniform', activation='sigmoid')) # Compile model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # Fit the model model.fit(X, Y, epochs=150, batch_size=10, verbose=0) # evaluate the model scores = model.evaluate(X, Y, verbose=0) print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100)) # serialize model to YAML model_yaml = model.to_yaml() with open("model.yaml", "w") as yaml_file: yaml_file.write(model_yaml) # serialize weights to HDF5 model.save_weights("model.h5") print("Saved model to disk") # later... # load YAML and create model yaml_file = open('model.yaml', 'r') loaded_model_yaml = yaml_file.read() yaml_file.close() loaded_model = model_from_yaml(loaded_model_yaml) # load weights into new model loaded_model.load_weights("model.h5") print("Loaded model from disk") # evaluate loaded model on test data loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) score = loaded_model.evaluate(X, Y, verbose=0) print("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100)) ``` 運行該示例將顯示以下輸出: ```py acc: 78.78% Saved model to disk Loaded model from disk acc: 78.78% ``` 以 YAML 格式描述的模型如下所示: ```py backend: theano class_name: Sequential config: - class_name: Dense config: activation: relu activity_regularizer: null batch_input_shape: !!python/tuple [null, 8] bias_constraint: null bias_initializer: class_name: Zeros config: {} bias_regularizer: null dtype: float32 kernel_constraint: null kernel_initializer: class_name: RandomUniform config: {maxval: 0.05, minval: -0.05, seed: null} kernel_regularizer: null name: dense_1 trainable: true units: 12 use_bias: true - class_name: Dense config: activation: relu activity_regularizer: null bias_constraint: null bias_initializer: class_name: Zeros config: {} bias_regularizer: null kernel_constraint: null kernel_initializer: class_name: RandomUniform config: {maxval: 0.05, minval: -0.05, seed: null} kernel_regularizer: null name: dense_2 trainable: true units: 8 use_bias: true - class_name: Dense config: activation: sigmoid activity_regularizer: null bias_constraint: null bias_initializer: class_name: Zeros config: {} bias_regularizer: null kernel_constraint: null kernel_initializer: class_name: RandomUniform config: {maxval: 0.05, minval: -0.05, seed: null} kernel_regularizer: null name: dense_3 trainable: true units: 1 use_bias: true keras_version: 2.0.2 ``` ## 進一步閱讀 * [如何保存 Keras 型號? Keras 文檔中的](https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model)。 * [關于 Keras 文檔中的 Keras 型號](https://keras.io/models/about-keras-models/)。 ## 摘要 在這篇文章中,您了解了如何序列化您的 Keras 深度學習模型。 您學習了如何將訓練過的模型保存到文件中,然后加載它們并使用它們進行預測。 您還了解到,使用 HDF5 格式可以輕松存儲模型權重,并且網絡結構可以以 JSON 或 YAML 格式保存。 您對保存深度學習模型或此帖子有任何疑問嗎?在評論中提出您的問題,我會盡力回答。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看