Skip to main content

9 posts tagged with "ai"

View All Tags

Agentic SDLC

· One min read

Agentic SDLC

  • Agentic Software Development Life Cycle (SDLC) is an approach that integrates autonomous agents into the software development process.
  • This method decreases human intervention by allowing AI agents to handle various stages of development, from requirements gathering to deployment and maintainance.
  • It reduces the cycle time for SW development. Traditional SDLC takes weeks-to-months, while Agentic SDLC can potentially reduce this to days or even hours.

Cycles

Key differences

AspectTraditional SDLCAgentic SDLC
Cycle TimeWeeks to MonthsDays to Hours
FlowLinear, SequentialFluid, Iterative
Human InvolvementHuman codes everythingHuman guides, agent executes
DocumentationDocs as afterthoughtAuto-generated inline docs
TestingManual testingAutomated agent testing
Incident ResponseManual Incident handlingAgent-assisted remediation

Ref

GCN, Graph Convolutional Networks

· 7 min read

개념

GCN (Graph Convolutional Networks) 은 그래프 구조 데이터에서 노드(Node)와 엣지(Edge) 정보를 활용하여 특징(Feature)을 학습하는 딥러닝 모델임. 이미지 처리에 주로 사용되는 CNN(Convolutional Neural Networks)의 합성곱 연산을 그래프 데이터로 확장한 개념으로, 이웃 노드들의 정보를 집계(Aggregate)하여 현재 노드의 표현(Representation)을 업데이트하는 방식을 사용함.

Graph Concept

등장배경

  • 비유클리드 데이터 처리의 한계: 기존의 CNN은 이미지나 텍스트와 같이 격자(Grid) 구조를 가진 유클리드 데이터(Euclidean Data)에서 뛰어난 성능을 보였으나, 소셜 네트워크, 분자 구조, 웹 링크 등 불규칙한 관계를 가진 **비유클리드 데이터(Non-Euclidean Data)**를 처리하는 데에는 한계가 존재함.
  • 관계성 정보의 중요성: 데이터 자체의 속성뿐만 아니라 데이터 간의 **연결 관계(Structure)**가 중요한 정보를 담고 있는 경우가 많아, 이를 효과적으로 학습할 수 있는 모델이 필요해짐.

유형

  • Node Classification: 노드의 속성이나 레이블을 예측하는 작업
  • Graph Classification: 그래프 전체의 속성이나 레이블을 예측하는 작업
  • Node Clustering: 노드들을 유사한 특성을 가진 그룹으로 묶는 작업
  • Link Prediction: 그래프 내에서 존재하지 않는 엣지를 예측하는 작업
  • Influence Maximization: 그래프 내에서 영향력을 극대화할 수 있는 노드를 찾는 작업

구성도

GCN은 기본적으로 입력된 그래프 데이터에 대해 여러 번의 그래프 합성곱 연산(Graph Convolution)과 활성화 함수(Activation Function)를 거쳐 최종적으로 노드 분류나 링크 예측 등의 작업을 수행함.

  1. Input Layer: 노드의 특징 행렬(XX)과 인접 행렬(AA)을 입력받음.
  2. Hidden Layers (Graph Convolution): 각 노드는 이웃 노드의 정보를 모아 자신의 정보를 갱신함. (Message Passing)
  3. Activation Function: 비선형성(Non-linearity)을 추가하기 위해 ReLU 등을 사용함.
  4. Output Layer: 최종적으로 학습된 노드 임베딩을 사용하여 분류(Classification)나 회귀(Regression) 등의 태스크를 수행함.

GCN의 유형

GCN은 접근 방식에 따라 크게 두 가지 유형으로 분류됨.

  1. 스펙트럼 기반 (Spectral-based GCNs)

    • 그래프 신호 처리 이론에 기반하여, 그래프 라플라시안(Graph Laplacian)과 푸리에 변환(Fourier Transform)을 이용해 스펙트럼 도메인에서 합성곱을 수행함.
    • 특징: 이론적 토대가 탄탄하지만, 그래프 전체 구조에 의존적이어서 구조가 바뀌면 재학습이 필요하며 계산 복잡도가 높음.
    • 대표 모델: ChebNet (Chebyshev 다항식 근사), GCN (Kipf & Welling의 1차 근사).
  2. 공간 기반 (Spatial-based GCNs)

    • 노드의 공간적 이웃 관계를 기반으로 정보를 직접 집계(Aggregation)하는 방식. CNN 필터가 픽셀 위를 이동하는 것과 유사함.
    • 특징: 직관적이며 계산 효율성이 높고, 거대 그래프나 유동적인 그래프에도 적용하기 용이함.
    • 대표 모델: GraphSAGE (이웃 샘플링), GAT (Attention 가중치).

구성요소

