Loading the lesson...
In the print dialog, choose "Save as PDF" as the destination.
Advanced NLP - Lesson 3
Turning text into numbers: one-hot encoding, bag-of-words, TF-IDF, and word embeddings
5 English sentences is used as the running example throughout this lessonText Representation
maps words and documents to numbers
Sparse / count-based
One-Hot, BoW, TF-IDF
Dense / learned
Word2Vec, GloVe
vocab = sorted(set(word for sentence in texts for word in sentence.split()))Machine learning is awesome1, and the rest are 0.def one_hot_encode(word):
vec = np.zeros(len(vocab))
if word in word_to_index:
vec[word_to_index[word]] = 1
return vecfrom sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(sparse_output=False, handle_unknown='ignore')
encoder.fit(vocab_np)handle_unknown='ignore' avoids errors on out-of-vocabulary words1 if the word appears in the document, 0 otherwise: no counts.def binary_transform(text):
output = np.zeros(len(vocab))
words = set(text.split())
for i, v in enumerate(vocab):
output[i] = v in words
return outputfrom sklearn.feature_extraction.text import CountVectorizer
vec = CountVectorizer(binary=True)
vec.fit(texts)binary=True gives presence/absence instead of counts5 documents by 43-word vocabulary in the example)from sklearn.feature_extraction.text import CountVectorizer
vec = CountVectorizer()
vec.fit(texts)the appears twice in sentence 1, giving a count of 2 rather than just 1from sklearn.feature_extraction.text import TfidfVectorizer
vec = TfidfVectorizer()
vec.fit(texts)Analogy
1 trait
a point on a line
2 traits
a 2D vector
5 traits
a 5D vector (Big Five)
Word meaning
an N-D vector
2D traits to 300D word embeddings.1 means the vectors point in a similar direction: more similarimport gensim
word2vec_model = gensim.models.KeyedVectors.load_word2vec_format(
"GoogleNews-vectors-negative300.bin", binary=True)
word2vec_model["king"][:10]Word2Vec, GloVe factorizes a word-word co-occurrence matrix, capturing global word relationships across the whole corpus.glove_embeddings = {}
with open("glove.6B.100d.txt", encoding="utf-8") as f:
for line in f:
values = line.split()
glove_embeddings[values[0]] = np.asarray(values[1:], dtype="float32")BoW, TF-IDF) count words but ignore meaning and orderTF-IDF weights rare-but-meaningful words higher than common wordsWord2Vec (CBOW/Skip-Gram) and GloVe learn dense embeddings that capture semantic relationshipsMahmoud Abas|Text Representation Techniques in NLP (Including Arabic Data)