Modelleri kaydedin ve yükleyin

TensorFlow.org'da görüntüleyin Google Colab'da çalıştırın Kaynağı GitHub'da görüntüleyin Not defterini indir

Model ilerlemesi, eğitim sırasında ve sonrasında kaydedilebilir. Bu, bir modelin kaldığı yerden devam edebileceği ve uzun eğitim sürelerinden kaçınabileceği anlamına gelir. Kaydetmek aynı zamanda modelinizi paylaşabileceğiniz ve başkalarının çalışmanızı yeniden oluşturabileceği anlamına gelir. Araştırma modellerini ve tekniklerini yayınlarken çoğu makine öğrenimi uygulayıcısı şunları paylaşır:

  • modeli oluşturmak için kod ve
  • model için eğitilmiş ağırlıklar veya parametreler

Bu verileri paylaşmak, başkalarının modelin nasıl çalıştığını anlamasına ve yeni verilerle kendilerinin denemesine yardımcı olur.

Seçenekler

Kullanmakta olduğunuz API'ye bağlı olarak TensorFlow modellerini kaydetmenin farklı yolları vardır. Bu kılavuz, TensorFlow'da modeller oluşturmak ve eğitmek için üst düzey bir API olan tf.keras'ı kullanır. Diğer yaklaşımlar için TensorFlow Kaydetme ve Geri Yükleme kılavuzuna veya İstekte Kaydetme'ye bakın.

Kurmak

Yüklemeler ve içe aktarmalar

TensorFlow ve bağımlılıkları kurun ve içe aktarın:

pip install pyyaml h5py  # Required to save models in HDF5 format
import os

import tensorflow as tf
from tensorflow import keras

print(tf.version.VERSION)
-yer tutucu2 l10n-yer
2.8.0-rc1

Örnek bir veri kümesi alın

Ağırlıkların nasıl kaydedileceğini ve yükleneceğini göstermek için MNIST veri setini kullanacaksınız. Bu çalıştırmaları hızlandırmak için ilk 1000 örneği kullanın:

(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()

train_labels = train_labels[:1000]
test_labels = test_labels[:1000]

train_images = train_images[:1000].reshape(-1, 28 * 28) / 255.0
test_images = test_images[:1000].reshape(-1, 28 * 28) / 255.0

Bir model tanımlayın

Basit bir sıralı model oluşturarak başlayın:

# Define a simple sequential model
def create_model():
  model = tf.keras.models.Sequential([
    keras.layers.Dense(512, activation='relu', input_shape=(784,)),
    keras.layers.Dropout(0.2),
    keras.layers.Dense(10)
  ])

  model.compile(optimizer='adam',
                loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),
                metrics=[tf.metrics.SparseCategoricalAccuracy()])

  return model

# Create a basic model instance
model = create_model()

# Display the model's architecture
model.summary()
tutucu5 l10n-yer
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 dense (Dense)               (None, 512)               401920    
                                                                 
 dropout (Dropout)           (None, 512)               0         
                                                                 
 dense_1 (Dense)             (None, 10)                5130      
                                                                 
=================================================================
Total params: 407,050
Trainable params: 407,050
Non-trainable params: 0
_________________________________________________________________

Eğitim sırasında kontrol noktalarını kaydedin

Eğitilmiş bir modeli yeniden eğitmek zorunda kalmadan kullanabilir veya eğitim sürecinin kesintiye uğraması durumunda kaldığınız yerden eğitime devam edebilirsiniz. tf.keras.callbacks.ModelCheckpoint geri çağrısı, modeli hem eğitim sırasında hem de sonunda sürekli olarak kaydetmenize olanak tanır.

Kontrol noktası geri arama kullanımı

Yalnızca eğitim sırasında ağırlıktan tasarruf sağlayan bir tf.keras.callbacks.ModelCheckpoint geri çağrısı oluşturun:

checkpoint_path = "training_1/cp.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)

# Create a callback that saves the model's weights
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,
                                                 save_weights_only=True,
                                                 verbose=1)

# Train the model with the new callback
model.fit(train_images, 
          train_labels,  
          epochs=10,
          validation_data=(test_images, test_labels),
          callbacks=[cp_callback])  # Pass callback to training

