具有张量流的RBM实现

时间:2016-01-13 07:42:53

标签: tensorflow

我正在尝试使用tensorflow实现RBM,这是代码:

rbm.py

""" An rbm implementation for TensorFlow, based closely on the one in Theano """
import tensorflow as tf
import math
def sample_prob(probs):
    return tf.nn.relu(
        tf.sign(
            probs - tf.random_uniform(probs.get_shape())))
class RBM(object):
    def __init__(self, name, input_size, output_size):
        with tf.name_scope("rbm_" + name):
            self.weights = tf.Variable(
                tf.truncated_normal([input_size, output_size],
                    stddev=1.0 / math.sqrt(float(input_size))), name="weights")
            self.v_bias = tf.Variable(tf.zeros([input_size]), name="v_bias")
            self.h_bias = tf.Variable(tf.zeros([output_size]), name="h_bias")

    def propup(self, visible):
        return tf.nn.sigmoid(tf.matmul(visible, self.weights) + self.h_bias)

    def propdown(self, hidden):
        return tf.nn.sigmoid(tf.matmul(hidden, tf.transpose(self.weights)) + self.v_bias)

    def sample_h_given_v(self, v_sample):
        return sample_prob(self.propup(v_sample))

    def sample_v_given_h(self, h_sample):
        return sample_prob(self.propdown(h_sample))

    def gibbs_hvh(self, h0_sample):
        v_sample = self.sample_v_given_h(h0_sample)
        h_sample = self.sample_h_given_v(v_sample)
        return [v_sample, h_sample]

    def gibbs_vhv(self, v0_sample):
        h_sample = self.sample_h_given_v(v0_sample)
        v_sample = self.sample_v_given_h(h_sample)
        return  [h_sample, v_sample]

    def cd1(self, visibles, learning_rate=0.1):
        h_start = self.propup(visibles)
        v_end = self.propdown(h_start)
        h_end = self.propup(v_end)
        w_positive_grad = tf.matmul(tf.transpose(visibles), h_start)
        w_negative_grad = tf.matmul(tf.transpose(v_end), h_end)
        update_w = self.weights.assign_add(learning_rate * (w_positive_grad - w_negative_grad))
        update_vb = self.v_bias.assign_add(learning_rate * tf.reduce_mean(visibles - v_end, 0))
        update_hb = self.h_bias.assign_add(learning_rate * tf.reduce_mean(h_start - h_end, 0))
        return [update_w, update_vb, update_hb]

    def reconstruction_error(self, dataset):
        err = tf.stop_gradient(dataset - self.gibbs_vhv(dataset)[1])
        return tf.reduce_sum(err * err)

rbm_MNIST_test.py

import tensorflow as tf
import numpy as np
import rbm
import input_data

def build_model(X, w1, b1, wo, bo):
    h1 = tf.nn.sigmoid(tf.matmul(X, w1)+b1)
    model = tf.nn.sigmoid(tf.matmul(h1, wo)+bo)
    return model

def init_weight(shape):
    return tf.Variable(tf.random_normal(shape, mean=0.0, stddev=0.01))

def init_bias(dim):
    return tf.Variable(tf.zeros([dim]))

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels

X = tf.placeholder("float", [None, 784])
Y = tf.placeholder("float", [None, 10])

rbm_layer = rbm.RBM("mnist", 784, 500)

for i in range(10):
    print "RBM CD: ", i
    rbm_layer.cd1(trX)

rbm_w, rbm_vb, rbm_hb = rbm_layer.cd1(trX)


wo = init_weight([500,10])
bo = init_bias(10)
py_x = build_model(X, rbm_w, rbm_hb, wo, bo)

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(py_x, Y))
train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost)
predict_op = tf.argmax(py_x, 1)

sess = tf.Session()
init = tf.initialize_all_variables()
sess.run(init)

for i in range(10):
    for start, end in zip(range(0, len(trX), 128), range(128, len(trX), 128)):
        sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]})
    print i, np.mean(np.argmax(teY, axis=1) ==
                     sess.run(predict_op, feed_dict={X: teX, Y: teY}))

但是出现了错误:

  

文件   “/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py”   第1626行,as_graph_def       提高ValueError(“GraphDef不能大于2GB。”)ValueError:GraphDef不能大于2GB。

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:12)

TensorFlow在GraphDef原型上的限制为2GB,这源于协议缓冲区实现的限制。如果图表中有大的常量张量,则可以快速达到该限制。特别是,如果多次使用相同 numpy数组,TensorFlow会在图表中添加多个常量张量。

在您的情况下,mnist.train.images返回的input_data.read_data_sets是一个形状为(55000, 784)的numpy浮点数组,因此约为164 MB。您将该numpy数组传递给rbm_layer.cd1,并且在该函数内部,每次使用visibles时,都会从numpy数组创建TensorFlow Const节点。您在3个地点使用visibiles,因此每次调用cd1都会使图表大小增加大约492 MB,因此您很容易超出限制。解决方案是创建一次TensorFlow常量并将该常量传递给cd1函数,如下所示:

trX_constant = tf.constant(trX)
for i in range(10):
    print "RBM CD: ", i
    rbm_layer.cd1(trX_constant)
顺便说一下,我不确定你在上面的循环中是什么意思。请注意,cd1函数只是将assign_add个节点添加到图形中,并且实际上并不执行赋值。如果您真的希望在训练时发生这些分配,您应该考虑通过控制依赖关系将这些分配链接到最终的train_op节点。

答案 1 :(得分:4)

为了实现@keveman的问题,我认为你正试图通过使用该循环来实现CD-k(对比差异)步骤。

但是我担心代码是不合适的,因为CD-k是应该在RBM中采用自动微分的位置的函数。这意味着costtrain_op不是RBM中使用 Gradient Descent 的正确方法(这是因为CD-k的特殊作用) 。顺便说一句, RBM 层应该逐个训练,而不需要完全连接的层,这不在您的代码中。

我是tensorflow的新手,我也希望得到实现。我想我不想使用tensorflow提供的 Gradient Descent ,因为我需要CD-k来进行特殊区分。希望我能尽快找到解决方案。

<强>更新 我在整个工作日都参与了这项实施工作。所以,这是当前的状态。我实现了一个简单直接的版本,但它只是得到了错误的结果。 请参阅code and result

我只是引用DeepLearnToolbox中的具体方法。我认为我试图通过tensorflow实现的过程没问题,但是不知道实际代码出了什么问题。

更新2:我修改了代码,现在我已经通过tensorflow实现了最简单的rbm。请参阅上面的code and result链接。