TensorFlow : Edward : Getting Started (notebook) (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 11/28/2018
* 本ページは、Edward サイトの Getting Started (notebook) を翻訳した上で適宜、補足説明したものです:
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
貴方の最初の Edward プログラム
Edward の確率モデリングは確率変数の単純な言語です。ここではベイジアン・ニューラルネットワークを示します。それはその重み上で事前分布を持つニューラルネットワークです。
web ページ版は Getting Started で利用可能です。
%matplotlib inline from __future__ import absolute_import from __future__ import division from __future__ import print_function import edward as ed import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from edward.models import Normal plt.style.use('ggplot')
def build_toy_dataset(N=50, noise_std=0.1): x = np.linspace(-3, 3, num=N) y = np.cos(x) + np.random.normal(0, noise_std, size=N) x = x.astype(np.float32).reshape((N, 1)) y = y.astype(np.float32) return x, y def neural_network(x, W_0, W_1, b_0, b_1): h = tf.tanh(tf.matmul(x, W_0) + b_0) h = tf.matmul(h, W_1) + b_1 return tf.reshape(h, [-1])
最初に、コサイン関係を持つ 50 観測の toy データセットをシミュレートします。
ed.set_seed(42) N = 50 # number of data points D = 1 # number of features x_train, y_train = build_toy_dataset(N)
次に、2 層ベイジアン・ニューラルネットワークを定義します。ここでは、tanh 非線形を持つニューラルネットワークを定義します。
W_0 = Normal(loc=tf.zeros([D, 2]), scale=tf.ones([D, 2])) W_1 = Normal(loc=tf.zeros([2, 1]), scale=tf.ones([2, 1])) b_0 = Normal(loc=tf.zeros(2), scale=tf.ones(2)) b_1 = Normal(loc=tf.zeros(1), scale=tf.ones(1)) x = x_train y = Normal(loc=neural_network(x, W_0, W_1, b_0, b_1), scale=0.1 * tf.ones(N))
次にデータからのモデルについて推論を行ないます。変分推論を使用します。重みとバイアスに渡る正規分布近似を指定します。
qW_0 = Normal(loc=tf.get_variable("qW_0/loc", [D, 2]), scale=tf.nn.softplus(tf.get_variable("qW_0/scale", [D, 2]))) qW_1 = Normal(loc=tf.get_variable("qW_1/loc", [2, 1]), scale=tf.nn.softplus(tf.get_variable("qW_1/scale", [2, 1]))) qb_0 = Normal(loc=tf.get_variable("qb_0/loc", [2]), scale=tf.nn.softplus(tf.get_variable("qb_0/scale", [2]))) qb_1 = Normal(loc=tf.get_variable("qb_1/loc", [1]), scale=tf.nn.softplus(tf.get_variable("qb_1/scale", [1])))
tf.get_variable の定義は変分因子のパラメータに変化することを可能にします。それらはランダムに初期化されます。標準偏差パラメータは softplus 変換によりゼロより大きいとして制約されます。
# fit を可視化するための変分モデルからのサンプル関数 rs = np.random.RandomState(0) inputs = np.linspace(-5, 5, num=400, dtype=np.float32) x = tf.expand_dims(inputs, 1) mus = tf.stack( [neural_network(x, qW_0.sample(), qW_1.sample(), qb_0.sample(), qb_1.sample()) for _ in range(10)])
# FIRST VISUALIZATION (prior) sess = ed.get_session() tf.global_variables_initializer().run() outputs = mus.eval() fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(111) ax.set_title("Iteration: 0") ax.plot(x_train, y_train, 'ks', alpha=0.5, label='(x, y)') ax.plot(inputs, outputs[0].T, 'r', lw=2, alpha=0.5, label='prior draws') ax.plot(inputs, outputs[1:].T, 'r', lw=2, alpha=0.5) ax.set_xlim([-5, 5]) ax.set_ylim([-2, 2]) ax.legend() plt.show()
さて、与えられたデータでモデルの潜在変数を推論するために Kullback-Leibler divergence で変分推論を実行します。1000 反復を指定します。
inference = ed.KLqp({W_0: qW_0, b_0: qb_0, W_1: qW_1, b_1: qb_1}, data={y: y_train}) inference.run(n_iter=1000, n_samples=5)
1000/1000 [100%] ██████████████████████████████ Elapsed: 12s | Loss: -5.755
最後に、モデル fit を批評します。ベイジアン・ニューラルネットワークはニューラルネットワークに渡る分布を定義しますので、グラフィカル・チェックを遂行できます。推論されたモデルからニューラルネットワークを描いてそれがデータにどのくらい上手く fit したかを可視化します。
# SECOND VISUALIZATION (posterior) outputs = mus.eval() fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(111) ax.set_title("Iteration: 1000") ax.plot(x_train, y_train, 'ks', alpha=0.5, label='(x, y)') ax.plot(inputs, outputs[0].T, 'r', lw=2, alpha=0.5, label='posterior draws') ax.plot(inputs, outputs[1:].T, 'r', lw=2, alpha=0.5) ax.set_xlim([-5, 5]) ax.set_ylim([-2, 2]) ax.legend() plt.show()
モデルは観測された領域の x と y の間のコサイン関係を捕捉しました。
To learn more about Edward, delve in!
以上