# This may generate warnings related to saving the state of the optimizer.
# These warnings (and similar warnings throughout this notebook)
# are in place to discourage outdated usage, and can be ignored.
tutucu7 l10n-yer
Epoch 1/10
23/32 [====================>.........] - ETA: 0s - loss: 1.3666 - sparse_categorical_accuracy: 0.6060 
Epoch 1: saving model to training_1/cp.ckpt
32/32 [==============================] - 1s 10ms/step - loss: 1.1735 - sparse_categorical_accuracy: 0.6690 - val_loss: 0.7180 - val_sparse_categorical_accuracy: 0.7750
Epoch 2/10
24/32 [=====================>........] - ETA: 0s - loss: 0.4238 - sparse_categorical_accuracy: 0.8789
Epoch 2: saving model to training_1/cp.ckpt
32/32 [==============================] - 0s 5ms/step - loss: 0.4201 - sparse_categorical_accuracy: 0.8810 - val_loss: 0.5621 - val_sparse_categorical_accuracy: 0.8150
Epoch 3/10
24/32 [=====================>........] - ETA: 0s - loss: 0.2795 - sparse_categorical_accuracy: 0.9336
Epoch 3: saving model to training_1/cp.ckpt
32/32 [==============================] - 0s 5ms/step - loss: 0.2815 - sparse_categorical_accuracy: 0.9310 - val_loss: 0.4790 - val_sparse_categorical_accuracy: 0.8430
Epoch 4/10
24/32 [=====================>........] - ETA: 0s - loss: 0.2027 - sparse_categorical_accuracy: 0.9427
Epoch 4: saving model to training_1/cp.ckpt
32/32 [==============================] - 0s 5ms/step - loss: 0.2016 - sparse_categorical_accuracy: 0.9440 - val_loss: 0.4361 - val_sparse_categorical_accuracy: 0.8610
Epoch 5/10
24/32 [=====================>........] - ETA: 0s - loss: 0.1739 - sparse_categorical_accuracy: 0.9583
Epoch 5: saving model to training_1/cp.ckpt
32/32 [==============================] - 0s 5ms/step - loss: 0.1683 - sparse_categorical_accuracy: 0.9610 - val_loss: 0.4640 - val_sparse_categorical_accuracy: 0.8580
Epoch 6/10
23/32 [====================>.........] - ETA: 0s - loss: 0.1116 - sparse_categorical_accuracy: 0.9796
Epoch 6: saving model to training_1/cp.ckpt
32/32 [==============================] - 0s 5ms/step - loss: 0.1125 - sparse_categorical_accuracy: 0.9780 - val_loss: 0.4420 - val_sparse_categorical_accuracy: 0.8580
Epoch 7/10
24/32 [=====================>........] - ETA: 0s - loss: 0.0978 - sparse_categorical_accuracy: 0.9831
Epoch 7: saving model to training_1/cp.ckpt
32/32 [==============================] - 0s 5ms/step - loss: 0.0989 - sparse_categorical_accuracy: 0.9820 - val_loss: 0.4163 - val_sparse_categorical_accuracy: 0.8590
Epoch 8/10
21/32 [==================>...........] - ETA: 0s - loss: 0.0669 - sparse_categorical_accuracy: 0.9911
Epoch 8: saving model to training_1/cp.ckpt
32/32 [==============================] - 0s 6ms/step - loss: 0.0690 - sparse_categorical_accuracy: 0.9910 - val_loss: 0.4411 - val_sparse_categorical_accuracy: 0.8600
Epoch 9/10
22/32 [===================>..........] - ETA: 0s - loss: 0.0495 - sparse_categorical_accuracy: 0.9972
Epoch 9: saving model to training_1/cp.ckpt
32/32 [==============================] - 0s 5ms/step - loss: 0.0516 - sparse_categorical_accuracy: 0.9950 - val_loss: 0.4064 - val_sparse_categorical_accuracy: 0.8650
Epoch 10/10
24/32 [=====================>........] - ETA: 0s - loss: 0.0436 - sparse_categorical_accuracy: 0.9948
Epoch 10: saving model to training_1/cp.ckpt
32/32 [==============================] - 0s 5ms/step - loss: 0.0437 - sparse_categorical_accuracy: 0.9960 - val_loss: 0.4061 - val_sparse_categorical_accuracy: 0.8770
<keras.callbacks.History at 0x7eff8d865390>