구성요소설명역할
Node (Vertex)그래프의 각 점 (데이터 개체)데이터의 주체, 특징(XX) 보유
Edge (Link)노드 간의 연결 선데이터 간의 관계 및 상호작용 정보 제공
Adjacency Matrix (AA)노드 간 연결 정보를 담은 행렬그래프의 구조적 정보를 수학적으로 표현
Node Feature Matrix (XX)각 노드의 속성 벡터를 모은 행렬노드 자체의 고유 정보 입력
Degree Matrix (DD)각 노드의 연결 수(차수)를 나타내는 대각 행렬연산 시 정보의 크기를 정규화(Normalize)하는 데 사용
Weight Matrix (WW)학습 가능한 파라미터 행렬입력 특징을 변환하고 중요도 학습
Aggregation Function이웃 노드의 정보를 합치는 함수이웃 정보의 평균(Mean)이나 합(Sum) 등을 계산

작동 원리

GCN의 핵심 작동 원리는 메시지 패싱(Message Passing) 으로, 이웃 노드의 정보를 수집하고 가중치를 적용하여 자신의 상태를 업데이트하는 과정임.

1. 수학적 정의

가장 널리 쓰이는 Kipf & Welling의 GCN 레이어 갱신 규칙은 다음과 같음.

H(l+1)=σ(A~H(l)W(l))H^{(l+1)} = \sigma(\tilde{A}H^{(l)}W^{(l)})
  • H(l)H^{(l)}: ll번째 층의 노드 특징 행렬 (N×DN \times D).
  • A~\tilde{A}: 정규화된 인접 행렬 (Normalized Adjacency Matrix).
    • 보통 A~=D12A^D12\tilde{A} = D^{-\frac{1}{2}}\hat{A}D^{-\frac{1}{2}}로 정의 (A^=A+I\hat{A} = A + I, II는 자기 자신을 포함하기 위한 단위 행렬).
  • W(l)W^{(l)}: 학습 가능한 가중치 행렬 (D×FD \times F).
  • σ\sigma: 활성화 함수 (ReLU 등).

2. 정규화

단순히 인접 행렬 AA를 곱하면 연결이 많은 노드(Hub)의 값이 폭발적으로 커지거나, 적은 노드는 소실될 수 있음. 이를 방지하기 위해 차수(Degree) DD를 이용해 정규화(D12AD12D^{-\frac{1}{2}}AD^{-\frac{1}{2}})를 수행하여 수치적 안정성을 확보함.

3. 구현 예시

import numpy as np

def graph_convolutional_layer(A, X, W):
# A: Adjacency matrix, X: Input features, W: Weights

# 1. Self-loop 추가 (자기 자신의 정보도 포함하기 위함)
I = np.eye(A.shape[0])
A_hat = A + I

# 2. 차수 행렬 계산 및 정규화 (Normalization)
D = np.sum(A_hat, axis=0)
D_inv_sqrt = np.power(D, -0.5)
D_inv_sqrt[np.isinf(D_inv_sqrt)] = 0.
D_mat_inv_sqrt = np.diag(D_inv_sqrt)

# A_norm = D^-0.5 * A_hat * D^-0.5
A_norm = np.dot(np.dot(D_mat_inv_sqrt, A_hat), D_mat_inv_sqrt)

# 3. 집계 및 변환 (Aggregation & Transformation)
output = np.dot(A_norm, X) # 이웃 정보 집계
output = np.dot(output, W) # 가중치 변환

return output

CNN과의 비교

비교 항목CNN (Convolutional Neural Networks)GCN (Graph Convolutional Networks)
주요 데이터이미지, 텍스트 (유클리드 데이터, Grid)소셜 네트워크, 분자 구조 (비유클리드 데이터, Graph)
이웃 구조고정된 크기와 순서 (상, 하, 좌, 우 픽셀)가변적인 크기와 순서 없음 (연결된 모든 노드)
합성곱 연산필터(Kernel)가 윈도우를 슬라이딩하며 연산이웃 노드의 정보를 집계(Aggregate)하여 연산
불변성 (Invariance)이동 불변성: 대상이 이동해도 인식 가능순열 불변성: 노드 순서가 바뀌어도 결과는 동일해야 함
주요 목적지역적 특징(Local Feature) 추출관계성 및 구조적 특징(Structural Feature) 학습

주요 변형 모델 (Variants)

  • GraphSAGE: 모든 이웃을 사용하는 GCN의 계산 비용 문제를 해결하기 위해, 고정된 수의 이웃을 **샘플링(Sampling)**하여 집계함.
  • GAT (Graph Attention Networks): 모든 이웃에 동일한 중요도를 부여하는 대신, 어텐션(Attention) 메커니즘을 적용하여 더 중요한 이웃의 정보에 높은 가중치를 부여함.
  • ChebNet: 스펙트럼 기반 방식을 효율화하기 위해 Chebyshev 다항식을 사용하여 필터를 근사함.
  • GIN (Graph Isomorphism Network): 그래프 동형성(Isomorphism)을 구분할 수 있을 정도로 강력한 표현력을 갖도록 설계됨.

장단점

