始める無料で始める

勾配で最適化する

損失関数 \(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() です。

この演習はコースの一部です

Introduction to TensorFlow in Python

コースを見る

演習の手順

  • x0 を初期値とする変数として x を定義します。
  • 演算子のオーバーロードは使わず、損失関数 yx かける x と等しく設定します。
  • 関数の戻り値として、yx に関する勾配を返すようにします。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

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))
コードを編集して実行