Bu, her dönemin sonunda güncellenen tek bir TensorFlow kontrol noktası dosyası koleksiyonu oluşturur:

os.listdir(checkpoint_dir)
tutucu9 l10n-yer
['checkpoint', 'cp.ckpt.index', 'cp.ckpt.data-00000-of-00001']

İki model aynı mimariyi paylaştığı sürece, aralarında ağırlıkları paylaşabilirsiniz. Bu nedenle, bir modeli yalnızca ağırlıklardan geri yüklerken, orijinal modelle aynı mimariye sahip bir model oluşturun ve ardından ağırlıklarını ayarlayın.

Şimdi yeni, eğitimsiz bir modeli yeniden oluşturun ve test setinde değerlendirin. Eğitimsiz bir model şans seviyelerinde performans gösterecektir (~%10 doğruluk):

# Create a basic model instance
model = create_model()

# Evaluate the model
loss, acc = model.evaluate(test_images, test_labels, verbose=2)
print("Untrained model, accuracy: {:5.2f}%".format(100 * acc))
tutucu11 l10n-yer
32/32 - 0s - loss: 2.4473 - sparse_categorical_accuracy: 0.0980 - 145ms/epoch - 5ms/step
Untrained model, accuracy:  9.80%

Ardından ağırlıkları kontrol noktasından yükleyin ve yeniden değerlendirin:

# Loads the weights
model.load_weights(checkpoint_path)

# Re-evaluate the model
loss, acc = model.evaluate(test_images, test_labels, verbose=2)
print("Restored model, accuracy: {:5.2f}%".format(100 * acc))
tutucu13 l10n-yer
32/32 - 0s - loss: 0.4061 - sparse_categorical_accuracy: 0.8770 - 65ms/epoch - 2ms/step
Restored model, accuracy: 87.70%

Kontrol noktası geri arama seçenekleri

Geri arama, kontrol noktaları için benzersiz adlar sağlamak ve kontrol noktası sıklığını ayarlamak için çeşitli seçenekler sunar.

Yeni bir model eğitin ve her beş çağda bir benzersiz olarak adlandırılmış kontrol noktalarını kaydedin:

# Include the epoch in the file name (uses `str.format`)
checkpoint_path = "training_2/cp-{epoch:04d}.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)

batch_size = 32

# Create a callback that saves the model's weights every 5 epochs
cp_callback = tf.keras.callbacks.ModelCheckpoint(
    filepath=checkpoint_path, 
    verbose=1, 
    save_weights_only=True,
    save_freq=5*batch_size)

# Create a new model instance
model = create_model()

# Save the weights using the `checkpoint_path` format
model.save_weights(checkpoint_path.format(epoch=0))

# Train the model with the new callback
model.fit(train_images, 
          train_labels,
          epochs=50, 
          batch_size=batch_size, 
          callbacks=[cp_callback],
          validation_data=(test_images, test_labels),
          verbose=0)
tutucu15 l10n-yer
Epoch 5: saving model to training_2/cp-0005.ckpt

Epoch 10: saving model to training_2/cp-0010.ckpt

Epoch 15: saving model to training_2/cp-0015.ckpt

Epoch 20: saving model to training_2/cp-0020.ckpt

Epoch 25: saving model to training_2/cp-0025.ckpt

Epoch 30: saving model to training_2/cp-0030.ckpt

Epoch 35: saving model to training_2/cp-0035.ckpt

Epoch 40: saving model to training_2/cp-0040.ckpt

Epoch 45: saving model to training_2/cp-0045.ckpt

Epoch 50: saving model to training_2/cp-0050.ckpt
<keras.callbacks.History at 0x7eff807703d0>

Şimdi ortaya çıkan kontrol noktalarına bakın ve en yenisini seçin:

os.listdir(checkpoint_dir)
['cp-0005.ckpt.data-00000-of-00001',
 'cp-0050.ckpt.index',
 'checkpoint',
 'cp-0010.ckpt.index',
 'cp-0035.ckpt.data-00000-of-00001',
 'cp-0000.ckpt.data-00000-of-00001',
 'cp-0050.ckpt.data-00000-of-00001',
 'cp-0010.ckpt.data-00000-of-00001',
 'cp-0020.ckpt.data-00000-of-00001',
 'cp-0035.ckpt.index',
 'cp-0040.ckpt.index',
 'cp-0025.ckpt.data-00000-of-00001',
 'cp-0045.ckpt.index',
 'cp-0020.ckpt.index',
 'cp-0025.ckpt.index',
 'cp-0030.ckpt.data-00000-of-00001',
 'cp-0030.ckpt.index',
 'cp-0000.ckpt.index',
 'cp-0045.ckpt.data-00000-of-00001',
 'cp-0015.ckpt.index',
 'cp-0015.ckpt.data-00000-of-00001',
 'cp-0005.ckpt.index',
 'cp-0040.ckpt.data-00000-of-00001']
