[Keras] 내가 보려고 쓴 Probability Bayesian Neural Network(Probability BNN) 구현하기

2021. 11. 21. 19:35스터디/Python

- 이 글은 작성자가 이해한 바 대로 작성되어, 내용이 실제와 다를 수 있습니다.
- 이 글은 다음 사이트를 참조하여 작성되었습니다.

 

Keras documentation: Probabilistic Bayesian Neural Networks

Probabilistic Bayesian Neural Networks Author: Khalid Salama Date created: 2021/01/15 Last modified: 2021/01/15 Description: Building probabilistic Bayesian neural network models with TensorFlow Probability. View in Colab • GitHub source Introduction Tak

keras.io

- 제가 사용하기 편하게 정리한 코드는 다음에 있습니다.

 

GitHub - MIA-khm/basemodel: base models of machine learning algorithm

base models of machine learning algorithm. Contribute to MIA-khm/basemodel development by creating an account on GitHub.

github.com

- 다음 글은 이 글에 앞서 BNN의 구현을 이해하기 위해 작성한 글입니다.

 

[Keras] Bayesian Neural Network(BNN) 구현하기

- 이 글은 작성자가 이해한 바 대로 작성되어, 내용이 실제와 다를 수 있습니다. - 이 글은 다음 사이트를 참조하여 작성되었습니다. Keras documentation: Probabilistic Bayesian Neural Networks Probabilistic..

optilog.tistory.com


1. 모델의 입출력 값
Probability Bayesian Neural Network(이하 PBNN)은 BNN과 같이 일반적인 인공신경망 모델과 동일한 입력값을 갖는다.
이에 반해 출력값은 정규분포의 하이퍼 파라미터인 mean값과 std이 출력되게 된다.

2. 코드 해석
(1) Negative log likelihood

def negative_loglikelihood(targets, estimated_distribution):
    return -estimated_distribution.log_prob(targets)

negative log likelihood는 PBNN에서 loss function으로 활용되는 함수이다.
보다 자세한 설명은 ratsgo님의 블로그를 참고하자.

 

딥러닝 모델의 손실함수 · ratsgo's blog

이번 글에서는 딥러닝 모델의 손실함수에 대해 살펴보도록 하겠습니다. 이 글은 Ian Goodfellow 등이 집필한 Deep Learning Book과 위키피디아, 그리고 하용호 님의 자료를 참고해 제 나름대로 정리했음

ratsgo.github.io


(2) 모델 생성

def create_probablistic_bnn_model(FEATURE_NAMES, train_size, hidden_units, prior, posterior):
    inputs = create_model_inputs(FEATURE_NAMES)
    features = keras.layers.concatenate(list(inputs.values()))
    features = layers.BatchNormalization()(features)

    # Create hidden layers with weight uncertainty using the DenseVariational layer.
    for units in hidden_units:
        features = tfp.layers.DenseVariational(
            units=units,
            make_prior_fn=prior,
            make_posterior_fn=posterior,
            kl_weight=1 / train_size,
            activation="sigmoid",
        )(features)

    # Create a probabilisticå output (Normal distribution), and use the `Dense` layer
    # to produce the parameters of the distribution.
    # We set units=2 to learn both the mean and the variance of the Normal distribution.
    distribution_params = layers.Dense(units=2)(features)
    outputs = tfp.layers.IndependentNormal(1)(distribution_params)

    model = keras.Model(inputs=inputs, outputs=outputs)
    return model

모델이 받는 입력 레이어와 hidden layer를 구성하는 방식은 BNN과 동일하다. BNN에 추가되는 부분은 출력 값을 분포로 표현하기 위한 레이어로, distribution_params와 outputs이다. distribution_params는 2개의 unit으로 구성되는데 각 unit은 mean과 variance을 갖도록 학습된다. 이렇게 처리될 수 있는 이유는 파라미터를 바탕으로 하는 정규분포에 대한 값으로 출력하는 tfp.layers.IndependentNormal의 파라미터로 사용되기 때문이다. tfp.layers.IndenpendentNormal(1)은 distributtion_params을 파라미터로 하는 정규분포의 샘플 값이 unit이 1개 출력되도록 하는 것이다.