| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | ||
| 6 | 7 | 8 | 9 | 10 | 11 | 12 |
| 13 | 14 | 15 | 16 | 17 | 18 | 19 |
| 20 | 21 | 22 | 23 | 24 | 25 | 26 |
| 27 | 28 | 29 | 30 |
- 파이썬
- 바이오인포매틱스
- COVID
- 인공신경망
- BLaST
- 딥러닝
- 시그모이드
- ncbi
- 단백질 구조 예측
- 로제타폴드
- 생물정보학
- 결정트리
- Java
- CNN
- SVM
- AP Computer Science A
- 자바
- 생명정보학
- Kaggle
- 알파폴드
- RNN
- 바이오파이썬
- AP
- bioinformatics
- 인공지능
- 캐글
- 인공지능 수학
- 오류역전파
- 이항분포
- 서열정렬
- Today
- Total
데이터 과학
리뷰 문장 분석 (허깅페이스) 본문
다음은 Hugging Face의 다국어 감성분석 모델을 이용해서 네이버 리뷰 문장을 1~5점 별점처럼 예측하는 방법에 대한 내용입니다. 모델은 nlptown/bert-base-multilingual-uncased-sentiment를 사용합니다.
!pip install transformers torch -q
from transformers import pipeline
# Hugging Face 감성분석 모델
classifier = pipeline(
"sentiment-analysis",
model="nlptown/bert-base-multilingual-uncased-sentiment"
)
text = "배송도 빠르고 제품도 정말 마음에 들어요."
result = classifier(text)
print(result)
------------------
조금 다른 방법을 사용하면 다음과 같습니다.
from transformers import pipeline
classifier = pipeline(
"sentiment-analysis",
model="nlptown/bert-base-multilingual-uncased-sentiment"
)
text = input("리뷰를 입력하세요 : ")
result = classifier(text)[0]
label = result["label"]
score = result["score"]
rating = int(label.split()[0])
print()
print("리뷰 :", text)
print("예측 평점 :", rating, "점")
print("별점 :", "★" * rating + "☆" * (5-rating))
print("신뢰도 :", round(score * 100, 2), "%")
------------------------------------
from transformers import pipeline
classifier = pipeline(
"sentiment-analysis",
model="nlptown/bert-base-multilingual-uncased-sentiment"
)
reviews = [
"배송도 빠르고 제품 품질도 좋습니다.",
"그냥 평범한 제품입니다.",
"배송도 늦고 제품도 마음에 들지 않습니다.",
"가격 대비 상당히 만족스럽습니다.",
"다시는 구매하지 않을 것 같습니다."
]
results = classifier(reviews)
for review, result in zip(reviews, results):
rating = int(result["label"].split()[0])
print("리뷰 :", review)
print("예측 평점 :", rating)
print("별점 :", "★" * rating + "☆" * (5-rating))
print("신뢰도 :", round(result["score"] * 100, 2), "%")
print("-" * 50)
----------------------------------------------------
다음 모델은 네이버 평점 리뷰를 평가하는 모델을 좀 더 정밀하게 만든 예시입니다.
판다스 라이브러리가 들어갑니다.
!pip install transformers torch pandas matplotlib -q
from transformers import pipeline
import pandas as pd
import matplotlib.pyplot as plt
# 1. Hugging Face 감성분석 모델 불러오기
classifier = pipeline(
"sentiment-analysis",
model="nlptown/bert-base-multilingual-uncased-sentiment"
)
# 2. 네이버 리뷰 형태의 예시 데이터
data = {
"review": [
"배송도 빠르고 제품 품질도 정말 좋습니다.",
"가격 대비 만족스럽고 다시 구매하고 싶어요.",
"그냥 평범한 제품입니다.",
"생각보다 품질이 좋지 않았습니다.",
"배송도 늦고 제품 상태도 좋지 않았어요.",
"정말 만족합니다. 강력 추천합니다.",
"나쁘지는 않지만 특별히 좋지도 않습니다.",
"포장도 엉망이고 제품도 마음에 들지 않습니다.",
"디자인도 예쁘고 성능도 좋습니다.",
"가격이 조금 비싸지만 전체적으로 만족합니다."
],
# 사람이 직접 매긴 실제 평점
"actual_rating": [
5, 5, 3, 2, 1,
5, 3, 1, 5, 4
]
}
df = pd.DataFrame(data)
df
------------
predicted_ratings = []
confidence_scores = []
for review in df["review"]:
result = classifier(review)[0]
# "5 stars" → 5
rating = int(result["label"].split()[0])
predicted_ratings.append(rating)
confidence_scores.append(result["score"])
df["predicted_rating"] = predicted_ratings
df["confidence"] = confidence_scores
df
---------------
별점을 시각적으로 표현하는 방법
def star_rating(rating):
return "★" * rating + "☆" * (5 - rating)
df["actual_star"] = df["actual_rating"].apply(star_rating)
df["predicted_star"] = df["predicted_rating"].apply(star_rating)
df[
[
"review",
"actual_rating",
"actual_star",
"predicted_rating",
"predicted_star",
"confidence"
]
]
--------------------
예측에 대한 예시
df["correct"] = (
df["actual_rating"]
==
df["predicted_rating"]
)
df
---------------------
정확도 확인
accuracy = df["correct"].mean()
print("전체 리뷰 개수 :", len(df))
print("정확하게 예측한 리뷰 :", df["correct"].sum())
print(
"정확도 :",
round(accuracy * 100, 2),
"%"
)
----------------------
plt.figure(figsize=(12, 5))
x = range(len(df))
plt.plot(
x,
df["actual_rating"],
marker="o",
label="Actual Rating"
)
plt.plot(
x,
df["predicted_rating"],
marker="s",
label="Predicted Rating"
)
plt.xticks(
x,
[f"Review {i+1}" for i in x]
)
plt.yticks([1, 2, 3, 4, 5])
plt.xlabel("Review")
plt.ylabel("Rating")
plt.title(
"Actual Rating vs Hugging Face Predicted Rating"
)
plt.legend()
plt.grid()
plt.show()
-----------------------------------
rating_count = (
df["predicted_rating"]
.value_counts()
.sort_index()
)
rating_count
----------------------------------
plt.figure(figsize=(8, 5))
rating_count.plot(
kind="bar"
)
plt.xlabel("Predicted Rating")
plt.ylabel("Number of Reviews")
plt.title(
"Distribution of Predicted Ratings"
)
plt.xticks(rotation=0)
plt.show()
----------------------------
result_df = df[
[
"review",
"actual_rating",
"predicted_rating",
"confidence",
"correct"
]
].copy()
result_df["confidence"] = (
result_df["confidence"] * 100
).round(2)
result_df.columns = [
"리뷰",
"실제 평점",
"AI 예측 평점",
"AI 신뢰도(%)",
"예측 성공"
]
result_df
