Ниже приведены несколько популярных методов извлечения признаков обработки естественного языка (NLP) с использованием Python, а также примеры кода:
- Мешок слов (BoW):
Техника BoW представляет текст как набор уникальных слов без учета грамматики и порядка слов.
from sklearn.feature_extraction.text import CountVectorizer
# Sample corpus
corpus = ['This is the first document.',
'This document is the second document.',
'And this is the third one.',
'Is this the first document?']
# Create the Bag-of-Words model
vectorizer = CountVectorizer()
bow_features = vectorizer.fit_transform(corpus)
# Get the feature names
feature_names = vectorizer.get_feature_names()
# Print the features
for doc_index, doc_features in enumerate(bow_features):
print(f"Document {doc_index + 1} features:")
for feature_index, feature_count in zip(doc_features.indices, doc_features.data):
print(f"{feature_names[feature_index]}: {feature_count}")
print()
- TF-IDF (частота термина, обратная частоте документа):
TF-IDF — это числовая статистика, которая отражает, насколько важно слово для документа в коллекции.
from sklearn.feature_extraction.text import TfidfVectorizer
# Create the TF-IDF model
vectorizer = TfidfVectorizer()
tfidf_features = vectorizer.fit_transform(corpus)
# Print the features
for doc_index, doc_features in enumerate(tfidf_features):
print(f"Document {doc_index + 1} features:")
for feature_index, feature_score in zip(doc_features.indices, doc_features.data):
print(f"{feature_names[feature_index]}: {feature_score}")
print()
- Word2Vec:
Word2Vec представляет слова в виде плотных векторов, фиксируя семантические значения и связи между словами.
from gensim.models import Word2Vec
# Sample sentences
sentences = [['this', 'is', 'the', 'first', 'sentence', 'for', 'word2vec'],
['this', 'is', 'the', 'second', 'sentence'],
['yet', 'another', 'sentence'],
['one', 'more', 'sentence'],
['and', 'the', 'final', 'sentence']]
# Train the Word2Vec model
model = Word2Vec(sentences, min_count=1)
# Get the word vector for a word
vector = model.wv['sentence']
print(vector)
- Распознавание именованных объектов (NER):
NER идентифицирует и классифицирует именованные объекты (например, имена, организации, местоположения) в тексте.
import spacy
# Load the English NER model
nlp = spacy.load('en_core_web_sm')
# Sample sentence
text = "Apple Inc. is planning to open a new store in New York City."
# Process the text
doc = nlp(text)
# Extract named entities
entities = [(entity.text, entity.label_) for entity in doc.ents]
# Print the named entities
for entity, label in entities:
print(f"{entity}: {label}")
- Теги частей речи (POS):
Теги POS присваивают грамматические теги словам в предложении.