NLP là gì?
Natural Language Processing (NLP) giúp máy tính hiểu, phân tích và tạo ngôn ngữ tự nhiên. Ứng dụng: chatbot, dịch thuật, tóm tắt văn bản, phân tích cảm xúc.
Tokenization và tiền xử lý
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
text = "Python là ngôn ngữ lập trình tuyệt vời cho AI"
tokens = word_tokenize(text, language='vietnamese')
print(tokens)
# Với spaCy
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Python is the best language for AI")
for token in doc:
print(f"{token.text}: {token.pos_} - {token.dep_}")
Sentiment Analysis với Transformers
from transformers import pipeline
# Pipeline sentiment analysis
classifier = pipeline("sentiment-analysis")
results = classifier([
"I love programming in Python!",
"This code has too many bugs"
])
for r in results:
print(f"{r['label']}: {r['score']:.2%}")
Text Generation với GPT
from transformers import pipeline
generator = pipeline("text-generation", model="gpt2")
output = generator(
"Python is great for",
max_length=50,
num_return_sequences=1
)
print(output[0]["generated_text"])
Thư viện NLP phổ biến
- NLTK: Cổ điển, tốt cho học tập
- spaCy: Nhanh, production-ready
- Hugging Face Transformers: State-of-the-art models (BERT, GPT, T5)
- Gensim: Topic modeling, Word2Vec