yer tutucu18 l10n-yer
latest = tf.train.latest_checkpoint(checkpoint_dir)
latest
'training_2/cp-0050.ckpt'

Test etmek için modeli sıfırlayın ve en son kontrol noktasını yükleyin:

# Create a new model instance
model = create_model()

# Load the previously saved weights
model.load_weights(latest)

# Re-evaluate the model
loss, acc = model.evaluate(test_images, test_labels, verbose=2)
print("Restored model, accuracy: {:5.2f}%".format(100 * acc))
tutucu21 l10n-yer
32/32 - 0s - loss: 0.4996 - sparse_categorical_accuracy: 0.8770 - 150ms/epoch - 5ms/step
Restored model, accuracy: 87.70%

Bu dosyalar nelerdir?

Yukarıdaki kod, ağırlıkları, yalnızca ikili biçimde eğitilmiş ağırlıkları içeren denetim noktası biçimli dosyalardan oluşan bir koleksiyona depolar. Kontrol noktaları şunları içerir:

  • Modelinizin ağırlıklarını içeren bir veya daha fazla parça.
  • Hangi ağırlıkların hangi parçada depolandığını gösteren bir dizin dosyası.

Tek bir makinede bir model eğitiyorsanız, son eki olan bir parçanız olur: .data-00000-of-00001

Ağırlıkları manuel olarak kaydedin

Model.save_weights yöntemiyle ağırlıkları manuel olarak kaydetme. Varsayılan olarak, tf.keras ve özellikle save_weights , .ckpt uzantılı TensorFlow denetim noktası biçimini kullanır ( .ckpt uzantılı HDF5'te kaydetme, .h5 kaydetme ve serileştirme kılavuzunda ele alınmıştır):

# Save the weights
model.save_weights('./checkpoints/my_checkpoint')

# Create a new model instance
model = create_model()

# Restore the weights
model.load_weights('./checkpoints/my_checkpoint')

# Evaluate the model
loss, acc = model.evaluate(test_images, test_labels, verbose=2)
print("Restored model, accuracy: {:5.2f}%".format(100 * acc))
tutucu23 l10n-yer
32/32 - 0s - loss: 0.4996 - sparse_categorical_accuracy: 0.8770 - 143ms/epoch - 4ms/step
Restored model, accuracy: 87.70%

Tüm modeli kaydet

Bir modelin mimarisini, ağırlıklarını ve eğitim yapılandırmasını tek bir dosya/klasöre kaydetmek için model.save arayın. Bu, orijinal Python koduna* erişim olmadan kullanılabilmesi için bir modeli dışa aktarmanıza olanak tanır. Optimize edici durumu kurtarıldığından, eğitime tam olarak kaldığınız yerden devam edebilirsiniz.

Bütün bir model iki farklı dosya formatında kaydedilebilir ( SavedModel ve HDF5 ). TensorFlow SavedModel formatı, TF2.x'teki varsayılan dosya formatıdır. Ancak modeller HDF5 formatında kaydedilebilir. Tüm modellerin iki dosya biçiminde kaydedilmesiyle ilgili daha fazla ayrıntı aşağıda açıklanmıştır.

Tam işlevli bir modeli kaydetmek çok faydalıdır; bunları TensorFlow.js'ye ( Kaydedilen Model , HDF5 ) yükleyebilir ve ardından bunları web tarayıcılarında eğitip çalıştırabilir veya TensorFlow Lite ( Saved Model , HDF5 kullanarak mobil cihazlarda çalışacak şekilde dönüştürebilirsiniz) )

*Özel nesneler (örn. alt sınıflı modeller veya katmanlar), kaydetme ve yükleme sırasında özel dikkat gerektirir. Aşağıdaki Özel nesneleri kaydetme bölümüne bakın

Kaydedilmiş Model biçimi

SavedModel formatı, modelleri seri hale getirmenin başka bir yoludur. Bu biçimde kaydedilen modeller, tf.keras.models.load_model kullanılarak geri yüklenebilir ve TensorFlow Serving ile uyumludur. SavedModel kılavuzu , SavedModel'in nasıl sunulacağı/inceleneceği hakkında ayrıntılı bilgi verir. Aşağıdaki bölüm, modeli kaydetme ve geri yükleme adımlarını gösterir.

# Create and train a new model instance.
model = create_model()
model.fit(train_images, train_labels, epochs=5)

# Save the entire model as a SavedModel.
!mkdir -p saved_model
model.save('saved_model/my_model')
tutucu25 l10n-yer
Epoch 1/5
32/32 [==============================] - 0s 2ms/step - loss: 1.1988 - sparse_categorical_accuracy: 0.6550
Epoch 2/5
32/32 [==============================] - 0s 2ms/step - loss: 0.4180 - sparse_categorical_accuracy: 0.8930
Epoch 3/5
32/32 [==============================] - 0s 2ms/step - loss: 0.2900 - sparse_categorical_accuracy: 0.9220
Epoch 4/5
32/32 [==============================] - 0s 2ms/step - loss: 0.2070 - sparse_categorical_accuracy: 0.9540
Epoch 5/5
32/32 [==============================] - 0s 2ms/step - loss: 0.1593 - sparse_categorical_accuracy: 0.9630
2022-01-26 07:30:22.888387: W tensorflow/python/util/util.cc:368] Sets are not currently considered sequences, but this may change in the future, so consider avoiding using them.
WARNING:tensorflow:Detecting that an object or model or tf.train.Checkpoint is being deleted with unrestored values. See the following logs for the specific values in question. To silence these warnings, use `status.expect_partial()`. See https://www.tensorflow.org/api_docs/python/tf/train/Checkpoint#restorefor details about the status object returned by the restore function.
WARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.iter
WARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.beta_1
WARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.beta_2
WARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.decay
WARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.learning_rate
WARNING:tensorflow:Detecting that an object or model or tf.train.Checkpoint is being deleted with unrestored values. See the following logs for the specific values in question. To silence these warnings, use `status.expect_partial()`. See https://www.tensorflow.org/api_docs/python/tf/train/Checkpoint#restorefor details about the status object returned by the restore function.
WARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.iter
WARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.beta_1
WARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.beta_2
WARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.decay
WARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.learning_rate
INFO:tensorflow:Assets written to: saved_model/my_model/assets

SavedModel formatı, bir protobuf ikili dosyası ve bir TensorFlow kontrol noktası içeren bir dizindir. Kaydedilen model dizinini inceleyin:

# my_model directory
ls saved_model

# Contains an assets folder, saved_model.pb, and variables folder.
ls saved_model/my_model
tutucu27 l10n-yer
my_model
assets  keras_metadata.pb  saved_model.pb  variables

Kaydedilen modelden yeni bir Keras modelini yeniden yükleyin:

new_model = tf.keras.models.load_model('saved_model/my_model')

# Check its architecture
new_model.summary()
tutucu29 l10n-yer
Model: "sequential_5"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 dense_10 (Dense)            (None, 512)               401920    
                                                                 
 dropout_5 (Dropout)         (None, 512)               0         
                                                                 
 dense_11 (Dense)            (None, 10)                5130      
                                                                 
=================================================================
Total params: 407,050
Trainable params: 407,050
Non-trainable params: 0
_________________________________________________________________

Geri yüklenen model, orijinal modelle aynı argümanlarla derlenir. Yüklenen modelle değerlendirmeyi ve tahmin etmeyi çalıştırmayı deneyin:

# Evaluate the restored model
loss, acc = new_model.evaluate(test_images, test_labels, verbose=2)
print('Restored model, accuracy: {:5.2f}%'.format(100 * acc))

print(new_model.predict(test_images).shape)
tutucu31 l10n-yer
32/32 - 0s - loss: 0.4577 - sparse_categorical_accuracy: 0.8430 - 156ms/epoch - 5ms/step
Restored model, accuracy: 84.30%
(1000, 10)

HDF5 formatı

Keras, HDF5 standardını kullanarak temel bir kaydetme formatı sağlar.

