2017-10-26 6 views
2

制限付きボルツマンマシンをシミュレーションで再構築するアルゴリズムを実装します。 Mは可視変数の数であり、Nは隠れ変数の数である。 GPU上で並列実行するには、まずPythonを使用してテンソルフローで記述します。私の主な機能RBMIC()においてGPUのTensorflowで独立したループを並列実行する方法

  1. 、Iは、L1ペナルティとM独立ロジスティックス回帰を実行し、自分の体重とバイアス行列を更新する必要がある:(w及びb)は、次いで、隠された値を転嫁するために後でそれらを使用変数。だから私は独立したforループを書く。テンソルフローは、独立したforループを識別し、それを効率的に実行することができますか(各コアは1回の反復でGPU上で実行できますか?

  2. また、ロス関数を最小限に抑えるためにepoch = 1000回実行する必要があるため、特にロジスティクス回帰の実行には非常に時間がかかります。しかし、sklearn.linear_model.LogisticRegressionを使用すると非常に高速です。なぜそれは大きな違いですか?しかし、GPUを使用するには、テンソルフローを使用してロジスティック回帰を記述したいと考えています。誰も私にそれをより効率的に書く方法について助言を与えることができますか?

  3. ロジスティクス回帰関数LogisticsReg()を書くとき、私は重みとバイアスを取得する必要があり、さらに計算するためにテンソルフロー変数として保持する必要があります。しかし、私の関数:LogisticsReg()によると、sess.run()の後に非テンソル変数を返します。だから私は再びそれらをテンソル変数に変換します。この部分は合理的ですか?あるいは、それをテンソル変数に保持する効率的な方法がありますか?それで、重み行列とバイアス行列(wとb)を更新するために使用できますか?あなたの提案をありがとう!

私は、テンソルフローとPythonの新機能です。中断して申し訳ありません、ありがとうございます!

import numpy as np 
 
import tensorflow as tf 
 

 

 
n = 200 
 
M = 4 
 
N = 2 
 
mu, sigma = 0, 0.1 
 
beta = 0.001 
 
lr=0.05 
 
epochs = 1000 
 
Maxepochs = 10 
 
iteration = 100 
 

 

 
visible = np.array([[1,0,1,0],[0,1,1,0],[1,0,0,1],[0,1,0,1]]) 
 
vis = np.tile(visible,50).reshape(n,M) 
 
vis = tf.cast(vis, tf.float32) 
 
err_hat = np.zeros([iteration]) 
 

 

 
def Bionimal(x): 
 
    sample = tf.where(tf.random_uniform(shape=x.shape) - x < 0, 
 
         tf.ones(shape=x.shape), tf.zeros(shape=x.shape)) 
 
    return sample 
 

 
def LogisticsReg(X, Y, wj, bj, beta, lr, epochs): 
 
    logitj = tf.add(tf.matmul(X, wj), bj) 
 
    loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=Y, logits=logitj)) 
 
    l1_regularizer = tf.reduce_sum(tf.abs(wj)) 
 
    loss = tf.reduce_mean(loss + beta * l1_regularizer) 
 
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=lr).minimize(loss, var_list=[wj, bj]) 
 
    with tf.Session() as sess: 
 
     tf.global_variables_initializer().run() 
 
     for k in range(epochs): # train the model n_epochs times 
 
      _, bf, wf = sess.run([optimizer, bj, wj]) 
 
    # bf = tf.Variable(bf,name="bf") 
 
    # wf = tf.Variable(wf,name="wf") 
 
    return [bf, wf] 
 

 
def UpdateC(wi, hi, c_opt, Maxepochs): 
 
    ph = tf.sigmoid(tf.add(tf.matmul(vis, tf.transpose(wi)), c_opt)) 
 
    lik = tf.add(tf.multiply(hi, tf.log(ph)), tf.multiply((1. - hi), tf.log(1. - ph))) 
 
    loss2 = -tf.reduce_sum(lik) 
 
    optimizer = tf.contrib.opt.ScipyOptimizerInterface(loss2, var_to_bounds={c_opt: (-1,1)},options={'maxiter': Maxepochs}, var_list=[c_opt]) 
 
    with tf.Session() as sess: 
 
     tf.global_variables_initializer().run() 
 
     optimizer.minimize(sess) 
 
     return sess.run(c_opt) 
 

 

 

 
# initial 
 
w = tf.Variable(tf.random_normal(shape=(N, M), stddev=0.1), name="weights") 
 
c = tf.Variable(tf.random_normal(shape=(1, N), stddev=0.1), name="hbias") 
 
b = tf.Variable(tf.random_normal(shape=(1, M), stddev=0.1), name="vbias") 
 

 

 
def RBMIC(w,c,vis): 
 
    # calculate hidden variables 
 
    logits = tf.add(tf.matmul(vis, tf.transpose(w)), tf.tile(c, [n, 1])) 
 
    prob = tf.sigmoid(logits) 
 
    hids = Bionimal(prob) 
 
    # estimate bias, weight by logistics regression with l1 penalty and also bias c for visible variables. 
 
    bs = np.zeros([1, M]) 
 
    ws = np.zeros([N, M]) 
 
    X = hids 
 
    for j in range(M): 
 
     Y = tf.reshape(vis[:, j], [n, 1]) 
 
     wj = tf.Variable(tf.reshape(w[:, j], [N, 1]), name="wj") 
 
     bj = tf.Variable(tf.random_normal(shape=[1, 1], stddev=0.1), name="bj") 
 
     bf, wf = LogisticsReg(X, Y, wj, bj, beta, lr, epochs) 
 
     bs[0, j] = bf 
 
     ws[:, [j]] = wf 
 
    b = tf.cast(tf.Variable(bs, name="vbias"), tf.float32) 
 
    w = tf.cast(tf.Variable(ws, name="weights"), tf.float32) 
 
    cs = np.zeros([1, N]) 
 
    for i in range(N): 
 
     wi = tf.reshape(w[i, :], [1, M]) 
 
     hi = tf.reshape(hids[:, i], [n, 1]) 
 
     c_opt = tf.Variable(c[0, i], name="c_opt") 
 
     cs[0, i] = UpdateC(wi, hi, c_opt, Maxepochs) 
 
    c = tf.cast(tf.Variable(cs, name="hbias"), tf.float32) 
 
    # evaluate performance 
 
    vis_pred = tf.sigmoid(tf.add(tf.matmul(hids, w), tf.tile(b, [n, 1]))) 
 
    err = tf.reduce_sum((vis_pred - vis) ** 2) 
 
    return err 
 

 

 

 
for step in range(iteration): # train the model iteration times 
 
     err = RBMIC(w,c,vis) 
 
     init = tf.global_variables_initializer() 
 
     sess = tf.Session() 
 
     sess.run(init) 
 
     print 'reconstruct at step %d = \n' % (step) 
 
     print sess.run(err)

答えて

0

あなたのポストのタイトルで質問に答えるために、制御フロー構造tf.while_loopは(キーワード引数parallel_iterationsを介して露光)反復処理の並列実行をサポートしています。

2番目と3番目の質問に関しては、複数のセッションを作成したくない可能性があります。単一のセッションを使用する場合は、たとえば、テンソルを変数に変換する必要はありません。 TensorFlow graphs and sessionsのセマンティクスの詳細については、チュートリアルとドキュメントを参照することを強くお勧めします。

関連する問題