设置
importtensorflow astftf.enable_eager_execution()
梯度带
tensorflow 提供用于自动微分的 tf.gradienttapeapi - 计算与其输入变量相关的计算梯度。tensorflow 通过tf.gradienttape“记录” 在上下文中执行的所有操作到 “磁带”(tape)上。然后,tensorflow 使用该磁带和与每个记录操作相关联的梯度来计算使用反向模式微分的 “记录” 计算的梯度。
例如:
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 被垃圾收集时释放资源。例如:
x = tf.constant(3.0)with tf.gradienttape(persistent=true) as t: t.watch(x) y = x * x z = y * ydz_dx = t.gradient(z, x) # 108.0 (4*x^3 at x = 3)dy_dx = t.gradient(y, x) # 6.0del t # drop the reference to the tape
记录控制流
因为磁带(tape)在执行时记录操作,所以自然会处理 python 控制流(例如使用 ifs 和 whiles):
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
下一步
以上教程中,我们介绍了 tensorflow 中的梯度计算。有了这些,我们就有了足够的基本要素来构建和训练神经网络。
AMEYA360分析尼得科体积小扭矩大无刷直流电机
华为Mate20Pro拆机图赏
杭州智慧社区采用基于容器技术的微服务架构
国内LED封装行业发展现状及未来状况分析
AI技术将为我国教育带来深刻影响 未来3年将迎来市场应用爆发期
探究优化机器学习模型的关键技术
教你如何优化与创新交通运输系统的电源解决方案
5G时代数据与资本的远与近
达实FRT365智慧派梯屏支持多种权限认证方式
UFS3.0和UFS2.1性能差距有多大
工业LCD液晶电子看板:智能化管理,提升生产效率
加速度传感器的技术要求和正确选型
宁德时代麒麟电池即将发布,电池密度比特斯拉4680电池高13%
【世说芯品】通过自举扩展运算放大器工作范围
开关电源的主电路
红外耳机接驳器的制作
LG将ATBM8859解调芯片应用于TDSN-C201D
从自动驾驶到足式机器人 前文远知行高管张力加入逐际动力
后疫情时代 厨卫家电市场迎来“开门红”
2018年银行新增贷款资金仍然集中在房地产行业,制造业贷款金额不断萎缩