使用Keras / Tensorflow或autograd计算验证误差wrt输入的梯度

桑达马尔

我需要计算验证误差wrt输入x的梯度。我试图查看扰动训练样本之一时验证错误发生了多少变化。

  • 验证误差(E)明确取决于模型权重(W)。
  • 模型权重明确取决于输入(x和y)。
  • 因此,验证错误隐含地取决于输入。

我正在尝试直接计算E wrt x的梯度一种替代方法是计算E wrt W的梯度(可以很容易地计算)和W wrt x的梯度(目前不能),这将允许计算E wrt x的梯度

我附上了一个玩具的例子。提前致谢!

import numpy as np
import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import to_categorical
import tensorflow as tf
from autograd import grad

train_images = mnist.train_images()
train_labels = mnist.train_labels()
test_images = mnist.test_images()
test_labels = mnist.test_labels()

# Normalize the images.
train_images = (train_images / 255) - 0.5
test_images = (test_images / 255) - 0.5

# Flatten the images.
train_images = train_images.reshape((-1, 784))
test_images = test_images.reshape((-1, 784))

# Build the model.
model = Sequential([
    Dense(64, activation='relu', input_shape=(784,)),
    Dense(64, activation='relu'),
    Dense(10, activation='softmax'),
])

# Compile the model.
model.compile(
    optimizer='adam',
    loss='categorical_crossentropy',
    metrics=['accuracy'],
)

# Train the model.
model.fit(
    train_images,
    to_categorical(train_labels),
    epochs=5,
    batch_size=32,
)
model.save_weights('model.h5')
# Load the model's saved weights.
# model.load_weights('model.h5')

calculate_mse = tf.keras.losses.MeanSquaredError()

test_x = test_images[:5]
test_y = to_categorical(test_labels)[:5]

train_x = train_images[:1]
train_y = to_categorical(train_labels)[:1]

train_y = tf.convert_to_tensor(train_y, np.float32)
train_x = tf.convert_to_tensor(train_x, np.float64)

with tf.GradientTape() as tape:
    tape.watch(train_x)
    model.fit(train_x, train_y, epochs=1, verbose=0)
    valid_y_hat = model(test_x, training=False)
    mse = calculate_mse(test_y, valid_y_hat)
de_dx = tape.gradient(mse, train_x)
print(de_dx)


# approach 2 - does not run
def calculate_validation_mse(x):
    model.fit(x, train_y, epochs=1, verbose=0)
    valid_y_hat = model(test_x, training=False)
    mse = calculate_mse(test_y, valid_y_hat)
    return mse


train_x = train_images[:1]
train_y = to_categorical(train_labels)[:1]

validation_gradient = grad(calculate_validation_mse)
de_dx = validation_gradient(train_x)
print(de_dx)


sohv89

这是您可以执行的操作。推导如下。

在此处输入图片说明

没什么要注意的,

  • 当我在colab中的内存不足时(在代码中标记的行),我已将功能大小从784减小到256。可能必须进行一些内存剖析才能找出原因
  • 仅计算第一层的毕业成绩。易于扩展到其他层

免责声明:据我所知,此推导是正确的。请进行一些研究并验证是否确实如此。对于较大的输入和更大的层,您将遇到内存问题。

import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import to_categorical
import tensorflow as tf

f = 256

model = Sequential([
    Dense(64, activation='relu', input_shape=(f,)),
    Dense(64, activation='relu'),
    Dense(10, activation='softmax'),
])

# Compile the model.
model.compile(
    optimizer='adam',
    loss='categorical_crossentropy',
    metrics=['accuracy'],
)
w = model.weights[0]

# Inputs and labels
x_tr = tf.Variable(np.random.normal(size=(1,f)), shape=(1, f), dtype='float32')
y_tr = np.random.choice([0,1,2,3,4,5,6,7,8,9], size=(1,1))
y_tr_onehot = tf.keras.utils.to_categorical(y_tr, num_classes=10).astype('float32')
x_v = tf.Variable(np.random.normal(size=(1,f)), shape=(1, f), dtype='float32')
y_v = np.random.choice([0,1,2,3,4,5,6,7,8,9], size=(1,1))
y_v_onehot = tf.keras.utils.to_categorical(y_v, num_classes=10).astype('float32')

# In the context of GradientTape

with tf.GradientTape() as tape1:

  with tf.GradientTape() as tape2:
    y_tr_pred = model(x_tr)   
    tr_loss = tf.keras.losses.MeanSquaredError()(y_tr_onehot, y_tr_pred)

  tmp_g = tape2.gradient(tr_loss, w)
  print(tmp_g.shape)

# d(dE_tr/d(theta))/dx
# Warning this step consumes lot of memory for large layers
lr = 0.001
grads_1 = -lr * tape1.jacobian(tmp_g, x_tr)

with tf.GradientTape() as tape3:
  y_v_pred = model(x_v)   
  v_loss = tf.keras.losses.MeanSquaredError()(y_v_onehot, y_v_pred)

