본문으로 건너뛰기
기술 노트 목록

TensorFlow Probability (확률적 프로그래밍)

AI/TensorFlow. 2024-12-13에 씀. 8분 분량

AI, TensorFlow

TensorFlow Probability (확률적 프로그래밍)

개요

TensorFlow Probability (TFP)는 TensorFlow 생태계 내에서 확률적 추론과 통계 분석을 수행하기 위한 라이브러리입니다. 다양한 확률 분포, 변환(bijectors), 확률적 레이어, 마르코프 연쇄 몬테카를로(MCMC) 및 변분 추론(VI)과 같은 추론 알고리즘을 제공하여, 머신러닝 모델에 불확실성을 통합하고 베이지안 접근 방식을 쉽게 구현할 수 있도록 지원합니다.

1. 주요 개념

  • 확률 분포 (Probability Distributions): 데이터의 확률적 특성을 모델링합니다. TFP는 정규 분포, 베르누이 분포, 포아송 분포 등 다양한 스칼라 및 다변량 분포를 제공합니다.
  • 변환 (Bijectors): 확률 분포를 다른 분포로 변환하는 가역적이고 미분 가능한 함수입니다. 복잡한 분포를 간단한 분포로부터 생성하는 데 사용됩니다 (예: TransformedDistribution).
  • 확률적 레이어 (Probabilistic Layers): 신경망에 확률적 요소를 도입합니다. 예를 들어, 가중치가 분포를 따르는 베이지안 신경망(BNN)을 구축하거나, 신경망의 출력이 특정 분포의 파라미터를 예측하도록 할 수 있습니다.
  • 마르코프 연쇄 몬테카를로 (MCMC): 사후 분포(posterior distribution)에서 샘플링하여 복잡한 확률 모델을 추론하는 알고리즘 클래스입니다. TFP는 해밀토니안 몬테카를로(HMC), No-U-Turn Sampler (NUTS) 등을 제공합니다.
  • 변분 추론 (Variational Inference, VI): 사후 분포를 더 간단하고 다루기 쉬운 분포(대리 사후 분포, surrogate posterior)로 근사하는 최적화 기반의 추론 방법입니다. 증거 하한(ELBO)을 최대화하는 방식으로 작동합니다.
  • 하드웨어 가속: TensorFlow를 기반으로 하므로 GPU 및 TPU 가속을 활용할 수 있습니다.

2. TFP 설치

pip install tensorflow-probability
# TensorFlow도 함께 설치되거나, 호환되는 버전이 이미 설치되어 있어야 합니다.

3. TFP의 주요 구성 요소 및 사용 예시

3.1. 확률 분포 (tfp.distributions 또는 tfd)

import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions

# 정규 분포 생성
normal_dist = tfd.Normal(loc=0., scale=1.) # 평균 0, 표준편차 1
# print(f"Normal distribution: {normal_dist}")

# 샘플링
# samples = normal_dist.sample(10)
# print(f"Samples from Normal: {samples.numpy()}")

# 로그 확률 계산
# log_prob_value = normal_dist.log_prob(0.5)
# print(f"Log probability of 0.5: {log_prob_value.numpy()}")

# 다변량 정규 분포 (하삼각 행렬을 사용한 공분산)
mvn_dist = tfd.MultivariateNormalTriL(
    loc=[0., 0.],
    scale_tril=[[1., 0.], [0.2, 0.8]] # 공분산의 Cholesky 분해 L (L L^T = Cov)
)
# print(f"\nMultivariate Normal distribution: {mvn_dist}")
# mvn_samples = mvn_dist.sample(5)
# print(f"Samples from MVN: \n{mvn_samples.numpy()}")
# mvn_log_prob = mvn_dist.log_prob([0.1, -0.1])
# print(f"Log probability of [0.1, -0.1]: {mvn_log_prob.numpy()}")

3.2. 변환 (tfp.bijectors 또는 tfb)

Bijector는 분포를 변환하여 새로운 분포를 만듭니다. tfd.TransformedDistribution과 함께 사용됩니다.

import tensorflow_probability.python.bijectors as tfb

# 기본 분포: 표준 정규 분포
base_distribution = tfd.Normal(loc=0., scale=1.)

# 변환: Exp Bijector (정규 분포 -> 로그-정규 분포)
exp_bijector = tfb.Exp()
log_normal_dist = tfd.TransformedDistribution(
    distribution=base_distribution,
    bijector=exp_bijector
)
# print(f"\nLog-Normal distribution (via Exp bijector): {log_normal_dist}")
# log_normal_samples = log_normal_dist.sample(5)
# print(f"Samples from Log-Normal: {log_normal_samples.numpy()}")

