国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 后端開發(fā) Python教程 使用 Matplotlib 在 Python 中可視化情感分析結(jié)果

使用 Matplotlib 在 Python 中可視化情感分析結(jié)果

Jan 05, 2025 pm 12:38 PM

在本文中,我們將使用 Matplotlib 添加情感分析結(jié)果的圖形表示。目標(biāo)是可視化多個句子的情緒分?jǐn)?shù),并使用條形圖使用不同的顏色區(qū)分積極和消極情緒。

先決條件

確保您安裝了以下庫:

pip install transformers torch matplotlib
  • Transformer:用于處理預(yù)先訓(xùn)練的 NLP 模型。
  • torch:用于運(yùn)行模型。
  • matplotlib:用于創(chuàng)建情感分析結(jié)果的圖形表示。

可視化 Python 代碼

Visualizing Sentiment Analysis Results in Python using Matplotlib

這是更新后的 Python 代碼,它將情感分析與數(shù)據(jù)可視化相集成。

import matplotlib.pyplot as plt
from transformers import pipeline
from transformers import AutoTokenizer, AutoModelForSequenceClassification

# Load pre-trained model and tokenizer
model_name = "distilbert-base-uncased-finetuned-sst-2-english"
model = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)

# Initialize the sentiment-analysis pipeline
classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)

# List of 10 sentences for sentiment analysis
sentences = [
    "I love you! I love you! I love you!",
    "I feel so sad today.",
    "This is the best day ever!",
    "I can't stand the rain.",
    "Everything is going so well.",
    "I hate waiting in line.",
    "The weather is nice, but it's cold.",
    "I'm so proud of my achievements.",
    "I am very upset with the decision.",
    "I am feeling optimistic about the future."
]

# Prepare data for the chart
scores = []
colors = []

for sentence in sentences:
    result = classifier(sentence)
    sentiment = result[0]['label']
    score = result[0]['score']
    scores.append(score)

    # Color bars based on sentiment: Positive -> green, Negative -> red
    if sentiment == "POSITIVE":
        colors.append("green")
    else:
        colors.append("red")

# Create a bar chart
plt.figure(figsize=(10, 6))
bars = plt.bar(sentences, scores, color=colors)

# Add labels and title with a line break
plt.xlabel('Sentences')
plt.ylabel('Sentiment Score')
plt.title('Sentiment Analysis of 10 Sentences\n')  # Added newline here
plt.xticks(rotation=45, ha="right")

# Adjust spacing with top margin (to add ceiling space)
plt.subplots_adjust(top=0.85)  # Adjust the top spacing (20px roughly equivalent to 0.1 top margin)

plt.tight_layout()  # Adjusts the rest of the layout

# Display the sentiment score on top of the bars
for bar in bars:
    yval = bar.get_height()
    plt.text(bar.get_x() + bar.get_width() / 2, yval + 0.02, f'{yval:.2f}', ha='center', va='bottom', fontsize=9)

# Show the plot
plt.show()

代碼分解

導(dǎo)入必要的庫:
我們導(dǎo)入 matplotlib.pyplot 來創(chuàng)建繪圖和轉(zhuǎn)換器來執(zhí)行情感分析。

   import matplotlib.pyplot as plt
   from transformers import pipeline
   from transformers import AutoTokenizer, AutoModelForSequenceClassification

加載預(yù)訓(xùn)練模型:
我們加載針對 SST-2 數(shù)據(jù)集進(jìn)行情感分析而微調(diào)的 DistilBERT 模型。我們還加載關(guān)聯(lián)的標(biāo)記生成器,將文本轉(zhuǎn)換為模型可讀的標(biāo)記。

   model_name = "distilbert-base-uncased-finetuned-sst-2-english"
   model = AutoModelForSequenceClassification.from_pretrained(model_name)
   tokenizer = AutoTokenizer.from_pretrained(model_name)

