OPEN HYPER STEP
← 목록으로 (math)
MATH · 39 / 45
math
CHAPTER 39 / 45
읽기 약 2
FUNCTION

선형대수 종합: AI를 위한 기초


핵심 개념

모듈 5 종합 — 임베딩 → 벡터 검색 → 유사도 → 추천. AI 파이프라인의 수학적 흐름.

본문

모듈 5 핵심 개념 매핑

📋 코드 (5줄)
벡터    → 사용자 임베딩, 단어 임베딩, 위치
내적    → 코사인 유사도, 어텐션 점수
행렬    → 데이터 테이블, 가중치, 이미지
행렬곱  → 신경망 순전파, 변환 합성
변환    → 회전/크기/이동, CSS, 3D

AI 파이프라인의 수학

PYTHON📋 코드 (36줄)
import numpy as np

# 단계 1: 데이터 → 벡터 (임베딩)
def embed(text, dim=128):
    """가상 임베딩 — 실전은 OpenAI API 또는 sentence-transformers"""
    np.random.seed(hash(text) % (2**32))
    return np.random.randn(dim)


# 단계 2: 벡터 검색 — 코사인 유사도
def cos_sim(a, b):
    return (a @ b) / (np.linalg.norm(a) * np.linalg.norm(b))


# 단계 3: 추천 — 가장 유사한 N개
def recommend(query, candidates, top_n=3):
    q_vec = embed(query)
    scores = [
        (item, cos_sim(q_vec, embed(item)))
        for item in candidates
    ]
    return sorted(scores, key=lambda x: -x[1])[:top_n]


# 실전
docs = [
    "React 컴포넌트 가이드",
    "Vue 3 Composition API",
    "PostgreSQL 인덱스 최적화",
    "Next.js App Router 시작",
    "MongoDB 집계 파이프라인",
]

results = recommend("React 시작", docs)
for doc, score in results:
    print(f"{score:+.3f}  {doc}")

신경망 한 층 = 행렬 곱셈

PYTHON📋 코드 (29줄)
import numpy as np

# 입력 (배치 크기, 특성 수)
X = np.random.randn(32, 784)  # MNIST 28x28 이미지 32장

# 가중치
W1 = np.random.randn(784, 128) * 0.01  # 히든 1
b1 = np.zeros(128)
W2 = np.random.randn(128, 10) * 0.01   # 출력
b2 = np.zeros(10)


def softmax(x):
    e = np.exp(x - np.max(x, axis=1, keepdims=True))
    return e / e.sum(axis=1, keepdims=True)


def forward(X):
    Z1 = X @ W1 + b1
    A1 = np.maximum(0, Z1)  # ReLU
    Z2 = A1 @ W2 + b2
    return softmax(Z2)


probs = forward(X)
print(probs.shape)         # (32, 10) — 32장 각각 10클래스 확률
print(probs.sum(axis=1))   # 모두 1.0 (확률 합)
predictions = np.argmax(probs, axis=1)
print(predictions[:5])     # 첫 5장 예측 클래스

RAG 시스템 통합

PYTHON📋 코드 (35줄)
# 1. 문서 청크 → 임베딩 행렬
documents = [
    "Python은 동적 타입 언어",
    "Java는 정적 타입 + JVM",
    "Rust는 메모리 안전 + 성능",
    "Go는 동시성 + 간결",
]

# 가상 임베딩 (실전은 OpenAI ada-002 등)
def get_embeddings(texts, dim=384):
    return np.array([embed(t, dim) for t in texts])


doc_matrix = get_embeddings(documents)
print(doc_matrix.shape)  # (4, 384)


# 2. 쿼리 임베딩
query = "동시성 프로그래밍 언어"
q_vec = embed(query, dim=384)


# 3. 벡터 검색 — 행렬 곱셈으로 한 번에
def retrieve(query_vec, doc_matrix, top_k=2):
    # 모든 문서와의 코사인 유사도
    norms = np.linalg.norm(doc_matrix, axis=1) * np.linalg.norm(query_vec)
    similarities = (doc_matrix @ query_vec) / norms
    top_indices = np.argsort(-similarities)[:top_k]
    return top_indices, similarities[top_indices]