# 변환 체인: 여러 Bijector 결합
# 예: Affine 변환 (scale * X + shift) 후 Exp
affine_bijector = tfb.AffineScalar(shift=2., scale=3.)
chain_bijector = tfb.Chain([exp_bijector, affine_bijector]) # 적용 순서: affine -> exp
transformed_dist_chain = tfd.TransformedDistribution(
    distribution=base_distribution,
    bijector=chain_bijector
)
# print(f"\nTransformed distribution (Affine then Exp): {transformed_dist_chain}")
# chain_samples = transformed_dist_chain.sample(5)
# print(f"Samples from chained transformation: {chain_samples.numpy()}")

3.3. 확률적 레이어 (tfp.layers)

베이지안 신경망(BNN) 등을 구축하는 데 사용됩니다.

# DenseVariational 레이어: 가중치가 분포를 따르는 Dense 레이어
# 입력: 이전 레이어의 출력
# 출력: (일반적으로) 분포의 파라미터 (예: 정규 분포의 평균)
# 이 레이어는 KL 발산 항을 모델의 손실에 추가 (ELBO 계산 시 사용)
# model = tf.keras.Sequential([
#     tf.keras.layers.Dense(128, activation='relu', input_shape=(input_dim,)),
#     tfp.layers.DenseVariational(
#         units=num_classes, # 출력 유닛 수
#         make_prior_fn=tfp.layers.default_multivariate_normal_fn, # 가중치 사전 분포
#         make_posterior_fn=tfp.layers.default_mean_field_normal_fn(is_singular=False), # 가중치 사후 분포 (평균장 근사)
#         kl_weight=1/num_train_samples, # KL 발산 가중치 (학습 데이터 크기에 따라 조절)
#         activation='softmax' # 또는 None 후 DistributionLambda 사용
#     )
# ])

# DistributionLambda 레이어: 신경망의 출력을 특정 분포로 변환
# 예: 신경망이 정규 분포의 평균과 표준편차를 예측
# def normal_params_from_output(params):
#     loc = params[..., :num_classes]
#     scale = tf.math.softplus(params[..., num_classes:]) + 1e-6 # 양수 보장 및 안정성
#     return tfd.Normal(loc=loc, scale=scale)

# model_with_dist_lambda = tf.keras.Sequential([
#     tf.keras.layers.Dense(128, activation='relu', input_shape=(input_dim,)),
#     tf.keras.layers.Dense(num_classes * 2), # 평균과 표준편차를 위한 유닛
#     tfp.layers.DistributionLambda(make_distribution_fn=normal_params_from_output)
# ])

# 손실 함수 (예: 분포 출력 모델의 경우)
# def nll(y_true, y_pred_distribution):
#     return -y_pred_distribution.log_prob(y_true)
# model_with_dist_lambda.compile(optimizer='adam', loss=nll)

3.4. 마르코프 연쇄 몬테카를로 (MCMC) (tfp.mcmc)

사후 분포에서 샘플링합니다. 주로 베이지안 모델의 파라미터 추론에 사용됩니다.

# 목표 로그 확률 함수 정의 (예: 베이지안 선형 회귀의 사후 분포)
# def target_log_prob_fn(weights, bias, x_data, y_data):
#     # 사전 분포 정의
#     prior_weights = tfd.Normal(loc=0., scale=1.).log_prob(weights)
#     prior_bias = tfd.Normal(loc=0., scale=1.).log_prob(bias)
    
#     # 가능도 정의
#     predictions = tf.linalg.matvec(x_data, weights) + bias
#     likelihood = tfd.Normal(loc=predictions, scale=0.1).log_prob(y_data) # 데이터 노이즈 가정
    
#     return tf.reduce_sum(prior_weights) + tf.reduce_sum(prior_bias) + tf.reduce_sum(likelihood)

# # 초기 상태 설정
# initial_state = [
#     tf.random.normal([num_features], name='init_weights'),
#     tf.random.normal([], name='init_bias')
# ]

# # MCMC 커널 설정 (예: Hamiltonian Monte Carlo)
# num_burnin_steps = 500
# num_results = 1000

# hmc_kernel = tfp.mcmc.HamiltonianMonteCarlo(
#     target_log_prob_fn=lambda w, b: target_log_prob_fn(w, b, x_train_data, y_train_data),
#     step_size=0.01,
#     num_leapfrog_steps=3
# )
# # 적응형 스텝 크기 사용 (No U-Turn Sampler와 유사하게)
# adaptive_hmc = tfp.mcmc.SimpleStepSizeAdaptation(
#     inner_kernel=hmc_kernel,
#     num_adaptation_steps=int(num_burnin_steps * 0.8)
# )

