【问题标题】:Gradients of operations done in the tensorflow.data.Dataset.map() function在 tensorflow.data.Dataset.map() 函数中完成的操作梯度
【发布时间】:2018-11-19 21:55:27
【问题描述】:

我有一个包含 X 和 Y 部分的数据集。 X 在输入到神经网络之前需要变成 D。

我使用tf.data.Dataset 类来做到这一点:

# Making the place holders
X = tf.placeholder(shape=[n_samples, n_atoms, 3], dtype=tf.float32)
Y = tf.placeholder(shape=[n_samples, 1], dtype=tf.float32)

# Creating the data set
dataset = tf.data.Dataset.from_tensor_slices((X, Y))

# Transforming X to D using the map function 
dataset = dataset.map(X_to_D)
dataset = dataset.batch(200)
iterator = tf.data.Iterator.from_structure(dataset.output_types, dataset.output_shapes)
batch_D, batch_Y = iterator.get_next()

其中函数X_to_D是一个张量流函数,它将XY张量作为输入并返回DY张量。

D 然后分批拆分并用作神经网络的输入。神经网络的输出是Y_prediction

我需要获取Y_prediction 相对于X 的梯度。但是,尝试时:

gradients = tf.gradients(Y_prediction, X)

发生错误:

LookupError:梯度注册表没有条目:IteratorGetNext LookupError:没有为操作“IteratorGetNext_1”定义梯度(操作 类型:IteratorGetNext)

问题: 似乎很容易获得Y_prediction 相对于D 的梯度。但是,我将如何计算Y_prediction 相对于X 的梯度?

注意: X_to_D 函数非常占用内存,只能在非常小批量的数据上完成。所以我无法创建数据集,将其分批拆分,并在每批用于训练之前进行从XD 的转换。这是因为用于训练的批量大小对于进行XD 的转换来说太大了。

【问题讨论】:

  • 您不计算相对于X(您的网络输入)的梯度。您根据模型中的变量(神经网络权重、偏差等)计算梯度。
  • @xdurch0 我想要关于占位符 X 的渐变。通常这会起作用(参见示例gist.github.com/SilviaAmAm/b09a1a178fe34cf8f6c67d1d735919d5),但由于 tf.data.Iterator 这似乎不起作用。我正在寻找解决此问题的方法。

标签: python tensorflow neural-network tensorflow-datasets


【解决方案1】:

使用 tensorflow 2.0,您可以编写自定义模型,这允许您计算 w.r.t 的导数。输入。例如,

class MyModel(tf.keras.Model):
    def __init__(self):
        super(MyModel,self).__init__(name = 'my_model')
        self.dense_1 = layers.Dense(32,activation = 'relu', input_dim=2)
        self.dense_2 = layers.Dense(64,activation=tf.sin)
        self.dense_3 = layers.Dense(1)
    def call(self, inputs):
        # Define your forward pass here
        x = self.dense_1(inputs)
        x = self.dense_2(x)
        return self.dense_3(x)

model = MyModel()
optimizer = tf.keras.optimizers.RMSprop(0.001)
model.compile(loss='mse',
              optimizer=optimizer,
              metrics=['mae', 'mse'])
history = model.fit(X_train, y_train, epochs=10, batch_size = 1,
                    validation_split = 0.2, verbose=0)

计算导数:

x = tf.constant(X_train[:1,:])
with tf.GradientTape() as g:
    g.watch(x)
    y = model.call(x)
dy_dx = g.gradient(y, x)
print(y)
dy_dx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-27
    • 2018-01-23
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多