# Create and train a new model instance.
model = create_model()
model.fit(train_images, train_labels, epochs=5)

# Save the entire model to a HDF5 file.
# The '.h5' extension indicates that the model should be saved to HDF5.
model.save('my_model.h5')
tutucu33 l10n-yer
Epoch 1/5
32/32 [==============================] - 0s 2ms/step - loss: 1.1383 - sparse_categorical_accuracy: 0.6970
Epoch 2/5
32/32 [==============================] - 0s 2ms/step - loss: 0.4094 - sparse_categorical_accuracy: 0.8920
Epoch 3/5
32/32 [==============================] - 0s 2ms/step - loss: 0.2936 - sparse_categorical_accuracy: 0.9160
Epoch 4/5
32/32 [==============================] - 0s 2ms/step - loss: 0.2050 - sparse_categorical_accuracy: 0.9460
Epoch 5/5
32/32 [==============================] - 0s 2ms/step - loss: 0.1485 - sparse_categorical_accuracy: 0.9690

Şimdi, modeli bu dosyadan yeniden oluşturun:

# Recreate the exact same model, including its weights and the optimizer
new_model = tf.keras.models.load_model('my_model.h5')

# Show the model architecture
new_model.summary()
tutucu35 l10n-yer
Model: "sequential_6"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 dense_12 (Dense)            (None, 512)               401920    
                                                                 
 dropout_6 (Dropout)         (None, 512)               0         
                                                                 
 dense_13 (Dense)            (None, 10)                5130      
                                                                 
=================================================================
Total params: 407,050
Trainable params: 407,050
Non-trainable params: 0
_________________________________________________________________

Doğruluğunu kontrol edin:

loss, acc = new_model.evaluate(test_images, test_labels, verbose=2)
print('Restored model, accuracy: {:5.2f}%'.format(100 * acc))
tutucu37 l10n-yer
32/32 - 0s - loss: 0.4266 - sparse_categorical_accuracy: 0.8620 - 141ms/epoch - 4ms/step
Restored model, accuracy: 86.20%

Keras, modellerini mimarilerini inceleyerek kaydeder. Bu teknik her şeyi kurtarır:

  • ağırlık değerleri
  • Modelin mimarisi
  • Modelin eğitim yapılandırması ( .compile() yöntemine ilettiğiniz şey)
  • Optimize edici ve varsa durumu (bu, eğitime kaldığınız yerden yeniden başlamanızı sağlar)

Keras, kontrol noktalarıyla uyumlu olmadıkları için v1.x optimize edicilerini ( tf.compat.v1.train 'den) kaydedemez. v1.x optimize ediciler için, optimize edicinin durumunu kaybederek yükledikten sonra modeli yeniden derlemeniz gerekir.

Özel nesneleri kaydetme

SavedModel biçimini kullanıyorsanız bu bölümü atlayabilirsiniz. HDF5 ve SavedModel arasındaki temel fark, HDF5'in model mimarisini kaydetmek için nesne yapılandırmalarını kullanması ve SavedModel'in yürütme grafiğini kaydetmesidir. Böylece, SavedModels, orijinal kod gerektirmeden alt sınıflanmış modeller ve özel katmanlar gibi özel nesneleri kaydedebilir.

Özel nesneleri HDF5'e kaydetmek için aşağıdakileri yapmanız gerekir:

  1. Nesnenizde bir get_config yöntemi ve isteğe bağlı olarak bir from_config sınıf yöntemi tanımlayın.
    • get_config(self) , nesneyi yeniden oluşturmak için gereken JSON ile seri hale getirilebilir bir parametre sözlüğü döndürür.
    • from_config(cls, config) , yeni bir nesne oluşturmak için get_config döndürülen yapılandırmayı kullanır. Varsayılan olarak, bu işlev yapılandırmayı başlatma kwargs ( return cls(**config) ) olarak kullanır.
  2. Modeli yüklerken nesneyi custom_objects bağımsız değişkenine iletin. Argüman, dize sınıfı adını Python sınıfına eşleyen bir sözlük olmalıdır. Ör tf.keras.models.load_model(path, custom_objects={'CustomLayer': CustomLayer})

Özel nesne örnekleri ve get_config için Sıfırdan katmanlar ve modeller yazma öğreticisine bakın.

# MIT License
#
# Copyright (c) 2017 François Chollet
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.