2

我正在使用 TensorFlow Eager 模式为 MNIST 数据集创建一个基本的自动编码器。我想观察我的损失函数在训练时相对于网络参数的二阶偏导数。目前,调用返回的tape.gradient()输出(嵌套在外部称为磁带的地方,我在下面包含了我的代码)in_tape.gradientNonein_tapeGradientTapeGradientTape

我试过tape.gradient()直接在in_tape.gradient()没有返回的情况下调用。我的下一个方法是迭代输出in_tape.gradient()并分别应用于tape.gradient()每个梯度(相对于我的模型变量),None每次都返回。

None对于任何调用,我都会收到一个值tape.gradient(),而不是我认为会指示None单个偏导数的 None 值列表,这在某些情况下是可以预期的。

我目前只尝试获得第一组权重(从输入到隐藏层)的二阶导数,但是,一旦我完成这项工作,我将对其进行缩放以包含所有权重。

tf.enable_eager_execution()

mnist = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images = train_images.reshape((train_images.shape[0], train_images.shape[1]*train_images.shape[2])).astype(np.float32)/255
test_images = test_images.reshape((test_images.shape[0], test_images.shape[1]*test_images.shape[2])).astype(np.float32)/255

num_epochs = 200
batch_size = 100
learning_rate = 0.0003

class MNISTModel(tf.keras.Model):
    def __init__(self, device='/gpu:0'):
        super(MNISTModel, self).__init__()
        self.device = device
        self.initializer = tf.initializers.random_uniform(0.0, 0.5)
        self.hidden = tf.keras.layers.Dense(200, use_bias=False, kernel_initializer=tf.initializers.random_uniform(0.0, 0.5), name="Hidden")
        self.out = tf.keras.layers.Dense(train_images.shape[1], use_bias=False, kernel_initializer=tf.initializers.random_uniform(0.0, 0.5), name="Output")
        self.hidden.build(train_images.shape[1])
        self.out.build(200)

    def call(self, x):
        return self.out(self.hidden(x))

def loss_func(model, x, y_):
    return tf.reduce_mean(tf.losses.mean_squared_error(labels=y_, predictions=model(x)))
    #return tf.reduce_mean((y_ - model(x))**4)

model = MNISTModel()
optimizer = tf.train.GradientDescentOptimizer(learning_rate)

for epochs in range(num_epochs):
    print("Started epoch ", epochs)
    print("Num batches is: ", train_images.shape[0]/batch_size)
    for i in range(0,1): #(int(train_images.shape[0]/batch_size)):
        with tfe.GradientTape(persistent=True) as tape:
            tape.watch(model.variables)
            with tfe.GradientTape() as in_tape:
                in_tape.watch(model.variables)
                loss = loss_func(model,train_images[0:batch_size],train_images[0:batch_size])
        grads = tape.gradient(loss, model.variables)
        IH_partial_grads = np.array([]) 
        for i in range(len(grads[0])):
            collector = np.array([])
            for j in range(len(grads[0][i])):
                collector = np.append(collector, tape.gradient(grads[0][i][j], model.variables[0]))
            IH_partial_grads = np.append(IH_partial_grads, collector)
        optimizer.apply_gradients(zip(grads, model.variables), global_step=tf.train.get_or_create_global_step())
    print("Epoch test loss: ", loss_func(model, test_images, test_images))

我的最终目标是针对我的网络的所有参数形成损失函数的 hessian 矩阵。

感谢您的任何帮助!

4

0 回答 0