Как сохранить обученную нейронную сеть python
Перейти к содержимому

Как сохранить обученную нейронную сеть python

  • автор:

Как сохранить обученную нейронную сеть python

Пройдите мой бесплатный двухнедельный курс электронной почты и откройте для себя MLP, CNN и LSTM (с кодом).

Нажмите, чтобы зарегистрироваться прямо сейчас, а также получите бесплатную PDF-версию курса Ebook.

Сохранить вашу модель нейронной сети в JSON

JSON — это простой формат файла для иерархического описания данных.

Keras предоставляет возможность описать любую модель, используя формат JSON сto_json ()функция. Это может быть сохранено в файл и позже загружено черезmodel_from_json ()функция, которая создаст новую модель из спецификации JSON.

Веса сохраняются непосредственно из модели с помощьюsave_weights ()функция и позже загружается с использованием симметричногоload_weights ()функция.

Приведенный ниже пример обучает и оценивает простую модель в наборе данных индейцев Пима. Затем модель преобразуется в формат JSON и записывается в файл model.json в локальном каталоге. Веса сети записываются вmodel.h5в локальном каталоге.

Данные модели и веса загружаются из сохраненных файлов, и создается новая модель. Важно скомпилировать загруженную модель перед ее использованием. Это сделано для того, чтобы прогнозы, сделанные с использованием модели, могли использовать соответствующие эффективные вычисления из бэкэнда Keras.

Модель оценивается таким же образом, печатая ту же оценку.

Запуск этого примера обеспечивает вывод ниже.

Формат JSON модели выглядит следующим образом:

Сохранить вашу модель нейронной сети в YAML

Этот пример очень похож на приведенный выше пример JSON, за исключением YAML Формат используется для спецификации модели.

Модель описывается с использованием YAML, сохраняется в файле model.yaml, а затем загружается в новую модель черезmodel_from_yaml ()функция. Веса обрабатываются так же, как указано выше в формате HDF5, как модель .h5.

При выполнении примера отображается следующий вывод:

Модель, описанная в формате YAML, выглядит следующим образом:

Дальнейшее чтение

  • Как я могу сохранить модель Keras? в документации Keras.
  • О моделях Keras в документации Keras.

Резюме

В этом посте вы узнали, как сериализовать модели глубокого обучения Keras.

Вы узнали, как сохранить свои обученные модели в файлы, а затем загрузить их и использовать для прогнозирования.

Вы также узнали, что веса моделей легко сохраняются в формате HDF5 и что структура сети может быть сохранена в формате JSON или YAML.

У вас есть вопросы о сохранении ваших моделей глубокого обучения или об этом посте? Задайте свои вопросы в комментариях, и я сделаю все возможное, чтобы ответить на них.

Сохранение нейросети в процессе обучения

Обучение нейронной сети, как правило, требует значительного времени, поэтому важно сохранять обученную сеть для дальнейшего использования. Но иногда бывает что веса, полученные на последней эпохе обучения сети, не являются лучшими. Например, у нас началось переобучение и обобщающая способность сети стала снижаться. Можно перезапустить процесс обучения с меньшим количеством эпох, но это не является хорошим решением если обучение идет долго. Альтернативный вариант – использовать ModelCheckpoint Callback , который позволяет сохранять веса нейронной сети на каждой эпохе обучения.

Демонстрационная нейросеть для распознавания рукописных цифр

Давайте рассмотрим, как применить ModelCheckpoint Callback на примере нейронной сети для распознавания рукописных цифр из набора данных MNIST.

На первом этапе нужно подключить интересующий нас callback совместно с другими модулями Keras:

Загружаем данные и создаем нейронную сеть:

Создаем ModelCheckpoint сallback

ModelCheckpoint callback создается следующим образом:

При создании callback нужно указать путь, куда будут сохраняться веса моделей. Путь задается с помощью шаблона, который передается в виде параметра при создании ModelCheckpoint callback . В начале шаблона находится префикс, одинаковый для всех эпох: save/mnist-dense- . Модели будут записываться в каталог save , имя файла начинается с mnist-dense- – полносвязная сеть для распознавания рукописных цифр из набора данных MNIST.

На каждой эпохе обучения нужно сохранять сеть в отдельный файл, поэтому вторая часть шаблона содержит переменные. будет заменена на номер эпохи (целое число с двумя знаками), а – на долю верных ответов на проверочном наборе данных (число с плавающей точкой, 4 знака после запятой). Вместо val_acc можно указывать другие метрики, если вы их используете, как на обучающем, так и на проверочном наборах данных, а также значение функции ошибки.

Запускаем обучение с сохранением сети на каждой эпохе

Чтобы сеть сохранялась на каждой эпохе обучения, при вызове метода fit в параметре callbacks мы указываем созданный ранее сheckpoint . Не забудьте перед запуском создать каталог save , куда будут записываться модели, иначе обучение остановится на первой эпохе из-за ошибки записи в несуществующий каталог.

После завершения обучения в каталоге save мы получим 25 файлов:

Список файлов с весами моделей на каждой эпохе

В имени каждого файла есть номер эпохи и доля верных ответов на проверочном наборе данных. В моем случае самый высокий показатель 0.9830 был на 22 эпохе. После этого доля верных ответов начала снижаться, что говорит о переобучении.

Сохранение только лучшей сети

Полносвязная сеть для распознавания рукописных цифр MNIST занимает мало места, ее можно сохранять на каждой эпохе. Но что делать, если вы обучаете крупную сеть с большим количеством весов, сохранять которую на каждом этапе не эффективно? Для этого случая ModelCheckpoint callback предоставляет возможность сохранения только одного состояния нейронной сети с лучшей метрикой. Такой режим работы включается, если указать параметр save_best_only=True :

Будет сохраняться только лучшее состояние сети, так что вместо шаблона указывается имя файла – save/mnist-dense.hdf5 . Параметр monitor показывает, какая метрика будет использоваться для определения лучшего состояния. В примере это val_acc – доля верных ответов на проверочном множестве. Как и в предыдущем случае, можно использовать любую метрику, которую вы применяете, а также значение ошибки.

Итоги

ModelCheckpoint сallback в Keras позволяет сохранить нейронную сеть в процессе обучения. Это полезно, если обучение сети занимает длительное время. Если вы указали слишком много эпох и началось переобучение, то вам не придется перезапускать обучение сети заново.

How to save final model using keras?

But How to save the final model for future prediction?

I usually use below code to save model:

But I don’t know how to insert the saving model’s code into KerasClassifier’s code.

yensheng's user avatar

8 Answers 8

The model has a save method, which saves all the details necessary to reconstitute the model. An example from the keras documentation:

you can save the model in json and weights in a hdf5 file format.

files «model_num.h5» and «model_num.json» are created which contain our model and weights

To use the same trained model for further testing you can simply load the hdf5 file and use it for the prediction of different data. here’s how to load the model from saved files.

To predict for different data you can use this

MMK's user avatar

You can use model.save(filepath) to save a Keras model into a single HDF5 file which will contain:

  • the architecture of the model, allowing to re-create the model.
  • the weights of the model.
  • the training configuration (loss, optimizer)
  • the state of the optimizer, allowing to resume training exactly where you left off.

In your Python code probable the last line should be:

This allows you to save the entirety of the state of a model in a single file. Saved models can be reinstantiated via keras.models.load_model() .

The model returned by load_model() is a compiled model ready to be used (unless the saved model was never compiled in the first place).

  • filepath: String, path to the file to save the weights to.
  • overwrite: Whether to silently overwrite any existing file at the target location, or provide the user with a manual prompt.
  • include_optimizer: If True, save optimizer’s state together.

prosti's user avatar

you can save the model and load in this way.

TRINADH NAGUBADI's user avatar

Generally, we save the model and weights in the same file by calling the save() function.

For Loading the model,

In this case, we can simply save and load the model without re-compiling our model again. Note — This is the preferred way for saving and loading your Keras model.

NelsonGon's user avatar

Saving a Keras model:

Loading the model back:

For more information, read Documentation

Charith Jayasanka's user avatar

This will save the best model in your working directory.

Ransaka Ravihara's user avatar

Since the syntax of keras, how to save a model, changed over the years I will post a fresh answer. In principle the earliest answer of bogatron, posted Mar 13 ’17 at 12:10 is still good, if you want to save your model including the weights into one file.

This will save the model in the older Keras H5 format.

However, there is a new format, the TensorFlow SavedModel format, which will be used if you do not specify the extension .h5, .hdf5 or .keras after the filename.

The syntax in this case is

If the given folder name does not yet exist, it will be created. Two files and two folders will be created within this folder:

Save, serialize, and export models

Authors: Neel Kovelamudi, Francois Chollet
Date created: 2023/06/14
Last modified: 2023/06/14
Description: Complete guide to saving, serializing, and exporting models.

Note: this guide assumes Keras >= 2.13

Introduction

A Keras model consists of multiple components:

  • The architecture, or configuration, which specifies what layers the model contain, and how they’re connected.
  • A set of weights values (the «state of the model»).
  • An optimizer (defined by compiling the model).
  • A set of losses and metrics (defined by compiling the model).

The Keras API saves all of these pieces together in a unified format, marked by the .keras extension. This is a zip archive consisting of the following:

  • A JSON-based configuration file (config.json): Records of model, layer, and other trackables’ configuration.
  • A H5-based state file, such as model.weights.h5 (for the whole model), with directory keys for layers and their weights.
  • A metadata file in JSON, storing things such as the current Keras version.

Let’s take a look at how this works.

How to save and load a model

If you only have 10 seconds to read this guide, here’s what you need to know.

Saving a Keras model:

Loading the model back:

Now, let’s look at the details.

Setup

Saving

This section is about saving an entire model to a single file. The file will include:

  • The model’s architecture/config
  • The model’s weight values (which were learned during training)
  • The model’s compilation information (if compile() was called)
  • The optimizer and its state, if any (this enables you to restart training where you left)

You can save a model with model.save() or keras.models.save_model() (which is equivalent). You can load it back with keras.models.load_model() .

The recommended format is the «Keras v3» format, which uses the .keras extension. There are, however, two legacy formats that are available: the TensorFlow SavedModel format and the older Keras H5 format.

You can switch to the SavedModel format by:

  • Passing save_format=’tf’ to save()
  • Passing a filename without an extension

You can switch to the H5 format by:

  • Passing save_format=’h5′ to save()
  • Passing a filename that ends in .h5

Example:

Custom objects

This section covers the basic workflows for handling custom layers, functions, and models in Keras saving and reloading.

When saving a model that includes custom objects, such as a subclassed Layer, you must define a get_config() method on the object class. If the arguments passed to the constructor ( __init__() method) of the custom object aren’t Python objects (anything other than base types like ints, strings, etc.), then you must serialize these arguments in get_config() method and also explicitly deserialize these arguments in the from_config() class method.

Please see the Defining the config methods section for more details and examples.

The saved .keras file is lightweight and does not store the Python code for custom objects. Therefore, to reload the model, load_model requires access to the definition of any custom objects used through one of the following methods:

  1. Registering custom objects (preferred),
  2. Passing custom objects directly when loading, or
  3. Using a custom object scope

Below are examples of each workflow:

Registering custom objects (preferred)

This is the preferred method, as custom object registration greatly simplifies saving and loading code. Adding the @keras.saving.register_keras_serializable decorator to the class definition of a custom object registers the object globally in a master list, allowing Keras to recognize the object when loading the model.

Let’s create a custom model involving both a custom layer and a custom activation function to demonstrate this.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *