简体   繁体   English

TF Gradient Tape 有交叉产品的问题?

[英]TF Gradient Tape has issues with cross products?

I'm trying to use TF gradient tape as an autograd tool for root finding via Newton's method.我正在尝试使用 TF 渐变带作为自动梯度工具,通过牛顿法进行根查找。 But when I'm trying to compute the Jacobian matrix, it seems that tf.GradientTape.jacobian can't handle cross products:但是当我试图计算雅可比矩阵时,似乎 tf.GradientTape.jacobian 无法处理叉积:

x = tf.convert_to_tensor(np.array([1., 2., 3.]))
Wx = np.ones((3))
with tf.GradientTape() as tape:
    tape.watch(x)
    y = tf.linalg.cross(x, Wx)
print(tape.jacobian(y, x))

gives below error:给出以下错误:

StagingError: in converted code: relative to /Users/xinzhang/anaconda3/lib/python3.7/site-packages: StagingError:在转换后的代码中:相对于/Users/xinzhang/anaconda3/lib/python3.7/site-packages:

tensorflow_core/python/ops/parallel_for/control_flow_ops.py:184 f  *
    return _pfor_impl(loop_fn, iters, parallel_iterations=parallel_iterations)
tensorflow_core/python/ops/parallel_for/control_flow_ops.py:257 _pfor_impl
    outputs.append(converter.convert(loop_fn_output))
tensorflow_core/python/ops/parallel_for/pfor.py:1231 convert
    output = self._convert_helper(y)
tensorflow_core/python/ops/parallel_for/pfor.py:1395 _convert_helper
    if flags.FLAGS.op_conversion_fallback_to_while_loop:
tensorflow_core/python/platform/flags.py:84 __getattr__
    wrapped(_sys.argv)
absl/flags/_flagvalues.py:633 __call__
    name, value, suggestions=suggestions)

UnrecognizedFlagError: Unknown command line flag 'f'

Whereas if I switch out the call to jacobian to a simple gradient:而如果我将对 jacobian 的调用切换为简单的渐变:

x = tf.convert_to_tensor(np.array([1., 2., 3.]))
Wx = np.ones((3))
with tf.GradientTape() as tape:
    tape.watch(x)
    y = tf.linalg.cross(x, Wx)
print(tape.gradient(y, x))

gives the expected result:给出预期的结果:

tf.Tensor([0. 0. 0.], shape=(3,), dtype=float64)

Is this a bug??这是bug吗?? Or am I doing something wrong with the tape.jacobian method?还是我对 tape.jacobian 方法做错了什么?

ps python version 3.7.4; ps python 版本 3.7.4; tf version 2.0.0 Everything installed with conda. tf 版本 2.0.0 使用 conda 安装的所有内容。

This might be a bug in Tensorflow Version 2.0 but it is fixed in Tensorflow Version 2.1 .这可能是Tensorflow Version 2.0中的一个错误,但它已在Tensorflow Version 2.1中修复。

So, please upgrade your Tensorflow Version to either 2.1 or 2.2 and the issue will be resolved.因此,请将您的 Tensorflow 版本升级到2.12.2 ,问题将得到解决。

Working code is mentioned below:工作代码如下:

!pip install tensorflow==2.2

import tensorflow as tf
import numpy as np

print(tf.__version__)

x = tf.convert_to_tensor(np.array([1., 2., 3.]))
Wx = np.ones((3))
with tf.GradientTape() as tape:
    tape.watch(x)
    y = tf.linalg.cross(x, Wx)
print(tape.jacobian(y, x))

Output is shown below: Output 如下图所示:

2.2.0

tf.Tensor(
[[ 0.  1. -1.]
 [-1.  0.  1.]
 [ 1. -1.  0.]], shape=(3, 3), dtype=float64)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM