可以在訓練期間和訓練后保存模型進度。 這意味著模型可以從中斷的地方恢復,并避免長時間的訓練。 保存也意味著您可以共享您的模型,而其他人可以重新創建您的工作。 在發布研究模型和技術時,大多數機器學習從業者分享:
- 用于創建模型的代碼
- 模型的訓練權重或參數
共享此數據有助于其他人了解模型的工作原理,并使用新數據自行嘗試。
注意:小心不受信任的代碼 - TensorFlow模型是代碼。 有關詳細信息,請參閱安全使用TensorFlow。
選項
保存TensorFlow模型有多種方法 - 取決于您使用的API。 本指南使用tf.keras,一個高級API,用于在TensorFlow中構建和訓練模型。 有關其他方法,請參閱TensorFlow保存和還原指南或保存在急切中。
安裝
安裝和引用
安裝和導入TensorFlow和依賴項,有下面兩種方式:
- 命令行:pip install -q h5py pyyaml
- 在Anaconda Navigator中安裝;
下載樣本數據集
from __future__ import absolute_import, division, print_function
import os
import tensorflow as tf
from tensorflow import keras
tf.__version__
'1.11.0'
(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
定義模型
讓我們構建一個簡單的模型,我們將用它來演示保存和加載權重。
# Returns a short sequential model
def create_model():
model = tf.keras.models.Sequential([
keras.layers.Dense(512, activation=tf.nn.relu, input_shape=(784,)),
keras.layers.Dropout(0.2),
keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer=tf.keras.optimizers.Adam(),
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['accuracy'])
return model
# Create a basic model instance
model = create_model()
model.summary()
在訓練期間保存檢查點
主要用例是在訓練期間和訓練結束時自動保存檢查點。 通過這種方式,您可以使用訓練有素的模型,而無需重新訓練,或者在您離開的地方接受訓練 - 以防止訓練過程中斷。
tf.keras.callbacks.ModelCheckpoint是執行此任務的回調。 回調需要幾個參數來配置檢查點。
檢查點回調使用情況
訓練模型并將模型傳遞給ModelCheckpoint:
checkpoint_path = "training_1/cp.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)
# Create checkpoint callback
cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path,
save_weights_only=True,
verbose=1)
model = create_model()
model.fit(train_images, train_labels, epochs = 10,
validation_data = (test_images,test_labels),
callbacks = [cp_callback]) # pass callback to training
這將創建一個TensorFlow檢查點文件集合,這些文件在每個時期結束時更新:
!ls {checkpoint_dir}
checkpoint cp.ckpt.data-00000-of-00001 cp.ckpt.index
創建一個新的未經訓練的模型。 僅從權重還原模型時,必須具有與原始模型具有相同體系結構的模型。 由于它是相同的模型架構,我們可以共享權重,盡管它是模型的不同實例。
現在重建一個新的未經訓練的模型,并在測試集上進行評估。 未經訓練的模型將在偶然水平上執行(準確度約為10%):
model = create_model()
loss, acc = model.evaluate(test_images, test_labels)
print("Untrained model, accuracy: {:5.2f}%".format(100*acc))
然后從檢查點加載權重,并重新評估:
model.load_weights(checkpoint_path)
loss,acc = model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
1000/1000 [==============================] - 0s 40us/step
Restored model, accuracy: 87.60%
檢查點回調選項
回調提供了幾個選項,可以為生成的檢查點提供唯一的名稱,并調整檢查點頻率。
訓練一個新模型,每5個時期保存一次唯一命名的檢查點:
# 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)
cp_callback = tf.keras.callbacks.ModelCheckpoint(
checkpoint_path, verbose=1, save_weights_only=True,
# Save weights, every 5-epochs.
period=5)
model = create_model()
model.fit(train_images, train_labels,
epochs = 50, callbacks = [cp_callback],
validation_data = (test_images,test_labels),
verbose=0)
現在,查看生成的檢查點并選擇最新的檢查點:
! ls {checkpoint_dir}
checkpoint cp-0030.ckpt.data-00000-of-00001
cp-0005.ckpt.data-00000-of-00001 cp-0030.ckpt.index
cp-0005.ckpt.index cp-0035.ckpt.data-00000-of-00001
cp-0010.ckpt.data-00000-of-00001 cp-0035.ckpt.index
cp-0010.ckpt.index cp-0040.ckpt.data-00000-of-00001
cp-0015.ckpt.data-00000-of-00001 cp-0040.ckpt.index
cp-0015.ckpt.index cp-0045.ckpt.data-00000-of-00001
cp-0020.ckpt.data-00000-of-00001 cp-0045.ckpt.index
cp-0020.ckpt.index cp-0050.ckpt.data-00000-of-00001
cp-0025.ckpt.data-00000-of-00001 cp-0050.ckpt.index
cp-0025.ckpt.index
latest = tf.train.latest_checkpoint(checkpoint_dir)
latest
'training_2/cp-0050.ckpt'
注意:默認的tensorflow格式僅保存最近的5個檢查點。
要測試,請重置模型并加載最新的檢查點:
model = create_model()
model.load_weights(latest)
loss, acc = model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
1000/1000 [==============================] - 0s 96us/step
Restored model, accuracy: 86.80%
這些文件是什么?
上述代碼將權重存儲到檢查點格式的文件集合中,這些文件僅包含二進制格式的訓練權重。 檢查點包含:*一個或多個包含模型權重的分片。 *索引文件,指示哪些權重存儲在哪個分片中。
如果您只在一臺機器上訓練模型,那么您將有一個帶有后綴的分片:.data-00000-of-00001
# Save the weights
model.save_weights('./checkpoints/my_checkpoint')
# Restore the weights
model = create_model()
model.load_weights('./checkpoints/my_checkpoint')
loss,acc = model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
保存整個模型
整個模型可以保存到包含權重值,模型配置甚至優化器配置的文件中。 這允許您檢查模型并稍后從完全相同的狀態恢復培訓 - 無需訪問原始代碼。
在Keras中保存功能齊全的模型非常有用 - 您可以在TensorFlow.js中加載它們,然后在Web瀏覽器中訓練和運行它們。
Keras使用HDF5標準提供基本保存格式。 出于我們的目的,可以將保存的模型視為單個二進制blob。
model = create_model()
model.fit(train_images, train_labels, epochs=5)
# Save entire model to a HDF5 file
model.save('my_model.h5')
Epoch 1/5
1000/1000 [==============================] - 0s 395us/step - loss: 1.1260 - acc: 0.6870
Epoch 2/5
1000/1000 [==============================] - 0s 135us/step - loss: 0.4136 - acc: 0.8760
Epoch 3/5
1000/1000 [==============================] - 0s 138us/step - loss: 0.2811 - acc: 0.9280
Epoch 4/5
1000/1000 [==============================] - 0s 153us/step - loss: 0.2078 - acc: 0.9480
Epoch 5/5
1000/1000 [==============================] - 0s 154us/step - loss: 0.1452 - acc: 0.9750
現在從該文件重新創建模型:
# Recreate the exact same model, including weights and optimizer.
new_model = keras.models.load_model('my_model.h5')
new_model.summary()
檢查其準確性:
loss, acc = new_model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
這項技術可以保存以下:
- 權重值
- 模型的配置(架構)
- 優化器配置
Keras通過檢查架構來保存模型。 目前,它無法保存TensorFlow優化器(來自tf.train)。 使用這些時,您需要在加載后重新編譯模型,并且您將失去優化器的狀態。
下一步是什么
這是使用tf.keras保存和加載的快速指南。
tf.keras指南顯示了有關使用tf.keras保存和加載模型的更多信息。
請參閱在急切執行期間保存以備保存。
“保存和還原”指南包含有關TensorFlow保存的低級詳細信息。
完整代碼:
from __future__ import absolute_import,division,print_function
import os
import tensorflow as tf
from tensorflow import keras
print(tf.__version__)
# Download dataset
(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
# Define a model
# Returns a short sequential model
def create_model():
model = tf.keras.models.Sequential([
keras.layers.Dense(512,activation=tf.nn.relu,input_shape=(784,)),
keras.layers.Dropout(0.2),
keras.layers.Dense(10,activation=tf.nn.softmax)
])
model.compile(optimizer=tf.keras.optimizers.Adam(),
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['accuracy'])
return model
# Create a basic model instance
model = create_model()
model.summary()
# Checkpoint callback usage
checkpoint_path = "training_1/cp.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)
# Create checkpoint callback
cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path,
save_weights_only=True,
verbose=1)
model = create_model()
model.fit(train_images,train_labels,epochs=10,
validation_data=(test_images,test_labels),
callbacks=[cp_callback]) # pass callback to training
# Create a new, untrained model.
model = create_model()
loss,acc = model.evaluate(test_images,test_labels)
print("Untrained model, accuracy: {:5.2f}%".format(100*acc))
# Load the weights from chekpoint, and re-evaluate.
model.load_weights(checkpoint_path)
loss,acc = model.evaluate(test_images,test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
# Train a new model, and save uniquely named checkpoints once every 5epochs
# 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)
cp_callback = tf.keras.callbacks.ModelCheckpoint(
checkpoint_path, verbose=1,save_weights_only=True,
# Save weights, every 5-epochs
period=5)
model = create_model()
model.fit(train_images,train_labels,
epochs=50,callbacks = [cp_callback],
validation_data = (test_images,test_labels),
verbose=0)
latest = tf.train.latest_checkpoint(checkpoint_dir)
print(latest)
# To test, reset the model and load the latest checkpoint
model = create_model()
model.load_weights(latest)
loss, acc = model.evaluate(test_images,test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
# Manually save weights
# Save the weights
model.save_weights('./checkpoints/my_checkpoint')
# Restore the weights
model = create_model()
model.load_weights('./checkpoints/my_checkpoint')
loss, acc = model.evaluate(test_images,test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
# Save the entire model
model = create_model()
model.fit(train_images,train_labels,
epochs=5)
# Save entire model to a HDF5 file
model.save('my_model.h5')
# Recreate the exact same model, including weights and optimizer.
new_model = keras.models.load_model('my_model.h5')
new_model.summary()
loss, acc = new_model.evaluate(test_images,test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))