Tensorflow 张量流约束优化张量
我想通过剪切更新的变量来约束更新。我知道变量的边界,所以我需要约束它Tensorflow 张量流约束优化张量,tensorflow,machine-learning,optimization,Tensorflow,Machine Learning,Optimization,我想通过剪切更新的变量来约束更新。我知道变量的边界,所以我需要约束它 import tensorflow as tf tf.compat.v1.enable_eager_execution() import tensorflow_probability as tfp import numpy as np import matplotlib.pyplot as plt def rosen(x): """The Rosenbrock function"
import tensorflow as tf
tf.compat.v1.enable_eager_execution()
import tensorflow_probability as tfp
import numpy as np
import matplotlib.pyplot as plt
def rosen(x):
"""The Rosenbrock function"""
return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)
x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
"Trial #1"
x = tf.Variable(x0)
opt = tf.keras.optimizers.Adam(learning_rate=0.1)
ls = []
clip_min = [0,0,0,0,0]
clip_max = [2,2,2,2,2]
for _ in range(3000):
with tf.GradientTape() as tape:
tape.watch(x)
loss = rosen(x)
ls.append(loss.numpy())
grads = tape.gradient(loss, x)
opt.apply_gradients(zip([grads], [x]))
"This is the error !!!!!"
x = tf.clip_by_value(x, clip_value_min=clip_min,
clip_value_max=clip_max)
sol1 = x.numpy()
plt.plot(np.arange(len(ls)), ls)
它给了我这个错误:
AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute '_in_graph_mode'
如何解决这个问题???你能发布完整的回溯(错误消息)吗?嗨,这是完整的错误消息。当我尝试在每次迭代中剪裁变量时,它就会出现。在pytorch中,我通过应用torch.zero\u grad()来解决这个问题。但我不知道如何在TensorFlow中实现这一点这不是完整的回溯。您是否可以发布一条消息,以
回溯(最近一次调用上次)
开始,以AttributeError'tensorflow.python.framework.ops.热切Tensor'对象在图形模式下没有属性'
结束?。(即使有很多行)。