关于TensorFlow的tensorflow.org教程展示了使用tf.GradientTape的方法:
x = tf.convert_to_tensor([1,2,3]);
with tf.GradientTape() as t:
t.watch(x);
我想知道为什么我不能像这样将t.watch(x)移动到with块之外:
x = tf.convert_to_tensor([1,2,3]);
t = tf.GradientTape();
t.watch(x); #ERROR
错误是:
tape.py (59):
pywrap_tensorflow.TFE_Py_TapeWatch(
我已经构建了一个非常简单的TensorFlow Keras模型,只有一个密集的层。它在GradientTape块之外工作得很好,但在GradientTape块内部它会引发LookupError: No gradient defined for operation 'IteratorGetNext' (op type: IteratorGetNext)
要重现的代码:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import tensorflow
我试图计算TensorFlow神经网络的输出相对于它的输入的雅可比。这很容易用tf.GradientTape.jacobian方法实现。TensorFlow文档中提供的简单示例如下:
with tf.GradientTape() as g:
x = tf.constant([1.0, 2.0])
g.watch(x)
y = x * x
jacobian = g.jacobian(y, x)
如果我只想计算输入张量x的单个实例的Jacobian,这是很好的。但是,对于x的各种实例,我需要多次、多次地对这个Jacobian进行评估。对于一个非平凡的雅可比计算(例如,对于具有非线性激
import tensorflow as tf
def f(x):
return tf.multiply(x, x)
x = tf.Variable([3.])
with tf.GradientTape() as test_tape:
test_tape.watch(x)
with tf.GradientTape() as train_tape:
train_tape.watch(x)
fx = f(x)
gradient = train_tape.gradient(fx, x) # df(x)/x = d(x^2)
我正在重写与TF 2.0兼容的代码。不幸的是,网站提供的几乎每个示例都使用keras。但是,我想编写带有原始tensorflow函数的代码。
在某种程度上,在培训过程中计算和应用梯度的新方法如下所示(从窃取的代码):
# Optimization process.
def run_optimization(x, y):
# Wrap computation inside a GradientTape for automatic differentiation.
with tf.GradientTape() as g:
pred = logistic_regre
我正在尝试对我使用SavedModel应用编程接口加载的模型进行对抗性攻击。我想做一个关于给定目标的模型损失的输入的梯度下降。代码有点长,但这是说明问题的最小要求。
from __future__ import absolute_import, division, print_function, unicode_literals
from tensorflow import keras
from tensorflow.keras import layers, models
import tensorflow as tf
from sklearn.datasets import make_cl
继续使用tensorflow 2.0获取这些错误。这样能行吗?
import tensorflow as tf
import numpy as np
x = tf.constant(3.0)
with tf.GradientTape() as t:
t.watch(x)
y = (x - 10) ** 2
opt = tf.optimizers.Adam()
opt.minimize(lambda: y, var_list=[x])
我理解,只要我在tf.GradientTape()上下文中定义一个计算,梯度磁带就会计算出计算输出所依赖的所有变量。但是,我认为我并没有完全理解梯度的子属性,因为下面的代码没有像我期望的那样执行:
import tensorflow as tf
x = tf.Variable(2.)
loss_ = x**2-2*x+1
with tf.GradientTape(persistent=True) as g:
loss = loss_*1
print(g.gradient(loss,x))
output: None
为什么不计算梯度wrt?
我只能计算wrt到上下文中显式使用的变量的梯度
我正在使用Tensorflow 2.0并计算二阶导数。然而,tensorflow为u_tt和u_xx返回了None。正确计算了u_x、u_t。变量u,x,t是在前面定义的,它们是tf.Tensor的 import tensorflow as tf
# defining u,x,t
with tf.GradientTape(persistent=True) as tp2:
with tf.GradientTape(persistent=True) as tp1:
tp1.watch(t)
tp1.watch(x)
u_x = tp1.gr
当我使用numpy数学时,为什么GradientTape返回None
我正在尝试理解RL损失函数的tensorflow GradientTape计算。当我使用np.math调用函数时,GradientTape返回None。如果我在函数中使用tf.math,它工作得很好。我正在尝试做什么(我已经尝试了至少50个其他版本)。下面的代码有什么问题?我遗漏了什么?
窗口10,python 3.6.8,tensorflow 2.0.0参考:
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
def my
我理解,只要我在tf.GradientTape()上下文中定义一个计算,梯度磁带就会计算出计算输出所依赖的所有变量。但是,我认为我并没有完全理解梯度的子属性,因为下面的代码没有像我期望的那样执行:
import tensorflow as tf
x = tf.Variable(2.)
loss_ = x**2-2*x+1
with tf.GradientTape(persistent=True) as g:
loss = loss_*1
print(g.gradient(loss,x))
output: None
为什么不计算梯度wrt?
我只能计算wrt到上下文中显式使用的变量的梯度
我是Tensorflow的新手。在教科书示例中,我看到了以下代码,用于使用Tensorflow 2.x API来训练简单的线性模型:
m = tf.Variable(0.)
b = tf.Variable(0.)
def predict_y_value(x):
y = m * x + b
return y
def squared_error(y_pred, y_true):
return tf.reduce_mean(tf.square(y_pred - y_true))
learning_rate = 0.05
steps = 500
for i in range(s
我目前正在尝试使用TensorFlow 2中的GradientTape()和batch_jacobian在我的训练循环中计算雅可比矩阵。遗憾的是,我只能获得None值…… 我当前的尝试如下所示: for step, (batch_x, batch_y) in enumerate(train_data):
with tf.GradientTape(persistent=True) as g:
g.watch(batch_x)
g.watch(batch_y)
logits
我想将tensorflow 2.0中的损失函数替换为梯度函数。
例如,我有一个损失函数,如下所示:
def loss_function(prediction):
# do some standard tensorflow things here
return loss
然后,我使用tf.GradientTape方法应用梯度,即
with tf.GradientTape() as tape:
prediction = model(input)
loss = loss_function(prediction)
gradients = tf.gradient(
下面是我尝试运行的一段代码:
import tensorflow as tf
a = tf.constant([[1, 2], [2, 3]], dtype=tf.float32)
b = tf.constant([[1, 2], [2, 3]], dtype=tf.float32)
with tf.GradientTape() as tape1, tf.GradientTape() as tape2:
tape1.watch(a)
tape2.watch(a)
c = a * b
grad1 = tape1.gradient(c, a)
grad2 =
我试图计算我的模型的损失相对于它的输入的梯度,以便创建一个对抗性的例子。由于模型的输入是不可训练的,所以我需要计算关于张量的梯度,而不是变量。但是,如果张量不是可训练变量,则TensorFlow的GradientTape返回None梯度:
import numpy as np
import tensorflow as tf
tf.enable_eager_execution()
a = tf.convert_to_tensor(np.array([1., 2., 3.]), dtype=tf.float32)
b = tf.constant([1., 2., 3.])
c = tf.Var
我正在使用Python中的GradientTape()和jacobian()在Tensorflow 2.0中。
此代码执行得很好:
x = tf.Variable(2.0, dtype=tf.float32)
with tf.GradientTape() as gT:
gT.watch(x)
g = tf.convert_to_tensor([x, 0.0], dtype=tf.float32)
dg = gT.jacobian(g, x)
但这段代码破坏了:
x = tf.Variable(2.0, dtype=tf.float32)
with tf.GradientTape
我正在用tensorflow 2.0.1的gradienttape()训练一个GAN。培训持续到2000/2562批次,并冻结了系统。我甚至将gpu内存限制为8GB:
if gpus:
# Restrict TensorFlow to only allocate 1GB of memory on the first GPU
try:
tf.config.experimental.set_virtual_device_configuration(
gpus[0],
[tf.config.experimental.VirtualDeviceConfi
我正在处理tensorflow 1.15中的一个例程,该例程针对不同的向量计算几个hessian向量乘积 def hessian_v_prod(self, v):
with tf.GradientTape() as t1:
with tf.GradientTape() as t2:
# evaluate loss which uses self.variables
loss_val = self.loss()
grad = t2.gradient(loss_val, self.variables)
我想使用来观察急切执行模式下的渐变。是否可以只创建一次GradientTape,然后将所有内容记录下来,就好像它具有全局上下文一样?
下面是我想做的一个例子:
import numpy as np
import tensorflow as tf
x = tf.Variable(np.ones((2,)))
y=2*x
z=2*y
tf.gradients(z, x) # RuntimeError, not supported in eager execution
现在,这可以很容易地修复:
with tf.GradientTape() as g:
y = 2*x
z = 2*
我想计算Tensorflow中神经网络关于所有参数(或可训练变量)的损失函数的hessian。通过修改Tensorflow文档(https://www.tensorflow.org/api_docs/python/tf/GradientTape)中的示例代码,我设法计算了第一层的权重矩阵(如果我没有弄错的话): with tf.GradientTape(persistent=True) as tape:
loss = tf.reduce_mean(model(x,training=True)**2)
g = tape.gradient(loss,model.trainable
TensorFlow有一个名为GradientTape的特性,它使用蒙特卡罗方法(?)获得梯度。
我试图模拟ReLU的梯度,但这在X的负一半上不起作用。
#colab or ipython reset
%reset -f
#libs
import tensorflow as tf;
#init
tf.enable_eager_execution();
#code
x = tf.convert_to_tensor([-3,-2,-1,0,1,2,3],dtype=tf.float32);
with tf.GradientTape() as t:
t.watch(x);
y = f
下面的代码应该为x=2输出y=x*x的渐变,即值4。但是,当使用TensorFlow 2.0.0-alpha0时,代码会打印一个值None。当x的定义更改为使用tf.float32而不是tf.int32时,输出将更改为正确的值4。是否有任何文档阐明了数据类型必须是浮点数的要求,以便GradientTape在此场景中正常工作? print(tf.__version__)
x = tf.constant(2, dtype=tf.int32)
with tf.GradientTape() as tape:
tape.watch(x)
y = x ** 2
print(tape.gr
假设我们有一些函数y=x^2
然后,我们可以使用梯度磁带为我们自动计算梯度(当我们提供一些x到tensorflow的值时)。
x = tf.Variable(3.0)
with tf.GradientTape() as tape:
y = x**2
dy_dx = tape.gradient(y, x)
不管怎样,我能找到tensorflow对我的输入做了什么吗?例如,在这种情况下,很容易找到dy/dx=2x,这是否意味着tensorflow将2乘以我的输入值x,然后返回me 6(即3*2)?
我有一个非常复杂的函数,我不知道如何区分,所以我想从tensorflow梯度磁带中找到洞察
我正在尝试理解tensorflow tf.gradientTape的一个API。 下面是我从官网得到的代码: x = tf.constant(3.0)
with tf.GradientTape(persistent=True) as g:
g.watch(x)
y = x * x
z = y * y
dz_dx = g.gradient(z, x) # 108.0 (4*x^3 at x = 3)
dy_dx = g.gradient(y, x) # 6.0 我想知道他们是如何获得dz_dx as 108和dy_dx as 6的? 我还做了另一个类似下面的测试: x = tf
我需要一个与TensorFlow兼容的Python库,它提供了一个用于机器学习的二阶导数-- CTC (ConnectificationTemporal分类法)丢失函数。
也就是说,一个在Python中提供ctc_loss函数实现的库,与tf.nn.ctc_loss不同,第二个梯度必须是可解析计算的,性能合理,如下所示:
with tf.GradientTape() as tape1:
with tf.GradientTape() as tape2:
loss = ctc_loss(logits=logits, ...)
gradient = tape2.gr