如何在Comet平台上部署和监控你的Keras模型

810 阅读7分钟

Comet是研究人员和数据科学家使用的人工智能和机器学习的在线实验平台,它为跟踪ML模型和比较服务器上模型的结果提供了一个简单的平台。Comet提供了一个很好的仪表盘,以可视化界面中部署的模型的各种参数,并在内部保持对模型的跟踪。因此,本文简要介绍了如何在Comet的在线平台上部署Keras模型,并从模型中做出合适的解释。

目录

  1. 彗星简介
  2. 从头开始实现一个Keras模型
  3. 登录到彗星界面
  4. 将Keras模型集成到彗星接口中
  5. 从彗星接口获取预测结果
  6. 在彗星服务器中安装模型
  7. 可视化部署在服务器上的模型
  8. 总结

让我们先来简单讨论一下彗星的情况。

彗星简介

彗星是一个在线API,作为一个在线平台来部署机器学习或深度学习模型,并持续验证模型部署生命周期的所有阶段,直到生产。平台上的模型可以公开部署,也可以限制某些访问,以分析部署在其平台上的模型的参数。通过相关访问,彗星提供了在任何时候访问服务器上的模型的灵活性,并监控部署在他们服务器上的模型。

从头开始实施Keras模型

Keras模块为深度学习模型的开发提供了有用的数据集,这里我们使用MNIST数字数据集进行模型开发,并在Comet服务器上部署开发的模型。

因此,最初获得的数据集被分割成训练和测试,并使用子图对分割的数据进行可视化。后来,一个简单的顺序模型被建立起来,有适当的输入维度和激活函数。数据集的从属特征被适当地重塑,目标变量则根据MNIST数据集中的数字数量进行编码。经过适当的预处理后,该模型以分类交叉熵为损失函数,以准确性为指标,对所开发的模型进行评估。此外,该模型的训练和测试准确度和损失也得到了验证。下面是为MNIST数据集实现基本数字分类模型的完整步骤。

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import random
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.preprocessing import image
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.utils import to_categorical
 
(X_train,y_train),(X_test,y_test)=mnist.load_data()
print('Number of training records',X_train.shape)
print('Number of testing records',y_test.shape)

plt.figure(figsize=(5,10))
 
for i in range(9):
   plt.subplot(3,3,i+1)
   num = random.randint(0, len(X_train))
   plt.imshow(X_train[num], cmap='gray', interpolation='none')
   plt.title("Class {}".format(y_train[num]))
   #plt.tight_layout()
   plt.axis('off')
 plt.show()

X_test_original=X_test.copy()
# preprocess and normalize the data
X_train = X_train.reshape(60000, 28*28)
X_test = X_test.reshape(10000, 28*28)
X_train1=X_train/255.
X_test1=X_test/255.
## Encoding the target variable
y_train=to_categorical(y_train,10)
y_test=to_categorical(y_test,10)


建立模型

model=Sequential()
 
model.add(Dense(units=512,activation='relu',input_dim=784))
model.add(Dense(units=256,activation='relu'))
model.add(Dense(units=125,activation='relu'))
model.add(Dense(units=10,activation='softmax'))
 
model.summary()

model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
model_res=model.fit(X_train1,y_train,epochs=5,validation_data=(X_test,y_test))

评估模型的性能

plt.figure(0)
plt.plot(model_res.history['accuracy'],label='training accuracy')
plt.plot(model_res.history['val_accuracy'],label='testing accuracy')
plt.title('Accuracy')
plt.xlabel('epochs')
plt.ylabel('accuracy')
plt.legend()
plt.show()
 
plt.figure(1)
plt.plot(model_res.history['loss'],label='training loss')
plt.plot(model_res.history['val_loss'],label='testing loss')
plt.title('Loss')
plt.xlabel('epochs')
plt.ylabel('loss')
plt.legend()
plt.show()

model.evaluate(X_train,y_train)
model.evaluate(X_test,y_test)

登录到彗星界面

首先,彗星模块可以使用pip命令轻松地安装在工作环境中,并且可以使用导入语句加载模块。因此,一旦模块成功地安装在工作环境中,必须给模型一个随机的名字,这个模型将使用init() 内置函数部署到彗星服务器上。

因此,一个链接将在那个特定的运行实例中生成,一个独特的API密钥将被生成,它可以以字符串的形式存储在工作环境中,并在需要时加以利用。所涉及的步骤如下所示:

