java系统找不到指定文件怎么解决
284
2022-10-30
探究优化机器学习模型的关键技术
设置
梯度带
例如:
x = tf.ones((2, 2)) with tf.GradientTape() as t: t.watch(x) y = tf.reduce_sum(x) z = tf.multiply(y, y)# Derivative of z with respect to the original input tensor xdz_dx = t.gradient(z, x)for i in [0, 1]: for j in [0, 1]: assert dz_dx[i][j].numpy() == 8.0
您还可以根据在 “记录”tf.GradientTape 上下文时计算的中间值请求输出的梯度。
x = tf.ones((2, 2)) with tf.GradientTape() as t: t.watch(x) y = tf.reduce_sum(x) z = tf.multiply(y, y)# Use the tape to compute the derivative of z with respect to the# intermediate value y.dz_dy = t.gradient(z, y)assert dz_dy.numpy() == 8.0
默认情况下,GradientTape 持有的资源会在调用 GradientTape.gradient() 方法后立即释放。要在同一计算中计算多个梯度,创建一个持久的梯度带。这允许多次调用 gradient() 方法。当磁带对象 tape 被垃圾收集时释放资源。例如:
记录控制流
def f(x, y): output = 1.0 for i in range(y): if i > 1 and i < 5: output = tf.multiply(output, x) return outputdef grad(x, y): with tf.GradientTape() as t: t.watch(x) out = f(x, y) return t.gradient(out, x) x = tf.convert_to_tensor(2.0)assert grad(x, 6).numpy() == 12.0assert grad(x, 5).numpy() == 12.0assert grad(x, 4).numpy() == 4.0
高阶梯度
GradientTape 记录上下文管理器内部的操作以实现自动区分。如果梯度是在这个上下文中计算的,那么梯度计算也会被记录下来。因此,同样的 API 也适用于高阶梯度。例如:
x = tf.Variable(1.0) # Create a Tensorflow variable initialized to 1.0with tf.GradientTape() as t: with tf.GradientTape() as t2: y = x * x * x # Compute the gradient inside the 't' context manager # which means the gradient computation is differentiable as well. dy_dx = t2.gradient(y, x)d2y_dx2 = t.gradient(dy_dx, x)assert dy_dx.numpy() == 3.0assert d2y_dx2.numpy() == 6.0
下一步
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~