🤖 AI/ML

FastText

FastText

Embeddings using character n-grams. Strong at handling out-of-vocabulary (OOV) words.

📖 Detailed Explanation

FastText is a word embedding and text classification library developed in 2016 by Facebook AI Research (now Meta AI). As an extension of Word2Vec, it represents a word as the sum of its character n-grams, which resolves the out-of-vocabulary (OOV) problem. It provides pretrained models for 157 languages, including Korean.

FastText's core innovation is its use of subword information. It decomposes the word "apple" into n-grams such as "<ap", "app", "ppl", "ple", and "le>", and builds the word vector as the sum of the vectors of each n-gram. This makes it possible to obtain meaningful vectors even for words that were not in the training data, such as "apples" and "pineapple".

FastText supports two modes. Skipgram/CBOW mode learns word embeddings similarly to Word2Vec, and Supervised mode performs text classification. In text classification, FastText trains hundreds of times faster than deep learning models while achieving similar accuracy, which makes it useful in resource-constrained environments.

In practice, FastText is used for rapid prototyping and as a baseline model. For spam classification, language detection, sentiment analysis, and similar tasks, it can process hundreds of thousands of items per second on a CPU alone. In Korean NLP, it works to some extent even without morphological analysis, but applying morphological analysis greatly improves performance.

💻 Code Example

import fasttext
import fasttext.util
import numpy as np

# 1. 사전 학습된 한국어 모델 다운로드 및 로드
fasttext.util.download_model('ko', if_exists='ignore')  # 약 4.5GB
model = fasttext.load_model('cc.ko.300.bin')

# 단어 벡터 얻기
word_vector = model.get_word_vector("인공지능")
print(f"벡터 차원: {word_vector.shape}")  # (300,)

# 유사 단어 찾기
similar_words = model.get_nearest_neighbors("인공지능", k=5)
print("유사 단어:", similar_words)

# OOV 단어도 벡터 생성 가능 (FastText의 강점)
oov_vector = model.get_word_vector("인공지능개발자")
print("OOV 단어 벡터도 생성됨:", oov_vector[:5])

# 2. 텍스트 분류 모델 학습
# 학습 데이터 형식: __label__레이블 텍스트
# train.txt 예시:
# __label__positive 이 영화 정말 재미있어요
# __label__negative 시간 낭비였습니다

# 분류 모델 학습
classifier = fasttext.train_supervised(
    input='train.txt',
    epoch=25,
    lr=0.5,
    wordNgrams=2,  # bi-gram 사용
    dim=100,
    loss='softmax'
)

# 예측
prediction = classifier.predict("정말 좋은 제품이에요")
print(f"예측: {prediction}")  # (('__label__positive',), array([0.98]))

# 여러 문장 예측
texts = ["최악이에요", "추천합니다", "그냥 그래요"]
predictions = classifier.predict(texts)
print("배치 예측:", predictions)

# 모델 평가
result = classifier.test("test.txt")
print(f"정확도: {result[1]:.4f}")

# 3. 커스텀 임베딩 학습
# corpus.txt: 한 줄에 하나의 문장
custom_model = fasttext.train_unsupervised(
    input='corpus.txt',
    model='skipgram',  # 또는 'cbow'
    dim=100,
    minCount=5,
    minn=2,  # 최소 n-gram 길이
    maxn=5,  # 최대 n-gram 길이
    epoch=5
)

# 모델 저장
custom_model.save_model("my_fasttext.bin")

# 차원 축소 (메모리 절약)
fasttext.util.reduce_model(model, 100)  # 300 -> 100 차원

🗣️ Say It Like This in Practice

At an NLP project kickoff meeting

"We need to build the spam classifier quickly, so let's set a baseline with FastText first. Training takes 30 minutes on a CPU without a GPU, and if accuracy exceeds 90%, we deploy it for now and refine it with BERT later, which seems more efficient."

During a technical discussion with the data team

"I think using FastText embeddings for product search would be good. New product names keep being added, and since FastText is subword-based, it can create similar product vectors even for product names it hasn't been trained on. Even if 'iPhone15ProMax' isn't in the training data, it can build a vector from the 'iPhone', 'Pro', and 'Max' n-grams."

In an ML engineer interview

"FastText's advantage over Word2Vec is its OOV handling. When Word2Vec encounters a word it hasn't been trained on, it just lumps it into a UNK token, whereas FastText builds a meaningful vector from the sum of character n-gram vectors. It's especially effective for analyzing social media data with many typos and newly coined words."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

1
Morphological analysis is recommended for Korean

FastText operates on whitespace-based tokenization, so in Korean, an agglutinative language, "먹었다", "먹고", and "먹으면" are recognized as different words. Preprocessing with a morphological analyzer (Mecab, Komoran, etc.) splits them into forms like "먹+었+다", which improves semantic learning.

2
Watch the size of the pretrained model

The FastText pretrained model (cc.ko.300.bin) is quite large at about 4.5GB. Deploying it on a server requires at least 8GB of memory. Reduce the dimensions with fasttext.util.reduce_model(), or extract only the words you need from the .vec file (text format) and use those.

3
Training data format for classification models

When training in supervised mode, the label format must be "__label__labelname". Labels are separated by whitespace, so a label must not contain spaces. For multi-label classification, specify multiple labels in the format "__label__A __label__B text".

🔗 Related Terms

📚 Learn More