import comet_ml
from comet_ml import Experiment
comet_ml.init('comet-keras')

启动彗星接口

keras_exp=Experiment(project_name='comet-keras',api_key=API_key)

So now this comet interface can be used to train, test, and evaluate the parameters of the model on the comet server. Now the interface and the login with the appropriate API key can be validated using the 
keras_exp.display()

在彗星接口中整合Keras模型

将模型集成到服务器中,主要是从使用log_dataset_hash() 函数对训练数据集进行散列开始的,实验可以在彗星界面上使用彗星的内建函数train() 进行训练。散列数据集和加载模型的步骤如下:

keras_exp.log_dataset_hash(X_train)
with keras_exp.train():
model_res=model.fit(X_train1,y_train,batch_size=32,epochs=10,validation_data=(X_test1,y_test))

在彗星界面上评估模型参数

现在使用彗星的test() 内置函数,可以对部署在服务器上的模型进行各种参数评估。这里涉及到评估训练和测试的损失和准确性的步骤如下:

with keras_exp.test():
   test_loss, test_accuracy = model.evaluate(X_test1, y_test)
   train_loss, train_accuracy = model.evaluate(X_train1, y_train)
   metrics = {'test_loss':test_loss,'test_accuracy':test_accuracy,'train_loss':train_loss,'train_accuracy':train_accuracy}
}

在彗星界面记录各种指标

log_metrics() 内置函数被用来部署或记录用于评估彗星服务器上的模型的度量:

keras_exp.log_metrics(metrics)

现在让我们看看如何从部署在彗星界面上的模型获得预测结果。

从彗星界面获取预测结果

为了从彗星界面获得预测结果,log_figure() 函数被用来提供模型对每个被分类的数字的预测输出,如下所示。但是为了获得预测结果,必须使用原始的TensorFlow模型,并且可以使用Comet的内置功能来可视化模型的性能。

model_pred = model.predict(X_test1[:10]).argmax(-1)
 
# remember our copy of x_test? This is where it comes into play again!
# Since we flatted x_test during pre-processing, we need to preserve an unflattened version
plt.figure(figsize=(16,8))
for i in range(10):
   plt.subplot(1, 10, i+1)
   plt.imshow(X_test_original[i], interpolation='nearest')
   plt.text(0, 0, model_pred[i], color='black',
            bbox=dict(facecolor='white', alpha=1))
   plt.axis('off')
 
 
keras_exp.log_figure('Predicted MNIST Digits from Comet Interface',plt)

通过点击从获得的图中的网络链接,可以下载部署在服务器上的模型的输出,如果需要的话,还可以下载文件和REST api信息。现在,彗星服务器上的实验必须结束,以观察彗星接口如何监测部署在其服务器上的模型。

注销部署在服务器上的模型

现在,在服务器上进行的实验必须使用end() 内置函数来结束。在结束服务器上的实验时,与数据有关的一些信息,用于评估模型的指标,以及其他各种信息将被提供,如下所示。

keras_exp.end()

在彗星服务器上安装模型

模型可以以HDF5(h5)格式保存,并且可以使用log_model() 函数将模型挂载到彗星服务器上,这样可以方便将模型权重用于任何参数评估或将模型权重用于任何其他任务。在彗星服务器上安装模型的步骤如下。

model.save('keras-comet-new.h5')
keras_exp.log_model('Saved Keras model',"/content/keras-comet-new.h5")

将部署在服务器上的模型可视化

彗星的display() 函数可以用来可视化参数和监控服务器上的模型功能。

keras_exp.display()

在服务器上部署的整个代码可以在服务器的代码部分看到,在那里整个代码对有权限的人是可见的:

所有在服务器上进行的实验及其记录时间和评估的参数都可以在指标窗格中显示出来,如下图所示:

除此之外,硬件资源的使用情况也可以在服务器上显示出来,如下图所示:

总结

本文简要介绍了如何开发一个Keras模型并将其部署在Comet服务器上以持续监控该模型。对于服务器上的模型性能,产生了易于解释的报告和图表,并且使用系统指标可以直观地看到模型对前提下使用的每个硬件资源的内存消耗。因此,通过使用彗星服务器,模型可以在任何平台上使用,并相应地利用来监测服务器上的模型。