LLM 课程文档

高级界面功能

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

高级界面功能

Ask a Question Open In Colab Open In Studio Lab

现在我们已经可以构建和共享一个基本的界面了,接下来我们探索一些更高级的功能,例如状态和解释。

使用状态来持久化数据

Gradio 支持会话状态 (session state),其中数据在页面加载期间的多次提交中保持不变。会话状态对于构建聊天机器人等演示很有用,您希望在用户与模型交互时持久化数据。请注意,会话状态不会在您的模型的不同用户之间共享数据。

要将会话状态中的数据,您需要执行三件事:

  1. 在您的函数中传入一个表示界面状态的*额外参数*。
  2. 在函数末尾,将更新后的状态值作为*额外返回值*返回。
  3. 在创建 `Interface` 时添加“状态”输入和“状态”输出组件。

请参阅下面的聊天机器人示例

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()

注意输出组件的状态是如何在多次提交中保持不变的。注意:您可以向状态参数传入默认值,该值将用作状态的初始值。

使用解释来理解预测

大多数机器学习模型都是黑箱,函数内部逻辑对最终用户是隐藏的。为了提高透明度,我们通过简单地将 `Interface` 类中的 `interpretation` 关键字设置为 `default`,从而可以非常轻松地为模型添加解释。这允许您的用户了解输入的哪些部分导致了输出。请看下面的简单界面,它显示了一个图像分类器,其中也包含解释:

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()

通过提交输入,然后点击输出组件下的“解释”来测试解释功能。

除了 Gradio 提供的默认解释方法外,您还可以将 `interpretation` 参数指定为 `shap` 并设置 `num_shap` 参数。这使用了基于 Shapley 的解释,您可以在此处阅读更多相关信息。最后,您还可以将自己的解释函数传递给 `interpretation` 参数。请在 Gradio 的入门页面此处查看示例。

至此,我们对 Gradio 的 `Interface` 类进行了深入探讨。正如我们所看到的,这个类使得用几行 Python 代码创建机器学习演示变得非常简单。然而,有时您会希望通过更改布局或将多个预测函数串联起来来自定义您的演示。如果我们能以某种方式将 `Interface` 分割成可自定义的“块”就好了?幸运的是,确实有!这就是最后一节的主题。

< > 在 GitHub 上更新