TensorFlow or Theano:他们怎么知道基于神经网络图的损失函数导数?

TensorFlow or Theano: how do they know the loss function derivative based on the neural network graph?

在 TensorFlow 或 Theano 中,您只需告诉库您的神经网络如何,以及前馈应该如何运行。

例如,在 TensorFlow 中,您可以这样写:

with graph.as_default():
    _X = tf.constant(X)
    _y = tf.constant(y)

    hidden = 20
    w0 = tf.Variable(tf.truncated_normal([X.shape[1], hidden]))
    b0 = tf.Variable(tf.truncated_normal([hidden]))

    h = tf.nn.softmax(tf.matmul(_X, w0) + b0)

    w1 = tf.Variable(tf.truncated_normal([hidden, 1]))
    b1 = tf.Variable(tf.truncated_normal([1]))

    yp = tf.nn.softmax(tf.matmul(h, w1) + b1)

    loss = tf.reduce_mean(0.5*tf.square(yp - _y))
    optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

我正在使用 L2 范数损失函数,C=0.5*sum((y-yp)^2),并且在反向传播步骤中可能必须计算导数,dC=sum(y-yp ).参见 (30) in this book

我的问题是:TensorFlow(或 Theano)如何知道反向传播的解析导数?或者他们做一个近似值?或者以某种方式不使用导数?

我已经在 TensorFlow 上完成了 deep learning udacity course,但对于如何理解这些库的工作原理,我仍然存在分歧。

差异发生在最后一行:

    optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

当您执行 minimize() 方法时,TensorFlow 会识别 loss 所依赖的变量集,并为每个变量计算梯度。微分在ops/gradients.py, and it uses "reverse accumulation". Essentially it searches backwards from the loss tensor to the variables, applying the chain rule at each operator in the dataflow graph. TensorFlow includes "gradient functions" for most (differentiable) operators, and you can see an example of how these are implemented in ops/math_grad.py中实现。梯度函数可以使用原始运算(包括其输入、输出和属性)和为其每个输出计算的梯度来为其每个输入生成梯度。

Ilya Sutskever's PhD thesis 的第 7 页很好地解释了这个过程的一般工作原理。