初始化情感分析管道:
分類器管道是為情感分析而設(shè)置的。該管道負(fù)責(zé)對輸入文本進(jìn)行標(biāo)記、執(zhí)行推理并返回結(jié)果。

   classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)

情感分析句子:
我們創(chuàng)建一個包含 10 個句子的列表來進(jìn)行分析。每句話都是一種獨(dú)特的情感表達(dá),從非常積極到消極。

   sentences = [
       "I love you! I love you! I love you!",
       "I feel so sad today.",
       "This is the best day ever!",
       "I can't stand the rain.",
       "Everything is going so well.",
       "I hate waiting in line.",
       "The weather is nice, but it's cold.",
       "I'm so proud of my achievements.",
       "I am very upset with the decision.",
       "I am feeling optimistic about the future."
   ]

處理情緒并準(zhǔn)備數(shù)據(jù):
對于每個句子,我們對其情感進(jìn)行分類并提取分?jǐn)?shù)。根據(jù)情緒標(biāo)簽(積極或消極),我們?yōu)閳D表中的條形指定顏色。積極的句子將是綠色的,而消極的句子將是紅色的。

   scores = []
   colors = []

   for sentence in sentences:
       result = classifier(sentence)
       sentiment = result[0]['label']
       score = result[0]['score']
       scores.append(score)

       if sentiment == "POSITIVE":
           colors.append("green")
       else:
           colors.append("red")

創(chuàng)建條形圖:
我們使用 matplotlib 創(chuàng)建條形圖。每個條形的高度代表一個句子的情感分?jǐn)?shù),顏色區(qū)分積極和消極情緒。

   plt.figure(figsize=(10, 6))
   bars = plt.bar(sentences, scores, color=colors)

添加標(biāo)簽并調(diào)整布局:
我們通過旋轉(zhuǎn) x 軸標(biāo)簽以提高可讀性、添加標(biāo)題以及調(diào)整布局以獲得最佳間距來自定義繪圖的外觀。

   plt.xlabel('Sentences')
   plt.ylabel('Sentiment Score')
   plt.title('Sentiment Analysis of 10 Sentences\n')  # Added newline here
   plt.xticks(rotation=45, ha="right")
   plt.subplots_adjust(top=0.85)  # Adjust the top spacing
   plt.tight_layout()  # Adjusts the rest of the layout

在條形頂部顯示情緒分?jǐn)?shù):
我們還在每個條形的頂部顯示情緒得分,以使圖表提供更多信息。

pip install transformers torch matplotlib

顯示圖:
最后,使用 plt.show() 顯示圖表,它渲染繪圖。

import matplotlib.pyplot as plt
from transformers import pipeline
from transformers import AutoTokenizer, AutoModelForSequenceClassification

# Load pre-trained model and tokenizer
model_name = "distilbert-base-uncased-finetuned-sst-2-english"
model = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)

# Initialize the sentiment-analysis pipeline
classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)

# List of 10 sentences for sentiment analysis
sentences = [
    "I love you! I love you! I love you!",
    "I feel so sad today.",
    "This is the best day ever!",
    "I can't stand the rain.",
    "Everything is going so well.",
    "I hate waiting in line.",
    "The weather is nice, but it's cold.",
    "I'm so proud of my achievements.",
    "I am very upset with the decision.",
    "I am feeling optimistic about the future."
]

# Prepare data for the chart
scores = []
colors = []

for sentence in sentences:
    result = classifier(sentence)
    sentiment = result[0]['label']
    score = result[0]['score']
    scores.append(score)

    # Color bars based on sentiment: Positive -> green, Negative -> red
    if sentiment == "POSITIVE":
        colors.append("green")
    else:
        colors.append("red")

# Create a bar chart
plt.figure(figsize=(10, 6))
bars = plt.bar(sentences, scores, color=colors)

# Add labels and title with a line break
plt.xlabel('Sentences')
plt.ylabel('Sentiment Score')
plt.title('Sentiment Analysis of 10 Sentences\n')  # Added newline here
plt.xticks(rotation=45, ha="right")