구분내용
장점- 비정형 데이터 처리: 이미지/텍스트 외의 복잡한 연결 관계 데이터 처리에 탁월.
- 관계 학습: 개체 간의 상호작용과 구조적 정보를 효과적으로 포착.
- 성과: 추천 시스템, 신약 개발 등 다양한 분야에서 SOTA(State-of-the-Art) 성능 달성.
단점- Oversmoothing: 층이 깊어질수록 노드 간의 정보가 섞여 구분이 어려워지는 현상.
- 확장성(Scalability): 거대 그래프의 경우 전체 인접 행렬을 메모리에 올리기 어려움 (GraphSAGE 등으로 해결 시도).
- 동적 그래프: 실시간으로 변하는 그래프 구조를 반영하기 까다로움.

활용방안

  • 소셜 네트워크 분석 (Social Network Analysis): 친구 추천(Facebook), 커뮤니티 탐지, 가짜 뉴스 전파 경로 분석.
  • 생물정보학 및 화학 (Bioinformatics & Chemistry): 신약 개발을 위한 분자 구조 분석(Drug Discovery), 단백질 상호작용 예측.
  • 추천 시스템 (Recommender Systems): 사용자(User)와 아이템(Item) 간의 상호작용 그래프를 분석하여 정교한 추천 제공 (Pinterest 등).
  • 지식 그래프 (Knowledge Graph): 개체 간의 복잡한 관계를 추론하고 질의응답 시스템 고도화(Google).
  • 컴퓨터 비전 (Computer Vision): 이미지 내 객체 간의 관계를 그래프로 모델링하여 장면(Scene) 이해.

최근 연구 동향

  1. GNN과 LLM의 융합 (GNN-LLM Convergence): GCN 모델 자체의 개선을 넘어, GraphRAG와 같이 지식 그래프를 인코딩하여 LLM의 추론을 돕거나 상호보완하는 연구가 주류를 이룸.
  2. 그래프 파운데이션 모델 (Graph Foundation Models): 특정 태스크에 국한되지 않고, 다양한 그래프 데이터에 범용적으로 적용 가능한 대규모 사전 학습 모델(Pre-trained Models) 개발이 가속화됨.
  3. Graph Transformers: 기존 메시지 패싱(Message Passing) 방식의 한계를 넘어서기 위해, 트랜스포머(Transformer) 아키텍처를 그래프 도메인에 최적화하여 적용하는 연구 활발.
  4. 생성형 GNN (Generative GNNs): 신약 개발이나 소재 설계 등에서 원하는 속성을 가진 새로운 그래프 구조를 생성하는 확산 모델(Diffusion Models) 기반 연구 증가.
  5. 설명 가능성 및 신뢰성 (Explainability & Trustworthiness): 금융이나 의료 등 민감한 분야의 도입 확대로 인해, 모델의 예측 근거를 제시하고 견고성(Robustness)을 확보하는 기술이 필수적임.

Ref

Conditional GAN Review

· 4 min read

1. Problem Statement

Modeling tabular data poses unique challenges for GANs, which existing statistical and deep neural network models fail to address properly:

  • Mixed Data Types: Tabular data contains a mix of discrete and continuous columns.
  • Non-Gaussian & Multimodal Distributions: Continuous columns often have multiple modes (peaks) and do not follow a simple Gaussian distribution.
  • Imbalanced Discrete Columns: Categorical columns are often heavily imbalanced (e.g., 90% 'Normal', 10% 'Fraud'), leading to mode collapse where minor categories are ignored.

2. Methodology

To address these challenges, the authors propose CTGAN, which introduces Mode-specific Normalization, a Conditional Generator, and a Training-by-Sampling strategy.

A. Mode-Specific Normalization

  • Challenge: Representing continuous values with arbitrary, non-Gaussian distributions is non-trivial. Simple Min-Max normalization to [-1, 1] fails on multimodal data.

  • Solution: Treat each continuous column CiC_i independently using a Variational Gaussian Mixture Model (VGM).

    1. Estimate the number of modes mim_i and fit a Gaussian mixture.

    2. Represent each value as a concatenation of:

      • One-hot vector (β\beta): Indicates which mode the value belongs to.
      • Scalar (α\alpha): Represents the normalized value within that mode.

B. Conditional Generator and Training-by-Sampling

  • Challenge: Random sampling during training neglects minor categories in imbalanced columns, causing the generator to fail in learning them.
  • Solution: Condition the generator to produce specific discrete values.
    • Conditional Vector: defined as cond=m1...mNdcond = m_1 \oplus ... \oplus m_{N_d}.

      • Example: For columns D1={1,2,3}D_1=\{1,2,3\} and D2={1,2}D_2=\{1,2\}, the condition (D2=1)(D_2=1) is represented as mask vectors m1=[0,0,0]m_1=[0,0,0] (ignored) and m2=[1,0]m_2=[1,0] (selected).
    • Generator Loss: Penalize the generator if it fails to produce the requested condition. This is done by adding the cross-entropy between the input mask mim_{i^*} and the generated output d^i\hat{d}_{i^*} to the loss.

    • Training-by-Sampling (Curriculum):

      1. Create zero-filled mask vectors.
      2. Randomly select a discrete column DiD_i.
      3. Construct a PMF based on the log-frequency of values in that column (giving minor classes a higher chance).
      4. Sample a value kk^* based on this PMF and set the mask bit to 1.
      5. This ensures the model evenly explores all possible discrete values, not just the majority classes.

