9-Building_and_sharing_demos-5-Advanced_Interface_features

中英文对照学习,效果更佳!
原课程链接:https://huggingface.co/course/chapter9/6?fw=pt

Advanced Interface features

高级界面功能

Ask a Question
Open In Colab
Open In Studio Lab
Now that we can build and share a basic interface, let’s explore some more advanced features such as state, and interpretation.

现在,我们可以构建和共享基本界面,让我们探索一些更高级的功能,如状态和解释。

Using state to persist data

使用状态持久化数据

Gradio supports session state, where data persists across multiple submits within a
page load. Session state is useful for building demos of, for example, chatbots where you want to
persist data as the user interacts with the model. Note that session state does not share data between different users of your model.

GRadio支持会话状态,在这种状态下,数据在页面加载中跨多个提交持续存在。会话状态对于构建聊天机器人的演示非常有用,在这些演示中,您希望在用户与模型交互时持久化数据。请注意,会话状态不会在模型的不同用户之间共享数据。

To store data in a session state, you need to do three things:

要在会话状态下存储数据,您需要做三件事:

  1. Pass in an extra parameter into your function, which represents the state of the interface.
  2. At the end of the function, return the updated value of the state as an extra return value.
  3. Add the ‘state’ input and ‘state’ output components when creating your Interface.

See the chatbot example below:

将一个额外的参数传递到您的函数中,该参数表示接口的状态。在函数的末尾,将更新后的状态值作为额外的返回值返回。在创建`接口‘时添加’STATE‘输入和’STATE‘输出组件。请参阅下面的聊天机器人示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import random

import gradio as gr


def chat(message, history):
history = history or []
if message.startswith("How many"):
response = random.randint(1, 10)
elif message.startswith("How"):
response = random.choice(["Great", "Good", "Okay", "Bad"])
elif message.startswith("Where"):
response = random.choice(["Here", "There", "Somewhere"])
else:
response = "I don't know"
history.append((message, response))
return history, history


iface = gr.Interface(
chat,
["text", "state"],
["chatbot", "state"],
allow_screenshot=False,
allow_flagging="never",
)
iface.launch()

Notice how the state of the output component persists across submits.
Note: you can pass in a default value to the state parameter,
which is used as the initial value of the state.

请注意,输出组件的状态如何在提交期间保持不变。注意:您可以将缺省值传递给状态参数,该参数用作状态的初始值。

Using interpretation to understand predictions

使用解释来理解预测

Most machine learning models are black boxes and the internal logic of the function is hidden from the end user. To encourage transparency, we’ve made it very easy to add interpretation to your model by simply setting the interpretation keyword in the Interface class to default. This allows your users to understand what parts of the input are responsible for the output. Take a look at the simple interface below which shows an image classifier that also includes interpretation:

大多数机器学习模型都是黑盒,功能的内部逻辑对最终用户是隐藏的。为了鼓励透明度,我们已经使向模型添加解释变得非常容易,只需将接口类中的解释关键字设置为Default即可。这使您的用户能够了解输入的哪些部分负责输出。看看下面的简单界面,它显示了一个也包括解释的图像分类器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import requests
import tensorflow as tf

import gradio as gr

inception_net = tf.keras.applications.MobileNetV2() # load the model

# Download human-readable labels for ImageNet.
response = requests.get("https://git.io/JJkYN")
labels = response.text.split("\n")


def classify_image(inp):
inp = inp.reshape((-1, 224, 224, 3))
inp = tf.keras.applications.mobilenet_v2.preprocess_input(inp)
prediction = inception_net.predict(inp).flatten()
return {labels[i]: float(prediction[i]) for i in range(1000)}


image = gr.Image(shape=(224, 224))
label = gr.Label(num_top_classes=3)

title = "Gradio Image Classifiction + Interpretation Example"
gr.Interface(
fn=classify_image, inputs=image, outputs=label, interpretation="default", title=title
).launch()

Test the interpretation function by submitting an input then clicking Interpret under the output component.

测试解释功能,方法是提交一个输入,然后单击输出组件下的解释。

Besides the default interpretation method Gradio provides, you can also specify shap for the interpretation parameter and set the num_shap parameter. This uses Shapley-based interpretation, which you can read more about here.
Lastly, you can also pass in your own interpretation function into the interpretation parameter. See an example in Gradio’s getting started page here.

除了GRadio提供的默认解释方法外,您还可以为Interpretation参数指定shap,并设置num_shap参数。这使用了基于Shapley的解释,您可以在这里阅读更多信息。最后,您也可以将您自己的解释函数传入到Interpretation参数中。请点击此处查看GRadio入门页面中的示例。

This wraps up our deep dive into the Interface class of Gradio. As we’ve seen, this class makes it simple to create machine learning demos in a few lines of Python code. However, sometimes you’ll want to customise your demo by changing the layout or chaining multiple prediction functions together. Wouldn’t it be nice if we could somehow split the Interface into customizable “blocks”? Fortunately, there is! That’s the topic of the final section.

这结束了我们对GRadio的Interface‘类的深入研究。正如我们已经看到的,这个类使得用几行Python代码创建机器学习演示变得很简单。然而,有时您可能希望通过更改布局或将多个预测函数链接在一起来定制您的演示。如果我们能以某种方式将Interface`拆分成可定制的“块”,不是很好吗?幸运的是,有!这就是最后一节的主题。