作為一個練習,我試圖在 Tensorflow 中構建一個自定義運算子,并針對由 Tensorflow API 操作組成的相同前向操作的 Tensorflow 的 autodiff 檢查梯度。但是,我的自定義運算子的梯度不正確。看來我的復雜分析是不正確的,需要一些復習。
import tensorflow as tf
shape = (1, 16)
dtype = tf.complex64
x = tf.cast(tf.complex(tf.random.normal(shape), tf.random.normal(shape)), dtype=dtype)
def fun(x):
phi = x * tf.math.conj(x)
e = tf.exp(1j * phi)
return e
def d_fun(x):
d_phi = x tf.math.conj(x)
phi = x * tf.math.conj(x)
d_e = 1j * d_phi * tf.exp(1j * phi)
return d_e
@tf.custom_gradient
def tf_custom(x):
e = fun(x)
def grad(dy):
d_e = d_fun(x)
return dy * d_e
return e, grad
with tf.GradientTape() as g:
g.watch(x)
res = fun(x)
dy_dx = g.gradient(res, x)
with tf.GradientTape() as g:
g.watch(x)
res2 = tf_custom(x)
dy_dx2 = g.gradient(res2, x)
print(tf.reduce_sum(tf.abs(res - res2)).numpy())
print(tf.reduce_sum(tf.abs(dy_dx - dy_dx2)).numpy())
uj5u.com熱心網友回復:
TensorFlow 2 不直接計算復變數函式的導數。似乎它使用Wirtinger 演算將復變數的函式的導數計算為實部和虛部的函式。您也可以在此處找到解釋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/450724.html
上一篇:如何在備忘錄中傳遞帶有引數的函式