# # MCMC 샘플링 실행
# @tf.function # 성능 향상을 위해 tf.function으로 컴파일
# def run_chain():
#     samples, kernel_results = tfp.mcmc.sample_chain(
#         num_results=num_results,
#         num_burnin_steps=num_burnin_steps,
#         current_state=initial_state,
#         kernel=adaptive_hmc,
#         trace_fn=lambda _, pkr: pkr.inner_results.is_accepted # 수용 여부 추적
#     )
#     return samples, kernel_results

# # samples_weights, samples_bias = run_chain()[0]
# # print(f"MCMC - Sampled weights shape: {samples_weights.shape}") # (num_results, num_features)
# # print(f"MCMC - Sampled bias shape: {samples_bias.shape}")     # (num_results,)

3.5. 변분 추론 (VI) (tfp.vi)

사후 분포를 근사합니다. 대규모 데이터셋에 MCMC보다 효율적일 수 있습니다.

# # 목표 로그 확률 함수 (위 MCMC 예시와 동일하거나 유사)
# # target_log_prob_fn = ...

# # 대리 사후 분포 정의 (예: 평균장 정규 분포)
# # 학습 가능한 변수들로 파라미터화
# surrogate_posterior = tfd.JointDistributionNamed(dict(
#     weights=tfd.Normal(loc=tf.Variable(tf.random.normal([num_features])),
#                        scale=tfp.util.TransformedVariable(tf.random.normal([num_features]), tfb.Softplus())),
#     bias=tfd.Normal(loc=tf.Variable(tf.random.normal([])),
#                     scale=tfp.util.TransformedVariable(tf.random.normal([]), tfb.Softplus()))
# ))

# # ELBO (Evidence Lower Bound) 손실 함수를 최소화하여 학습
# # losses = tfp.vi.fit_surrogate_posterior(
# #     target_log_prob_fn=lambda **params: target_log_prob_fn(**params, x_data=x_train_data, y_data=y_train_data),
# #     surrogate_posterior=surrogate_posterior,
# #     optimizer=tf.optimizers.Adam(learning_rate=0.01),
# #     num_steps=2000,
# #     sample_size=10 # 각 스텝에서 ELBO 추정을 위한 샘플 수
# # )

# # 학습 후, surrogate_posterior에서 파라미터 샘플링 가능
# # posterior_samples = surrogate_posterior.sample(1000)
# # print(f"VI - Sampled weights mean: {tf.reduce_mean(posterior_samples['weights'], axis=0).numpy()}")
# # print(f"VI - Sampled bias mean: {tf.reduce_mean(posterior_samples['bias'], axis=0).numpy()}")

4. TFP의 장점

  • TensorFlow 통합: TensorFlow의 자동 미분, 하드웨어 가속, Keras API, tf.data 파이프라인 등과 완벽하게 호환됩니다.
  • 유연성 및 확장성: 다양한 확률 모델과 추론 알고리즘을 조합하여 복잡한 모델을 구축할 수 있습니다.
  • 불확실성 정량화: 모델 예측의 불확실성을 측정하고 표현할 수 있어, 의사 결정에 중요한 정보를 제공합니다.
  • 베이지안 방법론 지원: 사전 지식을 모델에 통합하고, 데이터가 적을 때도 강건한 추론을 가능하게 합니다.
  • 활발한 커뮤니티 및 개발: 지속적으로 새로운 기능이 추가되고 개선되고 있습니다.

테스트 코드 (간단한 베이지안 선형 회귀 - VI 사용)

import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
tfd = tfp.distributions
tfb = tfp.bijectors

