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

首頁(yè) 後端開發(fā) Python教學(xué) 使用 Matplotlib 在 Python 中視覺(jué)化情緒分析結(jié)果

使用 Matplotlib 在 Python 中視覺(jué)化情緒分析結(jié)果

Jan 05, 2025 pm 12:38 PM

在本文中,我們將使用 Matplotlib 加入情緒分析結(jié)果的圖形表示。目標(biāo)是可視化多個(gè)句子的情緒分?jǐn)?shù),並使用長(zhǎng)條圖使用不同的顏色來(lái)區(qū)分正面和負(fù)面情緒。

先決條件

確保您安裝了以下程式庫(kù):

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

視覺(jué)化 Python 程式碼

Visualizing Sentiment Analysis Results in Python using Matplotlib

這是更新後的 Python 程式碼,它將情緒分析與資料視覺(jué)化整合。

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)入必要的函式庫(kù):
我們導(dǎo)入 matplotlib.pyplot 來(lái)建立繪圖和轉(zhuǎn)換器來(lái)執(zhí)行情緒分析。

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

載入預(yù)訓(xùn)練模型:
我們載入針對(duì) SST-2 資料集進(jìn)行情緒分析而微調(diào)的 DistilBERT 模型。我們也載入關(guān)聯(lián)的標(biāo)記產(chǎn)生器,將文字轉(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é)對(duì)輸入文字進(jìn)行標(biāo)記、執(zhí)行推理並傳回結(jié)果。

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

情緒分析句:
我們建立一個(gè)包含 10 個(gè)句子的清單來(lái)進(jìn)行分析。每句話都是一種獨(dú)特的情感表達(dá),從非常正面到負(fù)面。

   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)備資料:
對(duì)於每個(gè)句子,我們對(duì)其情緒進(jìn)行分類並提取分?jǐn)?shù)。根據(jù)情緒標(biāo)籤(正面或負(fù)面),我們?yōu)閳D表中的長(zhǎng)條指定顏色。正面的句子將是綠色的,而負(fù)面的句子將是紅色的。

   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")

建立長(zhǎng)條圖:
我們使用 matplotlib 建立條形圖。每個(gè)長(zhǎng)條的高度代表一個(gè)句子的情緒分?jǐn)?shù),顏色區(qū)分正面和負(fù)面情緒。

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

新增標(biāo)籤並調(diào)整版面:
我們透過(guò)旋轉(zhuǎn) x 軸標(biāo)籤以提高可讀性、添加標(biāo)題以及調(diào)整佈局以獲得最佳間距來(lái)自訂繪圖的外觀。

   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ù):
我們還在每個(gè)長(zhǎng)條的頂部顯示情緒得分,以使圖表提供更多資訊。

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()

樣本輸出

此程式碼的輸出將是一個(gè)顯示 10 個(gè)句子的情緒分?jǐn)?shù)的長(zhǎng)條圖。正面的句子將以綠色條表示,而負(fù)面的句子將顯示為紅色條。情緒分?jǐn)?shù)將顯示在每個(gè)長(zhǎng)條上方,顯示模型的置信水準(zhǔn)。

結(jié)論

透過(guò)將情緒分析與資料視覺(jué)化結(jié)合,我們可以更好地解讀文字資料背後的情緒基調(diào)。本文中的圖形表示可以讓您更清楚地了解情緒分佈,使您可以輕鬆發(fā)現(xiàn)文字中的趨勢(shì)。您可以將此技術(shù)應(yīng)用於各種用例,例如分析產(chǎn)品評(píng)論、社交媒體貼文或客戶回饋。

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

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

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

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

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

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

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)程式碼編輯軟體(SublimeText3)

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

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

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

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

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

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

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

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

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

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

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

"Hello,World!"程序是用Python編寫的最基礎(chǔ)示例,用於展示基本語(yǔ)法並驗(yàn)證開發(fā)環(huán)境是否正確配置。 1.它通過(guò)一行代碼print("Hello,World!")實(shí)現(xiàn),運(yùn)行後會(huì)在控制臺(tái)輸出指定文本;2.運(yùn)行步驟包括安裝Python、使用文本編輯器編寫代碼、保存為.py文件、在終端執(zhí)行該文件;3.常見錯(cuò)誤有遺漏括號(hào)或引號(hào)、誤用大寫Print、未保存為.py格式以及運(yùn)行環(huán)境錯(cuò)誤;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è)定所需長(zhǎng)度;4.調(diào)用random.choices()生成字符串。例如代碼包括importrandom與importstring、設(shè)置length=10、characters=string.ascii_letters string.digits並執(zhí)行''.join(random.c

See all articles