我想实现通过模拟重建受限玻尔兹曼机的算法。M 是可见变量的数量,N 是隐藏变量的数量。为了在 GPU 上并行运行,我想先使用 python 在 tensorflow 上编写它。
在我的主函数 RBMIC() 中,我需要使用 L1 惩罚运行 M 个独立逻辑回归并更新我的权重和偏差矩阵:(w 和 b),然后稍后使用它们来估算隐藏变量的值。所以我写了一个独立的for循环。我想知道 tensorflow 是否可以识别独立的 for 循环并在 GPU 上有效地运行它(每个内核进行一次迭代)?
该代码也非常慢,尤其是在运行逻辑回归时,因为它需要运行 epochs=1000 次以最小化损失函数。但是如果我使用 sklearn.linear_model.LogisticRegression,我发现它非常快。为什么会有很大的不同?但是为了使用GPU,我还是想用tensorflow来写逻辑回归。谁能给我一些关于如何更有效地编写它的建议?
当我编写物流回归函数:LogisticsReg() 时,我需要获取权重和偏差,并且还需要将它们保留为 tensorflow 变量以供我进一步计算。但是根据我的函数:LogisticsReg(),它在 sess.run() 之后返回非张量变量。所以我再次将它们转换为张量变量。这部分合理吗?或者是否有任何有效的方法将其保持在张量变量中,然后可用于更新权重和偏差矩阵(w 和 b)?谢谢你的建议!
我对 tensorflow 和 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)