LLM 课程文档
高级界面功能
并获得增强的文档体验
开始使用
高级界面功能
既然我们已经可以构建和分享基本界面,现在让我们探索一些更高级的功能,例如状态和解释性。
使用状态持久化数据
Gradio 支持会话状态,其中数据在页面加载期间的多次提交中保持持久。 会话状态对于构建演示(例如,聊天机器人)非常有用,在聊天机器人中,您希望在用户与模型交互时持久保存数据。 请注意,会话状态不会在模型的不同用户之间共享数据。
要在会话状态中存储数据,您需要做三件事
- 在函数中传入一个额外的参数,它代表界面的状态。
- 在函数结束时,返回状态的更新值作为额外的返回值。
- 在创建 Interface 时,添加“state”输入和“state”输出组件。
请看下面的聊天机器人示例
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 上更新