찾다
백엔드 개발파이썬 튜토리얼Matplotlib을 사용하여 Python에서 감정 분석 결과 시각화

이 글에서는 Matplotlib을 이용하여 감성분석 결과를 그래픽으로 표현해보겠습니다. 다양한 색상을 사용하여 긍정적인 감정과 부정적인 감정을 구분하는 막대 차트를 사용하여 여러 문장의 감정 점수를 시각화하는 것이 목표입니다.

전제조건

다음 라이브러리가 설치되어 있는지 확인하세요.

pip install transformers torch matplotlib
  • Transformers: 사전 훈련된 NLP 모델을 처리하는 데 사용됩니다.
  • 토치: 모델을 실행하기 위한 것입니다.
  • matplotlib: 감정 분석 결과의 그래픽 표현을 생성합니다.

시각화가 포함된 Python 코드

Visualizing Sentiment Analysis Results in Python using Matplotlib

감정 분석과 데이터 시각화를 통합한 업데이트된 Python 코드는 다음과 같습니다.

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

코드 분석

필요한 라이브러리 가져오기:
matplotlib.pyplot을 가져와 감정 분석을 수행하기 위한 플롯과 변환기를 생성합니다.

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

사전 훈련된 모델 로드:
SST-2 데이터 세트에 대한 감정 분석을 위해 미세 조정된 DistilBERT 모델을 로드합니다. 또한 텍스트를 모델이 읽을 수 있는 토큰으로 변환하는 관련 토크나이저를 로드합니다.

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

감정 분석 파이프라인 초기화:
감정 분석을 위해 분류자 파이프라인이 설정되었습니다. 이 파이프라인은 입력 텍스트 토큰화, 추론 수행 및 결과 반환을 담당합니다.

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

감성분석 문장:
분석할 10개의 문장 목록을 만듭니다. 각 문장은 매우 긍정적인 것부터 부정적인 것까지 독특한 감정 표현입니다.

   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."
   ]

감정 처리 및 데이터 준비:
각 문장에 대해 감정을 분류하고 점수를 추출합니다. 감정 레이블(POSITIVE 또는 NEGATIVE)에 따라 차트의 막대에 색상을 할당합니다. 긍정적인 문장은 녹색, 부정적인 문장은 빨간색으로 표시됩니다.

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

막대 차트 만들기:
matplotlib을 사용하여 막대 차트를 만듭니다. 각 막대의 높이는 문장의 감정 점수를 나타내며 색상으로 긍정적인 감정과 부정적인 감정을 구분합니다.

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

라벨 추가 및 레이아웃 조정:
가독성을 높이기 위해 x축 레이블을 회전하고, 제목을 추가하고, 최적의 간격을 위해 레이아웃을 조정하여 플롯의 모양을 사용자 정의합니다.

   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

막대 상단에 감정 점수 표시:
또한 차트의 정보를 더욱 풍부하게 만들기 위해 각 막대 상단에 감정 점수를 표시합니다.

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개 문장의 감정 점수를 표시하는 막대 차트입니다. 긍정적인 문장은 녹색 막대로 표시되고, 부정적인 문장은 빨간색 막대로 표시됩니다. 감정 점수는 각 막대 위에 표시되어 모델의 신뢰 수준을 보여줍니다.

결론

감정 분석과 데이터 시각화를 결합하면 텍스트 데이터 뒤에 숨은 감정을 더 잘 해석할 수 있습니다. 이 기사의 그래픽 표현을 통해 감정 분포를 더 명확하게 이해할 수 있으므로 텍스트의 추세를 쉽게 파악할 수 있습니다. 제품 리뷰, 소셜 미디어 게시물, 고객 피드백 분석 등 다양한 사용 사례에 이 기술을 적용할 수 있습니다.

Hugging Face의 변환기와 matplotlib의 강력한 조합을 통해 이 워크플로를 다양한 NLP 작업에 맞게 확장하고 사용자 정의할 수 있습니다.