indices, scores = retrieve(q_vec, doc_matrix)
print(f"\n쿼리: {query}")
for i, score in zip(indices, scores):
    print(f"  {score:.3f}  {documents[i]}")

추천 시스템 협업 필터링

PYTHON📋 코드 (36줄)
import numpy as np

# 사용자-아이템 평점 행렬
# 행 = 사용자, 열 = 영화
ratings = np.array([
    [5, 4, 0, 1, 2],  # Alice
    [4, 5, 0, 0, 1],  # Bob
    [0, 0, 5, 4, 0],  # Charlie
    [1, 2, 4, 5, 5],  # Dave
])


# 사용자별 평균 (0은 미평가)
user_means = np.where(ratings > 0, ratings, np.nan)
user_means = np.nanmean(user_means, axis=1)

# 평균 빼기 (편향 제거)
ratings_centered = np.where(ratings > 0, ratings - user_means[:, None], 0)


# 사용자 간 코사인 유사도 — 행렬 한 번으로
def user_similarity(R):
    norms = np.linalg.norm(R, axis=1)
    norm_matrix = np.outer(norms, norms)
    norm_matrix[norm_matrix == 0] = 1  # 0 분모 방지
    return (R @ R.T) / norm_matrix


sim_matrix = user_similarity(ratings_centered)
print("사용자 유사도 행렬:")
print(np.round(sim_matrix, 2))


# Alice(0)과 가장 비슷한 사용자
similar_to_alice = np.argsort(-sim_matrix[0])[1:3]
print(f"\nAlice와 비슷한 사용자: {similar_to_alice}")

모듈 5 자가 진단

📋 코드 (6줄)
□ 벡터의 크기·방향 + numpy 연산
□ 내적 = 코사인 유사도 분자 + 직교/평행 판단
□ 행렬 + 데이터 테이블 + 전치
□ 행렬 곱셈 (m×n)·(n×p)=(m×p) + 신경망 순전파
□ 회전·크기·이동 변환 행렬 + 합성 비가환성
□ AI 파이프라인 (임베딩 → 검색 → 추천)의 수학적 흐름 이해

다음 모듈 (확률·통계)

CH.40~ "확률과 통계" — Z-test·베이즈·머신러닝 분류기.


AI 프롬프트
🤖 AI에게 잘 물어보는 법 — 모델·전략별 프롬프트
Claude

무료: Sonnet 4.6 / Pro $20/mo: Opus 4.6

내 AI 파이프라인을 임베딩 → 검색 →
추천 단계로 분석해서 각 단계의 수학을
시각화해줘.
ChatGPT

무료: GPT-5.5 / Plus $20/mo: GPT-5.5 Pro

한국 AI 스타트업의 RAG 시스템
사례 5개를 비교 분석해서 베스트 프랙티스를
알려줘.
Gemini

무료: 2.5 Flash / Pro $19.99/mo: 3.1 Pro

내 데이터로 사용자-아이템 행렬을 만들고
협업 필터링 추천 시스템을 구축해서
정확도를 측정해줘.
Grok

무료: Grok 4.1 / SuperGrok $30/mo

2026년 벡터 DB(Pinecone/pgvector/Weaviate)와
LLM 통합 트렌드를 솔직히 알려줘.

⭐ 이것만 기억하세요
선형대수 종합: AI를 위한 기초 이 3가지만 확실히 잡으세요
1.벡터·행렬·곱셈은 AI 파이프라인의 모든 단계 — 임베딩, 검색, 추천, 신경망 모두 같은 수학
2.신경망 한 층 = 행렬 곱셈 + 활성화 — GPU 가속이 필수인 이유의 본질
3.다음 모듈(CH.40~) 확률과 통계 — A/B 테스트와 머신러닝의 수학적 기반


공유하기
진행도 39 / 45