在Tensorflow中保存和加载模型

在Tensorflow中保存和加载模型

在测试前后都可以保存模型的开发过程。因此,一个模型将从它离开的地方开始,以消除冗长的训练期。如果你保存了你的模型,你仍然可以分享你的模型并让其他人复制它。大多数机器学习专业人士在发布测试模型和技术时都会分享以下内容。

  • 创建模型的代码
  • 模型的训练权重

分享这些信息可以让其他人更好地理解模型的运作方式,并用新的数据来测试它。

除此之外,教授机器学习模型将花费大量的时间和精力。不过,关闭笔记本或机器会导致所有这些权重和更多的东西随着内存的冲刷而消失。重要的是要保存模型,以优化重用性,从而最大限度地利用你的时间。

在Tensorflow中保存和加载模型

一旦我们完成了对模型的评估,我们就可以着手拯救它。

我们可以保存和加载我们的机器学习模型的方法如下:

  • 使用内置的函数model.save()
  • 使用内置的函数model.save_weights()

使用save()方法

现在我们可以通过调用save()方法并传入文件路径作为参数来保存我们的模型。这将保存模型的

  • Model Architecture
  • Model Weights
  • 模型优化器的状态(从我们离开的地方恢复)。

语法: tensorflow.keras.X.save(location/model_name)

  • 这里的X指的是顺序类、功能模型或模型子类。它们都有save()方法。
  • 在这个方法中,位置和模型名称一起被作为一个参数传递。如果只传递模型名称,那么模型将被保存在与Python文件相同的位置。

我们可以使用tensorflow模块中的load_model()方法加载保存的模型。

语法: tensorflow.keras.models.load_model(location/model_name)

在这个方法中,位置和模型名称被作为一个参数传递。

注意:如果我们指定”.h5″,模型将以hdf5格式保存;如果没有指定扩展名,模型将以TensorFlow本地格式保存。

使用save_weights()方法

现在你可以使用save_weights()方法简单地保存所有层的权重。它保存了模型中包含的各层的权重。我们建议使用save()方法来保存h5模型,而不是使用tensorflow的save_weights()方法来保存一个模型。然而,h5模型也可以使用save_weights()方法保存。

语法: tensorflow.keras.Model.save_weights(location/weights_name)

在这个方法中,位置和权重名称被作为一个参数传递。如果只传递权重名称,那么它将被保存在与Python文件相同的位置。

下面是一个程序,我们保存初始模型的权重。

# import module
import tensorflow
 
# create object
model=tensorflow.keras.Model()
 
# assign location
path='Weights_folder/Weights'
 
# save
model.save_weights(path)

它将创建一个名为weights文件夹的新文件夹,并将所有的权重保存为Tensorflow本地格式的我的权重。总共会有三个文件夹。

  • 检查点:这是一个人类可读的文件,有以下文字。
model_checkpoint_path: "Weights"
all_model_checkpoint_paths: "Weights"
  • data-00000-of-00001: 这个文件包含模型的实际权重。
  • index。这个文件告诉TensorFlow哪些权重被存储在哪里。

我们可以使用load_weights()方法加载已保存的模型。

语法:

tensorflow.keras.Model.load_weights(location/weights_name)

在这个方法中,位置和权重名称被作为一个参数传递。

注意:当为一个模型加载权重时,我们必须首先确保该模型的设计是正确的。我们不能将一个模型(有2个密集层)的权重加载到一个有1个密集层的顺序模型上,因为两者并不一致。

下面是一个例子,描述了上述所有保存和加载模型的方法。在这里,我们开发了一个模型,并使用内置的数据集对其进行训练,最后以各种方式再次保存和加载该模型。

导入模块。

# import required modules
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Input, Conv2D, Dense, Flatten, Dropout
from tensorflow.keras.layers import GlobalMaxPooling2D, MaxPooling2D
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.models import Model
from tensorflow.keras.models import load_model

加载并分割数据集,然后改变数据的一些属性。

# Load in the data
cifar10 = tf.keras.datasets.cifar10
 
# Distribute it to train and test set
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
print(x_train.shape, y_train.shape, x_test.shape, y_test.shape)
 
# Reduce pixel values
x_train, x_test = x_train / 255.0, x_test / 255.0
 
# flatten the label values
y_train, y_test = y_train.flatten(), y_test.flatten()

输出:

在Tensorflow中保存和加载模型

通过添加层来开发模型。

# number of classes
K = len(set(y_train))
# calculate total number of classes for output layer
print("number of classes:", K)
 
# Build the model using the functional API
# input layer
i = Input(shape=x_train[0].shape)
x = Conv2D(32, (3, 3), activation='relu', padding='same')(i)
x = BatchNormalization()(x)
x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)
x = BatchNormalization()(x)
x = MaxPooling2D((2, 2))(x)
 
x = Conv2D(64, (3, 3), activation='relu', padding='same')(x)
x = BatchNormalization()(x)
x = Conv2D(64, (3, 3), activation='relu', padding='same')(x)
x = BatchNormalization()(x)
x = MaxPooling2D((2, 2))(x)
 
x = Conv2D(128, (3, 3), activation='relu', padding='same')(x)
x = BatchNormalization()(x)
x = Conv2D(128, (3, 3), activation='relu', padding='same')(x)
x = BatchNormalization()(x)
x = MaxPooling2D((2, 2))(x)
 
x = Flatten()(x)
x = Dropout(0.2)(x)
 
# Hidden layer
x = Dense(1024, activation='relu')(x)
x = Dropout(0.2)(x)
 
# last hidden layer i.e.. output layer
x = Dense(K, activation='softmax')(x)
 
model = Model(i, x)
model.summary()

输出:

在Tensorflow中保存和加载模型

使用save()方法将模型保存为h5格式。

# saving and loading the .h5 model
 
# save model
model.save('gfgModel.h5')
print('Model Saved!')
 
# load model
savedModel=load_model('gfgModel.h5')
savedModel.summary()

输出:

在Tensorflow中保存和加载模型

使用save_weights()方法保存模型的权重。

# saving and loading the model weights
 
# save model
model.save_weights('gfgModelWeights')
print('Model Saved!')
 
# load model
savedModel = model.load_weights('gfgModelWeights')
print('Model Loaded!')

输出:

在Tensorflow中保存和加载模型

使用save_weights()方法将模型保存为h5格式模型。

# saving and loading the .h5 model
 
# save model
model.save_weights('gfgModelWeights.h5')
print('Model Saved!')
 
# load model
savedModel = model.load_weights('gfgModelWeights.h5')
print('Model Loaded!')

输出:

在Tensorflow中保存和加载模型

上述模型是在Google colab中开发的。所以在保存模型时,它们被暂时储存起来,可以下载。下面是保存的模型和权重。

在Tensorflow中保存和加载模型

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

Tensorflow 教程