def test_tfp_bayesian_linear_regression_vi():
    print("=== TFP 베이지안 선형 회귀 (VI) 테스트 ===\n")

    # 1. 데이터 생성 (y = 2x + 1 + noise)
    true_w, true_b = 2.0, 1.0
    num_samples = 200
    x_train = np.random.uniform(-3., 3., size=num_samples).astype(np.float32)
    noise = np.random.normal(0., 0.5, size=num_samples).astype(np.float32)
    y_train = true_w * x_train + true_b + noise
    
    x_train_tf = tf.constant(x_train)
    y_train_tf = tf.constant(y_train)

    # 2. 모델 정의 (Root는 모든 파라미터의 결합 분포)
    Root = tfd.JointDistributionCoroutine.Root
    def model_fn():
        w = yield Root(tfd.Normal(loc=0., scale=1., name="w")) # 가중치 사전 분포
        b = yield Root(tfd.Normal(loc=0., scale=1., name="b")) # 편향 사전 분포
        noise_std = yield Root(tfd.HalfCauchy(loc=0., scale=1., name="noise_std")) # 노이즈 표준편차 사전 분포
        
        # 가능도
        y_model = yield tfd.Normal(loc=w * x_train_tf + b, scale=noise_std[..., tf.newaxis], name="y")
        # noise_std가 스칼라이므로, y_model의 scale에 맞게 브로드캐스팅되도록 newaxis 추가
    
    # 모델 인스턴스화
    linear_regression_model = tfd.JointDistributionCoroutine(model_fn)

    # 3. 목표 로그 확률 함수
    def target_log_prob(*params): # params: w, b, noise_std
        return linear_regression_model.log_prob(params + (y_train_tf,)) # 마지막 인자로 관측된 y 전달

    # 4. 대리 사후 분포 정의 (평균장 근사)
    # 각 파라미터에 대해 독립적인 정규 분포 가정
    # 변수 이름은 model_fn의 yield 이름과 일치해야 함
    surrogate_posterior = tfd.JointDistributionSequential([
        tfd.Normal( # w
            loc=tf.Variable(0., name='q_w_loc'),
            scale=tfp.util.TransformedVariable(1., tfb.Softplus(), name='q_w_scale')
        ),
        tfd.Normal( # b
            loc=tf.Variable(0., name='q_b_loc'),
            scale=tfp.util.TransformedVariable(1., tfb.Softplus(), name='q_b_scale')
        ),
        tfd.TransformedDistribution( # noise_std (양수여야 하므로 LogNormal 사용)
            distribution=tfd.Normal(
                loc=tf.Variable(0., name='q_noise_loc'),
                scale=tfp.util.TransformedVariable(1., tfb.Softplus(), name='q_noise_scale')
            ),
            bijector=tfb.Exp() # LogNormal = Exp(Normal)
        )
    ], name="surrogate_posterior")


    # 5. 변분 추론 실행
    optimizer = tf.optimizers.Adam(learning_rate=0.05)
    
    @tf.function # 성능 향상
    def run_vi():
        return tfp.vi.fit_surrogate_posterior(
            target_log_prob_fn=target_log_prob,
            surrogate_posterior=surrogate_posterior,
            optimizer=optimizer,
            num_steps=1000, # 반복 횟수
            sample_size=10, # ELBO 추정용 샘플 수
            seed=42
        )
    
    print("변분 추론 학습 시작...")
    losses = run_vi()
    print(f"변분 추론 학습 완료. 최종 ELBO 손실: {losses[-1]:.4f}")

    # 6. 결과 확인 (학습된 대리 사후 분포의 파라미터)
    # surrogate_posterior.model은 JointDistributionSequential의 구성 요소 리스트
    q_w, q_b, q_noise_std_lognormal = surrogate_posterior.model
    
    print(f"\n추정된 파라미터 (평균 ± 표준편차):")
    print(f"  w: {q_w.mean().numpy():.2f} ± {q_w.stddev().numpy():.2f} (실제: {true_w:.2f})")
    print(f"  b: {q_b.mean().numpy():.2f} ± {q_b.stddev().numpy():.2f} (실제: {true_b:.2f})")
    print(f"  noise_std: {q_noise_std_lognormal.mean().numpy():.2f} ± {q_noise_std_lognormal.stddev().numpy():.2f} (실제 데이터 생성 시 사용된 noise std: 0.5)")

    assert np.isclose(q_w.mean().numpy(), true_w, atol=0.5), "w 추정 오류"
    assert np.isclose(q_b.mean().numpy(), true_b, atol=0.5), "b 추정 오류"
    
    print("\nTensorFlow Probability VI 테스트 완료.")

if __name__ == "__main__":
    print(f"TensorFlow version: {tf.__version__}")
    print(f"TensorFlow Probability version: {tfp.__version__}")
    test_tfp_bayesian_linear_regression_vi()

5. 고려 사항 및 한계

  • 계산 비용: MCMC와 같은 일부 추론 알고리즘은 계산 비용이 매우 높을 수 있습니다. VI는 상대적으로 빠르지만 근사적인 결과를 제공합니다.
  • 모델 복잡성: 매우 복잡한 모델의 경우, 수렴 문제나 적절한 대리 사후 분포 설정의 어려움이 있을 수 있습니다.
  • 하이퍼파라미터 튜닝: MCMC의 스텝 크기, VI의 학습률 등은 신중하게 튜닝해야 합니다.
  • 확률적 프로그래밍의 학습 곡선: 베이지안 통계 및 확률 모델링에 대한 이해가 필요합니다.

다음 단계

다른 기술 노트 보기