위 내용은 Matplotlib을 사용하여 Python에서 감정 분석 결과 시각화의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
파이썬 목록을 어떻게 슬라이스합니까?파이썬 목록을 어떻게 슬라이스합니까?May 02, 2025 am 12:14 AM

slicepaythonlistisdoneusingthesyntaxlist [start : step : step] .here'showitworks : 1) startistheindexofthefirstelementtoinclude.2) stopistheindexofthefirstelemement.3) stepisincrementbetwetweentractionsoftortionsoflists

Numpy Array에서 수행 할 수있는 일반적인 작업은 무엇입니까?Numpy Array에서 수행 할 수있는 일반적인 작업은 무엇입니까?May 02, 2025 am 12:09 AM

NumpyAllowsForVariousOperationsOnArrays : 1) BasicArithmeticLikeadDition, Subtraction, A 및 Division; 2) AdvancedOperationsSuchasmatrixmultiplication; 3) extrayintondsfordatamanipulation; 5) Ag

파이썬으로 데이터 분석에 어레이가 어떻게 사용됩니까?파이썬으로 데이터 분석에 어레이가 어떻게 사용됩니까?May 02, 2025 am 12:09 AM

Arraysinpython, 특히 Stroughnumpyandpandas, areestentialfordataanalysis, setingspeedandefficiency

목록의 메모리 풋 프린트는 파이썬 배열의 메모리 풋 프린트와 어떻게 비교됩니까?목록의 메모리 풋 프린트는 파이썬 배열의 메모리 풋 프린트와 어떻게 비교됩니까?May 02, 2025 am 12:08 AM

ListSandnumpyArraysInpythonHavedifferentmoryfootPrints : ListSaremoreFlexibleButlessMemory-Efficer, whilumpyArraySareOptimizedFornumericalData.1) ListSTorERENFERENCESTOOBJECTS, OverHeadAround64ByTeson64-BitSyStems.2) NumpyArraysTATACONTACOTIGUOU

실행 파이썬 스크립트를 배포 할 때 환경 별 구성을 어떻게 처리합니까?실행 파이썬 스크립트를 배포 할 때 환경 별 구성을 어떻게 처리합니까?May 02, 2025 am 12:07 AM

ToensurePythonScriptTscriptsBecorrectelyRossDevelopment, Staging and Production, UsethesEStrategies : 1) EnvironmberVariblesForsimplesettings, 2) ConfigurationFilesforcomplexSetups 및 3) DynamicLoadingForAdAptability

파이썬 어레이를 어떻게 슬라이스합니까?파이썬 어레이를 어떻게 슬라이스합니까?May 01, 2025 am 12:18 AM

Python List 슬라이싱의 기본 구문은 목록 [start : stop : step]입니다. 1. Start는 첫 번째 요소 인덱스, 2.Stop은 첫 번째 요소 인덱스가 제외되고 3. Step은 요소 사이의 단계 크기를 결정합니다. 슬라이스는 데이터를 추출하는 데 사용될뿐만 아니라 목록을 수정하고 반전시키는 데 사용됩니다.

어떤 상황에서 목록이 배열보다 더 잘 수행 될 수 있습니까?어떤 상황에서 목록이 배열보다 더 잘 수행 될 수 있습니까?May 01, 2025 am 12:06 AM

ListSoutPerformArraysin : 1) DynamicsizingandFrequentInsertions/Deletions, 2) StoringHeterogeneousData 및 3) MemoryEfficiencyForsParsEdata, butMayHavesLightPerformanceCosceperationOperations.

파이썬 어레이를 파이썬 목록으로 어떻게 변환 할 수 있습니까?파이썬 어레이를 파이썬 목록으로 어떻게 변환 할 수 있습니까?May 01, 2025 am 12:05 AM

TOCONVERTAPYTHONARRAYTOALIST, USETHELIST () CONSTUCTORORAGENERATERATOREXPRESSION.1) importTheArrayModuleAndCreateAnarray.2) USELIST (ARR) 또는 [XFORXINARR] TOCONVERTITTOALIST.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.