Matplotlib을 사용하여 Python에서 감정 분석 결과 시각화
이 글에서는 Matplotlib을 이용하여 감성분석 결과를 그래픽으로 표현해보겠습니다. 다양한 색상을 사용하여 긍정적인 감정과 부정적인 감정을 구분하는 막대 차트를 사용하여 여러 문장의 감정 점수를 시각화하는 것이 목표입니다.
전제조건
다음 라이브러리가 설치되어 있는지 확인하세요.
pip install transformers torch matplotlib
- Transformers: 사전 훈련된 NLP 모델을 처리하는 데 사용됩니다.
- 토치: 모델을 실행하기 위한 것입니다.
- matplotlib: 감정 분석 결과의 그래픽 표현을 생성합니다.
시각화가 포함된 Python 코드
감정 분석과 데이터 시각화를 통합한 업데이트된 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

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

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Python은 데이터 과학, 웹 개발 및 자동화 작업에 적합한 반면 C는 시스템 프로그래밍, 게임 개발 및 임베디드 시스템에 적합합니다. Python은 단순성과 강력한 생태계로 유명하며 C는 고성능 및 기본 제어 기능으로 유명합니다.

2 시간 이내에 파이썬의 기본 사항을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우십시오. 이를 통해 간단한 파이썬 프로그램 작성을 시작하는 데 도움이됩니다.

Python은 게임 및 GUI 개발에서 탁월합니다. 1) 게임 개발은 Pygame을 사용하여 드로잉, 오디오 및 기타 기능을 제공하며 2D 게임을 만드는 데 적합합니다. 2) GUI 개발은 Tkinter 또는 PYQT를 선택할 수 있습니다. Tkinter는 간단하고 사용하기 쉽고 PYQT는 풍부한 기능을 가지고 있으며 전문 개발에 적합합니다.

2 시간 이내에 Python의 기본 프로그래밍 개념과 기술을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우기, 2. 마스터 제어 흐름 (조건부 명세서 및 루프), 3. 기능의 정의 및 사용을 이해하십시오. 4. 간단한 예제 및 코드 스 니펫을 통해 Python 프로그래밍을 신속하게 시작하십시오.

Python은 배우고 사용하기 쉽고 C는 더 강력하지만 복잡합니다. 1. Python Syntax는 간결하며 초보자에게 적합합니다. 동적 타이핑 및 자동 메모리 관리를 사용하면 사용하기 쉽지만 런타임 오류가 발생할 수 있습니다. 2.C는 고성능 응용 프로그램에 적합한 저수준 제어 및 고급 기능을 제공하지만 학습 임계 값이 높고 수동 메모리 및 유형 안전 관리가 필요합니다.

Python은 웹 개발, 데이터 과학, 기계 학습, 자동화 및 스크립팅 분야에서 널리 사용됩니다. 1) 웹 개발에서 Django 및 Flask 프레임 워크는 개발 프로세스를 단순화합니다. 2) 데이터 과학 및 기계 학습 분야에서 Numpy, Pandas, Scikit-Learn 및 Tensorflow 라이브러리는 강력한 지원을 제공합니다. 3) 자동화 및 스크립팅 측면에서 Python은 자동화 된 테스트 및 시스템 관리와 같은 작업에 적합합니다.

제한된 시간에 Python 학습 효율을 극대화하려면 Python의 DateTime, Time 및 Schedule 모듈을 사용할 수 있습니다. 1. DateTime 모듈은 학습 시간을 기록하고 계획하는 데 사용됩니다. 2. 시간 모듈은 학습과 휴식 시간을 설정하는 데 도움이됩니다. 3. 일정 모듈은 주간 학습 작업을 자동으로 배열합니다.

Python은 초보자부터 고급 개발자에 이르기까지 모든 요구에 적합한 단순성과 힘에 호의적입니다. 다목적 성은 다음과 같이 반영됩니다. 1) 배우고 사용하기 쉽고 간단한 구문; 2) Numpy, Pandas 등과 같은 풍부한 라이브러리 및 프레임 워크; 3) 다양한 운영 체제에서 실행할 수있는 크로스 플랫폼 지원; 4) 작업 효율성을 향상시키기위한 스크립팅 및 자동화 작업에 적합합니다.
