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
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: natural-language-processing3description: Build NLP applications using transformers library, BERT, GPT, text classification, named entity recognition, and sentiment analysis Use when this capability is needed.4---56# Natural Language Processing78## Overview910This 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.1112## When to Use1314- Building text classification systems for sentiment analysis, topic categorization, or intent detection15- Extracting named entities (people, places, organizations) from unstructured text16- Implementing machine translation, text summarization, or question answering systems17- Processing and analyzing large volumes of textual data for insights18- Creating chatbots, virtual assistants, or conversational AI applications19- Fine-tuning pre-trained transformer models for domain-specific NLP tasks2021## NLP Core Tasks2223- **Text Classification**: Sentiment, topic, intent classification24- **Named Entity Recognition**: Identifying people, places, organizations25- **Machine Translation**: Text translation between languages26- **Text Summarization**: Extracting key information27- **Question Answering**: Finding answers in documents28- **Text Generation**: Generating coherent text2930## Popular Models and Libraries3132- **Transformers**: BERT, GPT, RoBERTa, T533- **spaCy**: Industrial NLP pipeline34- **NLTK**: Classic NLP toolkit35- **Hugging Face**: Pre-trained models hub36- **PyTorch/TensorFlow**: Deep learning frameworks3738## Python Implementation3940```python41import numpy as np42import pandas as pd43import matplotlib.pyplot as plt44from collections import Counter45import re46import nltk47from nltk.tokenize import word_tokenize, sent_tokenize48from nltk.corpus import stopwords49from nltk.stem import PorterStemmer, WordNetLemmatizer50import torch51from transformers import (AutoTokenizer, AutoModelForSequenceClassification,52 AutoModelForTokenClassification, pipeline,53 TextClassificationPipeline)54from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer55from sklearn.naive_bayes import MultinomialNB56from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score57import warnings58warnings.filterwarnings('ignore')5960# Download required NLTK resources61try:62 nltk.data.find('tokenizers/punkt')63except LookupError:64 nltk.download('punkt')6566print("=== 1. Text Preprocessing ===")6768def preprocess_text(text, remove_stopwords=True, lemmatize=True):69 """Complete text preprocessing pipeline"""70 # Lowercase71 text = text.lower()7273 # Remove special characters and digits74 text = re.sub(r'[^a-zA-Z\s]', '', text)7576 # Tokenize77 tokens = word_tokenize(text)7879 # Remove stopwords80 if remove_stopwords:81 stop_words = set(stopwords.words('english'))82 tokens = [t for t in tokens if t not in stop_words]8384 # Lemmatize85 if lemmatize:86 lemmatizer = WordNetLemmatizer()87 tokens = [lemmatizer.lemmatize(t) for t in tokens]8889 return tokens, ' '.join(tokens)9091sample_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")9697# 2. Text Classification with sklearn98print("=== 2. Traditional Text Classification ===")99100# Sample data101texts = [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]113114labels = [1, 1, 1, 0, 0, 0, 1, 1, 0, 0] # 1: positive, 0: negative115116# TF-IDF vectorization117tfidf = TfidfVectorizer(max_features=100, ngram_range=(1, 2))118X_tfidf = tfidf.fit_transform(texts)119120# Train classifier121clf = MultinomialNB()122clf.fit(X_tfidf, labels)123124# Evaluate125predictions = 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")130131# 3. Transformer-based text classification132print("=== 3. Transformer-based Classification ===")133134try:135 # Use Hugging Face transformers for sentiment analysis136 sentiment_pipeline = pipeline(137 "sentiment-analysis",138 model="distilbert-base-uncased-finetuned-sst-2-english"139 )140141 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 ]147148 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")153154except Exception as e:155 print(f"Transformer model not available: {str(e)}\n")156157# 4. Named Entity Recognition (NER)158print("=== 4. Named Entity Recognition ===")159160try:161 ner_pipeline = pipeline(162 "ner",163 model="distilbert-base-uncased",164 aggregation_strategy="simple"165 )166167 text = "Apple Inc. was founded by Steve Jobs in Cupertino, California."168 entities = ner_pipeline(text)169170 print(f"Text: {text}")171 print("Entities:")172 for entity in entities:173 print(f" {entity['word']}: {entity['entity_group']} (score: {entity['score']:.4f})")174175except Exception as e:176 print(f"NER model not available: {str(e)}\n")177178# 5. Word embeddings and similarity179print("\n=== 5. Word Embeddings and Similarity ===")180181from sklearn.metrics.pairwise import cosine_similarity182183# Simple bag-of-words embeddings184vectorizer = CountVectorizer(max_features=50)185docs = [186 "machine learning is great",187 "deep learning uses neural networks",188 "machine learning and deep learning"189]190191embeddings = vectorizer.fit_transform(docs).toarray()192193# Compute similarity194similarity_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))198199# 6. Tokenization and vocabulary200print("\n=== 6. Tokenization Analysis ===")201202corpus = " ".join(texts)203tokens, _ = preprocess_text(corpus)204205# Vocabulary206vocab = 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}")211212# 7. Advanced Transformer pipeline213print("\n=== 7. Advanced NLP Tasks ===")214215try:216 # Zero-shot classification217 zero_shot_pipeline = pipeline(218 "zero-shot-classification",219 model="facebook/bart-large-mnli"220 )221222 sequence = "Apple is discussing the possibility of acquiring startup for 1 billion dollars"223 candidate_labels = ["business", "sports", "technology", "politics"]224225 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}")229230except Exception as e:231 print(f"Advanced pipeline not available: {str(e)}\n")232233# 8. Text statistics and analysis234print("\n=== 8. Text Statistics ===")235236sample_texts = [237 "Natural language processing is fascinating.",238 "Machine learning enables artificial intelligence.",239 "Deep learning revolutionizes computer vision."240]241242stats_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])247248 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_len253 })254255stats_df = pd.DataFrame(stats_data)256print(stats_df.to_string(index=False))257258# 9. Visualization259print("\n=== 9. NLP Visualization ===")260261fig, axes = plt.subplots(2, 2, figsize=(14, 10))262263# Word frequency264word_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()272273# Sentiment distribution274sentiments = ['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')279280# Document similarity heatmap281im = 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])288289# Text length distribution290text_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')296297plt.tight_layout()298plt.savefig('nlp_analysis.png', dpi=100, bbox_inches='tight')299print("\nNLP visualization saved as 'nlp_analysis.png'")300301# 10. Summary302print("\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}")307308print("\nNatural language processing setup completed!")309```310311## Common NLP Tasks and Models312313- **Classification**: DistilBERT, RoBERTa, ELECTRA314- **NER**: BioBERT, SciBERT, spaCy models315- **Translation**: MarianMT, M2M-100316- **Summarization**: BART, Pegasus, T5317- **QA**: BERT, RoBERTa, DeBERTa318319## Text Preprocessing Pipeline3203211. Lowercasing and cleaning3222. Tokenization3233. Stopword removal3244. Lemmatization/Stemming3255. Vectorization326327## Best Practices328329- Use pre-trained models when available330- Fine-tune on task-specific data331- Handle out-of-vocabulary words332- Batch process for efficiency333- Monitor for bias in models334335## Deliverables336337- Trained NLP model338- Text classification results339- Named entities extracted340- Performance metrics341- Visualization dashboard342- Inference API343344---345> Converted and distributed by [TomeVault](https://tomevault.io/claim/aj-geddes) — claim your Tome and manage your conversions.346<!-- tomevault:4.0:skill_md:2026-04-11 -->