import tensorflow as tf
import numpy as np
weight = tf.Variable(np.array([[3],[4]]).astype("float"))
with tf.GradientTape() as tape:
result = weight ** 2
gradients = tape.gradient(result,weight)
gradients
위 코드는 Tensorflow 내부의 Variable 변수를 사용해 [3],[4] 를 생성, 이를 내부적으로 **2 계산을 수행합니다. 이 과정에서 GradientTape 에 의해 모든 연산 정보는 기록되기 때문에 나중에 미분 값을 구할 수 있습니다.
gradients = tape.gradient(result,weight)
result은 연산 결과, weight는 미분 할 대상 변수를 의미합니다.
<tf.Tensor: shape=(2, 1), dtype=float64, numpy=
array([[6.],
[8.]])>
즉, weight ** 2 의 미분 값인 2 * weight, 즉 2 * 3은 6 값이 반환, 2 * 4가 반환된 것을 알 수 있습니다.