CTGAN Model

C. Network Structure (CTGAN)

  • Architecture: Two fully-connected hidden layers for both Generator and Critic.
    • Generator: Batch Normalization + ReLU.
    • Critic: Dropout + Leaky ReLU.
  • Optimization: WGAN loss with gradient penalty + Adam optimizer (lr=2104lr=2 \cdot 10^{-4}).

Generator Flow:

h0 = z ⊕ cond
h1 = h0 ⊕ ReLU(BN(FC_256(h0)))
h2 = h1 ⊕ ReLU(BN(FC_256(h1)))
α_hat = tanh(FC(h2)) # Continuous scalar
β_hat = gumbel_0.2(FC(h2)) # Continuous mode (one-hot)
d_hat = gumbel_0.2(FC(h2)) # Discrete value (one-hot)

Critic Flow:

h0 = r1 ⊕ ... ⊕ r10 ⊕ cond1 ⊕ ... ⊕ cond10
h1 = drop(leaky_0.2(FC_256(h0)))
h2 = drop(leaky_0.2(FC_256(h1)))
Score = FC_1(h2)

D. TVAE (Tabular Variational AutoEncoder)

The authors also propose TVAE as a robust baseline for comparison.

  • Uses two networks to model pθ(rjzj)p_\theta(r_j|z_j) and qϕ(zjrj)q_\phi(z_j|r_j).
  • Optimized using Evidence Lower-Bound (ELBO) loss.
  • Treats continuous variables (α\alpha) as Gaussian and discrete variables (β,d\beta, d) using softmax.

3. Evaluation & Benchmarks

Evaluation Metrics

  1. Likelihood Fitness (Simulated Data):

    • Uses a known Oracle SS (Gaussian Mixture or Bayesian Network).
    • Lsyn\mathcal{L}_{syn}: Likelihood of synthetic data on original Oracle SS. (Prone to overfitting).
    • Ltest\mathcal{L}_{test}: Train a new Oracle SS' using synthetic data TsynT_{syn}, then compute likelihood of real test data TtestT_{test} on SS'. (Detects mode collapse).
  2. Machine Learning Efficacy (Real Data):

    • Train classifiers/regressors on Synthetic Data (TsynT_{syn}).
    • Test them on Real Test Data (TtestT_{test}).
    • Metrics: Accuracy, F1-Score (Classification), R2R^2 (Regression).

Benchmarks

  • Baselines: 2 Bayesian Networks (CLBN, PrivBN) + 3 Deep Learning methods (MedGAN, VeeGAN, TableGAN).
  • Simulated Datasets: Grid, GridR (Grid + Offset), Ring (GMM Oracles), and Bayesian Networks (Alarm, Child, Asia, Insurance).
  • Real Datasets: 6 UCI datasets (Adult, Census, etc.), Credit (Kaggle), MNIST28.

4. Outcomes & Conclusion

  • Performance: CTGAN outperforms all deep learning methods and surpasses Bayesian networks on 87.5% of datasets.
  • TVAE vs CTGAN: TVAE is highly competitive and outperforms CTGAN in several cases. However, CTGAN is preferred for privacy applications (easier to implement Differential Privacy) since the generator doesn't access real data during inference.
  • Key Contributions:
    • Mode-specific normalization solves the non-Gaussian/multimodal distribution issue.
    • Conditional Generator & Training-by-sampling effectively solve the imbalanced data issue.

Ref

  • Xu, L., Skoularidou, M., Cuesta-Infante, A., & Veeramachaneni, K. (2019). Modeling tabular data using conditional gan. Advances in neural information processing systems, 32.

AI Engineering

· One min read

AI Application Categories

LLM Adoption by Use Case

  1. Text Summarization: 62%
  2. Internal Knowledge Management: 60%
  3. Customer Service: 59%
  4. Marketing Copy: 53%
  5. Software Development: 53%
  6. Contract Review: 45%
  7. External Chatbots: 39%
  8. Recommendation Algorithms: 39%

Developing ML Systems

· 5 min read

Problem formulation (문제 정의)

  • The first step is to figure out what problem you want to solve.
    1. “사용자에게 어떤 문제를 해결해주고 싶은가?” → 모호하지 않고 구체적으로 정의해야 함.
    2. “그 문제 중 어떤 부분을 머신러닝으로 풀 수 있는가?” → 예: 사진을 라벨로 매핑하는 함수 학습.
  • 이를 구체화하려면 ML 컴포넌트에 대해 loss function 을 지정해야 한다.
  • 문제를 쪼개보면 일부는 전통적 SW 엔지니어링으로 해결 가능하고, 일부만 ML로 다뤄야 할 수 있다.
  • 학습 유형은 지도·비지도·강화·준지도(semisupervised)까지 연속선상에 있음.
    • Semisupervised learning: 일부 라벨만 활용해 비라벨 데이터에서 더 많은 정보 추출.
    • Weakly supervised learning: 부정확·노이즈 라벨을 사용.
  • 결론: Noise와 label 부족은 “지도 ↔ 비지도” 사이의 연속체를 형성한다.

