1

我正在学习 RBM,并从 Hismael Costa 的 github 存储库中复制并分析了他的代码。我已经更改了代码,因此它仅适用于 tensorflow.v2。不知何故,当训练损失函数时,整个跳跃而不是下降。

数据集肯定是收敛的。

length = 64*100

col0 = np.random.randint(0,2,length)
col1 = np.random.randint(0,2,length)
col2 = np.bitwise_or(col0, col1)
train_X = np.array([col0, col1, col2], dtype=np.float32).T

最初我认为这是 GradientTape 的错误应用或错误的优化器语法,因为这是我主要自己编写的部分,但看起来还不错。隐藏节点的数量、learnig_rate 和步数都不会改变任何东西。我也尝试了 SGD 优化器,但无济于事。

有人可以看看我的代码吗:

import tensorflow as tf
import numpy as np

class RBM(tf.keras.Model):
    
    def __init__(self, nv, nh, cd_steps=3):
        super().__init__()
        self.W = tf.Variable(tf.random.truncated_normal((nv, nh), dtype=tf.float64) * 0.01) 
        self.bv = tf.Variable(tf.zeros((nv, 1), dtype=tf.float64))
        self.bh = tf.Variable(tf.zeros((nh, 1), dtype=tf.float64))
        self.cd_steps = cd_steps 
        self.modelW = None 
            
        
    def bernoulli(self, p):
        return tf.nn.relu(tf.sign(p- tf.random.uniform(p.shape, dtype=tf.float64)))
        
    def sample_h(self, v):
        ph_given_v = tf.sigmoid(tf.matmul(v, self.W) + tf.squeeze(self.bh))
        return self.bernoulli(ph_given_v)
    
    def sample_v(self, h):
        pv_given_h = tf.sigmoid(tf.matmul(h, tf.transpose(self.W)) + tf.squeeze(self.bv))
        return self.bernoulli(pv_given_h)
   
    def gibbs_step(self, i, k, vk):
        hk = self.sample_h(vk)
        vk = self.sample_v(hk)
        return i+1, k, vk
    
    def energy(self, v):
        b_term = tf.matmul(v, self.bv)
        linear_tranform = tf.matmul(v, self.W) + tf.squeeze(self.bh)
        h_term = tf.reduce_sum(tf.math.log(tf.exp(linear_tranform) + 1), axis=1) 
        return tf.reduce_mean(-h_term -b_term)
    
    def loss(self, v, vk):
        return self.energy(v) - self.energy(vk) 
     
    
    def call(self, X, lr=0.01, batch_size=64, epochs=5):
        X = tf.data.Dataset.from_tensor_slices(X).batch(batch_size)
        optimizer = tf.keras.optimizers.Adam(learning_rate=lr)
        for epoch in range(epochs):
            losses = []
            for n_batch, batch in enumerate(X):
                print('batch: ', n_batch, end='\r')
                with tf.GradientTape() as tape:
                    v = batch
                    vk = tf.identity(v)

                    i = tf.constant(0)
                    _, _, vk = tf.nest.map_structure(tf.stop_gradient,
                                                     tf.while_loop(cond = lambda i,k, *args: i<=k,
                                                                   body = self.gibbs_step,
                                                                   loop_vars =[i, tf.constant(0), v])
                                                    )

                    l = self.loss(v, vk)
                # grads = tape.gradient(l, [self.W, self.bv, self.bh])
                # optimizer.apply_gradients(zip(grads, self.trainable_variables))
                optimizer.minimize(l, var_list = [self.W, self.bv, self.bh], tape=tape) # this does the same job as the 2 lines abow (doesn't it?)
                

            losses.append(l)
            print('Epoch: {} Cost: {}'.format(epoch, np.mean(losses)))
        self.modelW = self.W


    def predict(self, Q, batch_size=64):
        Q = tf.data.Dataset.from_tensor_slices(Q).batch(batch_size)
        answers = []
        for n_batch, batch in enumerate(Q):
            print('batch: ', n_batch, end='\r')
            v = batch
            i = tf.constant(0)
            _, _, vk = tf.nest.map_structure(tf.stop_gradient,
                                                tf.while_loop(cond = lambda i,k, *args: i<=k,
                                                              body = self.gibbs_step,
                                                              loop_vars =[i, tf.constant(0), v])
                                               )
        
            answers.append(vk.numpy())
        return np.concatenate(answers)
                    
        
 

只需执行以下代码即可使用数据集运行类。

rbm = RBM(nv=train_X.shape[1], nh=5, cd_steps=3)
rbm(X=train_X, lr=0.001, epochs=10)
4

1 回答 1

1

好的 - 只是我是个白痴:

  1. 权重的启动可能并不理想:当它们完全随机时似乎效果更好:
self.W = tf.Variable(tf.random.truncated_normal((nv, nh), dtype=tf.float32)) 
self.bv = tf.Variable(tf.random.truncated_normal((nv, 1), dtype=tf.float32))
self.bh = tf.Variable(tf.random.truncated_normal((nh, 1), dtype=tf.float32))
  1. 损失计算:使用正方形效果更好:
def loss(self, v, vk):
    return (self.energy(v) - self.energy(vk))**2 
  1. 错误的缩进:“losses.append(l)”行应该和它上面的行一样缩进:
    optimizer.minimize(l, var_list = [self.W, self.bv, self.bh], tape=tape)
    losses.append(l)
  1. 调整优化器的 learning_rate
  2. 策划损失也有很大帮助。一些细微的变化在绘图上比在一堆数字中更容易理解。

于是话题就结束了。

于 2021-02-01T20:57:32.460 回答