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 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.