Natural Language Processing
Overview
This skill provides comprehensive tools for building NLP applications using modern transformers, BERT, GPT, and classical NLP techniques for text classification, named entity recognition, sentiment analysis, and more.
When to Use
- Building text classification systems for sentiment analysis, topic categorization, or intent detection
- Extracting named entities (people, places, organizations) from unstructured text
- Implementing machine translation, text summarization, or question answering systems
- Processing and analyzing large volumes of textual data for insights
- Creating chatbots, virtual assistants, or conversational AI applications
- Fine-tuning pre-trained transformer models for domain-specific NLP tasks
NLP Core Tasks
- Text Classification: Sentiment, topic, intent classification
- Named Entity Recognition: Identifying people, places, organizations
- Machine Translation: Text translation between languages
- Text Summarization: Extracting key information
- Question Answering: Finding answers in documents
- Text Generation: Generating coherent text
Popular Models and Libraries
- Transformers: BERT, GPT, RoBERTa, T5
- spaCy: Industrial NLP pipeline
- NLTK: Classic NLP toolkit
- Hugging Face: Pre-trained models hub
- PyTorch/TensorFlow: Deep learning frameworks
Python Implementation
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from collections import Counter
import re
import nltk
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer, WordNetLemmatizer
import torch
from transformers import (AutoTokenizer, AutoModelForSequenceClassification,
AutoModelForTokenClassification, pipeline,
TextClassificationPipeline)
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
import warnings
warnings.filterwarnings('ignore')
# Download required NLTK resources
try:
nltk.data.find('tokenizers/punkt')
except LookupError:
nltk.download('punkt')
print("=== 1. Text Preprocessing ===")
def preprocess_text(text, remove_stopwords=True, lemmatize=True):
"""Complete text preprocessing pipeline"""
# Lowercase
text = text.lower()
# Remove special characters and digits
text = re.sub(r'[^a-zA-Z\s]', '', text)
# Tokenize
tokens = word_tokenize(text)
# Remove stopwords
if remove_stopwords:
stop_words = set(stopwords.words('english'))
tokens = [t for t in tokens if t not in stop_words]
# Lemmatize
if lemmatize:
lemmatizer = WordNetLemmatizer()
tokens = [lemmatizer.lemmatize(t) for t in tokens]
return tokens, ' '.join(tokens)
sample_text = "The quick brown foxes are jumping over the lazy dogs! Amazing performance."
tokens, processed = preprocess_text(sample_text)
print(f"Original: {sample_text}")
print(f"Processed: {processed}")
print(f"Tokens: {tokens}\n")
# 2. Text Classification with sklearn
print("=== 2. Traditional Text Classification ===")
# Sample data
texts = [
"I love this product, it's amazing!",
"This movie is fantastic and entertaining.",
"Best purchase ever, highly recommended.",
"Terrible quality, very disappointed.",
"Worst experience, waste of money.",
"Horrible service and poor quality.",
"The food was delicious and fresh.",
"Great atmosphere and friendly staff.",
"Bad weather today, very gloomy.",
"The book was boring and uninteresting."
]
labels = [1, 1, 1, 0, 0, 0, 1, 1, 0, 0] # 1: positive, 0: negative
# TF-IDF vectorization
tfidf = TfidfVectorizer(max_features=100, ngram_range=(1, 2))
X_tfidf = tfidf.fit_transform(texts)
# Train classifier
clf = MultinomialNB()
clf.fit(X_tfidf, labels)
# Evaluate
predictions = clf.predict(X_tfidf)
print(f"Accuracy: {accuracy_score(labels, predictions):.4f}")
print(f"Precision: {precision_score(labels, predictions):.4f}")
print(f"Recall: {recall_score(labels, predictions):.4f}")
print(f"F1: {f1_score(labels, predictions):.4f}\n")
# 3. Transformer-based text classification
print("=== 3. Transformer-based Classification ===")
try:
# Use Hugging Face transformers for sentiment analysis
sentiment_pipeline = pipeline(
"sentiment-analysis",
model="distilbert-base-uncased-finetuned-sst-2-english"
)
test_sentences = [
"This is a wonderful movie!",
"I absolutely hate this product.",
"It's okay, nothing special.",
"Amazing quality and fast delivery!"
]
print("Sentiment Analysis Results:")
for sentence in test_sentences:
result = sentiment_pipeline(sentence)
print(f" Text: {sentence}")
print(f" Sentiment: {result[0]['label']}, Score: {result[0]['score']:.4f}\n")
except Exception as e:
print(f"Transformer model not available: {str(e)}\n")
# 4. Named Entity Recognition (NER)
print("=== 4. Named Entity Recognition ===")
try:
ner_pipeline = pipeline(
"ner",
model="distilbert-base-uncased",
aggregation_strategy="simple"
)
text = "Apple Inc. was founded by Steve Jobs in Cupertino, California."
entities = ner_pipeline(text)
print(f"Text: {text}")
print("Entities:")
for entity in entities:
print(f" {entity['word']}: {entity['entity_group']} (score: {entity['score']:.4f})")
except Exception as e:
print(f"NER model not available: {str(e)}\n")
# 5. Word embeddings and similarity
print("\n=== 5. Word Embeddings and Similarity ===")
from sklearn.metrics.pairwise import cosine_similarity
# Simple bag-of-words embeddings
vectorizer = CountVectorizer(max_features=50)
docs = [
"machine learning is great",
"deep learning uses neural networks",
"machine learning and deep learning"
]
embeddings = vectorizer.fit_transform(docs).toarray()
# Compute similarity
similarity_matrix = cosine_similarity(embeddings)
print("Document Similarity Matrix:")
print(pd.DataFrame(similarity_matrix, columns=[f"Doc{i}" for i in range(len(docs))],
index=[f"Doc{i}" for i in range(len(docs))]).round(3))
# 6. Tokenization and vocabulary
print("\n=== 6. Tokenization Analysis ===")
corpus = " ".join(texts)
tokens, _ = preprocess_text(corpus)
# Vocabulary
vocab = Counter(tokens)
print(f"Vocabulary size: {len(vocab)}")
print("Top 10 most common words:")
for word, count in vocab.most_common(10):
print(f" {word}: {count}")
# 7. Advanced Transformer pipeline
print("\n=== 7. Advanced NLP Tasks ===")
try:
# Zero-shot classification
zero_shot_pipeline = pipeline(
"zero-shot-classification",
model="facebook/bart-large-mnli"
)
sequence = "Apple is discussing the possibility of acquiring startup for 1 billion dollars"
candidate_labels = ["business", "sports", "technology", "politics"]
result = zero_shot_pipeline(sequence, candidate_labels)
print("Zero-shot Classification Results:")
for label, score in zip(result['labels'], result['scores']):
print(f" {label}: {score:.4f}")
except Exception as e:
print(f"Advanced pipeline not available: {str(e)}\n")
# 8. Text statistics and analysis
print("\n=== 8. Text Statistics ===")
sample_texts = [
"Natural language processing is fascinating.",
"Machine learning enables artificial intelligence.",
"Deep learning revolutionizes computer vision."
]
stats_data = []
for text in sample_texts:
words = text.split()
chars = len(text)
avg_word_len = np.mean([len(w) for w in words])
stats_data.append({
'Text': text[:40] + '...' if len(text) > 40 else text,
'Words': len(words),
'Characters': chars,
'Avg Word Len': avg_word_len
})
stats_df = pd.DataFrame(stats_data)
print(stats_df.to_string(index=False))
# 9. Visualization
print("\n=== 9. NLP Visualization ===")
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# Word frequency
word_freq = vocab.most_common(15)
words, freqs = zip(*word_freq)
axes[0, 0].barh(range(len(words)), freqs, color='steelblue')
axes[0, 0].set_yticks(range(len(words)))
axes[0, 0].set_yticklabels(words)
axes[0, 0].set_xlabel('Frequency')
axes[0, 0].set_title('Top 15 Most Frequent Words')
axes[0, 0].invert_yaxis()
# Sentiment distribution
sentiments = ['Positive', 'Negative', 'Positive', 'Negative', 'Positive']
sentiment_counts = Counter(sentiments)
axes[0, 1].pie(sentiment_counts.values(), labels=sentiment_counts.keys(),
autopct='%1.1f%%', colors=['green', 'red'])
axes[0, 1].set_title('Sentiment Distribution')
# Document similarity heatmap
im = axes[1, 0].imshow(similarity_matrix, cmap='YlOrRd', aspect='auto')
axes[1, 0].set_xticks(range(len(docs)))
axes[1, 0].set_yticks(range(len(docs)))
axes[1, 0].set_xticklabels([f'Doc{i}' for i in range(len(docs))])
axes[1, 0].set_yticklabels([f'Doc{i}' for i in range(len(docs))])
axes[1, 0].set_title('Document Similarity Heatmap')
plt.colorbar(im, ax=axes[1, 0])
# Text length distribution
text_lengths = [len(t.split()) for t in texts]
axes[1, 1].hist(text_lengths, bins=5, color='coral', edgecolor='black')
axes[1, 1].set_xlabel('Number of Words')
axes[1, 1].set_ylabel('Frequency')
axes[1, 1].set_title('Text Length Distribution')
axes[1, 1].grid(True, alpha=0.3, axis='y')
plt.tight_layout()
plt.savefig('nlp_analysis.png', dpi=100, bbox_inches='tight')
print("\nNLP visualization saved as 'nlp_analysis.png'")
# 10. Summary
print("\n=== NLP Summary ===")
print(f"Texts processed: {len(texts)}")
print(f"Unique vocabulary: {len(vocab)} words")
print(f"Average text length: {np.mean([len(t.split()) for t in texts]):.2f} words")
print(f"Classification accuracy: {accuracy_score(labels, predictions):.4f}")
print("\nNatural language processing setup completed!")
Common NLP Tasks and Models
- Classification: DistilBERT, RoBERTa, ELECTRA
- NER: BioBERT, SciBERT, spaCy models
- Translation: MarianMT, M2M-100
- Summarization: BART, Pegasus, T5
- QA: BERT, RoBERTa, DeBERTa
Text Preprocessing Pipeline
- Lowercasing and cleaning
- Tokenization
- Stopword removal
- Lemmatization/Stemming
- Vectorization
Best Practices
- Use pre-trained models when available
- Fine-tune on task-specific data
- Handle out-of-vocabulary words
- Batch process for efficiency
- Monitor for bias in models
Deliverables
- Trained NLP model
- Text classification results
- Named entities extracted
- Performance metrics
- Visualization dashboard
- Inference API
1---2name: natural-language-processing3description: Build NLP applications using transformers library, BERT, GPT, text classification, named entity recognition, and sentiment analysis4---5
6# Natural Language Processing
7
8## Overview
9
10This skill provides comprehensive tools for building NLP applications using modern transformers, BERT, GPT, and classical NLP techniques for text classification, named entity recognition, sentiment analysis, and more.
11
12## When to Use
13
14- Building text classification systems for sentiment analysis, topic categorization, or intent detection
15- Extracting named entities (people, places, organizations) from unstructured text
16- Implementing machine translation, text summarization, or question answering systems
17- Processing and analyzing large volumes of textual data for insights
18- Creating chatbots, virtual assistants, or conversational AI applications
19- Fine-tuning pre-trained transformer models for domain-specific NLP tasks
20
21## NLP Core Tasks
22
23- **Text Classification**: Sentiment, topic, intent classification
24- **Named Entity Recognition**: Identifying people, places, organizations
25- **Machine Translation**: Text translation between languages
26- **Text Summarization**: Extracting key information
27- **Question Answering**: Finding answers in documents
28- **Text Generation**: Generating coherent text
29
30## Popular Models and Libraries
31
32- **Transformers**: BERT, GPT, RoBERTa, T5
33- **spaCy**: Industrial NLP pipeline
34- **NLTK**: Classic NLP toolkit
35- **Hugging Face**: Pre-trained models hub
36- **PyTorch/TensorFlow**: Deep learning frameworks
37
38## Python Implementation
39
40```python
41import numpy as np
42import pandas as pd
43import matplotlib.pyplot as plt
44from collections import Counter
45import re
46import nltk
47from nltk.tokenize import word_tokenize, sent_tokenize
48from nltk.corpus import stopwords
49from nltk.stem import PorterStemmer, WordNetLemmatizer
50import torch
51from transformers import (AutoTokenizer, AutoModelForSequenceClassification,
52 AutoModelForTokenClassification, pipeline,
53 TextClassificationPipeline)
54from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
55from sklearn.naive_bayes import MultinomialNB
56from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
57import warnings
58warnings.filterwarnings('ignore')
59
60# Download required NLTK resources
61try:
62 nltk.data.find('tokenizers/punkt')
63except LookupError:
64 nltk.download('punkt')
65
66print("=== 1. Text Preprocessing ===")
67
68def preprocess_text(text, remove_stopwords=True, lemmatize=True):
69 """Complete text preprocessing pipeline"""
70 # Lowercase
71 text = text.lower()
72
73 # Remove special characters and digits
74 text = re.sub(r'[^a-zA-Z\s]', '', text)
75
76 # Tokenize
77 tokens = word_tokenize(text)
78
79 # Remove stopwords
80 if remove_stopwords:
81 stop_words = set(stopwords.words('english'))
82 tokens = [t for t in tokens if t not in stop_words]
83
84 # Lemmatize
85 if lemmatize:
86 lemmatizer = WordNetLemmatizer()
87 tokens = [lemmatizer.lemmatize(t) for t in tokens]
88
89 return tokens, ' '.join(tokens)
90
91sample_text = "The quick brown foxes are jumping over the lazy dogs! Amazing performance."
92tokens, processed = preprocess_text(sample_text)
93print(f"Original: {sample_text}")
94print(f"Processed: {processed}")
95print(f"Tokens: {tokens}\n")
96
97# 2. Text Classification with sklearn
98print("=== 2. Traditional Text Classification ===")
99
100# Sample data
101texts = [
102 "I love this product, it's amazing!",
103 "This movie is fantastic and entertaining.",
104 "Best purchase ever, highly recommended.",
105 "Terrible quality, very disappointed.",
106 "Worst experience, waste of money.",
107 "Horrible service and poor quality.",
108 "The food was delicious and fresh.",
109 "Great atmosphere and friendly staff.",
110 "Bad weather today, very gloomy.",
111 "The book was boring and uninteresting."
112]
113
114labels = [1, 1, 1, 0, 0, 0, 1, 1, 0, 0] # 1: positive, 0: negative
115
116# TF-IDF vectorization
117tfidf = TfidfVectorizer(max_features=100, ngram_range=(1, 2))
118X_tfidf = tfidf.fit_transform(texts)
119
120# Train classifier
121clf = MultinomialNB()
122clf.fit(X_tfidf, labels)
123
124# Evaluate
125predictions = clf.predict(X_tfidf)
126print(f"Accuracy: {accuracy_score(labels, predictions):.4f}")
127print(f"Precision: {precision_score(labels, predictions):.4f}")
128print(f"Recall: {recall_score(labels, predictions):.4f}")
129print(f"F1: {f1_score(labels, predictions):.4f}\n")
130
131# 3. Transformer-based text classification
132print("=== 3. Transformer-based Classification ===")
133
134try:
135 # Use Hugging Face transformers for sentiment analysis
136 sentiment_pipeline = pipeline(
137 "sentiment-analysis",
138 model="distilbert-base-uncased-finetuned-sst-2-english"
139 )
140
141 test_sentences = [
142 "This is a wonderful movie!",
143 "I absolutely hate this product.",
144 "It's okay, nothing special.",
145 "Amazing quality and fast delivery!"
146 ]
147
148 print("Sentiment Analysis Results:")
149 for sentence in test_sentences:
150 result = sentiment_pipeline(sentence)
151 print(f" Text: {sentence}")
152 print(f" Sentiment: {result[0]['label']}, Score: {result[0]['score']:.4f}\n")
153
154except Exception as e:
155 print(f"Transformer model not available: {str(e)}\n")
156
157# 4. Named Entity Recognition (NER)
158print("=== 4. Named Entity Recognition ===")
159
160try:
161 ner_pipeline = pipeline(
162 "ner",
163 model="distilbert-base-uncased",
164 aggregation_strategy="simple"
165 )
166
167 text = "Apple Inc. was founded by Steve Jobs in Cupertino, California."
168 entities = ner_pipeline(text)
169
170 print(f"Text: {text}")
171 print("Entities:")
172 for entity in entities:
173 print(f" {entity['word']}: {entity['entity_group']} (score: {entity['score']:.4f})")
174
175except Exception as e:
176 print(f"NER model not available: {str(e)}\n")
177
178# 5. Word embeddings and similarity
179print("\n=== 5. Word Embeddings and Similarity ===")
180
181from sklearn.metrics.pairwise import cosine_similarity
182
183# Simple bag-of-words embeddings
184vectorizer = CountVectorizer(max_features=50)
185docs = [
186 "machine learning is great",
187 "deep learning uses neural networks",
188 "machine learning and deep learning"
189]
190
191embeddings = vectorizer.fit_transform(docs).toarray()
192
193# Compute similarity
194similarity_matrix = cosine_similarity(embeddings)
195print("Document Similarity Matrix:")
196print(pd.DataFrame(similarity_matrix, columns=[f"Doc{i}" for i in range(len(docs))],
197 index=[f"Doc{i}" for i in range(len(docs))]).round(3))
198
199# 6. Tokenization and vocabulary
200print("\n=== 6. Tokenization Analysis ===")
201
202corpus = " ".join(texts)
203tokens, _ = preprocess_text(corpus)
204
205# Vocabulary
206vocab = Counter(tokens)
207print(f"Vocabulary size: {len(vocab)}")
208print("Top 10 most common words:")
209for word, count in vocab.most_common(10):
210 print(f" {word}: {count}")
211
212# 7. Advanced Transformer pipeline
213print("\n=== 7. Advanced NLP Tasks ===")
214
215try:
216 # Zero-shot classification
217 zero_shot_pipeline = pipeline(
218 "zero-shot-classification",
219 model="facebook/bart-large-mnli"
220 )
221
222 sequence = "Apple is discussing the possibility of acquiring startup for 1 billion dollars"
223 candidate_labels = ["business", "sports", "technology", "politics"]
224
225 result = zero_shot_pipeline(sequence, candidate_labels)
226 print("Zero-shot Classification Results:")
227 for label, score in zip(result['labels'], result['scores']):
228 print(f" {label}: {score:.4f}")
229
230except Exception as e:
231 print(f"Advanced pipeline not available: {str(e)}\n")
232
233# 8. Text statistics and analysis
234print("\n=== 8. Text Statistics ===")
235
236sample_texts = [
237 "Natural language processing is fascinating.",
238 "Machine learning enables artificial intelligence.",
239 "Deep learning revolutionizes computer vision."
240]
241
242stats_data = []
243for text in sample_texts:
244 words = text.split()
245 chars = len(text)
246 avg_word_len = np.mean([len(w) for w in words])
247
248 stats_data.append({
249 'Text': text[:40] + '...' if len(text) > 40 else text,
250 'Words': len(words),
251 'Characters': chars,
252 'Avg Word Len': avg_word_len
253 })
254
255stats_df = pd.DataFrame(stats_data)
256print(stats_df.to_string(index=False))
257
258# 9. Visualization
259print("\n=== 9. NLP Visualization ===")
260
261fig, axes = plt.subplots(2, 2, figsize=(14, 10))
262
263# Word frequency
264word_freq = vocab.most_common(15)
265words, freqs = zip(*word_freq)
266axes[0, 0].barh(range(len(words)), freqs, color='steelblue')
267axes[0, 0].set_yticks(range(len(words)))
268axes[0, 0].set_yticklabels(words)
269axes[0, 0].set_xlabel('Frequency')
270axes[0, 0].set_title('Top 15 Most Frequent Words')
271axes[0, 0].invert_yaxis()
272
273# Sentiment distribution
274sentiments = ['Positive', 'Negative', 'Positive', 'Negative', 'Positive']
275sentiment_counts = Counter(sentiments)
276axes[0, 1].pie(sentiment_counts.values(), labels=sentiment_counts.keys(),
277 autopct='%1.1f%%', colors=['green', 'red'])
278axes[0, 1].set_title('Sentiment Distribution')
279
280# Document similarity heatmap
281im = axes[1, 0].imshow(similarity_matrix, cmap='YlOrRd', aspect='auto')
282axes[1, 0].set_xticks(range(len(docs)))
283axes[1, 0].set_yticks(range(len(docs)))
284axes[1, 0].set_xticklabels([f'Doc{i}' for i in range(len(docs))])
285axes[1, 0].set_yticklabels([f'Doc{i}' for i in range(len(docs))])
286axes[1, 0].set_title('Document Similarity Heatmap')
287plt.colorbar(im, ax=axes[1, 0])
288
289# Text length distribution
290text_lengths = [len(t.split()) for t in texts]
291axes[1, 1].hist(text_lengths, bins=5, color='coral', edgecolor='black')
292axes[1, 1].set_xlabel('Number of Words')
293axes[1, 1].set_ylabel('Frequency')
294axes[1, 1].set_title('Text Length Distribution')
295axes[1, 1].grid(True, alpha=0.3, axis='y')
296
297plt.tight_layout()
298plt.savefig('nlp_analysis.png', dpi=100, bbox_inches='tight')
299print("\nNLP visualization saved as 'nlp_analysis.png'")
300
301# 10. Summary
302print("\n=== NLP Summary ===")
303print(f"Texts processed: {len(texts)}")
304print(f"Unique vocabulary: {len(vocab)} words")
305print(f"Average text length: {np.mean([len(t.split()) for t in texts]):.2f} words")
306print(f"Classification accuracy: {accuracy_score(labels, predictions):.4f}")
307
308print("\nNatural language processing setup completed!")
309```
310
311## Common NLP Tasks and Models
312
313- **Classification**: DistilBERT, RoBERTa, ELECTRA
314- **NER**: BioBERT, SciBERT, spaCy models
315- **Translation**: MarianMT, M2M-100
316- **Summarization**: BART, Pegasus, T5
317- **QA**: BERT, RoBERTa, DeBERTa
318
319## Text Preprocessing Pipeline
320
3211. Lowercasing and cleaning
3222. Tokenization
3233. Stopword removal
3244. Lemmatization/Stemming
3255. Vectorization
326
327## Best Practices
328
329- Use pre-trained models when available
330- Fine-tune on task-specific data
331- Handle out-of-vocabulary words
332- Batch process for efficiency
333- Monitor for bias in models
334
335## Deliverables
336
337- Trained NLP model
338- Text classification results
339- Named entities extracted
340- Performance metrics
341- Visualization dashboard
342- Inference API