# dE_val/d(theta)
grads_2 = tape3.gradient(v_loss, w)[tf.newaxis, :]

# Just crunching the dimension to get the final desired shape of (1,256)
grad = tf.matmul(tf.reshape(grads_2,[1, -1]), tf.reshape(tf.transpose(grads_1,[2,1,0,3]),[1, -1, 256]))

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

多个输出维度的 Keras 梯度 wrt 输入

来自分类Dev

Keras,计算 LSTM 上输入的损失梯度

来自分类Dev

使用autograd计算关于输入的输出Jacobian矩阵

来自分类Dev

如何在Tensorflow 2.0中计算输出WRT输入的梯度

来自分类Dev

我的keras后端tensorflow不使用GPU?

来自分类Dev

如何在导入行中直接使用“ keras”而不是使用“ tensorflow.keras”

来自分类Dev

Keras 和 tensorflow 的串联和拟合误差

来自分类Dev

Pandas / Keras:使用DataFrame中的数据训练Keras模型,输入形状错误

来自分类Dev

Keras:如何使用 Keras 中的输入张量对常量矩阵进行切片?

来自分类Dev

使用验证集确定 Keras 中的数字时代

来自分类Dev

梯度下降计算中的误差

来自分类Dev

梯度下降计算中的误差

来自分类Dev

使用ImageDataGenerator增强Keras数据(您的输入用完了数据)

来自分类Dev

如何使用python在keras中输入用于类预测的图像

来自分类Dev

使用 Keras 编程多输入神经网络架构

来自分类Dev

使用 Keras 创建具有多个输入的 NN 架构

来自分类Dev

如何使用keras在LSTM中实现多元回归的输入?

来自分类Dev

使用Tensorflow 2的Keras Functional API时传递`training = true`

来自分类Dev

在Tensorflow 2.0中无法使用vggface-keras

来自分类Dev

Keras中的CPU与GPU使用情况(Tensorflow 2.1)

来自分类Dev

如何打破定制Tensorflow模型内的循环(使用Keras)

来自分类Dev

如何在Tensorflow-keras中使用nlp的预测?

来自分类Dev

使用TensorFlow-Keras API进行数据增强

来自分类Dev

如何在Keras Tensorflow 2.3中使用随机缩放

来自分类Dev

我无法使用Anaconda安装Tensorflow和Keras

来自分类Dev

使用TensorFlow和Keras进行单类图像识别

来自分类Dev

使用Galaxy Zoo数据集,TensorFlow和Keras训练GAN

来自分类Dev

使用Tensorflow 2.1的Keras模型的自定义指标

来自分类Dev

将tf.keras.layers与Tensorflow低级API结合使用

Related 相关文章

  1. 1

    多个输出维度的 Keras 梯度 wrt 输入

  2. 2

    Keras,计算 LSTM 上输入的损失梯度

  3. 3

    使用autograd计算关于输入的输出Jacobian矩阵

  4. 4

    如何在Tensorflow 2.0中计算输出WRT输入的梯度

  5. 5

    我的keras后端tensorflow不使用GPU?

  6. 6

    如何在导入行中直接使用“ keras”而不是使用“ tensorflow.keras”

  7. 7

    Keras 和 tensorflow 的串联和拟合误差

  8. 8

    Pandas / Keras:使用DataFrame中的数据训练Keras模型,输入形状错误

  9. 9

    Keras:如何使用 Keras 中的输入张量对常量矩阵进行切片?

  10. 10

    使用验证集确定 Keras 中的数字时代

  11. 11

    梯度下降计算中的误差

  12. 12

    梯度下降计算中的误差

  13. 13

    使用ImageDataGenerator增强Keras数据(您的输入用完了数据)

  14. 14

    如何使用python在keras中输入用于类预测的图像

  15. 15

    使用 Keras 编程多输入神经网络架构

  16. 16

    使用 Keras 创建具有多个输入的 NN 架构

  17. 17

    如何使用keras在LSTM中实现多元回归的输入?

  18. 18

    使用Tensorflow 2的Keras Functional API时传递`training = true`

  19. 19

    在Tensorflow 2.0中无法使用vggface-keras

  20. 20

    Keras中的CPU与GPU使用情况(Tensorflow 2.1)

  21. 21

    如何打破定制Tensorflow模型内的循环(使用Keras)

  22. 22

    如何在Tensorflow-keras中使用nlp的预测?

  23. 23

    使用TensorFlow-Keras API进行数据增强

  24. 24

    如何在Keras Tensorflow 2.3中使用随机缩放

  25. 25

    我无法使用Anaconda安装Tensorflow和Keras

  26. 26

    使用TensorFlow和Keras进行单类图像识别

  27. 27

    使用Galaxy Zoo数据集,TensorFlow和Keras训练GAN

  28. 28

    使用Tensorflow 2.1的Keras模型的自定义指标

  29. 29

    将tf.keras.layers与Tensorflow低级API结合使用

热门标签

归档