Skip to main content 홈 크리에이터 aj-geddes useful-ai-prompts natural-language-processing
natural-language-processing Build NLP applications using transformers library, BERT, GPT, text classification, named entity recognition, and sentiment analysis
설치로 이동 Skills Marketplace 커뮤니티가 만든 AI 스킬을 발견하고 탐색하세요.
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
직접 명령은 검토 Prompt를 거치지 않습니다. 실행하기 전에 소스를 확인하세요.
npx skills add https://github.com/aj-geddes/useful-ai-prompts --skill natural-language-processing명령은 한 줄로 유지됩니다. 복사하기 전에 가로로 스크롤해 전체 내용을 확인하세요.
로컬 사본을 원하시나요? SkillsMP에서 현재 제공할 수 있는 파일을 다운로드하세요.
Zip 다운로드 다운로드 중... name Natural Language Processing description Build NLP applications using transformers library, BERT, GPT, text classification, named entity recognition, and sentiment analysis
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' )
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"""
text = text.lower()
text = re.sub(r'[^a-zA-Z\s]' , , text)
tokens = word_tokenize(text)
remove_stopwords:
stop_words = (stopwords.words( ))
tokens = [t t tokens t stop_words]
lemmatize:
lemmatizer = WordNetLemmatizer()
tokens = [lemmatizer.lemmatize(t) t tokens]
tokens, .join(tokens)
sample_text =
tokens, processed = preprocess_text(sample_text)
( )
( )
( )
( )
texts = [
,
,
,
,
,
,
,
,
,
]
labels = [ , , , , , , , , , ]
tfidf = TfidfVectorizer(max_features= , ngram_range=( , ))
X_tfidf = tfidf.fit_transform(texts)
clf = MultinomialNB()
clf.fit(X_tfidf, labels)
predictions = clf.predict(X_tfidf)
( )
( )
( )
( )
( )
:
sentiment_pipeline = pipeline(
,
model=
)
test_sentences = [
,
,
,
]
( )
sentence test_sentences:
result = sentiment_pipeline(sentence)
( )
( )
Exception e:
( )
( )
:
ner_pipeline = pipeline(
,
model= ,
aggregation_strategy=
)
text =
entities = ner_pipeline(text)
( )
( )
entity entities:
( )
Exception e:
( )
( )
sklearn.metrics.pairwise cosine_similarity
vectorizer = CountVectorizer(max_features= )
docs = [
,
,
]
embeddings = vectorizer.fit_transform(docs).toarray()
similarity_matrix = cosine_similarity(embeddings)
( )
(pd.DataFrame(similarity_matrix, columns=[ i ( (docs))],
index=[ i ( (docs))]). ( ))
( )
corpus = .join(texts)
tokens, _ = preprocess_text(corpus)
vocab = Counter(tokens)
( )
( )
word, count vocab.most_common( ):
( )
( )
:
zero_shot_pipeline = pipeline(
,
model=
)
sequence =
candidate_labels = [ , , , ]
result = zero_shot_pipeline(sequence, candidate_labels)
( )
label, score (result[ ], result[ ]):
( )
Exception e:
( )
( )
sample_texts = [
,
,
]
stats_data = []
text sample_texts:
words = text.split()
chars = (text)
avg_word_len = np.mean([ (w) w words])
stats_data.append({
: text[: ] + (text) > text,
: (words),
: chars,
: avg_word_len
})
stats_df = pd.DataFrame(stats_data)
(stats_df.to_string(index= ))
( )
fig, axes = plt.subplots( , , figsize=( , ))
word_freq = vocab.most_common( )
words, freqs = (*word_freq)
axes[ , ].barh( ( (words)), freqs, color= )
axes[ , ].set_yticks( ( (words)))
axes[ , ].set_yticklabels(words)
axes[ , ].set_xlabel( )
axes[ , ].set_title( )
axes[ , ].invert_yaxis()
sentiments = [ , , , , ]
sentiment_counts = Counter(sentiments)
axes[ , ].pie(sentiment_counts.values(), labels=sentiment_counts.keys(),
autopct= , colors=[ , ])
axes[ , ].set_title( )
im = axes[ , ].imshow(similarity_matrix, cmap= , aspect= )
axes[ , ].set_xticks( ( (docs)))
axes[ , ].set_yticks( ( (docs)))
axes[ , ].set_xticklabels([ i ( (docs))])
axes[ , ].set_yticklabels([ i ( (docs))])
axes[ , ].set_title( )
plt.colorbar(im, ax=axes[ , ])
text_lengths = [ (t.split()) t texts]
axes[ , ].hist(text_lengths, bins= , color= , edgecolor= )
axes[ , ].set_xlabel( )
axes[ , ].set_ylabel( )
axes[ , ].set_title( )
axes[ , ].grid( , alpha= , axis= )
plt.tight_layout()
plt.savefig( , dpi= , bbox_inches= )
( )
( )
( )
( )
( )
( )
( )
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
''
if
set
'english'
for
in
if
not
in
if
for
in
return
' '
"The quick brown foxes are jumping over the lazy dogs! Amazing performance."
print
f"Original: {sample_text} "
print
f"Processed: {processed} "
print
f"Tokens: {tokens} \n"
print
"=== 2. Traditional Text Classification ==="
"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."
1
1
1
0
0
0
1
1
0
0
100
1
2
print
f"Accuracy: {accuracy_score(labels, predictions):.4 f} "
print
f"Precision: {precision_score(labels, predictions):.4 f} "
print
f"Recall: {recall_score(labels, predictions):.4 f} "
print
f"F1: {f1_score(labels, predictions):.4 f} \n"
print
"=== 3. Transformer-based Classification ==="
try
"sentiment-analysis"
"distilbert-base-uncased-finetuned-sst-2-english"
"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
in
print
f" Text: {sentence} "
print
f" Sentiment: {result[0 ]['label' ]} , Score: {result[0 ]['score' ]:.4 f} \n"
except
as
print
f"Transformer model not available: {str (e)} \n"
print
"=== 4. Named Entity Recognition ==="
try
"ner"
"distilbert-base-uncased"
"simple"
"Apple Inc. was founded by Steve Jobs in Cupertino, California."
print
f"Text: {text} "
print
"Entities:"
for
in
print
f" {entity['word' ]} : {entity['entity_group' ]} (score: {entity['score' ]:.4 f} )"
except
as
print
f"NER model not available: {str (e)} \n"
print
"\n=== 5. Word Embeddings and Similarity ==="
from
import
50
"machine learning is great"
"deep learning uses neural networks"
"machine learning and deep learning"
print
"Document Similarity Matrix:"
print
f"Doc{i} "
for
in
range
len
f"Doc{i} "
for
in
range
len
round
3
print
"\n=== 6. Tokenization Analysis ==="
" "
print
f"Vocabulary size: {len (vocab)} "
print
"Top 10 most common words:"
for
in
10
print
f" {word} : {count} "
print
"\n=== 7. Advanced NLP Tasks ==="
try
"zero-shot-classification"
"facebook/bart-large-mnli"
"Apple is discussing the possibility of acquiring startup for 1 billion dollars"
"business"
"sports"
"technology"
"politics"
print
"Zero-shot Classification Results:"
for
in
zip
'labels'
'scores'
print
f" {label} : {score:.4 f} "
except
as
print
f"Advanced pipeline not available: {str (e)} \n"
print
"\n=== 8. Text Statistics ==="
"Natural language processing is fascinating."
"Machine learning enables artificial intelligence."
"Deep learning revolutionizes computer vision."
for
in
len
len
for
in
'Text'
40
'...'
if
len
40
else
'Words'
len
'Characters'
'Avg Word Len'
print
False
print
"\n=== 9. NLP Visualization ==="
2
2
14
10
15
zip
0
0
range
len
'steelblue'
0
0
range
len
0
0
0
0
'Frequency'
0
0
'Top 15 Most Frequent Words'
0
0
'Positive'
'Negative'
'Positive'
'Negative'
'Positive'
0
1
'%1.1f%%'
'green'
'red'
0
1
'Sentiment Distribution'
1
0
'YlOrRd'
'auto'
1
0
range
len
1
0
range
len
1
0
f'Doc{i} '
for
in
range
len
1
0
f'Doc{i} '
for
in
range
len
1
0
'Document Similarity Heatmap'
1
0
len
for
in
1
1
5
'coral'
'black'
1
1
'Number of Words'
1
1
'Frequency'
1
1
'Text Length Distribution'
1
1
True
0.3
'y'
'nlp_analysis.png'
100
'tight'
print
"\nNLP visualization saved as 'nlp_analysis.png'"
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]):.2 f} words"
print
f"Classification accuracy: {accuracy_score(labels, predictions):.4 f} "
print
"\nNatural language processing setup completed!"