# Adjust spacing with top margin (to add ceiling space)
plt.subplots_adjust(top=0.85)  # Adjust the top spacing (20px roughly equivalent to 0.1 top margin)

plt.tight_layout()  # Adjusts the rest of the layout

# Display the sentiment score on top of the bars
for bar in bars:
    yval = bar.get_height()
    plt.text(bar.get_x() + bar.get_width() / 2, yval + 0.02, f'{yval:.2f}', ha='center', va='bottom', fontsize=9)

# Show the plot
plt.show()

樣本輸出

此代碼的輸出將是一個顯示 10 個句子的情緒分?jǐn)?shù)的條形圖。積極的句子將用綠色條表示,而消極的句子將顯示為紅色條。情緒得分將顯示在每個條形上方,顯示模型的置信水平。

結(jié)論

通過將情感分析與數(shù)據(jù)可視化相結(jié)合,我們可以更好地解讀文本數(shù)據(jù)背后的情感基調(diào)。本文中的圖形表示可以讓您更清楚地了解情緒分布,使您可以輕松發(fā)現(xiàn)文本中的趨勢。您可以將此技術(shù)應(yīng)用于各種用例,例如分析產(chǎn)品評論、社交媒體帖子或客戶反饋。

通過 Hugging Face 的轉(zhuǎn)換器和 matplotlib 的強(qiáng)大組合,可以擴(kuò)展和定制此工作流程以適應(yīng)各種 NLP 任務(wù)。

以上是使用 Matplotlib 在 Python 中可視化情感分析結(jié)果的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機(jī)

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

什么是動態(tài)編程技術(shù),如何在Python中使用它們? 什么是動態(tài)編程技術(shù),如何在Python中使用它們? Jun 20, 2025 am 12:57 AM

動態(tài)規(guī)劃(DP)通過將復(fù)雜問題分解為更簡單的子問題并存儲其結(jié)果以避免重復(fù)計算,來優(yōu)化求解過程。主要方法有兩種:1.自頂向下(記憶化):遞歸分解問題,使用緩存存儲中間結(jié)果;2.自底向上(表格化):從基礎(chǔ)情況開始迭代構(gòu)建解決方案。適用于需要最大/最小值、最優(yōu)解或存在重疊子問題的場景,如斐波那契數(shù)列、背包問題等。在Python中,可通過裝飾器或數(shù)組實現(xiàn),并應(yīng)注意識別遞推關(guān)系、定義基準(zhǔn)情況及優(yōu)化空間復(fù)雜度。

如何使用插座在Python中執(zhí)行網(wǎng)絡(luò)編程? 如何使用插座在Python中執(zhí)行網(wǎng)絡(luò)編程? Jun 20, 2025 am 12:56 AM

Python的socket模塊是網(wǎng)絡(luò)編程的基礎(chǔ),提供低級網(wǎng)絡(luò)通信功能,適用于構(gòu)建客戶端和服務(wù)器應(yīng)用。要設(shè)置基本TCP服務(wù)器,需使用socket.socket()創(chuàng)建對象,綁定地址和端口,調(diào)用.listen()監(jiān)聽連接,并通過.accept()接受客戶端連接。構(gòu)建TCP客戶端需創(chuàng)建socket對象后調(diào)用.connect()連接服務(wù)器,再使用.sendall()發(fā)送數(shù)據(jù)和.recv()接收響應(yīng)。處理多個客戶端可通過1.線程:每次連接啟動新線程;2.異步I/O:如asyncio庫實現(xiàn)無阻塞通信。注意事

如何在Python中切片列表? 如何在Python中切片列表? Jun 20, 2025 am 12:51 AM

