Gradio机器学习模型快速部署工具quickstart
引言
书接上回 Gradio机器学习模型快速部署工具【quickstart】翻译,讲到多输入输出,其实很简单,就是把多个组件包装到列表,inputs和outputs对应的就是2个列表,输入输出列表,仅此而已。
1.图像示例
Gradio 支持多种类型的组件,例如Image
, DataFrame
, Video
, 或Label
. 让我们尝试一个图像到图像的功能来感受一下这些!
- import numpy as np
- import gradio as gr
- def sepia(input_img):
- sepia_filter = np.array([
- [0.393, 0.769, 0.189],
- [0.349, 0.686, 0.168],
- [0.272, 0.534, 0.131]
- ])
- sepia_img = input_img.dot(sepia_filter.T)
- sepia_img /= sepia_img.max()
- return sepia_img
- demo = gr.Interface(sepia, gr.Image(shape=(200, 200)), “image”)
- demo.launch()
使用该Image
组件作为输入时,您的函数将接收一个形状为 的 NumPy 数组(width, height, 3)
,其中最后一个维度表示 RGB 值。我们还将以 NumPy 数组的形式返回图像。
您还可以使用关键字参数设置组件使用的数据类型type=
。例如,如果您希望您的函数采用图像的文件路径而不是 NumPy 数组,则输入Image
组件可以写为:
- gr.Image(type=“filepath”, shape=…)
另请注意,我们的输入Image
组件带有一个编辑按钮,它允许裁剪和放大图像。以这种方式处理图像有助于揭示机器学习模型中的偏差或隐藏缺陷!
您可以在Gradio 文档中阅读更多关于许多组件以及如何使用它们的信息。
2.块:更多的灵活性和控制
Gradio 提供了两个类来构建应用程序:
1. Interface,它为创建我们迄今为止一直在讨论的演示提供了高级抽象。
2. Blocks,一种用于设计具有更灵活布局和数据流的网络应用程序的低级 API。Blocks 允许你做一些事情,比如以多个数据流和演示为特色,控制组件在页面上出现的位置,处理复杂的数据流(例如,输出可以作为其他功能的输入),以及根据用户交互更新组件的属性/可见性——仍然全部在 python 中。如果您需要这种可定制性,请试试Blocks
吧!
让我们看一个简单的例子。请注意此处的 API 与Interface
.
- import gradio as gr
- def greet(name):
- return “Hello “ + name + “!”
- with gr.Blocks() as demo:
- name = gr.Textbox(label=“Name”)
- output = gr.Textbox(label=“Output Box”)
- greet_btn = gr.Button(“Greet”)
- greet_btn.click(fn=greet, inputs=name, outputs=output)
- demo.launch()
注意事项:
Blocks
是用一个with
子句制作的,在这个子句中创建的任何组件都会自动添加到应用程序中。- 组件按照它们创建的顺序垂直显示在应用程序中。(稍后我们将介绍自定义布局!)
- 创建了A
Button
,然后将click
事件侦听器添加到此按钮。这个 API 应该看起来很熟悉!与 一样Interface
,该click
方法采用 Python 函数、输入组件和输出组件。
3.更复杂的 Blocks
这是一个应用程序,可让您体验Blocks
:
- import numpy as np
- import gradio as gr
- # 1.文字翻转
- def flip_text(x):
- return x[::-1]
- # 2.图像翻转
- def flip_image(x):
- return np.fliplr(x)
- with gr.Blocks() as demo:
- # 3.添加markdown组件
- gr.Markdown(“Flip text or image files using this demo.”)
- # 4.添加Tab
- with gr.Tab(“Flip Text”):
- text_input = gr.Textbox()
- text_output = gr.Textbox()
- text_button = gr.Button(“Flip”)
- with gr.Tab(“Flip Image”):
- with gr.Row():
- image_input = gr.Image()
- image_output = gr.Image()
- image_button = gr.Button(“Flip”)
- # 5.添加Accordion
- with gr.Accordion(“Open for More!”):
- gr.Markdown(“Look at me…”)
- # 6.添加2个按钮
- text_button.click(flip_text, inputs=text_input, outputs=text_output)
- image_button.click(flip_image, inputs=image_input, outputs=image_output)
- demo.launch()
参考网址:gradio.app/quickstart/
以上就是Gradio机器学习模型快速部署工具quickstart的详细内容,更多关于Gradio部署quickstart的资料请关注我们其它相关文章!
发表评论