Data collection & management (데이터 수집/관리)

  • 데이터는 직접 제작, 크라우드소싱, 사용자 행동에서 수집 가능.
  • 부족할 때는 transfer learning 활용.
  • Privacy 검토와 동의, 공정성, federated learning 등 고려 필요.
  • Data provenance(출처 관리): 데이터 정의, 값의 범위, 생성 주체, 중단 여부, 정의 변경 이력 등 추적 → 파이프라인 안정성이 알고리즘보다 중요.
  • 항상 자문: “이 데이터는 내 문제를 풀기에 적절한가? 입력과 출력 모두 충분히 담고 있는가?”
  • Learning curve 로 데이터 확장 효과/학습 plateau 확인.
  • 방어적 태도 필요: 입력 오류, 누락, 적대적 사용자, 철자 불일치 등 처리.
  • Data augmentation (회전, 이동, 노이즈 추가 등)으로 모델 강건성 향상.
  • 불균형 데이터는 undersampling, oversampling, SMOTE/ADASYN, boosting 등으로 완화.
  • 아웃라이어는 로그 변환 등으로 영향 축소, 트리 모델은 상대적으로 강건.

Feature engineering (특징 엔지니어링)

  • Quantization: 연속값을 구간(bin)으로 강제.
  • One-hot encoding: 범주형 속성을 다중 Boolean으로 변환.
  • 도메인 지식 기반 새 특성 추가 (예: 날짜 → 주말/공휴일 여부).
  • “At the end of the day, some ML projects succeed and some fail… the most important factor is the features used.” (Pedro Domingos)

Exploratory data analysis (EDA) & visualization

  • 목표: 예측/검증이 아닌 데이터 이해.
  • Histograms, scatter plots 로 분포/결측/오류/이상치 확인.
  • 클러스터링 → 프로토타입 시각화, 이상치 탐지 (“고양이 vs 사자 옷 입은 고양이”).
  • 차원 축소 (예: t-SNE)로 고차 데이터를 2D/3D로 시각화.

Model selection & training

  • 데이터가 정리되면 모델 구축 단계.
  • Random forests → 범주형 특징 많고 일부 무관할 때.
  • Nonparametric methods → 데이터 많고 지식 부족, 특징 선택 고민 줄이고 싶을 때.
  • Logistic regression → 선형 분리 가능(또는 feature engineering 후).
  • SVM → 데이터 크기 작고 차원 높을 때.
  • Deep neural nets → 패턴 인식(이미지·음성).
  • 하이퍼파라미터는 경험 + 탐색으로 조율.
  • 검증 데이터 남용 시 validation overfitting 위험 → 여러 검증셋 필요.
  • 성능 평가: ROC curve, AUC, confusion matrix.
  • 중요한 건 아이디어–실험–검증 반복 사이클을 빠르게 하는 것.

Trust, interpretability, explainability

  • 단순히 지표 성능만으로는 신뢰 부족 → 규제·언론·사용자도 신뢰성 원함.
  • Accountability: 오류 발생 시 책임 주체와 항소 절차 필요.
  • Interpretability: 모델 내부를 직접 이해 (트리, 선형회귀).
    • 핵심 질문: “If I change x, how will the output change?”
  • Explainability: 블랙박스 모델 + 별도 모듈로 설명 (예: LIME).
  • 단순 설명이 잘못된 확신을 줄 수 있음. → 테스트와 실제 성능이 더 큰 신뢰를 준다.
  • “안전하다고 설명만 있는 실험기 vs 100회 무사비행한 비행기” 비유.

Operation, monitoring, maintenance

  • 운영 단계에서는 롱테일 입력(long tail) 문제 등장 → 예상 못한 입력 지속 발생. → 실시간 모니터링과 사람 평가자 필요.
  • Nonstationarity: 세상과 사용자 행동 변화 → 최신 데이터 vs 안정적 모델 트레이드오프.
  • 신선도 요구 다름: 어떤 문제는 매일/매시간 새 모델, 어떤 문제는 수개월 동일 모델.
  • 배포 자동화 → 작은 변경은 자동 승인, 큰 변경은 리뷰.
  • Online vs Offline model: 기존 모델 점진적 수정 vs 매번 처음부터 재학습.
  • 데이터 자체가 바뀔 수도 있음 (스팸 이메일 → 스팸 문자, 음성, 영상 등).

Checklist

Tests for Features and Data

  • Feature expectations are captured in a schema.
  • All features are beneficial.
  • No feature’s cost is too much.
  • Features adhere to meta-level requirements.
  • The data pipeline has appropriate privacy controls.
  • New features can be added quickly.
  • All input feature code is tested.

Tests for Model Development

  • Every model specification undergoes a code review.
  • Every model is checked in to a repository.
  • Offline proxy metrics correlate with actual metrics.
  • All hyperparameters have been tuned.
  • The impact of model staleness is known.
  • A simpler model is not better.
  • Model quality is sufficient on all important data slices.
  • The model has been tested for considerations of inclusion.

