如何用Streamlit部署你的基于深度学习的图像分类模型

1,540 阅读4分钟

处理数据与在生产中实施机器学习模型是不同的。学习如何将深度学习模型作为离线制作部署到在线制作是非常必要的,但其中一个主要的问题是所学模型的大尺寸。本文将重点介绍用Streamlit部署一个图像分类器深度学习模型。以下是本文要介绍的主题。

目录

  1. 关于Streamlit
  2. 训练和保存DL模型
  3. 使用Streamlit进行部署

让我们先来了解一下Streamlit的高层情况

关于Streamlit

Streamlit是一个免费和开源的python框架。它允许用户快速构建交互式仪表盘和机器学习网络应用。不需要任何关于HTML、CSS和Javascript的先验知识。它还有助于热重载,以便你的应用程序可以在你编辑和保存文件时替换停留。添加一个小部件就相当于声明一个变量。不需要写一个背景,指定一个不同的路径,或处理一个HTTP请求。易于实现和管理。如果一个人知道Python,那么所有的人都有能力使用Streamlit来构建和分享你的网络应用,只需几个小时。

你是否在寻找一个完整的数据科学中使用的Python库。在此查看.

训练和保存DL模型

在这篇文章中,由于时间的限制,我们将使用一个预训练的模型。该模型将对图像进行分类。该模型是在有1000个标签类的Imagenet数据集上训练的。该模型由19层组成。这些层分为16个卷积层,3个全连接层,5个MaxPool层和1个SoftMax层。

预训练的是VGG19,它是Keras的Visual Geometry Group的196亿FLops版本。VGG是AlexNet的继承者。下面是对VGG19架构的高级描述。

印度分析杂志

让我们从导入必要的库开始。

from tensorflow.keras.applications.vgg19 import VGG19

接下来,我们将定义模型并保存预训练的模型。

classifier = VGG19(
    include_top=True,
    weights='imagenet',
    input_tensor=None,
    input_shape=None,
    pooling=None,
    classes=1000,
    classifier_activation='softmax'
)

印度分析杂志

classifier.save("image_classification.hdf5")

让我们从部署部分开始。

使用Streamlit进行部署

首先,我们需要安装Streamlit包。

!pip install -q streamlit

创建一个应用程序文件,并在该文件中写入所有代码。这是一个Python脚本,将在Web应用程序的后台运行。

%%writefile app.py
import streamlit as st
import tensorflow as tf
from tensorflow.keras.applications.imagenet_utils import decode_predictions
import cv2
from PIL import Image, ImageOps
import numpy as np
 
@st.cache(allow_output_mutation=True)
def load_model():
  model=tf.keras.models.load_model('/content/image_classification.hdf5')
  return model
with st.spinner('Model is being loaded..'):
  model=load_model()
 
st.write("""
         # Image Classification
         """
         )
 
file = st.file_uploader("Upload the image to be classified U0001F447", type=["jpg", "png"])
st.set_option('deprecation.showfileUploaderEncoding', False)
 
def upload_predict(upload_image, model):
    
        size = (180,180)    
        image = ImageOps.fit(upload_image, size, Image.ANTIALIAS)
        image = np.asarray(image)
        img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        img_resize = cv2.resize(img, dsize=(224, 224),interpolation=cv2.INTER_CUBIC)
        
        img_reshape = img_resize[np.newaxis,...]
    
        prediction = model.predict(img_reshape)
        pred_class=decode_predictions(prediction,top=1)
        
        return pred_class
if file is None:
    st.text("Please upload an image file")
else:
    image = Image.open(file)
    st.image(image, use_column_width=True)
    predictions = upload_predict(image, model)
    image_class = str(predictions[0][0][1])
    score=np.round(predictions[0][0][2]) 
    st.write("The image is classified as",image_class)
    st.write("The similarity score is approximately",score)
    print("The image is classified as ",image_class, "with a similarity score of",score)

使用 "st.cache "是因为Streamlit提供了一个缓存机制。该机制允许应用程序在从互联网上加载数据处理大型数据集或执行昂贵的计算时保持性能。

一旦需要分类的图像被上传。该图像应与Keras模型的输入大小相匹配(224,224)。要使用open cv resize函数来调整图像的大小。

使用TensorFlow的predict函数来预测作为输入的图像。使用Keras imagenet工具中的 "decode_prediction "函数对预测的图像信息进行解码。将预测结果和分数存储在一个变量中,并使用streamlit的写函数来显示该信息。这个写函数就像python的打印函数。

将应用程序文件连接到本地服务器上。如果使用google Colab研究笔记本,请使用以下命令。否则,就简单地运行应用程序文件。

! streamlit run app.py & npx localtunnel -port 8501

这段代码将产生一个链接。复制粘贴该链接或点击该链接,它将重定向到一个与钓鱼网站有关的警告页面。点击继续,streamlit网络应用程序就会启动。该网络应用程序看起来是这样的。

结论

创建一个机器学习模型需要大量的时间和精力。为了向世界展示这些努力,人们需要部署该模型并展示其能力。Streamlit是一个强大的、简单易用的平台,即使你缺乏必要的内部技术或前端专业知识,也能完成这个任务。通过这篇文章,我们已经了解了Streamlit在部署深度学习模型方面的用途。

参考资料