One Hot Encoding
Explore how text is transformed into sparse binary vectors for neural network processing.
Explore how text is transformed into sparse binary vectors for neural network processing.
A deep dive into converting categorical data into a machine-readable format.
One-Hot Encoding is a fundamental technique in data preprocessing, used to convert categorical variables into a numerical format that machine learning algorithms can understand. It takes a column with categorical data, which has been label encoded, and then splits the column into multiple columns. The numbers are replaced by 1s and 0s, depending on which column has what value.
Imagine you have a feature like "Color" with categories: "Red", "Green", and "Blue". A machine learning model can't work with these text labels directly. One-Hot Encoding transforms this single "Color" column into three new columns, one for each category: "Is_Red", "Is_Green", and "Is_Blue".
1, while "Is_Green" and "Is_Blue" will be 0.1, and the others get 0.This creates a sparse binary vector where only one bit is "hot" (set to 1), clearly and unambiguously representing the original category without implying any ordinal relationship between the categories.
The interactive visualization on this page lets you see this process in action. Follow these steps to build a strong mental model:
function oneHotEncode(corpus):
// 1. Tokenize and find unique words
tokens = tokenize(corpus)
vocabulary = sorted(unique(tokens))
// 2. Create a mapping from word to index
word_to_index = {word: i for i, word in enumerate(vocabulary)}
// 3. Generate vectors
encoded_vectors = []
for token in tokens:
vector = create_zero_vector(length=len(vocabulary))
index = word_to_index[token]
vector[index] = 1
encoded_vectors.append(vector)
return encoded_vectors
While One-Hot Encoding is a great starting point, for more complex tasks, especially in Natural Language Processing (NLP), more advanced techniques like Word Embeddings (e.g., Word2Vec, GloVe, FastText) are used. These methods represent words as dense, low-dimensional vectors that capture semantic relationships (e.g., the vectors for "king" and "queen" are closer to each other). One-Hot Encoding, in contrast, treats every word as equally different from all others.
One-Hot Encoding is a fundamental technique in data preprocessing, used to convert categorical variables into a numerical format that machine learning algorithms can understand. It takes a column with categorical data, which has been label encoded, and then splits the column into multiple columns. The numbers are replaced by 1s and 0s, depending on which column has what value.