开始使用免费开始使用

用梯度做优化

给定一个损失函数 $y = x^{2}$,目标是将其最小化。您可以在不同的 x 取值处,使用 GradientTape() 运算计算斜率。如果斜率为正,通过减小 x 可以降低损失;如果斜率为负,通过增大 x 可以降低损失。这就是梯度下降的工作原理。

The image shows a plot of y equals x squared. It also shows the gradient at x equals -1, x equals 0, and x equals 1.

在实际应用中,您会使用高层的 tensorflow 运算自动执行梯度下降。不过在本练习中,您将分别在 x 为 -1、1 和 0 时手动计算斜率。可用的运算有:GradientTape()multiply()Variable()

本练习是课程的一部分

Python 中的 TensorFlow 入门

查看课程

练习说明

  • x 定义为初始值为 x0 的变量。
  • 将损失函数 y 设为 x 乘以 x。不要使用运算符重载。
  • 使函数返回 y 关于 x 的梯度。

交互式实操练习

通过完成这段示例代码来试试这个练习。

def compute_gradient(x0):
  	# Define x as a variable with an initial value of x0
	x = ____(x0)
	with GradientTape() as tape:
		tape.watch(x)
        # Define y using the multiply operation
		y = ____
    # Return the gradient of y with respect to x
	return tape.gradient(____, ____).numpy()

# Compute and print gradients at x = -1, 1, and 0
print(compute_gradient(-1.0))
print(compute_gradient(1.0))
print(compute_gradient(0.0))
编辑并运行代码