共用方式為


將ai.analyze_sentiment與 PySpark 搭配使用

ai.analyze_sentiment 功能使用生成式 AI 來檢測輸入文本的情緒狀態,只需一行代碼即可。 它可以檢測輸入的情緒狀態是積極的、消極的、混合的還是中性的。 它還可以根據您指定的標籤檢測情緒狀態。 如果函式無法判斷情感,則會將輸出保留空白。

備註

  • 本文介紹了將 ai.analyze_sentiment 與 PySpark 一起使用。 要將 ai.analyze_sentiment 與熊貓一起使用,請參閱 這篇文章
  • 請參閱 此概述文章中的其他 AI 功能。
  • 瞭解如何自訂 AI 功能的設定

概觀

ai.analyze_sentiment 函式適用於 Spark DataFrames。 您必須將現有輸入資料行的名稱指定為參數。

函數會傳回新的 DataFrame,其中包含每個輸入文字數據列的情感標籤,並儲存在一個輸出欄位中。

語法

# Default sentiment labels
df.ai.analyze_sentiment(input_col="input", output_col="sentiment")

# Custom sentiment labels
df.ai.analyze_sentiment(input_col="input", output_col="sentiment", labels=["happy", "angry", "indifferent"])

參數

名稱 Description
input_col
為必填項目
包含現有資料行名稱的 字串 ,其中包含要分析情緒的輸入文字值。
output_col
可選
字串,其中包含新欄的名稱,用於儲存每列輸入文字的情感標籤。 如果您未設定此參數,則會為輸出資料行產生預設名稱。
labels
可選
一或多個 字串 ,代表要比對輸入文字值的情緒標籤集。
error_col
可選
字串,其中包含新欄位的名稱,以存儲處理每一行輸入文字時產生的任何 OpenAI 錯誤。 如果您未設定此參數,則會為錯誤資料行產生預設名稱。 如果輸入資料列沒有錯誤,則此資料列中的值會 null

退貨

函式會傳回 Spark DataFrame ,其中包含符合輸入資料行中每一列文字的情緒標籤的新資料行。 預設情緒標籤包括 positive、 、 negativeneutralmixed。 如果指定自訂標籤,則會改用這些標籤。 如果無法判斷情感,返回值為 null

Example

# This code uses AI. Always review output for mistakes.

df = spark.createDataFrame([
        ("The cleaning spray permanently stained my beautiful kitchen counter. Never again!",),
        ("I used this sunscreen on my vacation to Florida, and I didn't get burned at all. Would recommend.",),
        ("I'm torn about this speaker system. The sound was high quality, though it didn't connect to my roommate's phone.",),
        ("The umbrella is OK, I guess.",)
    ], ["reviews"])

sentiment = df.ai.analyze_sentiment(input_col="reviews", output_col="sentiment")
display(sentiment)

此範例程式碼儲存格提供下列輸出:

包含「評論」和「情緒」欄的資料框螢幕擷取畫面。「情緒」欄包括「負面」、「正面」、「混合」和「中性」。