Tests for Machine Learning Infrastructure

  • Training is reproducible.
  • Model specification code is unit tested.
  • The full ML pipeline is integration tested.
  • Model quality is validated before attempting to serve it.
  • The model allows debugging by observing the step-by-step computation of training or inference on a single example.
  • Models are tested via a canary process before they enter production serving environments.
  • Models can be quickly and safely rolled back to a previous serving version.

Monitoring Tests for Machine Learning

  • Dependency changes result in notification.
  • Data invariants hold in training and serving inputs.
  • Training and serving features compute the same values.
  • Models are not too stale.
  • The model is numerically stable.
  • The model has not experienced regressions in training speed, serving latency, throughput, or RAM usage.
  • The model has not experienced a regression in prediction quality on served data.

Ref

  • Breck, E., Cai, S., Nielsen, E., Salib, M., & Sculley, D. (2016). What’s your ML test score? A rubric for ML production systems. NIPS Workshop on Reliable Machine Learning in the Wild.

Nonparametric Models

· 2 min read

Nearest-neighbor Models

  • 쿼리점 xqx_q에 대해 가장 가까운 kk개의 이웃을 찾아 분류 또는 회귀에 사용한다.
    • 분류: 다수결
    • 회귀: 평균, 중앙값, 혹은 국소적 선형회귀
  • 거리 척도: Minkowski 거리
    • Lp(xj,xq)=(ixj,ixq,ip)1/pL_p(x_j, x_q) = \left( \sum_i |x_{j,i} - x_{q,i}|^p \right)^{1/p}
    • p=2p=2 → 유클리드 거리
    • p=1p=1 → 맨해튼 거리
    • 불리언 속성 → 해밍 거리
    • 공분산 고려 → 마할라노비스 거리
  • 차원의 저주 (curse of dimensionality):
    • 평균 이웃 부피: n=k/N        =(k/N)1/n\ell^n = k/N \;\;\Rightarrow\;\; \ell = (k/N)^{1/n}
    • nn이 커질수록 \ell 값이 커져 이웃이 “멀어진다”.
    • 대부분의 점은 고차원 공간에서 경계(껍질)에 몰린다.
    • 저차원: 보간(interpolation) 가능
    • 고차원: 외삽(extrapolation)이 많아져 일반화 어려움

k-d trees

  • 데이터를 차원별로 분할해 만든 이진 트리.
  • 각 노드에서 특정 차원의 중앙값 mm을 기준으로 ximx_i \le m 여부에 따라 좌/우로 분할한다.
  • 탐색: 쿼리점 기준으로 한쪽 브랜치로 내려가며 후보를 찾되, 경계와 가까우면 반대편 서브트리도 확인해야 한다.
  • 효율 조건: 데이터 수가 차원 수보다 훨씬 많아야 하며, 최소 2n2^n개 이상 필요하다.
  • 실용 범위:
    • 약 10차원 이하에서는 수천 개 데이터
    • 약 20차원 이하에서는 수백만 개 데이터

Support Vector Machines (SVM)

  • 최대 마진 분리자(maximum margin separator)를 찾는다.
  • 목표: 경험적 손실 최소화 대신 일반화 손실 최소화
  • 결정 경계: {x:wx+b=0}\{x : w \cdot x + b = 0\}
  • 학습은 이차계획법(QP) 최적화 문제로 정식화된다.
    • 이중 표현(dual form):
      argmaxαjαj12j,kαjαkyjyk(xjxk)\arg\max_\alpha \sum_j \alpha_j - \tfrac{1}{2} \sum_{j,k} \alpha_j \alpha_k y_j y_k (x_j \cdot x_k)
    • 제약조건: αj0,  jαjyj=0\alpha_j \ge 0,\; \sum_j \alpha_j y_j = 0
  • 최적 해에서 대부분 αj=0\alpha_j = 0이고, 경계 근처의 점들(서포트 벡터)만 αj>0\alpha_j > 0이다.
  • 예측 함수:
    h(x)=sign(jαjyj(xxj)b)h(x) = \text{sign}\Big(\sum_j \alpha_j y_j (x \cdot x_j) - b \Big)
  • 장점:
    • 서포트 벡터만 유지하면 되므로 효율적
    • 비모수적 유연성 + 모수적 안정성(과적합 억제)

The Kernel Trick

  • 커널 트릭: 실제 고차원 특징 공간 F(x)F(x)를 계산하지 않고, 내적만을 커널 함수로 대체한다.
    • K(x,z)=F(x)F(z)K(x,z) = F(x)\cdot F(z)
  • 대표 커널 함수:
    • 다항 커널: K(x,z)=(1+xz)dK(x,z) = (1 + x \cdot z)^d
    • 가우시안 커널 (RBF): K(x,z)=eγxz2K(x,z) = e^{-\gamma \|x-z\|^2}
  • 소프트 마진 분류기: 일부 오분류 허용, 오분류된 점을 올바른 쪽으로 이동시키는 거리만큼 패널티를 부여한다.
  • 커널 기법은 내적에만 의존하는 다른 알고리즘에도 적용 가능하다.
  • Mercer's theorem: “합리적인” 커널 함수는 항상 어떤 특징 공간에서의 내적에 해당한다.

