Natural Language Processing

Natural Language Processing

Builds NLP applications in Python with transformers and BERT: text classification, named entity recognition, sentiment analysis and summarization.

Skill files3 files

scripts/

templates/

SKILL.md343 lines
1
---
2
name: Natural Language Processing
3
description: Build NLP applications using transformers library, BERT, GPT, text classification, named entity recognition, and sentiment analysis
4
---
5
6
# Natural Language Processing
7
8
## Overview
9
10
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.
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
41
import numpy as np
42
import pandas as pd
43
import matplotlib.pyplot as plt
44
from collections import Counter
45
import re
46
import nltk
47
from nltk.tokenize import word_tokenize, sent_tokenize
48
from nltk.corpus import stopwords
49
from nltk.stem import PorterStemmer, WordNetLemmatizer
50
import torch
51
from transformers import (AutoTokenizer, AutoModelForSequenceClassification,
52
AutoModelForTokenClassification, pipeline,
53
TextClassificationPipeline)
54
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
55
from sklearn.naive_bayes import MultinomialNB
56
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
57
import warnings
58
warnings.filterwarnings('ignore')
59
60
# Download required NLTK resources
61
try:
62
nltk.data.find('tokenizers/punkt')
63
except LookupError:
64
nltk.download('punkt')
65
66
print("=== 1. Text Preprocessing ===")
67
68
def 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
91
sample_text = "The quick brown foxes are jumping over the lazy dogs! Amazing performance."
92
tokens, processed = preprocess_text(sample_text)
93
print(f"Original: {sample_text}")
94
print(f"Processed: {processed}")
95
print(f"Tokens: {tokens}\n")
96
97
# 2. Text Classification with sklearn
98
print("=== 2. Traditional Text Classification ===")
99
100
# Sample data
101
texts = [
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
114
labels = [1, 1, 1, 0, 0, 0, 1, 1, 0, 0] # 1: positive, 0: negative
115
116
# TF-IDF vectorization
117
tfidf = TfidfVectorizer(max_features=100, ngram_range=(1, 2))
118
X_tfidf = tfidf.fit_transform(texts)
119
120
# Train classifier
121
clf = MultinomialNB()
122
clf.fit(X_tfidf, labels)
123
124
# Evaluate
125
predictions = clf.predict(X_tfidf)
126
print(f"Accuracy: {accuracy_score(labels, predictions):.4f}")
127
print(f"Precision: {precision_score(labels, predictions):.4f}")
128
print(f"Recall: {recall_score(labels, predictions):.4f}")
129
print(f"F1: {f1_score(labels, predictions):.4f}\n")
130
131
# 3. Transformer-based text classification
132
print("=== 3. Transformer-based Classification ===")
133
134
try:
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
154
except Exception as e:
155
print(f"Transformer model not available: {str(e)}\n")
156
157
# 4. Named Entity Recognition (NER)
158
print("=== 4. Named Entity Recognition ===")
159
160
try:
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
175
except Exception as e:
176
print(f"NER model not available: {str(e)}\n")
177
178
# 5. Word embeddings and similarity
179
print("\n=== 5. Word Embeddings and Similarity ===")
180
181
from sklearn.metrics.pairwise import cosine_similarity
182
183
# Simple bag-of-words embeddings
184
vectorizer = CountVectorizer(max_features=50)
185
docs = [
186
"machine learning is great",
187
"deep learning uses neural networks",
188
"machine learning and deep learning"
189
]
190
191
embeddings = vectorizer.fit_transform(docs).toarray()
192
193
# Compute similarity
194
similarity_matrix = cosine_similarity(embeddings)
195
print("Document Similarity Matrix:")
196
print(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
200
print("\n=== 6. Tokenization Analysis ===")
201
202
corpus = " ".join(texts)
203
tokens, _ = preprocess_text(corpus)
204
205
# Vocabulary
206
vocab = Counter(tokens)
207
print(f"Vocabulary size: {len(vocab)}")
208
print("Top 10 most common words:")
209
for word, count in vocab.most_common(10):
210
print(f" {word}: {count}")
211
212
# 7. Advanced Transformer pipeline
213
print("\n=== 7. Advanced NLP Tasks ===")
214
215
try:
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
230
except Exception as e:
231
print(f"Advanced pipeline not available: {str(e)}\n")
232
233
# 8. Text statistics and analysis
234
print("\n=== 8. Text Statistics ===")
235
236
sample_texts = [
237
"Natural language processing is fascinating.",
238
"Machine learning enables artificial intelligence.",
239
"Deep learning revolutionizes computer vision."
240
]
241
242
stats_data = []
243
for 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
255
stats_df = pd.DataFrame(stats_data)
256
print(stats_df.to_string(index=False))
257
258
# 9. Visualization
259
print("\n=== 9. NLP Visualization ===")
260
261
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
262
263
# Word frequency
264
word_freq = vocab.most_common(15)
265
words, freqs = zip(*word_freq)
266
axes[0, 0].barh(range(len(words)), freqs, color='steelblue')
267
axes[0, 0].set_yticks(range(len(words)))
268
axes[0, 0].set_yticklabels(words)
269
axes[0, 0].set_xlabel('Frequency')
270
axes[0, 0].set_title('Top 15 Most Frequent Words')
271
axes[0, 0].invert_yaxis()
272
273
# Sentiment distribution
274
sentiments = ['Positive', 'Negative', 'Positive', 'Negative', 'Positive']
275
sentiment_counts = Counter(sentiments)
276
axes[0, 1].pie(sentiment_counts.values(), labels=sentiment_counts.keys(),
277
autopct='%1.1f%%', colors=['green', 'red'])
278
axes[0, 1].set_title('Sentiment Distribution')
279
280
# Document similarity heatmap
281
im = axes[1, 0].imshow(similarity_matrix, cmap='YlOrRd', aspect='auto')
282
axes[1, 0].set_xticks(range(len(docs)))
283
axes[1, 0].set_yticks(range(len(docs)))
284
axes[1, 0].set_xticklabels([f'Doc{i}' for i in range(len(docs))])
285
axes[1, 0].set_yticklabels([f'Doc{i}' for i in range(len(docs))])
286
axes[1, 0].set_title('Document Similarity Heatmap')
287
plt.colorbar(im, ax=axes[1, 0])
288
289
# Text length distribution
290
text_lengths = [len(t.split()) for t in texts]
291
axes[1, 1].hist(text_lengths, bins=5, color='coral', edgecolor='black')
292
axes[1, 1].set_xlabel('Number of Words')
293
axes[1, 1].set_ylabel('Frequency')
294
axes[1, 1].set_title('Text Length Distribution')
295
axes[1, 1].grid(True, alpha=0.3, axis='y')
296
297
plt.tight_layout()
298
plt.savefig('nlp_analysis.png', dpi=100, bbox_inches='tight')
299
print("\nNLP visualization saved as 'nlp_analysis.png'")
300
301
# 10. Summary
302
print("\n=== NLP Summary ===")
303
print(f"Texts processed: {len(texts)}")
304
print(f"Unique vocabulary: {len(vocab)} words")
305
print(f"Average text length: {np.mean([len(t.split()) for t in texts]):.2f} words")
306
print(f"Classification accuracy: {accuracy_score(labels, predictions):.4f}")
307
308
print("\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
321
1. Lowercasing and cleaning
322
2. Tokenization
323
3. Stopword removal
324
4. Lemmatization/Stemming
325
5. 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
343

© AJ Geddes · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…