Pipeline Hugging Face cho phân tích cảm xúc

Natural Language Processing (NLP) bằng Python

Fouad Trad

Machine Learning Engineer

Ôn tập: quy trình NLP

Sơ đồ quy trình đầy đủ, cho thấy Chương 1 nói về tiền xử lý và Chương 2 nói về trích xuất đặc trưng.

Natural Language Processing (NLP) bằng Python

Pipeline của Hugging Face

Sơ đồ quy trình đầy đủ, cho thấy Chương 3 và 4 sẽ nói về pipeline của Hugging Face gói trọn mọi bước: tiền xử lý, trích xuất đặc trưng và mô hình hóa.

  • Quy trình dựng sẵn, xử lý mọi bước trong một lần gọi hàm
  • Để tạo pipeline, cần:
    • Nhiệm vụ NLP
    • Mô hình để thực hiện nhiệm vụ
Natural Language Processing (NLP) bằng Python

Pipeline cho phân tích cảm xúc

 

 

  • Nhiệm vụ phân loại văn bản
  • Dự đoán văn bản mang cảm xúc tích cực hay tiêu cực

Hình minh họa: mặt cười giơ ngón cái cho cảm xúc tích cực và mặt buồn với ngón cái chúc xuống cho cảm xúc tiêu cực.

Natural Language Processing (NLP) bằng Python

Mô hình cho phân loại văn bản

Ảnh gif cho thấy cách cuộn trang và chọn đúng nhiệm vụ để có các mô hình phù hợp.

1 https://huggingface.co/models
Natural Language Processing (NLP) bằng Python

Pipeline trong mã

from transformers import pipeline

classification_pipeline = pipeline(
task="sentiment-analysis", # or text-classification
model="distilbert/distilbert-base-uncased-finetuned-sst-2-english" )
result = classification_pipeline("I really liked the movie!!")
print(result)
[{'label': 'POSITIVE', 'score': 0.9998093247413635}]
Natural Language Processing (NLP) bằng Python

Phân tích cảm xúc cho nhiều văn bản

texts = ["I really liked the movie!!",
         "Great job ruining my day.",
         "This product exceeded my expectations.",
         "Wow, just what I needed... another problem.", 
         "Absolutely fantastic experience!"]

results = classification_pipeline(texts)
print(results)
[{'label': 'POSITIVE', 'score': 0.9998093247413635}, 
 {'label': 'NEGATIVE', 'score': 0.8666700124740601}, 
 {'label': 'POSITIVE', 'score': 0.998874843120575}, 
 {'label': 'POSITIVE', 'score': 0.98626708984375}, 
 {'label': 'POSITIVE', 'score': 0.9998812675476074}]
Natural Language Processing (NLP) bằng Python

Đánh giá mô hình phân tích cảm xúc

texts = ["I really liked the movie!!",
         "Great job ruining my day.",
         "This product exceeded my expectations.",
         "Wow, just what I needed... another problem.", 
         "Absolutely fantastic experience!"]

true_labels = ["POSITIVE", "NEGATIVE", "POSITIVE", "NEGATIVE", "POSITIVE"]
results = classification_pipeline(texts)
predicted_labels = [result['label'] for result in results]
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(true_labels, predicted_labels)

print(f"Accuracy: {accuracy}")
Accuracy: 0.80
Natural Language Processing (NLP) bằng Python

Luyện tập nào!

Natural Language Processing (NLP) bằng Python

Preparing Video For Download...