Logistic regression

· 3 min read

단변량 선형 회귀 (Univariate Linear Regression)

  • 입력이 하나 xx인 경우, 가설: h(x)=w1x+w0h(x) = w_1x + w_0
  • 손실 함수: 제곱 오차 (Squared Error)
  • 경사 하강법으로 최적의 (w0,w1)(w_0, w_1) 찾기
    • w0w0+α(yh(x))w_0 \leftarrow w_0 + \alpha (y - h(x))
    • w1w1+α(yh(x))xw_1 \leftarrow w_1 + \alpha (y - h(x)) \cdot x
  • 손실 함수가 볼록(Convex) → 전역 최소값(Global Minimum) 보장

배치 / 확률적 경사 하강법 (Batch vs SGD)

  • 배치 경사 하강법(Batch GD): 모든 데이터 사용 → 정확하지만 느림, 대규모 데이터 비효율적
  • SGD(Stochastic GD): 무작위 예시 하나(또는 작은 minibatch)만으로 업데이트 → 빠르고 효율적
  • 미니배치(Minibatch): 속도 + 안정성 균형 가능
  • 학습률 α\alpha 감소 스케줄 → 수렴 보장

다변량 선형 회귀 (Multivariable Linear Regression)

  • 입력이 nn차원인 경우, 가설: h(x)=wx=iwixih(x) = w \cdot x = \sum_i w_i x_i
  • 정규 방정식 (Normal Equation): w=(XTX)1XTyw^* = (X^TX)^{-1}X^Ty
  • (XTX)1XT(X^TX)^{-1}X^T = 유사역행렬(Pseudoinverse)
  • 고차원에서는 과적합 위험이 크므로 정규화 필요

정규화 (Regularization)

  • 비용 함수: Cost(h)=Loss(h)+λComplexity(h)Cost(h) = Loss(h) + \lambda \cdot Complexity(h)
  • 복잡도 함수: Complexity(hw)=iwiqComplexity(h_w) = \sum_i |w_i|^q
  • q=1q = 1 → L1 정규화 (희소 모델, 많은 wi=0w_i = 0)
  • q=2q = 2 → L2 정규화 (가중치 제곱합 최소화)
  • L1 → 회전 불변성 없음 (축이 중요한 경우 적합)
  • L2 → 회전 불변성 있음 (축이 임의적일 때 적합)

퍼셉트론 학습 규칙 (Perceptron Learning Rule)

  • 선형 함수 + Hard Threshold → 선형 분류기
  • 가중치 업데이트: wiwi+α(yh(x))xiw_i \leftarrow w_i + \alpha (y - h(x)) \cdot x_i
  • 선형 분리 가능(linearly separable) → 완벽한 분리자로 수렴
  • 분리 불가능한 경우 → 수렴 보장 없음, α\alpha 스케줄 필요

로지스틱 회귀 (Logistic Regression)

  • Hard Threshold 문제
    • 불연속, 미분 불가능 → 학습 불안정
    • 항상 0 또는 1 확정 예측 → 경계 근처 비효율적
  • 해결책: 로지스틱 함수 g(z)=11+ezg(z) = \frac{1}{1 + e^{-z}}
  • 가설: hw(x)=g(wx)=11+ewxh_w(x) = g(w \cdot x) = \frac{1}{1 + e^{-w \cdot x}}
  • 출력 (0,1)\in (0,1) → 확률로 해석 가능, soft boundary 형성
  • 경계 중앙에서 0.5, 멀어질수록 0 또는 1에 가까움

로지스틱 함수의 도함수 성질

  • 로지스틱 함수: g(z)=11+ezg(z) = \frac{1}{1+e^{-z}}
  • 미분: g(z)=ez(1+ez)2g'(z) = \frac{e^{-z}}{(1+e^{-z})^2}
  • 1g(z)=ez1+ez1 - g(z) = \frac{e^{-z}}{1+e^{-z}}
  • 따라서 g(z)(1g(z))=ez(1+ez)2g(z)(1-g(z)) = \frac{e^{-z}}{(1+e^{-z})^2}
  • 결론: g(z)=g(z)(1g(z))g'(z) = g(z)(1-g(z))

