NLP 課程文件

高階介面功能

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強型文件體驗

開始使用

高階介面功能

Ask a Question Open In Colab Open In Studio Lab

現在我們已經可以構建和共享一個基本的介面,讓我們探索一些更高階的功能,例如狀態和解釋。

使用狀態來持久化資料

Gradio 支援會話狀態,其中資料在頁面載入期間跨多個提交持久化。會話狀態對於構建例如聊天機器人的演示很有用,在這些演示中,您希望在使用者與模型互動時持久化資料。請注意,會話狀態不會在模型的不同使用者之間共享資料。

要在會話狀態中儲存資料,您需要執行三件事

  1. 將一個額外的引數傳遞到您的函式中,該引數表示介面的狀態。
  2. 在函式結束時,將狀態的更新值作為額外的返回值返回。
  3. 在建立您的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 關鍵字即可設定為預設值。這允許您的使用者瞭解輸入的哪些部分對輸出負責。請檢視下面的簡單介面,它顯示了一個影像分類器,其中還包含解釋

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拆分為可自定義的“塊”,那豈不是很好?幸運的是,確實有!這是最後一部分的主題。

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