Python列表切片的核心答案是掌握[start:end:step]語法并理解其行為。1.列表切片的基本格式為list[start:end:step],其中start是起始索引(包含)、end是結(jié)束索引(不包含)、step是步長;2.省略start默認(rèn)從0開始,省略end默認(rèn)到末尾,省略step默認(rèn)為1;3.獲取前n項用my_list[:n],獲取后n項用my_list[-n:];4.使用step可跳過元素,如my_list[::2]取偶數(shù)位,負(fù)step值可反轉(zhuǎn)列表;5.常見誤區(qū)包括end索引不

如何使用DateTime模塊在Python中使用日期和時間? 如何使用DateTime模塊在Python中使用日期和時間? Jun 20, 2025 am 12:58 AM

Python的datetime模塊能滿足基本的日期和時間處理需求。1.可通過datetime.now()獲取當(dāng)前日期和時間,也可分別提取.date()和.time()。2.能手動創(chuàng)建特定日期時間對象,如datetime(year=2025,month=12,day=25,hour=18,minute=30)。3.使用.strftime()按格式輸出字符串,常見代碼包括%Y、%m、%d、%H、%M、%S;用strptime()將字符串解析為datetime對象。4.利用timedelta進(jìn)行日期運(yùn)

Python類中的多態(tài)性 Python類中的多態(tài)性 Jul 05, 2025 am 02:58 AM

多態(tài)是Python面向?qū)ο缶幊讨械暮诵母拍?,指“一種接口,多種實現(xiàn)”,允許統(tǒng)一處理不同類型的對象。1.多態(tài)通過方法重寫實現(xiàn),子類可重新定義父類方法,如Animal類的speak()方法在Dog和Cat子類中有不同實現(xiàn)。2.多態(tài)的實際用途包括簡化代碼結(jié)構(gòu)、增強(qiáng)可擴(kuò)展性,例如圖形繪制程序中統(tǒng)一調(diào)用draw()方法,或游戲開發(fā)中處理不同角色的共同行為。3.Python實現(xiàn)多態(tài)需滿足:父類定義方法,子類重寫該方法,但不要求繼承同一父類,只要對象實現(xiàn)相同方法即可,這稱為“鴨子類型”。4.注意事項包括保持方

我如何寫一個簡單的'你好,世界!” Python的程序? 我如何寫一個簡單的'你好,世界!” Python的程序? Jun 24, 2025 am 12:45 AM

"Hello,World!"程序是用Python編寫的最基礎(chǔ)示例,用于展示基本語法并驗證開發(fā)環(huán)境是否正確配置。1.它通過一行代碼print("Hello,World!")實現(xiàn),運(yùn)行后會在控制臺輸出指定文本;2.運(yùn)行步驟包括安裝Python、使用文本編輯器編寫代碼、保存為.py文件、在終端執(zhí)行該文件;3.常見錯誤有遺漏括號或引號、誤用大寫Print、未保存為.py格式以及運(yùn)行環(huán)境錯誤;4.可選工具包括本地文本編輯器 終端、在線編輯器(如replit.com)

Python中有哪些元素,它們與列表有何不同? Python中有哪些元素,它們與列表有何不同? Jun 20, 2025 am 01:00 AM

TuplesinPythonareimmutabledatastructuresusedtostorecollectionsofitems,whereaslistsaremutable.Tuplesaredefinedwithparenthesesandcommas,supportindexing,andcannotbemodifiedaftercreation,makingthemfasterandmorememory-efficientthanlists.Usetuplesfordatain

如何在Python中產(chǎn)生隨機(jī)字符串? 如何在Python中產(chǎn)生隨機(jī)字符串? Jun 21, 2025 am 01:02 AM

要生成隨機(jī)字符串,可以使用Python的random和string模塊組合。具體步驟為:1.導(dǎo)入random和string模塊;2.定義字符池如string.ascii_letters和string.digits;3.設(shè)定所需長度;4.調(diào)用random.choices()生成字符串。例如代碼包括importrandom與importstring、設(shè)置length=10、characters=string.ascii_letters string.digits并執(zhí)行''.join(random.c

See all articles