로지스틱 회귀 가중치 업데이트 유도 과정

  • 손실 함수: Loss(w)=(yhw(x))2Loss(w) = (y - h_w(x))^2
  • wiLoss(w)=wi(yhw(x))2\frac{\partial}{\partial w_i} Loss(w) = \frac{\partial}{\partial w_i}(y - h_w(x))^2
  • =2(yhw(x))wi(yhw(x))= 2(y - h_w(x)) \cdot \frac{\partial}{\partial w_i}(y - h_w(x))
  • =2(yhw(x))wihw(x)= -2(y - h_w(x)) \cdot \frac{\partial}{\partial w_i} h_w(x)
  • hw(x)=g(wx)h_w(x) = g(w \cdot x) 이므로 wihw(x)=g(wx)xi\frac{\partial}{\partial w_i} h_w(x) = g'(w \cdot x) \cdot x_i
  • g(wx)=hw(x)(1hw(x))g'(w \cdot x) = h_w(x)(1-h_w(x))
  • 최종: wiLoss(w)=2(yhw(x))hw(x)(1hw(x))xi\frac{\partial}{\partial w_i} Loss(w) = -2(y - h_w(x)) \cdot h_w(x)(1-h_w(x)) \cdot x_i
  • 경사 하강법 업데이트:
    wiwiαwiLoss(w)w_i \leftarrow w_i - \alpha \cdot \frac{\partial}{\partial w_i} Loss(w)
  • 따라서:
    wiwi+α(yhw(x))hw(x)(1hw(x))xiw_i \leftarrow w_i + \alpha (y - h_w(x)) \cdot h_w(x)(1-h_w(x)) \cdot x_i

결론

  • 발전 흐름: 선형 회귀 → 경사 하강법 → 다변량 확장 → 정규화 → 퍼셉트론 → 로지스틱 회귀
  • L1 vs L2 정규화
    • L1: 희소 모델 (축 중요)
    • L2: 회전 불변 (축 임의적)
  • 퍼셉트론: 선형 분리 가능할 때만 완벽 동작
  • 로지스틱 회귀: soft boundary 제공 → 확률적 예측 + 현실 데이터에 강함

AI 에이전트와 환경

· 4 min read

에이전트와 환경의 상호작용

환경

  • Static environment: crossword puzzle
  • Semi-dynamic environment: Chess
  • Dynamic environment: self-driving car

AI의 역사

· 2 min read

A rational agent is one that acts so as to achieve the best outcome or, when there is uncertainty, the best expected outcome

The inception of artificial intelligence (1943–1956)

  • Warren McCulloch와 Walter Pitts (1943): 인공 신경망(artificial neuron model)을 제안.
  • Alan Turing (1950): "Computing Machinery and Intelligence" 논문에서 튜링 테스트(Turing Test)라는 개념을 제안.
  • John McCarthy, Marvin Minsky, Nathaniel Rochester, Claude Shannon이 1956년 Dartmouth workshop을 개최, 여기서 "artificial intelligence"라는 용어가 공식적으로 등장.
  • 주요 성과
    • Logic Theorist (Newell & Simon): 최초의 ‘논리 추론’ 프로그램.
    • General Problem Solver (GPS): 범용 문제 해결 시스템.

Early enthusiasm, great expectations (1952–1969)

  • AI 연구자들은 symbolic reasoning과 search를 이용해 문제를 해결하려 시도.
  • Perceptron(Rosenblatt, 1957): 초기 신경망 모델로, 패턴 인식에 사용.
  • 대표적인 시스템
    • Samuel의 체커 프로그램: 컴퓨터가 스스로 학습해서 체커를 둘 수 있도록 설계.
    • ELIZA: 자연어 처리를 흉내 낸 최초의 대화형 프로그램.

A dose of reality (1966–1973)

  • 자동 번역(Machine Translation)의 한계가 드러남: 1966년 ALPAC 보고서가 정부 자금 축소로 이어짐.
  • Perceptron의 한계(Minsky & Papert, 1969): XOR 문제 등, 단층 신경망으로는 복잡한 문제를 해결할 수 없다는 것을 증명.
  • 연구의 중심이 "toy domains"(작은 문제 영역)로 한정.

Expert systems (1969–1986)

  • Weak methods(약한 방법): 범용성은 있으나 복잡한 문제엔 비효율적.
  • Domain-specific knowledge(도메인 특화 지식): 전문가의 경험을 수천 개의 규칙으로 시스템에 구현.
  • DENDRAL: 질량 분석 데이터를 바탕으로 분자 구조를 추론하는 시스템. Knowledge-intensive system의 대표 사례.
  • MYCIN: 450여 개의 규칙로 혈액 감염을 진단. certainty factors(불확실성 계산) 개념 도입.
  • R1(XCON): Digital Equipment Corporation의 컴퓨터 시스템 주문을 자동으로 구성.
  • 이 시기 Expert system의 상업적 성공: 대기업들이 적극 도입.
  • Frame, Semantic Networks, Description Logics 등 다양한 representation and reasoning tools의 등장.
  • Prolog와 PLANNER와 같은 논리 프로그래밍 언어의 활용.
  • "Fifth Generation" project(일본, 1981): 병렬형 인공지능 컴퓨터 연구 대형 프로젝트(성공적 성과는 제한적).
  • 미국, 유럽도 대응 프로젝트 진행.

The return of neural networks and machine learning (1986–present)

  • Back-propagation 알고리즘이 재발견되며 심층 신경망(deep neural networks)의 부흥이 시작됨.
  • Big Data와 컴퓨팅 파워의 증가로 deep learning이 현실의 다양한 문제를 해결하는 데 쓰이기 시작.
  • 2010년대 Yann LeCun, Geoffrey Hinton, Yoshua Bengio 등이 딥러닝 혁신을 주도.