Files
2nd/10_Wiki/Topics/AI_and_ML/Latent-Semantic-Analysis-LSA.md
T
koriweb d8a80f6272 chore(wiki): dangling 링크 canonical 정규화 (768파일/1200건)
이름만 다른(표기 변형) [[위키링크]]를 대상 문서의 canonical 제목으로 치환해
끊겼던 1,200개 링크를 연결. 제목/파일명 정규화 일치만 적용하고 별칭 매칭은
과병합 위험으로 제외(애매성 가드). 원본은 _link_reconcile_backup/ 에 백업.
도구: Datacollect/scripts/link_reconcile_apply.mjs

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 12:24:15 +09:00

136 lines
4.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
id: wiki-2026-0508-latent-semantic-analysis-lsa
title: Latent Semantic Analysis (LSA)
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [LSA, LSI, Latent Semantic Indexing]
duplicate_of: none
source_trust_level: A
confidence_score: 0.85
verification_status: applied
tags: [nlp, ir, svd, tfidf, topic-modeling, embeddings]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack: { language: Python, framework: scikit-learn/gensim }
---
# Latent Semantic Analysis (LSA)
## 매 한 줄
> **"매 LSA = TF-IDF 행렬에 truncated SVD"**. term-document을 저차원 latent semantic 공간에 투영해 동의어/다의어 부분 해소.
## 매 핵심
### 매 수학
- A (m×n) = U Σ Vᵀ. truncated rank-k → A_k = U_k Σ_k V_kᵀ.
- 행 = term embedding, 열 = document embedding.
- Cosine similarity in k-dim space → semantic similarity.
### 매 절차
1. Tokenize, stopword/lemma
2. TF-IDF 행렬 구축
3. Truncated SVD (k=100~300)
4. 쿼리도 동일 공간 투영: q_k = qᵀ U_k Σ_k⁻¹
5. cosine으로 유사 문서 검색
### 매 강점/한계
- ✅ 작은 corpus, 빠름, 해석 가능
- ✅ 동의어 부분 처리 (synonymy)
- ❌ 다의어 약함 (polysemy): 한 단어 = 한 벡터
- ❌ 비음수성 X → 토픽 해석 어려움 (→ NMF, LDA)
- ❌ Out-of-vocabulary 학습 불가
- ❌ contextual 의미 X (→ BERT)
### 매 vs 동족
- **NMF**: 비음수, 해석 ↑
- **LDA**: 확률적 토픽 모델
- **word2vec/GloVe**: 단어 단위 dense embedding
- **BERT/SBERT**: contextual, SoTA
## 💻 패턴
### scikit-learn LSA
```python
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import Normalizer
vec = TfidfVectorizer(stop_words="english", max_df=0.95, min_df=2)
svd = TruncatedSVD(n_components=200, random_state=0)
lsa = make_pipeline(vec, svd, Normalizer(copy=False))
doc_emb = lsa.fit_transform(corpus) # (n_docs, 200)
```
### Query → semantic search
```python
import numpy as np
q_emb = lsa.transform(["machine learning algorithms"])
sims = doc_emb @ q_emb.T # already L2-normed
top = np.argsort(-sims.ravel())[:10]
```
### gensim LSI
```python
from gensim import corpora, models
dictionary = corpora.Dictionary(tokenized_docs)
bow = [dictionary.doc2bow(d) for d in tokenized_docs]
tfidf = models.TfidfModel(bow)
lsi = models.LsiModel(tfidf[bow], id2word=dictionary, num_topics=200)
print(lsi.print_topics(5)) # 토픽별 top words
```
### Topic 해석
```python
terms = vec.get_feature_names_out()
for i, comp in enumerate(svd.components_[:5]):
top_terms = [terms[j] for j in comp.argsort()[-10:][::-1]]
print(f"Topic {i}: {top_terms}")
```
### Modern: BERT 대체
```python
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
doc_emb = model.encode(corpus, normalize_embeddings=True)
# 문맥 의미 반영, OOV 자유. LSA 대비 SoTA.
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 빠른 baseline, 적은 자원 | LSA |
| 해석 가능 토픽 | NMF, LDA |
| 단어 의미 (sparse 분포) | word2vec/GloVe |
| Production semantic search | SBERT + FAISS |
| 도메인 한정 corpus | LSA fine-tune or domain SBERT |
**기본값**: 신규 시스템은 SBERT. LSA는 baseline / 교육용 / 자원 제약.
## 🔗 Graph
- 부모: [[Information Retrieval]], [[NLP]], [[Dimensionality-Reduction]]
- 변형: [[LDA]], [[PCA]]
- 응용: [[Semantic Search|Semantic-Search]]
- Adjacent: [[TF-IDF]], [[Word-Embeddings]], [[SVD]]
## 🤖 LLM 활용
**언제**: 빠른 baseline 구현, SVD 직관 설명.
**언제 X**: 현대 production 시스템 — SBERT/LLM embedding이 대부분 우수.
## ❌ 안티패턴
- 매우 큰 corpus에 dense SVD (메모리) — truncated/randomized 사용
- TF-IDF 없이 raw count → 빈도 단어 dominate
- k 너무 작거나 큼 (k=50~300, perplexity/downstream으로 튜닝)
- BERT 시대에 LSA 단독 production
- Query 정규화/stopword 학습과 다름
## 🧪 검증 / 중복
- Verified (Deerwester 1990 LSI, scikit-learn/gensim docs). 신뢰도 A.
- 중복: 없음.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — 매 prefix, BERT 대체 비교 추가 |