攝影:Fauzan Saari?on?Unsplash
一、說明
????????這是我們對世界杯推特數據分析的第3部分,我們放棄了。我們將對我們的數據進行情緒分析,以了解人們對卡塔爾世界杯的感受。我將在這里介紹的一個功能強大的工具包是Hugging Face,您可以在其中找到各種模型,任務,數據集,它還為剛開始學習機器學習的人提供課程。在這篇文章中,我們將使用一個情緒分析模型和擁抱面孔令牌來完成我們的任務。
二、情緒分析
? ? ? 情感分析是使用自然語言處理(NLP)來識別,提取和研究情感狀態和主觀信息。我們可以將這種技術應用于客戶評論和調查響應,以對我對產品或服務的意見。
????????讓我們看幾個例子:
- 我喜歡今天的天氣!標記: 正面
- 天氣預報說明天會多云。標簽: 中性
- 雨不會停。野餐計劃被推遲了。無賴。。。標簽: 負面
????????上面的例子清楚地顯示了推文的極性,因為文本的結構很簡單。以下是一些難以輕易發現情緒的挑戰性案例。
- 我不喜歡下雨天。(否定)
- 我喜歡在刮風的時候跑步,但不會推薦給我的朋友。(有條件的積極情緒,難以分類)
- 一杯好咖啡真的需要時間,因為它讓我等了30分鐘才喝一口。(諷刺)
????????現在我們已經介紹了什么是情緒分析以及如何應用這種技術,讓我們學習如何在我們的 Twitter 數據上實現這種方法。
遇見“推特-羅伯塔-基地-情緒-最新"
????????用于情緒分析的 Twitter-roBERTa-base 是一個 RoBERTa-base 模型,從 124 年 2018 月到 2021 年 <> 月在 ~<>M 條推文上訓練,并使用 TweetEval 基準對情緒分析進行了微調。我不會深入探討 RoBERTa-base 模型的細節,但簡單地說,RoBERTa 從預訓練過程中刪除了下一句預測 (NSP) 任務,并引入了動態掩碼,因此掩碼標記在訓練期間會發生變化。對于更詳細的評論,我建議閱讀Suleiman Khan的文章和Chandan Durgia的文章。
????????要啟動此模型,我們可以使用由Hugging Face團隊創建的推理API。推理 API 允許您對 NLP、音頻和計算機視覺中的任務進行文本文本和評估 80, 000 多個機器學習模型。查看此處以獲取詳細文檔。它很容易使用推理API,您只需這樣做即可獲得您的擁抱臉令牌(它是免費的)。首先,您應該創建一個擁抱臉帳戶并注冊。然后,單擊您的個人資料并轉到設置。
- 讀取:如果您只需要從擁抱人臉中心讀取內容(例如,在下載私有模型或進行推理時),請使用此角色。
- 寫入:如果需要創建內容或將內容推送到存儲庫(例如,在訓練模型或修改模型卡時),請使用此令牌。
由作者創建
User access tokens
現在我們有了我們需要的一切,讓我們做一些分析!
三、準備我們的數據
????????首先,我們需要導入一些依賴項并加載數據。對我們擁有的 10, 000 條推文運行情緒分析需要一些時間。出于演示目的,我們將從池中隨機抽取 300 條推文。
import pandas as pd
import pickle
import requests
import randomwith open('world_cup_tweets.pkl', 'rb') as f:data = pickle.load(f)tweets = data.Tweet_processed.to_list()
tweets = random.sample(tweets, 300)
四、運行分析
????????然后我們將語言模型和我們的擁抱臉令牌分別傳遞給變量。
model = "cardiffnlp/twitter-roberta-base-sentiment-latest"
hf_token = "YOUR OWN TOKEN"
????????我們定義了一個采用單個參數的分析函數:數據。此函數將我們的 Twitter 數據轉換為 JSON 格式,其中包含對傳遞給函數的輸入數據的模型推理結果。
API_URL = "https://api-inference.huggingface.co/models/" + model
headers = {"Authorization": "Bearer %s" % (hf_token)}def analysis(data):payload = dict(inputs=data, options=dict(wait_for_model=True))response = requests.post(API_URL, headers=headers, json=payload)return response.json()
????????我們初始化一個空列表,以存儲每條推文的情緒分析結果。我們對列表中的每條推文使用循環。然后我們使用 try-except 塊技術:
- 對于可以分析的推文,我們調用我們定義的函數分析,將當前推文作為輸入,并從返回的列表中檢索第一個結果。此結果應為字典列表,每個詞典都包含情緒標簽和分數。我們使用內置的 max 函數在情緒結果中查找得分最高的字典。我們將一個新詞典附加到tweets_analysis列表中,其中包含推文及其相應的標簽,其中包含得分最高的情緒。
- 對于無法分析的推文,我們使用 except 塊,該塊捕獲 try 塊中發生的任何異常并打印錯誤消息。情緒分析功能可能無法分析某些推文,因此包含此塊以處理這些情況。
tweets_analysis = []
for tweet in tweets:try:sentiment_result = analysis(tweet)[0]top_sentiment = max(sentiment_result, key=lambda x: x['score']) # Get the sentiment with the higher scoretweets_analysis.append({'tweet': tweet, 'sentiment': top_sentiment['label']})except Exception as e:print(e)
????????然后我們可以將數據加載到數據框中并查看一些初步結果。
# Load the data in a dataframe
df = pd.DataFrame(tweets_analysis)# Show a tweet for each sentiment
print("Positive tweet:")
print(df[df['sentiment'] == 'positive']['tweet'].iloc[0])
print("\nNeutral tweet:")
print(df[df['sentiment'] == 'neutral']['tweet'].iloc[0])
print("\nNegative tweet:")
print(df[df['sentiment'] == 'negative']['tweet'].iloc[0])
# Outputs: (edited by author to remove vulgarity)Positive tweet:
Messi, you finally get this World Cup trophy. Happy ending and you are officially called球王 Neutral tweet:
Nicholas the Dolphin picks 2022 World Cup Final winner Negative tweet:
Yall XXXX and this XXXX world cup omg who XXXX CARESSS
我們還應該使用 groupby 函數來查看樣本中有多少推文是正數或負數。
sentiment_counts = df.groupby(['sentiment']).size()
print(sentiment_counts)# Outputs:
sentiment
negative 46
neutral 63
positive 166
dtype: int64
既然我們在這里,為什么不使用餅圖來可視化結果:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(6,6), dpi=100)
ax = plt.subplot(111)
sentiment_counts.plot.pie(ax=ax, autopct='%1.1f%%', startangle=270, fontsize=12, label="")
由作者創建
似乎大多數人對卡塔爾世界杯感到滿意。偉大!
人們在正面和負面推文中談論什么?我們可以使用詞云來顯示這些組中的關鍵字。
# pip install first if you have not installed wordcloud in your environment from wordcloud import WordCloud
from wordcloud import STOPWORDS# Wordcloud with positive tweets
positive_tweets = df[df['sentiment'] == 'positive']['tweet']
stop_words = ["https", "co", "RT"] + list(STOPWORDS)
positive_wordcloud = WordCloud(max_font_size=50, max_words=50, background_color="white", stopwords = stop_words).generate(str(positive_tweets))
plt.figure()
plt.title("Positive Tweets - Wordcloud")
plt.imshow(positive_wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()# Wordcloud with negative tweets
negative_tweets = df[df['sentiment'] == 'negative']['tweet']
stop_words = ["https", "co", "RT"] + list(STOPWORDS)
negative_wordcloud = WordCloud(max_font_size=50, max_words=50, background_color="white", stopwords = stop_words).generate(str(negative_tweets))
plt.figure()
plt.title("Negative Tweets - Wordcloud")
plt.imshow(negative_wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()
由作者創建

五、總結
????????現在我希望你已經學會了如何在擁抱臉中使用推理 API 對推文進行情感分析。這是一個功能強大的工具,高度適用于各個領域。關注我以獲取更多想法和技術。